Bug Summary

File:llvm/lib/CodeGen/CodeGenPrepare.cpp
Warning:line 2359, column 10
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 -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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.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-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen -I include -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include -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-14/lib/clang/14.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 -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -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-14~++20210926122410+d23fd8ae8906/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -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-2021-09-26-234817-15343-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp

/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/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/ConstantFolding.h"
27#include "llvm/Analysis/InstructionSimplify.h"
28#include "llvm/Analysis/LoopInfo.h"
29#include "llvm/Analysis/MemoryBuiltins.h"
30#include "llvm/Analysis/ProfileSummaryInfo.h"
31#include "llvm/Analysis/TargetLibraryInfo.h"
32#include "llvm/Analysis/TargetTransformInfo.h"
33#include "llvm/Analysis/ValueTracking.h"
34#include "llvm/Analysis/VectorUtils.h"
35#include "llvm/CodeGen/Analysis.h"
36#include "llvm/CodeGen/ISDOpcodes.h"
37#include "llvm/CodeGen/SelectionDAGNodes.h"
38#include "llvm/CodeGen/TargetLowering.h"
39#include "llvm/CodeGen/TargetPassConfig.h"
40#include "llvm/CodeGen/TargetSubtargetInfo.h"
41#include "llvm/CodeGen/ValueTypes.h"
42#include "llvm/Config/llvm-config.h"
43#include "llvm/IR/Argument.h"
44#include "llvm/IR/Attributes.h"
45#include "llvm/IR/BasicBlock.h"
46#include "llvm/IR/Constant.h"
47#include "llvm/IR/Constants.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DebugInfo.h"
50#include "llvm/IR/DerivedTypes.h"
51#include "llvm/IR/Dominators.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/GetElementPtrTypeIterator.h"
54#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/GlobalVariable.h"
56#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/InlineAsm.h"
58#include "llvm/IR/InstrTypes.h"
59#include "llvm/IR/Instruction.h"
60#include "llvm/IR/Instructions.h"
61#include "llvm/IR/IntrinsicInst.h"
62#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/IntrinsicsAArch64.h"
64#include "llvm/IR/LLVMContext.h"
65#include "llvm/IR/MDBuilder.h"
66#include "llvm/IR/Module.h"
67#include "llvm/IR/Operator.h"
68#include "llvm/IR/PatternMatch.h"
69#include "llvm/IR/Statepoint.h"
70#include "llvm/IR/Type.h"
71#include "llvm/IR/Use.h"
72#include "llvm/IR/User.h"
73#include "llvm/IR/Value.h"
74#include "llvm/IR/ValueHandle.h"
75#include "llvm/IR/ValueMap.h"
76#include "llvm/InitializePasses.h"
77#include "llvm/Pass.h"
78#include "llvm/Support/BlockFrequency.h"
79#include "llvm/Support/BranchProbability.h"
80#include "llvm/Support/Casting.h"
81#include "llvm/Support/CommandLine.h"
82#include "llvm/Support/Compiler.h"
83#include "llvm/Support/Debug.h"
84#include "llvm/Support/ErrorHandling.h"
85#include "llvm/Support/MachineValueType.h"
86#include "llvm/Support/MathExtras.h"
87#include "llvm/Support/raw_ostream.h"
88#include "llvm/Target/TargetMachine.h"
89#include "llvm/Target/TargetOptions.h"
90#include "llvm/Transforms/Utils/BasicBlockUtils.h"
91#include "llvm/Transforms/Utils/BypassSlowDivision.h"
92#include "llvm/Transforms/Utils/Local.h"
93#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
94#include "llvm/Transforms/Utils/SizeOpts.h"
95#include <algorithm>
96#include <cassert>
97#include <cstdint>
98#include <iterator>
99#include <limits>
100#include <memory>
101#include <utility>
102#include <vector>
103
104using namespace llvm;
105using namespace llvm::PatternMatch;
106
107#define DEBUG_TYPE"codegenprepare" "codegenprepare"
108
109STATISTIC(NumBlocksElim, "Number of blocks eliminated")static llvm::Statistic NumBlocksElim = {"codegenprepare", "NumBlocksElim"
, "Number of blocks eliminated"}
;
110STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated")static llvm::Statistic NumPHIsElim = {"codegenprepare", "NumPHIsElim"
, "Number of trivial PHIs eliminated"}
;
111STATISTIC(NumGEPsElim, "Number of GEPs converted to casts")static llvm::Statistic NumGEPsElim = {"codegenprepare", "NumGEPsElim"
, "Number of GEPs converted to casts"}
;
112STATISTIC(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"
}
113 "sunken Cmps")static llvm::Statistic NumCmpUses = {"codegenprepare", "NumCmpUses"
, "Number of uses of Cmp expressions replaced with uses of " "sunken Cmps"
}
;
114STATISTIC(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"
}
115 "of sunken Casts")static llvm::Statistic NumCastUses = {"codegenprepare", "NumCastUses"
, "Number of uses of Cast expressions replaced with uses " "of sunken Casts"
}
;
116STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "static llvm::Statistic NumMemoryInsts = {"codegenprepare", "NumMemoryInsts"
, "Number of memory instructions whose address " "computations were sunk"
}
117 "computations were sunk")static llvm::Statistic NumMemoryInsts = {"codegenprepare", "NumMemoryInsts"
, "Number of memory instructions whose address " "computations were sunk"
}
;
118STATISTIC(NumMemoryInstsPhiCreated,static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare"
, "NumMemoryInstsPhiCreated", "Number of phis created when address "
"computations were sunk to memory instructions"}
119 "Number of phis created when address "static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare"
, "NumMemoryInstsPhiCreated", "Number of phis created when address "
"computations were sunk to memory instructions"}
120 "computations were sunk to memory instructions")static llvm::Statistic NumMemoryInstsPhiCreated = {"codegenprepare"
, "NumMemoryInstsPhiCreated", "Number of phis created when address "
"computations were sunk to memory instructions"}
;
121STATISTIC(NumMemoryInstsSelectCreated,static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare"
, "NumMemoryInstsSelectCreated", "Number of select created when address "
"computations were sunk to memory instructions"}
122 "Number of select created when address "static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare"
, "NumMemoryInstsSelectCreated", "Number of select created when address "
"computations were sunk to memory instructions"}
123 "computations were sunk to memory instructions")static llvm::Statistic NumMemoryInstsSelectCreated = {"codegenprepare"
, "NumMemoryInstsSelectCreated", "Number of select created when address "
"computations were sunk to memory instructions"}
;
124STATISTIC(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"}
;
125STATISTIC(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"}
;
126STATISTIC(NumAndsAdded,static llvm::Statistic NumAndsAdded = {"codegenprepare", "NumAndsAdded"
, "Number of and mask instructions added to form ext loads"}
127 "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"}
;
128STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized")static llvm::Statistic NumAndUses = {"codegenprepare", "NumAndUses"
, "Number of uses of and mask instructions optimized"}
;
129STATISTIC(NumRetsDup, "Number of return instructions duplicated")static llvm::Statistic NumRetsDup = {"codegenprepare", "NumRetsDup"
, "Number of return instructions duplicated"}
;
130STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved")static llvm::Statistic NumDbgValueMoved = {"codegenprepare", "NumDbgValueMoved"
, "Number of debug value instructions moved"}
;
131STATISTIC(NumSelectsExpanded, "Number of selects turned into branches")static llvm::Statistic NumSelectsExpanded = {"codegenprepare"
, "NumSelectsExpanded", "Number of selects turned into branches"
}
;
132STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed")static llvm::Statistic NumStoreExtractExposed = {"codegenprepare"
, "NumStoreExtractExposed", "Number of store(extractelement) exposed"
}
;
133
134static cl::opt<bool> DisableBranchOpts(
135 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
136 cl::desc("Disable branch optimizations in CodeGenPrepare"));
137
138static cl::opt<bool>
139 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
140 cl::desc("Disable GC optimizations in CodeGenPrepare"));
141
142static cl::opt<bool> DisableSelectToBranch(
143 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
144 cl::desc("Disable select to branch conversion."));
145
146static cl::opt<bool> AddrSinkUsingGEPs(
147 "addr-sink-using-gep", cl::Hidden, cl::init(true),
148 cl::desc("Address sinking in CGP using GEPs."));
149
150static cl::opt<bool> EnableAndCmpSinking(
151 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
152 cl::desc("Enable sinkinig and/cmp into branches."));
153
154static cl::opt<bool> DisableStoreExtract(
155 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
156 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
157
158static cl::opt<bool> StressStoreExtract(
159 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
160 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
161
162static cl::opt<bool> DisableExtLdPromotion(
163 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
164 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
165 "CodeGenPrepare"));
166
167static cl::opt<bool> StressExtLdPromotion(
168 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
169 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
170 "optimization in CodeGenPrepare"));
171
172static cl::opt<bool> DisablePreheaderProtect(
173 "disable-preheader-prot", cl::Hidden, cl::init(false),
174 cl::desc("Disable protection against removing loop preheaders"));
175
176static cl::opt<bool> ProfileGuidedSectionPrefix(
177 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
178 cl::desc("Use profile info to add section prefix for hot/cold functions"));
179
180static cl::opt<bool> ProfileUnknownInSpecialSection(
181 "profile-unknown-in-special-section", cl::Hidden, cl::init(false),
182 cl::ZeroOrMore,
183 cl::desc("In profiling mode like sampleFDO, if a function doesn't have "
184 "profile, we cannot tell the function is cold for sure because "
185 "it may be a function newly added without ever being sampled. "
186 "With the flag enabled, compiler can put such profile unknown "
187 "functions into a special section, so runtime system can choose "
188 "to handle it in a different way than .text section, to save "
189 "RAM for example. "));
190
191static cl::opt<unsigned> FreqRatioToSkipMerge(
192 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
193 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
194 "(frequency of destination block) is greater than this ratio"));
195
196static cl::opt<bool> ForceSplitStore(
197 "force-split-store", cl::Hidden, cl::init(false),
198 cl::desc("Force store splitting no matter what the target query says."));
199
200static cl::opt<bool>
201EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
202 cl::desc("Enable merging of redundant sexts when one is dominating"
203 " the other."), cl::init(true));
204
205static cl::opt<bool> DisableComplexAddrModes(
206 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
207 cl::desc("Disables combining addressing modes with different parts "
208 "in optimizeMemoryInst."));
209
210static cl::opt<bool>
211AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
212 cl::desc("Allow creation of Phis in Address sinking."));
213
214static cl::opt<bool>
215AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
216 cl::desc("Allow creation of selects in Address sinking."));
217
218static cl::opt<bool> AddrSinkCombineBaseReg(
219 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
220 cl::desc("Allow combining of BaseReg field in Address sinking."));
221
222static cl::opt<bool> AddrSinkCombineBaseGV(
223 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
224 cl::desc("Allow combining of BaseGV field in Address sinking."));
225
226static cl::opt<bool> AddrSinkCombineBaseOffs(
227 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
228 cl::desc("Allow combining of BaseOffs field in Address sinking."));
229
230static cl::opt<bool> AddrSinkCombineScaledReg(
231 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
232 cl::desc("Allow combining of ScaledReg field in Address sinking."));
233
234static cl::opt<bool>
235 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
236 cl::init(true),
237 cl::desc("Enable splitting large offset of GEP."));
238
239static cl::opt<bool> EnableICMP_EQToICMP_ST(
240 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false),
241 cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
242
243static cl::opt<bool>
244 VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false),
245 cl::desc("Enable BFI update verification for "
246 "CodeGenPrepare."));
247
248static cl::opt<bool> OptimizePhiTypes(
249 "cgp-optimize-phi-types", cl::Hidden, cl::init(false),
250 cl::desc("Enable converting phi types in CodeGenPrepare"));
251
252namespace {
253
254enum ExtType {
255 ZeroExtension, // Zero extension has been seen.
256 SignExtension, // Sign extension has been seen.
257 BothExtension // This extension type is used if we saw sext after
258 // ZeroExtension had been set, or if we saw zext after
259 // SignExtension had been set. It makes the type
260 // information of a promoted instruction invalid.
261};
262
263using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
264using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
265using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
266using SExts = SmallVector<Instruction *, 16>;
267using ValueToSExts = DenseMap<Value *, SExts>;
268
269class TypePromotionTransaction;
270
271 class CodeGenPrepare : public FunctionPass {
272 const TargetMachine *TM = nullptr;
273 const TargetSubtargetInfo *SubtargetInfo;
274 const TargetLowering *TLI = nullptr;
275 const TargetRegisterInfo *TRI;
276 const TargetTransformInfo *TTI = nullptr;
277 const TargetLibraryInfo *TLInfo;
278 const LoopInfo *LI;
279 std::unique_ptr<BlockFrequencyInfo> BFI;
280 std::unique_ptr<BranchProbabilityInfo> BPI;
281 ProfileSummaryInfo *PSI;
282
283 /// As we scan instructions optimizing them, this is the next instruction
284 /// to optimize. Transforms that can invalidate this should update it.
285 BasicBlock::iterator CurInstIterator;
286
287 /// Keeps track of non-local addresses that have been sunk into a block.
288 /// This allows us to avoid inserting duplicate code for blocks with
289 /// multiple load/stores of the same address. The usage of WeakTrackingVH
290 /// enables SunkAddrs to be treated as a cache whose entries can be
291 /// invalidated if a sunken address computation has been erased.
292 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
293
294 /// Keeps track of all instructions inserted for the current function.
295 SetOfInstrs InsertedInsts;
296
297 /// Keeps track of the type of the related instruction before their
298 /// promotion for the current function.
299 InstrToOrigTy PromotedInsts;
300
301 /// Keep track of instructions removed during promotion.
302 SetOfInstrs RemovedInsts;
303
304 /// Keep track of sext chains based on their initial value.
305 DenseMap<Value *, Instruction *> SeenChainsForSExt;
306
307 /// Keep track of GEPs accessing the same data structures such as structs or
308 /// arrays that are candidates to be split later because of their large
309 /// size.
310 MapVector<
311 AssertingVH<Value>,
312 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
313 LargeOffsetGEPMap;
314
315 /// Keep track of new GEP base after splitting the GEPs having large offset.
316 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
317
318 /// Map serial numbers to Large offset GEPs.
319 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
320
321 /// Keep track of SExt promoted.
322 ValueToSExts ValToSExtendedUses;
323
324 /// True if the function has the OptSize attribute.
325 bool OptSize;
326
327 /// DataLayout for the Function being processed.
328 const DataLayout *DL = nullptr;
329
330 /// Building the dominator tree can be expensive, so we only build it
331 /// lazily and update it when required.
332 std::unique_ptr<DominatorTree> DT;
333
334 public:
335 static char ID; // Pass identification, replacement for typeid
336
337 CodeGenPrepare() : FunctionPass(ID) {
338 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
339 }
340
341 bool runOnFunction(Function &F) override;
342
343 StringRef getPassName() const override { return "CodeGen Prepare"; }
344
345 void getAnalysisUsage(AnalysisUsage &AU) const override {
346 // FIXME: When we can selectively preserve passes, preserve the domtree.
347 AU.addRequired<ProfileSummaryInfoWrapperPass>();
348 AU.addRequired<TargetLibraryInfoWrapperPass>();
349 AU.addRequired<TargetPassConfig>();
350 AU.addRequired<TargetTransformInfoWrapperPass>();
351 AU.addRequired<LoopInfoWrapperPass>();
352 }
353
354 private:
355 template <typename F>
356 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
357 // Substituting can cause recursive simplifications, which can invalidate
358 // our iterator. Use a WeakTrackingVH to hold onto it in case this
359 // happens.
360 Value *CurValue = &*CurInstIterator;
361 WeakTrackingVH IterHandle(CurValue);
362
363 f();
364
365 // If the iterator instruction was recursively deleted, start over at the
366 // start of the block.
367 if (IterHandle != CurValue) {
368 CurInstIterator = BB->begin();
369 SunkAddrs.clear();
370 }
371 }
372
373 // Get the DominatorTree, building if necessary.
374 DominatorTree &getDT(Function &F) {
375 if (!DT)
376 DT = std::make_unique<DominatorTree>(F);
377 return *DT;
378 }
379
380 void removeAllAssertingVHReferences(Value *V);
381 bool eliminateAssumptions(Function &F);
382 bool eliminateFallThrough(Function &F);
383 bool eliminateMostlyEmptyBlocks(Function &F);
384 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
385 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
386 void eliminateMostlyEmptyBlock(BasicBlock *BB);
387 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
388 bool isPreheader);
389 bool makeBitReverse(Instruction &I);
390 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
391 bool optimizeInst(Instruction *I, bool &ModifiedDT);
392 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
393 Type *AccessTy, unsigned AddrSpace);
394 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
395 bool optimizeInlineAsmInst(CallInst *CS);
396 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
397 bool optimizeExt(Instruction *&I);
398 bool optimizeExtUses(Instruction *I);
399 bool optimizeLoadExt(LoadInst *Load);
400 bool optimizeShiftInst(BinaryOperator *BO);
401 bool optimizeFunnelShift(IntrinsicInst *Fsh);
402 bool optimizeSelectInst(SelectInst *SI);
403 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
404 bool optimizeSwitchInst(SwitchInst *SI);
405 bool optimizeExtractElementInst(Instruction *Inst);
406 bool dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT);
407 bool fixupDbgValue(Instruction *I);
408 bool placeDbgValues(Function &F);
409 bool placePseudoProbes(Function &F);
410 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
411 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
412 bool tryToPromoteExts(TypePromotionTransaction &TPT,
413 const SmallVectorImpl<Instruction *> &Exts,
414 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
415 unsigned CreatedInstsCost = 0);
416 bool mergeSExts(Function &F);
417 bool splitLargeGEPOffsets();
418 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
419 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
420 bool optimizePhiTypes(Function &F);
421 bool performAddressTypePromotion(
422 Instruction *&Inst,
423 bool AllowPromotionWithoutCommonHeader,
424 bool HasPromoted, TypePromotionTransaction &TPT,
425 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
426 bool splitBranchCondition(Function &F, bool &ModifiedDT);
427 bool simplifyOffsetableRelocate(GCStatepointInst &I);
428
429 bool tryToSinkFreeOperands(Instruction *I);
430 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0,
431 Value *Arg1, CmpInst *Cmp,
432 Intrinsic::ID IID);
433 bool optimizeCmp(CmpInst *Cmp, bool &ModifiedDT);
434 bool combineToUSubWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
435 bool combineToUAddWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
436 void verifyBFIUpdates(Function &F);
437 };
438
439} // end anonymous namespace
440
441char CodeGenPrepare::ID = 0;
442
443INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,static void *initializeCodeGenPreparePassOnce(PassRegistry &
Registry) {
444 "Optimize for code generation", false, false)static void *initializeCodeGenPreparePassOnce(PassRegistry &
Registry) {
445INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)initializeLoopInfoWrapperPassPass(Registry);
446INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)initializeProfileSummaryInfoWrapperPassPass(Registry);
447INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
448INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)initializeTargetPassConfigPass(Registry);
449INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)initializeTargetTransformInfoWrapperPassPass(Registry);
450INITIALIZE_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)); }
451 "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)); }
452
453FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
454
455bool CodeGenPrepare::runOnFunction(Function &F) {
456 if (skipFunction(F))
457 return false;
458
459 DL = &F.getParent()->getDataLayout();
460
461 bool EverMadeChange = false;
462 // Clear per function information.
463 InsertedInsts.clear();
464 PromotedInsts.clear();
465
466 TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
467 SubtargetInfo = TM->getSubtargetImpl(F);
468 TLI = SubtargetInfo->getTargetLowering();
469 TRI = SubtargetInfo->getRegisterInfo();
470 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
471 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
472 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
473 BPI.reset(new BranchProbabilityInfo(F, *LI));
474 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
475 PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
476 OptSize = F.hasOptSize();
477 if (ProfileGuidedSectionPrefix) {
478 // The hot attribute overwrites profile count based hotness while profile
479 // counts based hotness overwrite the cold attribute.
480 // This is a conservative behabvior.
481 if (F.hasFnAttribute(Attribute::Hot) ||
482 PSI->isFunctionHotInCallGraph(&F, *BFI))
483 F.setSectionPrefix("hot");
484 // If PSI shows this function is not hot, we will placed the function
485 // into unlikely section if (1) PSI shows this is a cold function, or
486 // (2) the function has a attribute of cold.
487 else if (PSI->isFunctionColdInCallGraph(&F, *BFI) ||
488 F.hasFnAttribute(Attribute::Cold))
489 F.setSectionPrefix("unlikely");
490 else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() &&
491 PSI->isFunctionHotnessUnknown(F))
492 F.setSectionPrefix("unknown");
493 }
494
495 /// This optimization identifies DIV instructions that can be
496 /// profitably bypassed and carried out with a shorter, faster divide.
497 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
498 const DenseMap<unsigned int, unsigned int> &BypassWidths =
499 TLI->getBypassSlowDivWidths();
500 BasicBlock* BB = &*F.begin();
501 while (BB != nullptr) {
502 // bypassSlowDivision may create new BBs, but we don't want to reapply the
503 // optimization to those blocks.
504 BasicBlock* Next = BB->getNextNode();
505 // F.hasOptSize is already checked in the outer if statement.
506 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
507 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
508 BB = Next;
509 }
510 }
511
512 // Get rid of @llvm.assume builtins before attempting to eliminate empty
513 // blocks, since there might be blocks that only contain @llvm.assume calls
514 // (plus arguments that we can get rid of).
515 EverMadeChange |= eliminateAssumptions(F);
516
517 // Eliminate blocks that contain only PHI nodes and an
518 // unconditional branch.
519 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
520
521 bool ModifiedDT = false;
522 if (!DisableBranchOpts)
523 EverMadeChange |= splitBranchCondition(F, ModifiedDT);
524
525 // Split some critical edges where one of the sources is an indirect branch,
526 // to help generate sane code for PHIs involving such edges.
527 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
528
529 bool MadeChange = true;
530 while (MadeChange) {
531 MadeChange = false;
532 DT.reset();
533 for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
534 bool ModifiedDTOnIteration = false;
535 MadeChange |= optimizeBlock(BB, ModifiedDTOnIteration);
536
537 // Restart BB iteration if the dominator tree of the Function was changed
538 if (ModifiedDTOnIteration)
539 break;
540 }
541 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
542 MadeChange |= mergeSExts(F);
543 if (!LargeOffsetGEPMap.empty())
544 MadeChange |= splitLargeGEPOffsets();
545 MadeChange |= optimizePhiTypes(F);
546
547 if (MadeChange)
548 eliminateFallThrough(F);
549
550 // Really free removed instructions during promotion.
551 for (Instruction *I : RemovedInsts)
552 I->deleteValue();
553
554 EverMadeChange |= MadeChange;
555 SeenChainsForSExt.clear();
556 ValToSExtendedUses.clear();
557 RemovedInsts.clear();
558 LargeOffsetGEPMap.clear();
559 LargeOffsetGEPID.clear();
560 }
561
562 NewGEPBases.clear();
563 SunkAddrs.clear();
564
565 if (!DisableBranchOpts) {
566 MadeChange = false;
567 // Use a set vector to get deterministic iteration order. The order the
568 // blocks are removed may affect whether or not PHI nodes in successors
569 // are removed.
570 SmallSetVector<BasicBlock*, 8> WorkList;
571 for (BasicBlock &BB : F) {
572 SmallVector<BasicBlock *, 2> Successors(successors(&BB));
573 MadeChange |= ConstantFoldTerminator(&BB, true);
574 if (!MadeChange) continue;
575
576 for (BasicBlock *Succ : Successors)
577 if (pred_empty(Succ))
578 WorkList.insert(Succ);
579 }
580
581 // Delete the dead blocks and any of their dead successors.
582 MadeChange |= !WorkList.empty();
583 while (!WorkList.empty()) {
584 BasicBlock *BB = WorkList.pop_back_val();
585 SmallVector<BasicBlock*, 2> Successors(successors(BB));
586
587 DeleteDeadBlock(BB);
588
589 for (BasicBlock *Succ : Successors)
590 if (pred_empty(Succ))
591 WorkList.insert(Succ);
592 }
593
594 // Merge pairs of basic blocks with unconditional branches, connected by
595 // a single edge.
596 if (EverMadeChange || MadeChange)
597 MadeChange |= eliminateFallThrough(F);
598
599 EverMadeChange |= MadeChange;
600 }
601
602 if (!DisableGCOpts) {
603 SmallVector<GCStatepointInst *, 2> Statepoints;
604 for (BasicBlock &BB : F)
605 for (Instruction &I : BB)
606 if (auto *SP = dyn_cast<GCStatepointInst>(&I))
607 Statepoints.push_back(SP);
608 for (auto &I : Statepoints)
609 EverMadeChange |= simplifyOffsetableRelocate(*I);
610 }
611
612 // Do this last to clean up use-before-def scenarios introduced by other
613 // preparatory transforms.
614 EverMadeChange |= placeDbgValues(F);
615 EverMadeChange |= placePseudoProbes(F);
616
617#ifndef NDEBUG
618 if (VerifyBFIUpdates)
619 verifyBFIUpdates(F);
620#endif
621
622 return EverMadeChange;
623}
624
625bool CodeGenPrepare::eliminateAssumptions(Function &F) {
626 bool MadeChange = false;
627 for (BasicBlock &BB : F) {
628 CurInstIterator = BB.begin();
629 while (CurInstIterator != BB.end()) {
630 Instruction *I = &*(CurInstIterator++);
631 if (auto *Assume = dyn_cast<AssumeInst>(I)) {
632 MadeChange = true;
633 Value *Operand = Assume->getOperand(0);
634 Assume->eraseFromParent();
635
636 resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
637 RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr);
638 });
639 }
640 }
641 }
642 return MadeChange;
643}
644
645/// An instruction is about to be deleted, so remove all references to it in our
646/// GEP-tracking data strcutures.
647void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
648 LargeOffsetGEPMap.erase(V);
649 NewGEPBases.erase(V);
650
651 auto GEP = dyn_cast<GetElementPtrInst>(V);
652 if (!GEP)
653 return;
654
655 LargeOffsetGEPID.erase(GEP);
656
657 auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
658 if (VecI == LargeOffsetGEPMap.end())
659 return;
660
661 auto &GEPVector = VecI->second;
662 const auto &I =
663 llvm::find_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
664 if (I == GEPVector.end())
665 return;
666
667 GEPVector.erase(I);
668 if (GEPVector.empty())
669 LargeOffsetGEPMap.erase(VecI);
670}
671
672// Verify BFI has been updated correctly by recomputing BFI and comparing them.
673void LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__)) CodeGenPrepare::verifyBFIUpdates(Function &F) {
674 DominatorTree NewDT(F);
675 LoopInfo NewLI(NewDT);
676 BranchProbabilityInfo NewBPI(F, NewLI, TLInfo);
677 BlockFrequencyInfo NewBFI(F, NewBPI, NewLI);
678 NewBFI.verifyMatch(*BFI);
679}
680
681/// Merge basic blocks which are connected by a single edge, where one of the
682/// basic blocks has a single successor pointing to the other basic block,
683/// which has a single predecessor.
684bool CodeGenPrepare::eliminateFallThrough(Function &F) {
685 bool Changed = false;
686 // Scan all of the blocks in the function, except for the entry block.
687 // Use a temporary array to avoid iterator being invalidated when
688 // deleting blocks.
689 SmallVector<WeakTrackingVH, 16> Blocks;
690 for (auto &Block : llvm::drop_begin(F))
691 Blocks.push_back(&Block);
692
693 SmallSet<WeakTrackingVH, 16> Preds;
694 for (auto &Block : Blocks) {
695 auto *BB = cast_or_null<BasicBlock>(Block);
696 if (!BB)
697 continue;
698 // If the destination block has a single pred, then this is a trivial
699 // edge, just collapse it.
700 BasicBlock *SinglePred = BB->getSinglePredecessor();
701
702 // Don't merge if BB's address is taken.
703 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
704
705 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
706 if (Term && !Term->isConditional()) {
707 Changed = true;
708 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)
;
709
710 // Merge BB into SinglePred and delete it.
711 MergeBlockIntoPredecessor(BB);
712 Preds.insert(SinglePred);
713 }
714 }
715
716 // (Repeatedly) merging blocks into their predecessors can create redundant
717 // debug intrinsics.
718 for (auto &Pred : Preds)
719 if (auto *BB = cast_or_null<BasicBlock>(Pred))
720 RemoveRedundantDbgInstrs(BB);
721
722 return Changed;
723}
724
725/// Find a destination block from BB if BB is mergeable empty block.
726BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
727 // If this block doesn't end with an uncond branch, ignore it.
728 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
729 if (!BI || !BI->isUnconditional())
730 return nullptr;
731
732 // If the instruction before the branch (skipping debug info) isn't a phi
733 // node, then other stuff is happening here.
734 BasicBlock::iterator BBI = BI->getIterator();
735 if (BBI != BB->begin()) {
736 --BBI;
737 while (isa<DbgInfoIntrinsic>(BBI)) {
738 if (BBI == BB->begin())
739 break;
740 --BBI;
741 }
742 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
743 return nullptr;
744 }
745
746 // Do not break infinite loops.
747 BasicBlock *DestBB = BI->getSuccessor(0);
748 if (DestBB == BB)
749 return nullptr;
750
751 if (!canMergeBlocks(BB, DestBB))
752 DestBB = nullptr;
753
754 return DestBB;
755}
756
757/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
758/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
759/// edges in ways that are non-optimal for isel. Start by eliminating these
760/// blocks so we can split them the way we want them.
761bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
762 SmallPtrSet<BasicBlock *, 16> Preheaders;
763 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
764 while (!LoopList.empty()) {
765 Loop *L = LoopList.pop_back_val();
766 llvm::append_range(LoopList, *L);
767 if (BasicBlock *Preheader = L->getLoopPreheader())
768 Preheaders.insert(Preheader);
769 }
770
771 bool MadeChange = false;
772 // Copy blocks into a temporary array to avoid iterator invalidation issues
773 // as we remove them.
774 // Note that this intentionally skips the entry block.
775 SmallVector<WeakTrackingVH, 16> Blocks;
776 for (auto &Block : llvm::drop_begin(F))
777 Blocks.push_back(&Block);
778
779 for (auto &Block : Blocks) {
780 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
781 if (!BB)
782 continue;
783 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
784 if (!DestBB ||
785 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
786 continue;
787
788 eliminateMostlyEmptyBlock(BB);
789 MadeChange = true;
790 }
791 return MadeChange;
792}
793
794bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
795 BasicBlock *DestBB,
796 bool isPreheader) {
797 // Do not delete loop preheaders if doing so would create a critical edge.
798 // Loop preheaders can be good locations to spill registers. If the
799 // preheader is deleted and we create a critical edge, registers may be
800 // spilled in the loop body instead.
801 if (!DisablePreheaderProtect && isPreheader &&
802 !(BB->getSinglePredecessor() &&
803 BB->getSinglePredecessor()->getSingleSuccessor()))
804 return false;
805
806 // Skip merging if the block's successor is also a successor to any callbr
807 // that leads to this block.
808 // FIXME: Is this really needed? Is this a correctness issue?
809 for (BasicBlock *Pred : predecessors(BB)) {
810 if (auto *CBI = dyn_cast<CallBrInst>((Pred)->getTerminator()))
811 for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i)
812 if (DestBB == CBI->getSuccessor(i))
813 return false;
814 }
815
816 // Try to skip merging if the unique predecessor of BB is terminated by a
817 // switch or indirect branch instruction, and BB is used as an incoming block
818 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
819 // add COPY instructions in the predecessor of BB instead of BB (if it is not
820 // merged). Note that the critical edge created by merging such blocks wont be
821 // split in MachineSink because the jump table is not analyzable. By keeping
822 // such empty block (BB), ISel will place COPY instructions in BB, not in the
823 // predecessor of BB.
824 BasicBlock *Pred = BB->getUniquePredecessor();
825 if (!Pred ||
826 !(isa<SwitchInst>(Pred->getTerminator()) ||
827 isa<IndirectBrInst>(Pred->getTerminator())))
828 return true;
829
830 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
831 return true;
832
833 // We use a simple cost heuristic which determine skipping merging is
834 // profitable if the cost of skipping merging is less than the cost of
835 // merging : Cost(skipping merging) < Cost(merging BB), where the
836 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
837 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
838 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
839 // Freq(Pred) / Freq(BB) > 2.
840 // Note that if there are multiple empty blocks sharing the same incoming
841 // value for the PHIs in the DestBB, we consider them together. In such
842 // case, Cost(merging BB) will be the sum of their frequencies.
843
844 if (!isa<PHINode>(DestBB->begin()))
845 return true;
846
847 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
848
849 // Find all other incoming blocks from which incoming values of all PHIs in
850 // DestBB are the same as the ones from BB.
851 for (BasicBlock *DestBBPred : predecessors(DestBB)) {
852 if (DestBBPred == BB)
853 continue;
854
855 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
856 return DestPN.getIncomingValueForBlock(BB) ==
857 DestPN.getIncomingValueForBlock(DestBBPred);
858 }))
859 SameIncomingValueBBs.insert(DestBBPred);
860 }
861
862 // See if all BB's incoming values are same as the value from Pred. In this
863 // case, no reason to skip merging because COPYs are expected to be place in
864 // Pred already.
865 if (SameIncomingValueBBs.count(Pred))
866 return true;
867
868 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
869 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
870
871 for (auto *SameValueBB : SameIncomingValueBBs)
872 if (SameValueBB->getUniquePredecessor() == Pred &&
873 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
874 BBFreq += BFI->getBlockFreq(SameValueBB);
875
876 return PredFreq.getFrequency() <=
877 BBFreq.getFrequency() * FreqRatioToSkipMerge;
878}
879
880/// Return true if we can merge BB into DestBB if there is a single
881/// unconditional branch between them, and BB contains no other non-phi
882/// instructions.
883bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
884 const BasicBlock *DestBB) const {
885 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
886 // the successor. If there are more complex condition (e.g. preheaders),
887 // don't mess around with them.
888 for (const PHINode &PN : BB->phis()) {
889 for (const User *U : PN.users()) {
890 const Instruction *UI = cast<Instruction>(U);
891 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
892 return false;
893 // If User is inside DestBB block and it is a PHINode then check
894 // incoming value. If incoming value is not from BB then this is
895 // a complex condition (e.g. preheaders) we want to avoid here.
896 if (UI->getParent() == DestBB) {
897 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
898 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
899 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
900 if (Insn && Insn->getParent() == BB &&
901 Insn->getParent() != UPN->getIncomingBlock(I))
902 return false;
903 }
904 }
905 }
906 }
907
908 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
909 // and DestBB may have conflicting incoming values for the block. If so, we
910 // can't merge the block.
911 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
912 if (!DestBBPN) return true; // no conflict.
913
914 // Collect the preds of BB.
915 SmallPtrSet<const BasicBlock*, 16> BBPreds;
916 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
917 // It is faster to get preds from a PHI than with pred_iterator.
918 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
919 BBPreds.insert(BBPN->getIncomingBlock(i));
920 } else {
921 BBPreds.insert(pred_begin(BB), pred_end(BB));
922 }
923
924 // Walk the preds of DestBB.
925 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
926 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
927 if (BBPreds.count(Pred)) { // Common predecessor?
928 for (const PHINode &PN : DestBB->phis()) {
929 const Value *V1 = PN.getIncomingValueForBlock(Pred);
930 const Value *V2 = PN.getIncomingValueForBlock(BB);
931
932 // If V2 is a phi node in BB, look up what the mapped value will be.
933 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
934 if (V2PN->getParent() == BB)
935 V2 = V2PN->getIncomingValueForBlock(Pred);
936
937 // If there is a conflict, bail out.
938 if (V1 != V2) return false;
939 }
940 }
941 }
942
943 return true;
944}
945
946/// Eliminate a basic block that has only phi's and an unconditional branch in
947/// it.
948void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
949 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
950 BasicBlock *DestBB = BI->getSuccessor(0);
951
952 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)
953 << *BB << *DestBB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
<< *BB << *DestBB; } } while (false)
;
954
955 // If the destination block has a single pred, then this is a trivial edge,
956 // just collapse it.
957 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
958 if (SinglePred != DestBB) {
959 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 960, __extension__ __PRETTY_FUNCTION__))
960 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 960, __extension__ __PRETTY_FUNCTION__))
;
961 // Merge DestBB into SinglePred/BB and delete it.
962 MergeBlockIntoPredecessor(DestBB);
963 // Note: BB(=SinglePred) will not be deleted on this path.
964 // DestBB(=its single successor) is the one that was deleted.
965 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)
;
966 return;
967 }
968 }
969
970 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
971 // to handle the new incoming edges it is about to have.
972 for (PHINode &PN : DestBB->phis()) {
973 // Remove the incoming value for BB, and remember it.
974 Value *InVal = PN.removeIncomingValue(BB, false);
975
976 // Two options: either the InVal is a phi node defined in BB or it is some
977 // value that dominates BB.
978 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
979 if (InValPhi && InValPhi->getParent() == BB) {
980 // Add all of the input values of the input PHI as inputs of this phi.
981 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
982 PN.addIncoming(InValPhi->getIncomingValue(i),
983 InValPhi->getIncomingBlock(i));
984 } else {
985 // Otherwise, add one instance of the dominating value for each edge that
986 // we will be adding.
987 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
988 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
989 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
990 } else {
991 for (BasicBlock *Pred : predecessors(BB))
992 PN.addIncoming(InVal, Pred);
993 }
994 }
995 }
996
997 // The PHIs are now updated, change everything that refers to BB to use
998 // DestBB and remove BB.
999 BB->replaceAllUsesWith(DestBB);
1000 BB->eraseFromParent();
1001 ++NumBlocksElim;
1002
1003 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)
;
1004}
1005
1006// Computes a map of base pointer relocation instructions to corresponding
1007// derived pointer relocation instructions given a vector of all relocate calls
1008static void computeBaseDerivedRelocateMap(
1009 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1010 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
1011 &RelocateInstMap) {
1012 // Collect information in two maps: one primarily for locating the base object
1013 // while filling the second map; the second map is the final structure holding
1014 // a mapping between Base and corresponding Derived relocate calls
1015 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1016 for (auto *ThisRelocate : AllRelocateCalls) {
1017 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
1018 ThisRelocate->getDerivedPtrIndex());
1019 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
1020 }
1021 for (auto &Item : RelocateIdxMap) {
1022 std::pair<unsigned, unsigned> Key = Item.first;
1023 if (Key.first == Key.second)
1024 // Base relocation: nothing to insert
1025 continue;
1026
1027 GCRelocateInst *I = Item.second;
1028 auto BaseKey = std::make_pair(Key.first, Key.first);
1029
1030 // We're iterating over RelocateIdxMap so we cannot modify it.
1031 auto MaybeBase = RelocateIdxMap.find(BaseKey);
1032 if (MaybeBase == RelocateIdxMap.end())
1033 // TODO: We might want to insert a new base object relocate and gep off
1034 // that, if there are enough derived object relocates.
1035 continue;
1036
1037 RelocateInstMap[MaybeBase->second].push_back(I);
1038 }
1039}
1040
1041// Accepts a GEP and extracts the operands into a vector provided they're all
1042// small integer constants
1043static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1044 SmallVectorImpl<Value *> &OffsetV) {
1045 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1046 // Only accept small constant integer operands
1047 auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1048 if (!Op || Op->getZExtValue() > 20)
1049 return false;
1050 }
1051
1052 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1053 OffsetV.push_back(GEP->getOperand(i));
1054 return true;
1055}
1056
1057// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1058// replace, computes a replacement, and affects it.
1059static bool
1060simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1061 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1062 bool MadeChange = false;
1063 // We must ensure the relocation of derived pointer is defined after
1064 // relocation of base pointer. If we find a relocation corresponding to base
1065 // defined earlier than relocation of base then we move relocation of base
1066 // right before found relocation. We consider only relocation in the same
1067 // basic block as relocation of base. Relocations from other basic block will
1068 // be skipped by optimization and we do not care about them.
1069 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1070 &*R != RelocatedBase; ++R)
1071 if (auto *RI = dyn_cast<GCRelocateInst>(R))
1072 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1073 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1074 RelocatedBase->moveBefore(RI);
1075 break;
1076 }
1077
1078 for (GCRelocateInst *ToReplace : Targets) {
1079 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1080, __extension__ __PRETTY_FUNCTION__))
1080 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1080, __extension__ __PRETTY_FUNCTION__))
;
1081 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1082 // A duplicate relocate call. TODO: coalesce duplicates.
1083 continue;
1084 }
1085
1086 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1087 // Base and derived relocates are in different basic blocks.
1088 // In this case transform is only valid when base dominates derived
1089 // relocate. However it would be too expensive to check dominance
1090 // for each such relocate, so we skip the whole transformation.
1091 continue;
1092 }
1093
1094 Value *Base = ToReplace->getBasePtr();
1095 auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
1096 if (!Derived || Derived->getPointerOperand() != Base)
1097 continue;
1098
1099 SmallVector<Value *, 2> OffsetV;
1100 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1101 continue;
1102
1103 // Create a Builder and replace the target callsite with a gep
1104 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1105, __extension__ __PRETTY_FUNCTION__))
1105 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1105, __extension__ __PRETTY_FUNCTION__))
;
1106
1107 // Insert after RelocatedBase
1108 IRBuilder<> Builder(RelocatedBase->getNextNode());
1109 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1110
1111 // If gc_relocate does not match the actual type, cast it to the right type.
1112 // In theory, there must be a bitcast after gc_relocate if the type does not
1113 // match, and we should reuse it to get the derived pointer. But it could be
1114 // cases like this:
1115 // bb1:
1116 // ...
1117 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1118 // br label %merge
1119 //
1120 // bb2:
1121 // ...
1122 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1123 // br label %merge
1124 //
1125 // merge:
1126 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1127 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1128 //
1129 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1130 // no matter there is already one or not. In this way, we can handle all cases, and
1131 // the extra bitcast should be optimized away in later passes.
1132 Value *ActualRelocatedBase = RelocatedBase;
1133 if (RelocatedBase->getType() != Base->getType()) {
1134 ActualRelocatedBase =
1135 Builder.CreateBitCast(RelocatedBase, Base->getType());
1136 }
1137 Value *Replacement = Builder.CreateGEP(
1138 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
1139 Replacement->takeName(ToReplace);
1140 // If the newly generated derived pointer's type does not match the original derived
1141 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
1142 Value *ActualReplacement = Replacement;
1143 if (Replacement->getType() != ToReplace->getType()) {
1144 ActualReplacement =
1145 Builder.CreateBitCast(Replacement, ToReplace->getType());
1146 }
1147 ToReplace->replaceAllUsesWith(ActualReplacement);
1148 ToReplace->eraseFromParent();
1149
1150 MadeChange = true;
1151 }
1152 return MadeChange;
1153}
1154
1155// Turns this:
1156//
1157// %base = ...
1158// %ptr = gep %base + 15
1159// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1160// %base' = relocate(%tok, i32 4, i32 4)
1161// %ptr' = relocate(%tok, i32 4, i32 5)
1162// %val = load %ptr'
1163//
1164// into this:
1165//
1166// %base = ...
1167// %ptr = gep %base + 15
1168// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1169// %base' = gc.relocate(%tok, i32 4, i32 4)
1170// %ptr' = gep %base' + 15
1171// %val = load %ptr'
1172bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1173 bool MadeChange = false;
1174 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1175 for (auto *U : I.users())
1176 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
1177 // Collect all the relocate calls associated with a statepoint
1178 AllRelocateCalls.push_back(Relocate);
1179
1180 // We need at least one base pointer relocation + one derived pointer
1181 // relocation to mangle
1182 if (AllRelocateCalls.size() < 2)
1183 return false;
1184
1185 // RelocateInstMap is a mapping from the base relocate instruction to the
1186 // corresponding derived relocate instructions
1187 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
1188 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1189 if (RelocateInstMap.empty())
1190 return false;
1191
1192 for (auto &Item : RelocateInstMap)
1193 // Item.first is the RelocatedBase to offset against
1194 // Item.second is the vector of Targets to replace
1195 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1196 return MadeChange;
1197}
1198
1199/// Sink the specified cast instruction into its user blocks.
1200static bool SinkCast(CastInst *CI) {
1201 BasicBlock *DefBB = CI->getParent();
1202
1203 /// InsertedCasts - Only insert a cast in each block once.
1204 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
1205
1206 bool MadeChange = false;
1207 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1208 UI != E; ) {
1209 Use &TheUse = UI.getUse();
1210 Instruction *User = cast<Instruction>(*UI);
1211
1212 // Figure out which BB this cast is used in. For PHI's this is the
1213 // appropriate predecessor block.
1214 BasicBlock *UserBB = User->getParent();
1215 if (PHINode *PN = dyn_cast<PHINode>(User)) {
1216 UserBB = PN->getIncomingBlock(TheUse);
1217 }
1218
1219 // Preincrement use iterator so we don't invalidate it.
1220 ++UI;
1221
1222 // The first insertion point of a block containing an EH pad is after the
1223 // pad. If the pad is the user, we cannot sink the cast past the pad.
1224 if (User->isEHPad())
1225 continue;
1226
1227 // If the block selected to receive the cast is an EH pad that does not
1228 // allow non-PHI instructions before the terminator, we can't sink the
1229 // cast.
1230 if (UserBB->getTerminator()->isEHPad())
1231 continue;
1232
1233 // If this user is in the same block as the cast, don't change the cast.
1234 if (UserBB == DefBB) continue;
1235
1236 // If we have already inserted a cast into this block, use it.
1237 CastInst *&InsertedCast = InsertedCasts[UserBB];
1238
1239 if (!InsertedCast) {
1240 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1241 assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void
(0) : __assert_fail ("InsertPt != UserBB->end()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1241, __extension__ __PRETTY_FUNCTION__))
;
1242 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1243 CI->getType(), "", &*InsertPt);
1244 InsertedCast->setDebugLoc(CI->getDebugLoc());
1245 }
1246
1247 // Replace a use of the cast with a use of the new cast.
1248 TheUse = InsertedCast;
1249 MadeChange = true;
1250 ++NumCastUses;
1251 }
1252
1253 // If we removed all uses, nuke the cast.
1254 if (CI->use_empty()) {
1255 salvageDebugInfo(*CI);
1256 CI->eraseFromParent();
1257 MadeChange = true;
1258 }
1259
1260 return MadeChange;
1261}
1262
1263/// If the specified cast instruction is a noop copy (e.g. it's casting from
1264/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1265/// reduce the number of virtual registers that must be created and coalesced.
1266///
1267/// Return true if any changes are made.
1268static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1269 const DataLayout &DL) {
1270 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1271 // than sinking only nop casts, but is helpful on some platforms.
1272 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1273 if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
1274 ASC->getDestAddressSpace()))
1275 return false;
1276 }
1277
1278 // If this is a noop copy,
1279 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1280 EVT DstVT = TLI.getValueType(DL, CI->getType());
1281
1282 // This is an fp<->int conversion?
1283 if (SrcVT.isInteger() != DstVT.isInteger())
1284 return false;
1285
1286 // If this is an extension, it will be a zero or sign extension, which
1287 // isn't a noop.
1288 if (SrcVT.bitsLT(DstVT)) return false;
1289
1290 // If these values will be promoted, find out what they will be promoted
1291 // to. This helps us consider truncates on PPC as noop copies when they
1292 // are.
1293 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1294 TargetLowering::TypePromoteInteger)
1295 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1296 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1297 TargetLowering::TypePromoteInteger)
1298 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1299
1300 // If, after promotion, these are the same types, this is a noop copy.
1301 if (SrcVT != DstVT)
1302 return false;
1303
1304 return SinkCast(CI);
1305}
1306
1307// Match a simple increment by constant operation. Note that if a sub is
1308// matched, the step is negated (as if the step had been canonicalized to
1309// an add, even though we leave the instruction alone.)
1310bool matchIncrement(const Instruction* IVInc, Instruction *&LHS,
1311 Constant *&Step) {
1312 if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
1313 match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::uadd_with_overflow>(
1314 m_Instruction(LHS), m_Constant(Step)))))
1315 return true;
1316 if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
1317 match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
1318 m_Instruction(LHS), m_Constant(Step))))) {
1319 Step = ConstantExpr::getNeg(Step);
1320 return true;
1321 }
1322 return false;
1323}
1324
1325/// If given \p PN is an inductive variable with value IVInc coming from the
1326/// backedge, and on each iteration it gets increased by Step, return pair
1327/// <IVInc, Step>. Otherwise, return None.
1328static Optional<std::pair<Instruction *, Constant *> >
1329getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1330 const Loop *L = LI->getLoopFor(PN->getParent());
1331 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1332 return None;
1333 auto *IVInc =
1334 dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
1335 if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
1336 return None;
1337 Instruction *LHS = nullptr;
1338 Constant *Step = nullptr;
1339 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1340 return std::make_pair(IVInc, Step);
1341 return None;
1342}
1343
1344static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1345 auto *I = dyn_cast<Instruction>(V);
1346 if (!I)
1347 return false;
1348 Instruction *LHS = nullptr;
1349 Constant *Step = nullptr;
1350 if (!matchIncrement(I, LHS, Step))
1351 return false;
1352 if (auto *PN = dyn_cast<PHINode>(LHS))
1353 if (auto IVInc = getIVIncrement(PN, LI))
1354 return IVInc->first == I;
1355 return false;
1356}
1357
1358bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1359 Value *Arg0, Value *Arg1,
1360 CmpInst *Cmp,
1361 Intrinsic::ID IID) {
1362 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1363 if (!isIVIncrement(BO, LI))
1364 return false;
1365 const Loop *L = LI->getLoopFor(BO->getParent());
1366 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()\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1366, __extension__ __PRETTY_FUNCTION__))
;
1367 // Do not risk on moving increment into a child loop.
1368 if (LI->getLoopFor(Cmp->getParent()) != L)
1369 return false;
1370
1371 // Finally, we need to ensure that the insert point will dominate all
1372 // existing uses of the increment.
1373
1374 auto &DT = getDT(*BO->getParent()->getParent());
1375 if (DT.dominates(Cmp->getParent(), BO->getParent()))
1376 // If we're moving up the dom tree, all uses are trivially dominated.
1377 // (This is the common case for code produced by LSR.)
1378 return true;
1379
1380 // Otherwise, special case the single use in the phi recurrence.
1381 return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
1382 };
1383 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1384 // We used to use a dominator tree here to allow multi-block optimization.
1385 // But that was problematic because:
1386 // 1. It could cause a perf regression by hoisting the math op into the
1387 // critical path.
1388 // 2. It could cause a perf regression by creating a value that was live
1389 // across multiple blocks and increasing register pressure.
1390 // 3. Use of a dominator tree could cause large compile-time regression.
1391 // This is because we recompute the DT on every change in the main CGP
1392 // run-loop. The recomputing is probably unnecessary in many cases, so if
1393 // that was fixed, using a DT here would be ok.
1394 //
1395 // There is one important particular case we still want to handle: if BO is
1396 // the IV increment. Important properties that make it profitable:
1397 // - We can speculate IV increment anywhere in the loop (as long as the
1398 // indvar Phi is its only user);
1399 // - Upon computing Cmp, we effectively compute something equivalent to the
1400 // IV increment (despite it loops differently in the IR). So moving it up
1401 // to the cmp point does not really increase register pressure.
1402 return false;
1403 }
1404
1405 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1406 if (BO->getOpcode() == Instruction::Add &&
1407 IID == Intrinsic::usub_with_overflow) {
1408 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1408, __extension__ __PRETTY_FUNCTION__))
;
1409 Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1));
1410 }
1411
1412 // Insert at the first instruction of the pair.
1413 Instruction *InsertPt = nullptr;
1414 for (Instruction &Iter : *Cmp->getParent()) {
1415 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1416 // the overflow intrinsic are defined.
1417 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1418 InsertPt = &Iter;
1419 break;
1420 }
1421 }
1422 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1422, __extension__ __PRETTY_FUNCTION__))
;
1423
1424 IRBuilder<> Builder(InsertPt);
1425 Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
1426 if (BO->getOpcode() != Instruction::Xor) {
1427 Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
1428 BO->replaceAllUsesWith(Math);
1429 } else
1430 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1431, __extension__ __PRETTY_FUNCTION__))
1431 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1431, __extension__ __PRETTY_FUNCTION__))
;
1432 Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
1433 Cmp->replaceAllUsesWith(OV);
1434 Cmp->eraseFromParent();
1435 BO->eraseFromParent();
1436 return true;
1437}
1438
1439/// Match special-case patterns that check for unsigned add overflow.
1440static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
1441 BinaryOperator *&Add) {
1442 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1443 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1444 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1445
1446 // We are not expecting non-canonical/degenerate code. Just bail out.
1447 if (isa<Constant>(A))
1448 return false;
1449
1450 ICmpInst::Predicate Pred = Cmp->getPredicate();
1451 if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
1452 B = ConstantInt::get(B->getType(), 1);
1453 else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1454 B = ConstantInt::get(B->getType(), -1);
1455 else
1456 return false;
1457
1458 // Check the users of the variable operand of the compare looking for an add
1459 // with the adjusted constant.
1460 for (User *U : A->users()) {
1461 if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
1462 Add = cast<BinaryOperator>(U);
1463 return true;
1464 }
1465 }
1466 return false;
1467}
1468
1469/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1470/// intrinsic. Return true if any changes were made.
1471bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1472 bool &ModifiedDT) {
1473 Value *A, *B;
1474 BinaryOperator *Add;
1475 if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
1476 if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add))
1477 return false;
1478 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1479 A = Add->getOperand(0);
1480 B = Add->getOperand(1);
1481 }
1482
1483 if (!TLI->shouldFormOverflowOp(ISD::UADDO,
1484 TLI->getValueType(*DL, Add->getType()),
1485 Add->hasNUsesOrMore(2)))
1486 return false;
1487
1488 // We don't want to move around uses of condition values this late, so we
1489 // check if it is legal to create the call to the intrinsic in the basic
1490 // block containing the icmp.
1491 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1492 return false;
1493
1494 if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
1495 Intrinsic::uadd_with_overflow))
1496 return false;
1497
1498 // Reset callers - do not crash by iterating over a dead instruction.
1499 ModifiedDT = true;
1500 return true;
1501}
1502
1503bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1504 bool &ModifiedDT) {
1505 // We are not expecting non-canonical/degenerate code. Just bail out.
1506 Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
1507 if (isa<Constant>(A) && isa<Constant>(B))
1508 return false;
1509
1510 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1511 ICmpInst::Predicate Pred = Cmp->getPredicate();
1512 if (Pred == ICmpInst::ICMP_UGT) {
1513 std::swap(A, B);
1514 Pred = ICmpInst::ICMP_ULT;
1515 }
1516 // Convert special-case: (A == 0) is the same as (A u< 1).
1517 if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
1518 B = ConstantInt::get(B->getType(), 1);
1519 Pred = ICmpInst::ICMP_ULT;
1520 }
1521 // Convert special-case: (A != 0) is the same as (0 u< A).
1522 if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
1523 std::swap(A, B);
1524 Pred = ICmpInst::ICMP_ULT;
1525 }
1526 if (Pred != ICmpInst::ICMP_ULT)
1527 return false;
1528
1529 // Walk the users of a variable operand of a compare looking for a subtract or
1530 // add with that same operand. Also match the 2nd operand of the compare to
1531 // the add/sub, but that may be a negated constant operand of an add.
1532 Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
1533 BinaryOperator *Sub = nullptr;
1534 for (User *U : CmpVariableOperand->users()) {
1535 // A - B, A u< B --> usubo(A, B)
1536 if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
1537 Sub = cast<BinaryOperator>(U);
1538 break;
1539 }
1540
1541 // A + (-C), A u< C (canonicalized form of (sub A, C))
1542 const APInt *CmpC, *AddC;
1543 if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
1544 match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
1545 Sub = cast<BinaryOperator>(U);
1546 break;
1547 }
1548 }
1549 if (!Sub)
1550 return false;
1551
1552 if (!TLI->shouldFormOverflowOp(ISD::USUBO,
1553 TLI->getValueType(*DL, Sub->getType()),
1554 Sub->hasNUsesOrMore(2)))
1555 return false;
1556
1557 if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
1558 Cmp, Intrinsic::usub_with_overflow))
1559 return false;
1560
1561 // Reset callers - do not crash by iterating over a dead instruction.
1562 ModifiedDT = true;
1563 return true;
1564}
1565
1566/// Sink the given CmpInst into user blocks to reduce the number of virtual
1567/// registers that must be created and coalesced. This is a clear win except on
1568/// targets with multiple condition code registers (PowerPC), where it might
1569/// lose; some adjustment may be wanted there.
1570///
1571/// Return true if any changes are made.
1572static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
1573 if (TLI.hasMultipleConditionRegisters())
1574 return false;
1575
1576 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1577 if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
1578 return false;
1579
1580 // Only insert a cmp in each block once.
1581 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
1582
1583 bool MadeChange = false;
1584 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1585 UI != E; ) {
1586 Use &TheUse = UI.getUse();
1587 Instruction *User = cast<Instruction>(*UI);
1588
1589 // Preincrement use iterator so we don't invalidate it.
1590 ++UI;
1591
1592 // Don't bother for PHI nodes.
1593 if (isa<PHINode>(User))
1594 continue;
1595
1596 // Figure out which BB this cmp is used in.
1597 BasicBlock *UserBB = User->getParent();
1598 BasicBlock *DefBB = Cmp->getParent();
1599
1600 // If this user is in the same block as the cmp, don't change the cmp.
1601 if (UserBB == DefBB) continue;
1602
1603 // If we have already inserted a cmp into this block, use it.
1604 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1605
1606 if (!InsertedCmp) {
1607 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1608 assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void
(0) : __assert_fail ("InsertPt != UserBB->end()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1608, __extension__ __PRETTY_FUNCTION__))
;
1609 InsertedCmp =
1610 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
1611 Cmp->getOperand(0), Cmp->getOperand(1), "",
1612 &*InsertPt);
1613 // Propagate the debug info.
1614 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1615 }
1616
1617 // Replace a use of the cmp with a use of the new cmp.
1618 TheUse = InsertedCmp;
1619 MadeChange = true;
1620 ++NumCmpUses;
1621 }
1622
1623 // If we removed all uses, nuke the cmp.
1624 if (Cmp->use_empty()) {
1625 Cmp->eraseFromParent();
1626 MadeChange = true;
1627 }
1628
1629 return MadeChange;
1630}
1631
1632/// For pattern like:
1633///
1634/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1635/// ...
1636/// DomBB:
1637/// ...
1638/// br DomCond, TrueBB, CmpBB
1639/// CmpBB: (with DomBB being the single predecessor)
1640/// ...
1641/// Cmp = icmp eq CmpOp0, CmpOp1
1642/// ...
1643///
1644/// It would use two comparison on targets that lowering of icmp sgt/slt is
1645/// different from lowering of icmp eq (PowerPC). This function try to convert
1646/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
1647/// After that, DomCond and Cmp can use the same comparison so reduce one
1648/// comparison.
1649///
1650/// Return true if any changes are made.
1651static bool foldICmpWithDominatingICmp(CmpInst *Cmp,
1652 const TargetLowering &TLI) {
1653 if (!EnableICMP_EQToICMP_ST && TLI.isEqualityCmpFoldedWithSignedCmp())
1654 return false;
1655
1656 ICmpInst::Predicate Pred = Cmp->getPredicate();
1657 if (Pred != ICmpInst::ICMP_EQ)
1658 return false;
1659
1660 // If icmp eq has users other than BranchInst and SelectInst, converting it to
1661 // icmp slt/sgt would introduce more redundant LLVM IR.
1662 for (User *U : Cmp->users()) {
1663 if (isa<BranchInst>(U))
1664 continue;
1665 if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
1666 continue;
1667 return false;
1668 }
1669
1670 // This is a cheap/incomplete check for dominance - just match a single
1671 // predecessor with a conditional branch.
1672 BasicBlock *CmpBB = Cmp->getParent();
1673 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1674 if (!DomBB)
1675 return false;
1676
1677 // We want to ensure that the only way control gets to the comparison of
1678 // interest is that a less/greater than comparison on the same operands is
1679 // false.
1680 Value *DomCond;
1681 BasicBlock *TrueBB, *FalseBB;
1682 if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
1683 return false;
1684 if (CmpBB != FalseBB)
1685 return false;
1686
1687 Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
1688 ICmpInst::Predicate DomPred;
1689 if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
1690 return false;
1691 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
1692 return false;
1693
1694 // Convert the equality comparison to the opposite of the dominating
1695 // comparison and swap the direction for all branch/select users.
1696 // We have conceptually converted:
1697 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
1698 // to
1699 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
1700 // And similarly for branches.
1701 for (User *U : Cmp->users()) {
1702 if (auto *BI = dyn_cast<BranchInst>(U)) {
1703 assert(BI->isConditional() && "Must be conditional")(static_cast <bool> (BI->isConditional() && "Must be conditional"
) ? void (0) : __assert_fail ("BI->isConditional() && \"Must be conditional\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1703, __extension__ __PRETTY_FUNCTION__))
;
1704 BI->swapSuccessors();
1705 continue;
1706 }
1707 if (auto *SI = dyn_cast<SelectInst>(U)) {
1708 // Swap operands
1709 SI->swapValues();
1710 SI->swapProfMetadata();
1711 continue;
1712 }
1713 llvm_unreachable("Must be a branch or a select")::llvm::llvm_unreachable_internal("Must be a branch or a select"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1713)
;
1714 }
1715 Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
1716 return true;
1717}
1718
1719bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, bool &ModifiedDT) {
1720 if (sinkCmpExpression(Cmp, *TLI))
1721 return true;
1722
1723 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
1724 return true;
1725
1726 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
1727 return true;
1728
1729 if (foldICmpWithDominatingICmp(Cmp, *TLI))
1730 return true;
1731
1732 return false;
1733}
1734
1735/// Duplicate and sink the given 'and' instruction into user blocks where it is
1736/// used in a compare to allow isel to generate better code for targets where
1737/// this operation can be combined.
1738///
1739/// Return true if any changes are made.
1740static bool sinkAndCmp0Expression(Instruction *AndI,
1741 const TargetLowering &TLI,
1742 SetOfInstrs &InsertedInsts) {
1743 // Double-check that we're not trying to optimize an instruction that was
1744 // already optimized by some other part of this pass.
1745 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1746, __extension__ __PRETTY_FUNCTION__))
1746 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1746, __extension__ __PRETTY_FUNCTION__))
;
1747 (void) InsertedInsts;
1748
1749 // Nothing to do for single use in same basic block.
1750 if (AndI->hasOneUse() &&
1751 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1752 return false;
1753
1754 // Try to avoid cases where sinking/duplicating is likely to increase register
1755 // pressure.
1756 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1757 !isa<ConstantInt>(AndI->getOperand(1)) &&
1758 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1759 return false;
1760
1761 for (auto *U : AndI->users()) {
1762 Instruction *User = cast<Instruction>(U);
1763
1764 // Only sink 'and' feeding icmp with 0.
1765 if (!isa<ICmpInst>(User))
1766 return false;
1767
1768 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1769 if (!CmpC || !CmpC->isZero())
1770 return false;
1771 }
1772
1773 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1774 return false;
1775
1776 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)
;
1777 LLVM_DEBUG(AndI->getParent()->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { AndI->getParent()->dump(); } } while
(false)
;
1778
1779 // Push the 'and' into the same block as the icmp 0. There should only be
1780 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1781 // others, so we don't need to keep track of which BBs we insert into.
1782 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1783 UI != E; ) {
1784 Use &TheUse = UI.getUse();
1785 Instruction *User = cast<Instruction>(*UI);
1786
1787 // Preincrement use iterator so we don't invalidate it.
1788 ++UI;
1789
1790 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "sinking 'and' use: " <<
*User << "\n"; } } while (false)
;
1791
1792 // Keep the 'and' in the same place if the use is already in the same block.
1793 Instruction *InsertPt =
1794 User->getParent() == AndI->getParent() ? AndI : User;
1795 Instruction *InsertedAnd =
1796 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1797 AndI->getOperand(1), "", InsertPt);
1798 // Propagate the debug info.
1799 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1800
1801 // Replace a use of the 'and' with a use of the new 'and'.
1802 TheUse = InsertedAnd;
1803 ++NumAndUses;
1804 LLVM_DEBUG(User->getParent()->dump())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { User->getParent()->dump(); } } while
(false)
;
1805 }
1806
1807 // We removed all uses, nuke the and.
1808 AndI->eraseFromParent();
1809 return true;
1810}
1811
1812/// Check if the candidates could be combined with a shift instruction, which
1813/// includes:
1814/// 1. Truncate instruction
1815/// 2. And instruction and the imm is a mask of the low bits:
1816/// imm & (imm+1) == 0
1817static bool isExtractBitsCandidateUse(Instruction *User) {
1818 if (!isa<TruncInst>(User)) {
1819 if (User->getOpcode() != Instruction::And ||
1820 !isa<ConstantInt>(User->getOperand(1)))
1821 return false;
1822
1823 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
1824
1825 if ((Cimm & (Cimm + 1)).getBoolValue())
1826 return false;
1827 }
1828 return true;
1829}
1830
1831/// Sink both shift and truncate instruction to the use of truncate's BB.
1832static bool
1833SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1834 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
1835 const TargetLowering &TLI, const DataLayout &DL) {
1836 BasicBlock *UserBB = User->getParent();
1837 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1838 auto *TruncI = cast<TruncInst>(User);
1839 bool MadeChange = false;
1840
1841 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1842 TruncE = TruncI->user_end();
1843 TruncUI != TruncE;) {
1844
1845 Use &TruncTheUse = TruncUI.getUse();
1846 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1847 // Preincrement use iterator so we don't invalidate it.
1848
1849 ++TruncUI;
1850
1851 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1852 if (!ISDOpcode)
1853 continue;
1854
1855 // If the use is actually a legal node, there will not be an
1856 // implicit truncate.
1857 // FIXME: always querying the result type is just an
1858 // approximation; some nodes' legality is determined by the
1859 // operand or other means. There's no good way to find out though.
1860 if (TLI.isOperationLegalOrCustom(
1861 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
1862 continue;
1863
1864 // Don't bother for PHI nodes.
1865 if (isa<PHINode>(TruncUser))
1866 continue;
1867
1868 BasicBlock *TruncUserBB = TruncUser->getParent();
1869
1870 if (UserBB == TruncUserBB)
1871 continue;
1872
1873 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1874 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1875
1876 if (!InsertedShift && !InsertedTrunc) {
1877 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
1878 assert(InsertPt != TruncUserBB->end())(static_cast <bool> (InsertPt != TruncUserBB->end())
? void (0) : __assert_fail ("InsertPt != TruncUserBB->end()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1878, __extension__ __PRETTY_FUNCTION__))
;
1879 // Sink the shift
1880 if (ShiftI->getOpcode() == Instruction::AShr)
1881 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1882 "", &*InsertPt);
1883 else
1884 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1885 "", &*InsertPt);
1886 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
1887
1888 // Sink the trunc
1889 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1890 TruncInsertPt++;
1891 assert(TruncInsertPt != TruncUserBB->end())(static_cast <bool> (TruncInsertPt != TruncUserBB->end
()) ? void (0) : __assert_fail ("TruncInsertPt != TruncUserBB->end()"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1891, __extension__ __PRETTY_FUNCTION__))
;
1892
1893 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
1894 TruncI->getType(), "", &*TruncInsertPt);
1895 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
1896
1897 MadeChange = true;
1898
1899 TruncTheUse = InsertedTrunc;
1900 }
1901 }
1902 return MadeChange;
1903}
1904
1905/// Sink the shift *right* instruction into user blocks if the uses could
1906/// potentially be combined with this shift instruction and generate BitExtract
1907/// instruction. It will only be applied if the architecture supports BitExtract
1908/// instruction. Here is an example:
1909/// BB1:
1910/// %x.extract.shift = lshr i64 %arg1, 32
1911/// BB2:
1912/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1913/// ==>
1914///
1915/// BB2:
1916/// %x.extract.shift.1 = lshr i64 %arg1, 32
1917/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1918///
1919/// CodeGen will recognize the pattern in BB2 and generate BitExtract
1920/// instruction.
1921/// Return true if any changes are made.
1922static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1923 const TargetLowering &TLI,
1924 const DataLayout &DL) {
1925 BasicBlock *DefBB = ShiftI->getParent();
1926
1927 /// Only insert instructions in each block once.
1928 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1929
1930 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
1931
1932 bool MadeChange = false;
1933 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1934 UI != E;) {
1935 Use &TheUse = UI.getUse();
1936 Instruction *User = cast<Instruction>(*UI);
1937 // Preincrement use iterator so we don't invalidate it.
1938 ++UI;
1939
1940 // Don't bother for PHI nodes.
1941 if (isa<PHINode>(User))
1942 continue;
1943
1944 if (!isExtractBitsCandidateUse(User))
1945 continue;
1946
1947 BasicBlock *UserBB = User->getParent();
1948
1949 if (UserBB == DefBB) {
1950 // If the shift and truncate instruction are in the same BB. The use of
1951 // the truncate(TruncUse) may still introduce another truncate if not
1952 // legal. In this case, we would like to sink both shift and truncate
1953 // instruction to the BB of TruncUse.
1954 // for example:
1955 // BB1:
1956 // i64 shift.result = lshr i64 opnd, imm
1957 // trunc.result = trunc shift.result to i16
1958 //
1959 // BB2:
1960 // ----> We will have an implicit truncate here if the architecture does
1961 // not have i16 compare.
1962 // cmp i16 trunc.result, opnd2
1963 //
1964 if (isa<TruncInst>(User) && shiftIsLegal
1965 // If the type of the truncate is legal, no truncate will be
1966 // introduced in other basic blocks.
1967 &&
1968 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
1969 MadeChange =
1970 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
1971
1972 continue;
1973 }
1974 // If we have already inserted a shift into this block, use it.
1975 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1976
1977 if (!InsertedShift) {
1978 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1979 assert(InsertPt != UserBB->end())(static_cast <bool> (InsertPt != UserBB->end()) ? void
(0) : __assert_fail ("InsertPt != UserBB->end()", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 1979, __extension__ __PRETTY_FUNCTION__))
;
1980
1981 if (ShiftI->getOpcode() == Instruction::AShr)
1982 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1983 "", &*InsertPt);
1984 else
1985 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1986 "", &*InsertPt);
1987 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
1988
1989 MadeChange = true;
1990 }
1991
1992 // Replace a use of the shift with a use of the new shift.
1993 TheUse = InsertedShift;
1994 }
1995
1996 // If we removed all uses, or there are none, nuke the shift.
1997 if (ShiftI->use_empty()) {
1998 salvageDebugInfo(*ShiftI);
1999 ShiftI->eraseFromParent();
2000 MadeChange = true;
2001 }
2002
2003 return MadeChange;
2004}
2005
2006/// If counting leading or trailing zeros is an expensive operation and a zero
2007/// input is defined, add a check for zero to avoid calling the intrinsic.
2008///
2009/// We want to transform:
2010/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2011///
2012/// into:
2013/// entry:
2014/// %cmpz = icmp eq i64 %A, 0
2015/// br i1 %cmpz, label %cond.end, label %cond.false
2016/// cond.false:
2017/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2018/// br label %cond.end
2019/// cond.end:
2020/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2021///
2022/// If the transform is performed, return true and set ModifiedDT to true.
2023static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2024 const TargetLowering *TLI,
2025 const DataLayout *DL,
2026 bool &ModifiedDT) {
2027 // If a zero input is undefined, it doesn't make sense to despeculate that.
2028 if (match(CountZeros->getOperand(1), m_One()))
2029 return false;
2030
2031 // If it's cheap to speculate, there's nothing to do.
2032 auto IntrinsicID = CountZeros->getIntrinsicID();
2033 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2034 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2035 return false;
2036
2037 // Only handle legal scalar cases. Anything else requires too much work.
2038 Type *Ty = CountZeros->getType();
2039 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
2040 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
2041 return false;
2042
2043 // Bail if the value is never zero.
2044 if (llvm::isKnownNonZero(CountZeros->getOperand(0), *DL))
2045 return false;
2046
2047 // The intrinsic will be sunk behind a compare against zero and branch.
2048 BasicBlock *StartBlock = CountZeros->getParent();
2049 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2050
2051 // Create another block after the count zero intrinsic. A PHI will be added
2052 // in this block to select the result of the intrinsic or the bit-width
2053 // constant if the input to the intrinsic is zero.
2054 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2055 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2056
2057 // Set up a builder to create a compare, conditional branch, and PHI.
2058 IRBuilder<> Builder(CountZeros->getContext());
2059 Builder.SetInsertPoint(StartBlock->getTerminator());
2060 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2061
2062 // Replace the unconditional branch that was created by the first split with
2063 // a compare against zero and a conditional branch.
2064 Value *Zero = Constant::getNullValue(Ty);
2065 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2066 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2067 StartBlock->getTerminator()->eraseFromParent();
2068
2069 // Create a PHI in the end block to select either the output of the intrinsic
2070 // or the bit width of the operand.
2071 Builder.SetInsertPoint(&EndBlock->front());
2072 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2073 CountZeros->replaceAllUsesWith(PN);
2074 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2075 PN->addIncoming(BitWidth, StartBlock);
2076 PN->addIncoming(CountZeros, CallBlock);
2077
2078 // We are explicitly handling the zero case, so we can set the intrinsic's
2079 // undefined zero argument to 'true'. This will also prevent reprocessing the
2080 // intrinsic; we only despeculate when a zero input is defined.
2081 CountZeros->setArgOperand(1, Builder.getTrue());
2082 ModifiedDT = true;
2083 return true;
2084}
2085
2086bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
2087 BasicBlock *BB = CI->getParent();
2088
2089 // Lower inline assembly if we can.
2090 // If we found an inline asm expession, and if the target knows how to
2091 // lower it to normal LLVM code, do so now.
2092 if (CI->isInlineAsm()) {
2093 if (TLI->ExpandInlineAsm(CI)) {
2094 // Avoid invalidating the iterator.
2095 CurInstIterator = BB->begin();
2096 // Avoid processing instructions out of order, which could cause
2097 // reuse before a value is defined.
2098 SunkAddrs.clear();
2099 return true;
2100 }
2101 // Sink address computing for memory operands into the block.
2102 if (optimizeInlineAsmInst(CI))
2103 return true;
2104 }
2105
2106 // Align the pointer arguments to this call if the target thinks it's a good
2107 // idea
2108 unsigned MinSize, PrefAlign;
2109 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2110 for (auto &Arg : CI->arg_operands()) {
2111 // We want to align both objects whose address is used directly and
2112 // objects whose address is used in casts and GEPs, though it only makes
2113 // sense for GEPs if the offset is a multiple of the desired alignment and
2114 // if size - offset meets the size threshold.
2115 if (!Arg->getType()->isPointerTy())
2116 continue;
2117 APInt Offset(DL->getIndexSizeInBits(
2118 cast<PointerType>(Arg->getType())->getAddressSpace()),
2119 0);
2120 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
2121 uint64_t Offset2 = Offset.getLimitedValue();
2122 if ((Offset2 & (PrefAlign-1)) != 0)
2123 continue;
2124 AllocaInst *AI;
2125 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2126 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
2127 AI->setAlignment(Align(PrefAlign));
2128 // Global variables can only be aligned if they are defined in this
2129 // object (i.e. they are uniquely initialized in this object), and
2130 // over-aligning global variables that have an explicit section is
2131 // forbidden.
2132 GlobalVariable *GV;
2133 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2134 GV->getPointerAlignment(*DL) < PrefAlign &&
2135 DL->getTypeAllocSize(GV->getValueType()) >=
2136 MinSize + Offset2)
2137 GV->setAlignment(MaybeAlign(PrefAlign));
2138 }
2139 // If this is a memcpy (or similar) then we may be able to improve the
2140 // alignment
2141 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
2142 Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
2143 MaybeAlign MIDestAlign = MI->getDestAlign();
2144 if (!MIDestAlign || DestAlign > *MIDestAlign)
2145 MI->setDestAlignment(DestAlign);
2146 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
2147 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2148 Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
2149 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2150 MTI->setSourceAlignment(SrcAlign);
2151 }
2152 }
2153 }
2154
2155 // If we have a cold call site, try to sink addressing computation into the
2156 // cold block. This interacts with our handling for loads and stores to
2157 // ensure that we can fold all uses of a potential addressing computation
2158 // into their uses. TODO: generalize this to work over profiling data
2159 if (CI->hasFnAttr(Attribute::Cold) &&
2160 !OptSize && !llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
2161 for (auto &Arg : CI->arg_operands()) {
2162 if (!Arg->getType()->isPointerTy())
2163 continue;
2164 unsigned AS = Arg->getType()->getPointerAddressSpace();
2165 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
2166 }
2167
2168 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
2169 if (II) {
2170 switch (II->getIntrinsicID()) {
2171 default: break;
2172 case Intrinsic::assume:
2173 llvm_unreachable("llvm.assume should have been removed already")::llvm::llvm_unreachable_internal("llvm.assume should have been removed already"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2173)
;
2174 case Intrinsic::experimental_widenable_condition: {
2175 // Give up on future widening oppurtunties so that we can fold away dead
2176 // paths and merge blocks before going into block-local instruction
2177 // selection.
2178 if (II->use_empty()) {
2179 II->eraseFromParent();
2180 return true;
2181 }
2182 Constant *RetVal = ConstantInt::getTrue(II->getContext());
2183 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
2184 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
2185 });
2186 return true;
2187 }
2188 case Intrinsic::objectsize:
2189 llvm_unreachable("llvm.objectsize.* should have been lowered already")::llvm::llvm_unreachable_internal("llvm.objectsize.* should have been lowered already"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2189)
;
2190 case Intrinsic::is_constant:
2191 llvm_unreachable("llvm.is.constant.* should have been lowered already")::llvm::llvm_unreachable_internal("llvm.is.constant.* should have been lowered already"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2191)
;
2192 case Intrinsic::aarch64_stlxr:
2193 case Intrinsic::aarch64_stxr: {
2194 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2195 if (!ExtVal || !ExtVal->hasOneUse() ||
2196 ExtVal->getParent() == CI->getParent())
2197 return false;
2198 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2199 ExtVal->moveBefore(CI);
2200 // Mark this instruction as "inserted by CGP", so that other
2201 // optimizations don't touch it.
2202 InsertedInsts.insert(ExtVal);
2203 return true;
2204 }
2205
2206 case Intrinsic::launder_invariant_group:
2207 case Intrinsic::strip_invariant_group: {
2208 Value *ArgVal = II->getArgOperand(0);
2209 auto it = LargeOffsetGEPMap.find(II);
2210 if (it != LargeOffsetGEPMap.end()) {
2211 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2212 // Make sure not to have to deal with iterator invalidation
2213 // after possibly adding ArgVal to LargeOffsetGEPMap.
2214 auto GEPs = std::move(it->second);
2215 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
2216 LargeOffsetGEPMap.erase(II);
2217 }
2218
2219 II->replaceAllUsesWith(ArgVal);
2220 II->eraseFromParent();
2221 return true;
2222 }
2223 case Intrinsic::cttz:
2224 case Intrinsic::ctlz:
2225 // If counting zeros is expensive, try to avoid it.
2226 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
2227 case Intrinsic::fshl:
2228 case Intrinsic::fshr:
2229 return optimizeFunnelShift(II);
2230 case Intrinsic::dbg_value:
2231 return fixupDbgValue(II);
2232 case Intrinsic::vscale: {
2233 // If datalayout has no special restrictions on vector data layout,
2234 // replace `llvm.vscale` by an equivalent constant expression
2235 // to benefit from cheap constant propagation.
2236 Type *ScalableVectorTy =
2237 VectorType::get(Type::getInt8Ty(II->getContext()), 1, true);
2238 if (DL->getTypeAllocSize(ScalableVectorTy).getKnownMinSize() == 8) {
2239 auto *Null = Constant::getNullValue(ScalableVectorTy->getPointerTo());
2240 auto *One = ConstantInt::getSigned(II->getType(), 1);
2241 auto *CGep =
2242 ConstantExpr::getGetElementPtr(ScalableVectorTy, Null, One);
2243 II->replaceAllUsesWith(ConstantExpr::getPtrToInt(CGep, II->getType()));
2244 II->eraseFromParent();
2245 return true;
2246 }
2247 break;
2248 }
2249 case Intrinsic::masked_gather:
2250 return optimizeGatherScatterInst(II, II->getArgOperand(0));
2251 case Intrinsic::masked_scatter:
2252 return optimizeGatherScatterInst(II, II->getArgOperand(1));
2253 }
2254
2255 SmallVector<Value *, 2> PtrOps;
2256 Type *AccessTy;
2257 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2258 while (!PtrOps.empty()) {
2259 Value *PtrVal = PtrOps.pop_back_val();
2260 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2261 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
2262 return true;
2263 }
2264 }
2265
2266 // From here on out we're working with named functions.
2267 if (!CI->getCalledFunction()) return false;
2268
2269 // Lower all default uses of _chk calls. This is very similar
2270 // to what InstCombineCalls does, but here we are only lowering calls
2271 // to fortified library functions (e.g. __memcpy_chk) that have the default
2272 // "don't know" as the objectsize. Anything else should be left alone.
2273 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2274 IRBuilder<> Builder(CI);
2275 if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
2276 CI->replaceAllUsesWith(V);
2277 CI->eraseFromParent();
2278 return true;
2279 }
2280
2281 return false;
2282}
2283
2284/// Look for opportunities to duplicate return instructions to the predecessor
2285/// to enable tail call optimizations. The case it is currently looking for is:
2286/// @code
2287/// bb0:
2288/// %tmp0 = tail call i32 @f0()
2289/// br label %return
2290/// bb1:
2291/// %tmp1 = tail call i32 @f1()
2292/// br label %return
2293/// bb2:
2294/// %tmp2 = tail call i32 @f2()
2295/// br label %return
2296/// return:
2297/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2298/// ret i32 %retval
2299/// @endcode
2300///
2301/// =>
2302///
2303/// @code
2304/// bb0:
2305/// %tmp0 = tail call i32 @f0()
2306/// ret i32 %tmp0
2307/// bb1:
2308/// %tmp1 = tail call i32 @f1()
2309/// ret i32 %tmp1
2310/// bb2:
2311/// %tmp2 = tail call i32 @f2()
2312/// ret i32 %tmp2
2313/// @endcode
2314bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT) {
2315 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1
Assuming the object is a 'ReturnInst'
2316 if (!RetI
1.1
'RetI' is non-null
1.1
'RetI' is non-null
)
2
Taking false branch
2317 return false;
2318
2319 PHINode *PN = nullptr;
2320 ExtractValueInst *EVI = nullptr;
2321 BitCastInst *BCI = nullptr;
2322 Value *V = RetI->getReturnValue();
3
Calling 'ReturnInst::getReturnValue'
7
Returning from 'ReturnInst::getReturnValue'
2323 if (V
7.1
'V' is null
7.1
'V' is null
) {
2324 BCI = dyn_cast<BitCastInst>(V);
2325 if (BCI)
2326 V = BCI->getOperand(0);
2327
2328 EVI = dyn_cast<ExtractValueInst>(V);
2329 if (EVI) {
2330 V = EVI->getOperand(0);
2331 if (!llvm::all_of(EVI->indices(), [](unsigned idx) { return idx == 0; }))
2332 return false;
2333 }
2334
2335 PN = dyn_cast<PHINode>(V);
2336 if (!PN)
2337 return false;
2338 }
2339
2340 if (PN
7.2
'PN' is null
7.2
'PN' is null
&& PN->getParent() != BB)
2341 return false;
2342
2343 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
2344 const BitCastInst *BC = dyn_cast<BitCastInst>(Inst);
2345 if (BC && BC->hasOneUse())
2346 Inst = BC->user_back();
2347
2348 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
2349 return II->getIntrinsicID() == Intrinsic::lifetime_end;
2350 return false;
2351 };
2352
2353 // Make sure there are no instructions between the first instruction
2354 // and return.
2355 const Instruction *BI = BB->getFirstNonPHI();
8
'BI' initialized here
2356 // Skip over debug and the bitcast.
2357 while (isa<DbgInfoIntrinsic>(BI) || BI == BCI || BI == EVI ||
9
Assuming 'BI' is not a 'DbgInfoIntrinsic'
10
Assuming 'BI' is equal to 'BCI'
2358 isa<PseudoProbeInst>(BI) || isLifetimeEndOrBitCastFor(BI))
2359 BI = BI->getNextNode();
11
Called C++ object pointer is null
2360 if (BI != RetI)
2361 return false;
2362
2363 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2364 /// call.
2365 const Function *F = BB->getParent();
2366 SmallVector<BasicBlock*, 4> TailCallBBs;
2367 if (PN) {
2368 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2369 // Look through bitcasts.
2370 Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
2371 CallInst *CI = dyn_cast<CallInst>(IncomingVal);
2372 BasicBlock *PredBB = PN->getIncomingBlock(I);
2373 // Make sure the phi value is indeed produced by the tail call.
2374 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
2375 TLI->mayBeEmittedAsTailCall(CI) &&
2376 attributesPermitTailCall(F, CI, RetI, *TLI))
2377 TailCallBBs.push_back(PredBB);
2378 }
2379 } else {
2380 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
2381 for (BasicBlock *Pred : predecessors(BB)) {
2382 if (!VisitedBBs.insert(Pred).second)
2383 continue;
2384 if (Instruction *I = Pred->rbegin()->getPrevNonDebugInstruction(true)) {
2385 CallInst *CI = dyn_cast<CallInst>(I);
2386 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2387 attributesPermitTailCall(F, CI, RetI, *TLI))
2388 TailCallBBs.push_back(Pred);
2389 }
2390 }
2391 }
2392
2393 bool Changed = false;
2394 for (auto const &TailCallBB : TailCallBBs) {
2395 // Make sure the call instruction is followed by an unconditional branch to
2396 // the return block.
2397 BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator());
2398 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2399 continue;
2400
2401 // Duplicate the return into TailCallBB.
2402 (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
2403 assert(!VerifyBFIUpdates ||(static_cast <bool> (!VerifyBFIUpdates || BFI->getBlockFreq
(BB) >= BFI->getBlockFreq(TailCallBB)) ? void (0) : __assert_fail
("!VerifyBFIUpdates || BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB)"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2404, __extension__ __PRETTY_FUNCTION__))
2404 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)"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2404, __extension__ __PRETTY_FUNCTION__))
;
2405 BFI->setBlockFreq(
2406 BB,
2407 (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)).getFrequency());
2408 ModifiedDT = Changed = true;
2409 ++NumRetsDup;
2410 }
2411
2412 // If we eliminated all predecessors of the block, delete the block now.
2413 if (Changed && !BB->hasAddressTaken() && pred_empty(BB))
2414 BB->eraseFromParent();
2415
2416 return Changed;
2417}
2418
2419//===----------------------------------------------------------------------===//
2420// Memory Optimization
2421//===----------------------------------------------------------------------===//
2422
2423namespace {
2424
2425/// This is an extended version of TargetLowering::AddrMode
2426/// which holds actual Value*'s for register values.
2427struct ExtAddrMode : public TargetLowering::AddrMode {
2428 Value *BaseReg = nullptr;
2429 Value *ScaledReg = nullptr;
2430 Value *OriginalValue = nullptr;
2431 bool InBounds = true;
2432
2433 enum FieldName {
2434 NoField = 0x00,
2435 BaseRegField = 0x01,
2436 BaseGVField = 0x02,
2437 BaseOffsField = 0x04,
2438 ScaledRegField = 0x08,
2439 ScaleField = 0x10,
2440 MultipleFields = 0xff
2441 };
2442
2443
2444 ExtAddrMode() = default;
2445
2446 void print(raw_ostream &OS) const;
2447 void dump() const;
2448
2449 FieldName compare(const ExtAddrMode &other) {
2450 // First check that the types are the same on each field, as differing types
2451 // is something we can't cope with later on.
2452 if (BaseReg && other.BaseReg &&
2453 BaseReg->getType() != other.BaseReg->getType())
2454 return MultipleFields;
2455 if (BaseGV && other.BaseGV &&
2456 BaseGV->getType() != other.BaseGV->getType())
2457 return MultipleFields;
2458 if (ScaledReg && other.ScaledReg &&
2459 ScaledReg->getType() != other.ScaledReg->getType())
2460 return MultipleFields;
2461
2462 // Conservatively reject 'inbounds' mismatches.
2463 if (InBounds != other.InBounds)
2464 return MultipleFields;
2465
2466 // Check each field to see if it differs.
2467 unsigned Result = NoField;
2468 if (BaseReg != other.BaseReg)
2469 Result |= BaseRegField;
2470 if (BaseGV != other.BaseGV)
2471 Result |= BaseGVField;
2472 if (BaseOffs != other.BaseOffs)
2473 Result |= BaseOffsField;
2474 if (ScaledReg != other.ScaledReg)
2475 Result |= ScaledRegField;
2476 // Don't count 0 as being a different scale, because that actually means
2477 // unscaled (which will already be counted by having no ScaledReg).
2478 if (Scale && other.Scale && Scale != other.Scale)
2479 Result |= ScaleField;
2480
2481 if (countPopulation(Result) > 1)
2482 return MultipleFields;
2483 else
2484 return static_cast<FieldName>(Result);
2485 }
2486
2487 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
2488 // with no offset.
2489 bool isTrivial() {
2490 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
2491 // trivial if at most one of these terms is nonzero, except that BaseGV and
2492 // BaseReg both being zero actually means a null pointer value, which we
2493 // consider to be 'non-zero' here.
2494 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
2495 }
2496
2497 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2498 switch (Field) {
2499 default:
2500 return nullptr;
2501 case BaseRegField:
2502 return BaseReg;
2503 case BaseGVField:
2504 return BaseGV;
2505 case ScaledRegField:
2506 return ScaledReg;
2507 case BaseOffsField:
2508 return ConstantInt::get(IntPtrTy, BaseOffs);
2509 }
2510 }
2511
2512 void SetCombinedField(FieldName Field, Value *V,
2513 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2514 switch (Field) {
2515 default:
2516 llvm_unreachable("Unhandled fields are expected to be rejected earlier")::llvm::llvm_unreachable_internal("Unhandled fields are expected to be rejected earlier"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2516)
;
2517 break;
2518 case ExtAddrMode::BaseRegField:
2519 BaseReg = V;
2520 break;
2521 case ExtAddrMode::BaseGVField:
2522 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2523 // in the BaseReg field.
2524 assert(BaseReg == nullptr)(static_cast <bool> (BaseReg == nullptr) ? void (0) : __assert_fail
("BaseReg == nullptr", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2524, __extension__ __PRETTY_FUNCTION__))
;
2525 BaseReg = V;
2526 BaseGV = nullptr;
2527 break;
2528 case ExtAddrMode::ScaledRegField:
2529 ScaledReg = V;
2530 // If we have a mix of scaled and unscaled addrmodes then we want scale
2531 // to be the scale and not zero.
2532 if (!Scale)
2533 for (const ExtAddrMode &AM : AddrModes)
2534 if (AM.Scale) {
2535 Scale = AM.Scale;
2536 break;
2537 }
2538 break;
2539 case ExtAddrMode::BaseOffsField:
2540 // The offset is no longer a constant, so it goes in ScaledReg with a
2541 // scale of 1.
2542 assert(ScaledReg == nullptr)(static_cast <bool> (ScaledReg == nullptr) ? void (0) :
__assert_fail ("ScaledReg == nullptr", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 2542, __extension__ __PRETTY_FUNCTION__))
;
2543 ScaledReg = V;
2544 Scale = 1;
2545 BaseOffs = 0;
2546 break;
2547 }
2548 }
2549};
2550
2551} // end anonymous namespace
2552
2553#ifndef NDEBUG
2554static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2555 AM.print(OS);
2556 return OS;
2557}
2558#endif
2559
2560#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2561void ExtAddrMode::print(raw_ostream &OS) const {
2562 bool NeedPlus = false;
2563 OS << "[";
2564 if (InBounds)
2565 OS << "inbounds ";
2566 if (BaseGV) {
2567 OS << (NeedPlus ? " + " : "")
2568 << "GV:";
2569 BaseGV->printAsOperand(OS, /*PrintType=*/false);
2570 NeedPlus = true;
2571 }
2572
2573 if (BaseOffs) {
2574 OS << (NeedPlus ? " + " : "")
2575 << BaseOffs;
2576 NeedPlus = true;
2577 }
2578
2579 if (BaseReg) {
2580 OS << (NeedPlus ? " + " : "")
2581 << "Base:";
2582 BaseReg->printAsOperand(OS, /*PrintType=*/false);
2583 NeedPlus = true;
2584 }
2585 if (Scale) {
2586 OS << (NeedPlus ? " + " : "")
2587 << Scale << "*";
2588 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
2589 }
2590
2591 OS << ']';
2592}
2593
2594LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void ExtAddrMode::dump() const {
2595 print(dbgs());
2596 dbgs() << '\n';
2597}
2598#endif
2599
2600namespace {
2601
2602/// This class provides transaction based operation on the IR.
2603/// Every change made through this class is recorded in the internal state and
2604/// can be undone (rollback) until commit is called.
2605/// CGP does not check if instructions could be speculatively executed when
2606/// moved. Preserving the original location would pessimize the debugging
2607/// experience, as well as negatively impact the quality of sample PGO.
2608class TypePromotionTransaction {
2609 /// This represents the common interface of the individual transaction.
2610 /// Each class implements the logic for doing one specific modification on
2611 /// the IR via the TypePromotionTransaction.
2612 class TypePromotionAction {
2613 protected:
2614 /// The Instruction modified.
2615 Instruction *Inst;
2616
2617 public:
2618 /// Constructor of the action.
2619 /// The constructor performs the related action on the IR.
2620 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2621
2622 virtual ~TypePromotionAction() = default;
2623
2624 /// Undo the modification done by this action.
2625 /// When this method is called, the IR must be in the same state as it was
2626 /// before this action was applied.
2627 /// \pre Undoing the action works if and only if the IR is in the exact same
2628 /// state as it was directly after this action was applied.
2629 virtual void undo() = 0;
2630
2631 /// Advocate every change made by this action.
2632 /// When the results on the IR of the action are to be kept, it is important
2633 /// to call this function, otherwise hidden information may be kept forever.
2634 virtual void commit() {
2635 // Nothing to be done, this action is not doing anything.
2636 }
2637 };
2638
2639 /// Utility to remember the position of an instruction.
2640 class InsertionHandler {
2641 /// Position of an instruction.
2642 /// Either an instruction:
2643 /// - Is the first in a basic block: BB is used.
2644 /// - Has a previous instruction: PrevInst is used.
2645 union {
2646 Instruction *PrevInst;
2647 BasicBlock *BB;
2648 } Point;
2649
2650 /// Remember whether or not the instruction had a previous instruction.
2651 bool HasPrevInstruction;
2652
2653 public:
2654 /// Record the position of \p Inst.
2655 InsertionHandler(Instruction *Inst) {
2656 BasicBlock::iterator It = Inst->getIterator();
2657 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2658 if (HasPrevInstruction)
2659 Point.PrevInst = &*--It;
2660 else
2661 Point.BB = Inst->getParent();
2662 }
2663
2664 /// Insert \p Inst at the recorded position.
2665 void insert(Instruction *Inst) {
2666 if (HasPrevInstruction) {
2667 if (Inst->getParent())
2668 Inst->removeFromParent();
2669 Inst->insertAfter(Point.PrevInst);
2670 } else {
2671 Instruction *Position = &*Point.BB->getFirstInsertionPt();
2672 if (Inst->getParent())
2673 Inst->moveBefore(Position);
2674 else
2675 Inst->insertBefore(Position);
2676 }
2677 }
2678 };
2679
2680 /// Move an instruction before another.
2681 class InstructionMoveBefore : public TypePromotionAction {
2682 /// Original position of the instruction.
2683 InsertionHandler Position;
2684
2685 public:
2686 /// Move \p Inst before \p Before.
2687 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2688 : TypePromotionAction(Inst), Position(Inst) {
2689 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Beforedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: move: " << *
Inst << "\nbefore: " << *Before << "\n"; } }
while (false)
2690 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: move: " << *
Inst << "\nbefore: " << *Before << "\n"; } }
while (false)
;
2691 Inst->moveBefore(Before);
2692 }
2693
2694 /// Move the instruction back to its original position.
2695 void undo() override {
2696 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: moveBefore: " <<
*Inst << "\n"; } } while (false)
;
2697 Position.insert(Inst);
2698 }
2699 };
2700
2701 /// Set the operand of an instruction with a new value.
2702 class OperandSetter : public TypePromotionAction {
2703 /// Original operand of the instruction.
2704 Value *Origin;
2705
2706 /// Index of the modified instruction.
2707 unsigned Idx;
2708
2709 public:
2710 /// Set \p Idx operand of \p Inst with \p NewVal.
2711 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2712 : TypePromotionAction(Inst), Idx(Idx) {
2713 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)
2714 << "for:" << *Inst << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: setOperand: " <<
Idx << "\n" << "for:" << *Inst << "\n"
<< "with:" << *NewVal << "\n"; } } while (
false)
2715 << "with:" << *NewVal << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: setOperand: " <<
Idx << "\n" << "for:" << *Inst << "\n"
<< "with:" << *NewVal << "\n"; } } while (
false)
;
2716 Origin = Inst->getOperand(Idx);
2717 Inst->setOperand(Idx, NewVal);
2718 }
2719
2720 /// Restore the original value of the instruction.
2721 void undo() override {
2722 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)
2723 << "for: " << *Inst << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: setOperand:" <<
Idx << "\n" << "for: " << *Inst << "\n"
<< "with: " << *Origin << "\n"; } } while (
false)
2724 << "with: " << *Origin << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: setOperand:" <<
Idx << "\n" << "for: " << *Inst << "\n"
<< "with: " << *Origin << "\n"; } } while (
false)
;
2725 Inst->setOperand(Idx, Origin);
2726 }
2727 };
2728
2729 /// Hide the operands of an instruction.
2730 /// Do as if this instruction was not using any of its operands.
2731 class OperandsHider : public TypePromotionAction {
2732 /// The list of original operands.
2733 SmallVector<Value *, 4> OriginalValues;
2734
2735 public:
2736 /// Remove \p Inst from the uses of the operands of \p Inst.
2737 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2738 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: OperandsHider: " <<
*Inst << "\n"; } } while (false)
;
2739 unsigned NumOpnds = Inst->getNumOperands();
2740 OriginalValues.reserve(NumOpnds);
2741 for (unsigned It = 0; It < NumOpnds; ++It) {
2742 // Save the current operand.
2743 Value *Val = Inst->getOperand(It);
2744 OriginalValues.push_back(Val);
2745 // Set a dummy one.
2746 // We could use OperandSetter here, but that would imply an overhead
2747 // that we are not willing to pay.
2748 Inst->setOperand(It, UndefValue::get(Val->getType()));
2749 }
2750 }
2751
2752 /// Restore the original list of uses.
2753 void undo() override {
2754 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: OperandsHider: "
<< *Inst << "\n"; } } while (false)
;
2755 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2756 Inst->setOperand(It, OriginalValues[It]);
2757 }
2758 };
2759
2760 /// Build a truncate instruction.
2761 class TruncBuilder : public TypePromotionAction {
2762 Value *Val;
2763
2764 public:
2765 /// Build a truncate instruction of \p Opnd producing a \p Ty
2766 /// result.
2767 /// trunc Opnd to Ty.
2768 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2769 IRBuilder<> Builder(Opnd);
2770 Builder.SetCurrentDebugLocation(DebugLoc());
2771 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2772 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: TruncBuilder: " <<
*Val << "\n"; } } while (false)
;
2773 }
2774
2775 /// Get the built value.
2776 Value *getBuiltValue() { return Val; }
2777
2778 /// Remove the built instruction.
2779 void undo() override {
2780 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: TruncBuilder: " <<
*Val << "\n"; } } while (false)
;
2781 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2782 IVal->eraseFromParent();
2783 }
2784 };
2785
2786 /// Build a sign extension instruction.
2787 class SExtBuilder : public TypePromotionAction {
2788 Value *Val;
2789
2790 public:
2791 /// Build a sign extension instruction of \p Opnd producing a \p Ty
2792 /// result.
2793 /// sext Opnd to Ty.
2794 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2795 : TypePromotionAction(InsertPt) {
2796 IRBuilder<> Builder(InsertPt);
2797 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2798 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: SExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2799 }
2800
2801 /// Get the built value.
2802 Value *getBuiltValue() { return Val; }
2803
2804 /// Remove the built instruction.
2805 void undo() override {
2806 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: SExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2807 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2808 IVal->eraseFromParent();
2809 }
2810 };
2811
2812 /// Build a zero extension instruction.
2813 class ZExtBuilder : public TypePromotionAction {
2814 Value *Val;
2815
2816 public:
2817 /// Build a zero extension instruction of \p Opnd producing a \p Ty
2818 /// result.
2819 /// zext Opnd to Ty.
2820 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
2821 : TypePromotionAction(InsertPt) {
2822 IRBuilder<> Builder(InsertPt);
2823 Builder.SetCurrentDebugLocation(DebugLoc());
2824 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2825 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: ZExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2826 }
2827
2828 /// Get the built value.
2829 Value *getBuiltValue() { return Val; }
2830
2831 /// Remove the built instruction.
2832 void undo() override {
2833 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: ZExtBuilder: " <<
*Val << "\n"; } } while (false)
;
2834 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2835 IVal->eraseFromParent();
2836 }
2837 };
2838
2839 /// Mutate an instruction to another type.
2840 class TypeMutator : public TypePromotionAction {
2841 /// Record the original type.
2842 Type *OrigTy;
2843
2844 public:
2845 /// Mutate the type of \p Inst into \p NewTy.
2846 TypeMutator(Instruction *Inst, Type *NewTy)
2847 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2848 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: MutateType: " <<
*Inst << " with " << *NewTy << "\n"; } } while
(false)
2849 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: MutateType: " <<
*Inst << " with " << *NewTy << "\n"; } } while
(false)
;
2850 Inst->mutateType(NewTy);
2851 }
2852
2853 /// Mutate the instruction back to its original type.
2854 void undo() override {
2855 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTydo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: MutateType: " <<
*Inst << " with " << *OrigTy << "\n"; } } while
(false)
2856 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: MutateType: " <<
*Inst << " with " << *OrigTy << "\n"; } } while
(false)
;
2857 Inst->mutateType(OrigTy);
2858 }
2859 };
2860
2861 /// Replace the uses of an instruction by another instruction.
2862 class UsesReplacer : public TypePromotionAction {
2863 /// Helper structure to keep track of the replaced uses.
2864 struct InstructionAndIdx {
2865 /// The instruction using the instruction.
2866 Instruction *Inst;
2867
2868 /// The index where this instruction is used for Inst.
2869 unsigned Idx;
2870
2871 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2872 : Inst(Inst), Idx(Idx) {}
2873 };
2874
2875 /// Keep track of the original uses (pair Instruction, Index).
2876 SmallVector<InstructionAndIdx, 4> OriginalUses;
2877 /// Keep track of the debug users.
2878 SmallVector<DbgValueInst *, 1> DbgValues;
2879
2880 /// Keep track of the new value so that we can undo it by replacing
2881 /// instances of the new value with the original value.
2882 Value *New;
2883
2884 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
2885
2886 public:
2887 /// Replace all the use of \p Inst by \p New.
2888 UsesReplacer(Instruction *Inst, Value *New)
2889 : TypePromotionAction(Inst), New(New) {
2890 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *Newdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: UsersReplacer: " <<
*Inst << " with " << *New << "\n"; } } while
(false)
2891 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: UsersReplacer: " <<
*Inst << " with " << *New << "\n"; } } while
(false)
;
2892 // Record the original uses.
2893 for (Use &U : Inst->uses()) {
2894 Instruction *UserI = cast<Instruction>(U.getUser());
2895 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
2896 }
2897 // Record the debug uses separately. They are not in the instruction's
2898 // use list, but they are replaced by RAUW.
2899 findDbgValues(DbgValues, Inst);
2900
2901 // Now, we can replace the uses.
2902 Inst->replaceAllUsesWith(New);
2903 }
2904
2905 /// Reassign the original uses of Inst to Inst.
2906 void undo() override {
2907 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: UsersReplacer: "
<< *Inst << "\n"; } } while (false)
;
2908 for (InstructionAndIdx &Use : OriginalUses)
2909 Use.Inst->setOperand(Use.Idx, Inst);
2910 // RAUW has replaced all original uses with references to the new value,
2911 // including the debug uses. Since we are undoing the replacements,
2912 // the original debug uses must also be reinstated to maintain the
2913 // correctness and utility of debug value instructions.
2914 for (auto *DVI : DbgValues)
2915 DVI->replaceVariableLocationOp(New, Inst);
2916 }
2917 };
2918
2919 /// Remove an instruction from the IR.
2920 class InstructionRemover : public TypePromotionAction {
2921 /// Original position of the instruction.
2922 InsertionHandler Inserter;
2923
2924 /// Helper structure to hide all the link to the instruction. In other
2925 /// words, this helps to do as if the instruction was removed.
2926 OperandsHider Hider;
2927
2928 /// Keep track of the uses replaced, if any.
2929 UsesReplacer *Replacer = nullptr;
2930
2931 /// Keep track of instructions removed.
2932 SetOfInstrs &RemovedInsts;
2933
2934 public:
2935 /// Remove all reference of \p Inst and optionally replace all its
2936 /// uses with New.
2937 /// \p RemovedInsts Keep track of the instructions removed by this Action.
2938 /// \pre If !Inst->use_empty(), then New != nullptr
2939 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2940 Value *New = nullptr)
2941 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
2942 RemovedInsts(RemovedInsts) {
2943 if (New)
2944 Replacer = new UsesReplacer(Inst, New);
2945 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Do: InstructionRemover: "
<< *Inst << "\n"; } } while (false)
;
2946 RemovedInsts.insert(Inst);
2947 /// The instructions removed here will be freed after completing
2948 /// optimizeBlock() for all blocks as we need to keep track of the
2949 /// removed instructions during promotion.
2950 Inst->removeFromParent();
2951 }
2952
2953 ~InstructionRemover() override { delete Replacer; }
2954
2955 /// Resurrect the instruction and reassign it to the proper uses if
2956 /// new value was provided when build this action.
2957 void undo() override {
2958 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Undo: InstructionRemover: "
<< *Inst << "\n"; } } while (false)
;
2959 Inserter.insert(Inst);
2960 if (Replacer)
2961 Replacer->undo();
2962 Hider.undo();
2963 RemovedInsts.erase(Inst);
2964 }
2965 };
2966
2967public:
2968 /// Restoration point.
2969 /// The restoration point is a pointer to an action instead of an iterator
2970 /// because the iterator may be invalidated but not the pointer.
2971 using ConstRestorationPt = const TypePromotionAction *;
2972
2973 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2974 : RemovedInsts(RemovedInsts) {}
2975
2976 /// Advocate every changes made in that transaction. Return true if any change
2977 /// happen.
2978 bool commit();
2979
2980 /// Undo all the changes made after the given point.
2981 void rollback(ConstRestorationPt Point);
2982
2983 /// Get the current restoration point.
2984 ConstRestorationPt getRestorationPoint() const;
2985
2986 /// \name API for IR modification with state keeping to support rollback.
2987 /// @{
2988 /// Same as Instruction::setOperand.
2989 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2990
2991 /// Same as Instruction::eraseFromParent.
2992 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
2993
2994 /// Same as Value::replaceAllUsesWith.
2995 void replaceAllUsesWith(Instruction *Inst, Value *New);
2996
2997 /// Same as Value::mutateType.
2998 void mutateType(Instruction *Inst, Type *NewTy);
2999
3000 /// Same as IRBuilder::createTrunc.
3001 Value *createTrunc(Instruction *Opnd, Type *Ty);
3002
3003 /// Same as IRBuilder::createSExt.
3004 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3005
3006 /// Same as IRBuilder::createZExt.
3007 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3008
3009 /// Same as Instruction::moveBefore.
3010 void moveBefore(Instruction *Inst, Instruction *Before);
3011 /// @}
3012
3013private:
3014 /// The ordered list of actions made so far.
3015 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3016
3017 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
3018
3019 SetOfInstrs &RemovedInsts;
3020};
3021
3022} // end anonymous namespace
3023
3024void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3025 Value *NewVal) {
3026 Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
3027 Inst, Idx, NewVal));
3028}
3029
3030void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3031 Value *NewVal) {
3032 Actions.push_back(
3033 std::make_unique<TypePromotionTransaction::InstructionRemover>(
3034 Inst, RemovedInsts, NewVal));
3035}
3036
3037void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3038 Value *New) {
3039 Actions.push_back(
3040 std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
3041}
3042
3043void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3044 Actions.push_back(
3045 std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
3046}
3047
3048Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
3049 Type *Ty) {
3050 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3051 Value *Val = Ptr->getBuiltValue();
3052 Actions.push_back(std::move(Ptr));
3053 return Val;
3054}
3055
3056Value *TypePromotionTransaction::createSExt(Instruction *Inst,
3057 Value *Opnd, Type *Ty) {
3058 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3059 Value *Val = Ptr->getBuiltValue();
3060 Actions.push_back(std::move(Ptr));
3061 return Val;
3062}
3063
3064Value *TypePromotionTransaction::createZExt(Instruction *Inst,
3065 Value *Opnd, Type *Ty) {
3066 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3067 Value *Val = Ptr->getBuiltValue();
3068 Actions.push_back(std::move(Ptr));
3069 return Val;
3070}
3071
3072void TypePromotionTransaction::moveBefore(Instruction *Inst,
3073 Instruction *Before) {
3074 Actions.push_back(
3075 std::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
3076 Inst, Before));
3077}
3078
3079TypePromotionTransaction::ConstRestorationPt
3080TypePromotionTransaction::getRestorationPoint() const {
3081 return !Actions.empty() ? Actions.back().get() : nullptr;
3082}
3083
3084bool TypePromotionTransaction::commit() {
3085 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3086 Action->commit();
3087 bool Modified = !Actions.empty();
3088 Actions.clear();
3089 return Modified;
3090}
3091
3092void TypePromotionTransaction::rollback(
3093 TypePromotionTransaction::ConstRestorationPt Point) {
3094 while (!Actions.empty() && Point != Actions.back().get()) {
3095 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3096 Curr->undo();
3097 }
3098}
3099
3100namespace {
3101
3102/// A helper class for matching addressing modes.
3103///
3104/// This encapsulates the logic for matching the target-legal addressing modes.
3105class AddressingModeMatcher {
3106 SmallVectorImpl<Instruction*> &AddrModeInsts;
3107 const TargetLowering &TLI;
3108 const TargetRegisterInfo &TRI;
3109 const DataLayout &DL;
3110 const LoopInfo &LI;
3111 const std::function<const DominatorTree &()> getDTFn;
3112
3113 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3114 /// the memory instruction that we're computing this address for.
3115 Type *AccessTy;
3116 unsigned AddrSpace;
3117 Instruction *MemoryInst;
3118
3119 /// This is the addressing mode that we're building up. This is
3120 /// part of the return value of this addressing mode matching stuff.
3121 ExtAddrMode &AddrMode;
3122
3123 /// The instructions inserted by other CodeGenPrepare optimizations.
3124 const SetOfInstrs &InsertedInsts;
3125
3126 /// A map from the instructions to their type before promotion.
3127 InstrToOrigTy &PromotedInsts;
3128
3129 /// The ongoing transaction where every action should be registered.
3130 TypePromotionTransaction &TPT;
3131
3132 // A GEP which has too large offset to be folded into the addressing mode.
3133 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3134
3135 /// This is set to true when we should not do profitability checks.
3136 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3137 bool IgnoreProfitability;
3138
3139 /// True if we are optimizing for size.
3140 bool OptSize;
3141
3142 ProfileSummaryInfo *PSI;
3143 BlockFrequencyInfo *BFI;
3144
3145 AddressingModeMatcher(
3146 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
3147 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3148 const std::function<const DominatorTree &()> getDTFn,
3149 Type *AT, unsigned AS, Instruction *MI, ExtAddrMode &AM,
3150 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3151 TypePromotionTransaction &TPT,
3152 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3153 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
3154 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3155 DL(MI->getModule()->getDataLayout()), LI(LI), getDTFn(getDTFn),
3156 AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
3157 InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
3158 LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
3159 IgnoreProfitability = false;
3160 }
3161
3162public:
3163 /// Find the maximal addressing mode that a load/store of V can fold,
3164 /// give an access type of AccessTy. This returns a list of involved
3165 /// instructions in AddrModeInsts.
3166 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3167 /// optimizations.
3168 /// \p PromotedInsts maps the instructions to their type before promotion.
3169 /// \p The ongoing transaction where every action should be registered.
3170 static ExtAddrMode
3171 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3172 SmallVectorImpl<Instruction *> &AddrModeInsts,
3173 const TargetLowering &TLI, const LoopInfo &LI,
3174 const std::function<const DominatorTree &()> getDTFn,
3175 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3176 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3177 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3178 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
3179 ExtAddrMode Result;
3180
3181 bool Success = AddressingModeMatcher(
3182 AddrModeInsts, TLI, TRI, LI, getDTFn, AccessTy, AS, MemoryInst, Result,
3183 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
3184 BFI).matchAddr(V, 0);
3185 (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*?\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3185, __extension__ __PRETTY_FUNCTION__))
;
3186 return Result;
3187 }
3188
3189private:
3190 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3191 bool matchAddr(Value *Addr, unsigned Depth);
3192 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3193 bool *MovedAway = nullptr);
3194 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3195 ExtAddrMode &AMBefore,
3196 ExtAddrMode &AMAfter);
3197 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3198 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3199 Value *PromotedOperand) const;
3200};
3201
3202class PhiNodeSet;
3203
3204/// An iterator for PhiNodeSet.
3205class PhiNodeSetIterator {
3206 PhiNodeSet * const Set;
3207 size_t CurrentIndex = 0;
3208
3209public:
3210 /// The constructor. Start should point to either a valid element, or be equal
3211 /// to the size of the underlying SmallVector of the PhiNodeSet.
3212 PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
3213 PHINode * operator*() const;
3214 PhiNodeSetIterator& operator++();
3215 bool operator==(const PhiNodeSetIterator &RHS) const;
3216 bool operator!=(const PhiNodeSetIterator &RHS) const;
3217};
3218
3219/// Keeps a set of PHINodes.
3220///
3221/// This is a minimal set implementation for a specific use case:
3222/// It is very fast when there are very few elements, but also provides good
3223/// performance when there are many. It is similar to SmallPtrSet, but also
3224/// provides iteration by insertion order, which is deterministic and stable
3225/// across runs. It is also similar to SmallSetVector, but provides removing
3226/// elements in O(1) time. This is achieved by not actually removing the element
3227/// from the underlying vector, so comes at the cost of using more memory, but
3228/// that is fine, since PhiNodeSets are used as short lived objects.
3229class PhiNodeSet {
3230 friend class PhiNodeSetIterator;
3231
3232 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
3233 using iterator = PhiNodeSetIterator;
3234
3235 /// Keeps the elements in the order of their insertion in the underlying
3236 /// vector. To achieve constant time removal, it never deletes any element.
3237 SmallVector<PHINode *, 32> NodeList;
3238
3239 /// Keeps the elements in the underlying set implementation. This (and not the
3240 /// NodeList defined above) is the source of truth on whether an element
3241 /// is actually in the collection.
3242 MapType NodeMap;
3243
3244 /// Points to the first valid (not deleted) element when the set is not empty
3245 /// and the value is not zero. Equals to the size of the underlying vector
3246 /// when the set is empty. When the value is 0, as in the beginning, the
3247 /// first element may or may not be valid.
3248 size_t FirstValidElement = 0;
3249
3250public:
3251 /// Inserts a new element to the collection.
3252 /// \returns true if the element is actually added, i.e. was not in the
3253 /// collection before the operation.
3254 bool insert(PHINode *Ptr) {
3255 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
3256 NodeList.push_back(Ptr);
3257 return true;
3258 }
3259 return false;
3260 }
3261
3262 /// Removes the element from the collection.
3263 /// \returns whether the element is actually removed, i.e. was in the
3264 /// collection before the operation.
3265 bool erase(PHINode *Ptr) {
3266 if (NodeMap.erase(Ptr)) {
3267 SkipRemovedElements(FirstValidElement);
3268 return true;
3269 }
3270 return false;
3271 }
3272
3273 /// Removes all elements and clears the collection.
3274 void clear() {
3275 NodeMap.clear();
3276 NodeList.clear();
3277 FirstValidElement = 0;
3278 }
3279
3280 /// \returns an iterator that will iterate the elements in the order of
3281 /// insertion.
3282 iterator begin() {
3283 if (FirstValidElement == 0)
3284 SkipRemovedElements(FirstValidElement);
3285 return PhiNodeSetIterator(this, FirstValidElement);
3286 }
3287
3288 /// \returns an iterator that points to the end of the collection.
3289 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
3290
3291 /// Returns the number of elements in the collection.
3292 size_t size() const {
3293 return NodeMap.size();
3294 }
3295
3296 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
3297 size_t count(PHINode *Ptr) const {
3298 return NodeMap.count(Ptr);
3299 }
3300
3301private:
3302 /// Updates the CurrentIndex so that it will point to a valid element.
3303 ///
3304 /// If the element of NodeList at CurrentIndex is valid, it does not
3305 /// change it. If there are no more valid elements, it updates CurrentIndex
3306 /// to point to the end of the NodeList.
3307 void SkipRemovedElements(size_t &CurrentIndex) {
3308 while (CurrentIndex < NodeList.size()) {
3309 auto it = NodeMap.find(NodeList[CurrentIndex]);
3310 // If the element has been deleted and added again later, NodeMap will
3311 // point to a different index, so CurrentIndex will still be invalid.
3312 if (it != NodeMap.end() && it->second == CurrentIndex)
3313 break;
3314 ++CurrentIndex;
3315 }
3316 }
3317};
3318
3319PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
3320 : Set(Set), CurrentIndex(Start) {}
3321
3322PHINode * PhiNodeSetIterator::operator*() const {
3323 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3324, __extension__ __PRETTY_FUNCTION__))
3324 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3324, __extension__ __PRETTY_FUNCTION__))
;
3325 return Set->NodeList[CurrentIndex];
3326}
3327
3328PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
3329 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3330, __extension__ __PRETTY_FUNCTION__))
3330 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3330, __extension__ __PRETTY_FUNCTION__))
;
3331 ++CurrentIndex;
3332 Set->SkipRemovedElements(CurrentIndex);
3333 return *this;
3334}
3335
3336bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
3337 return CurrentIndex == RHS.CurrentIndex;
3338}
3339
3340bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
3341 return !((*this) == RHS);
3342}
3343
3344/// Keep track of simplification of Phi nodes.
3345/// Accept the set of all phi nodes and erase phi node from this set
3346/// if it is simplified.
3347class SimplificationTracker {
3348 DenseMap<Value *, Value *> Storage;
3349 const SimplifyQuery &SQ;
3350 // Tracks newly created Phi nodes. The elements are iterated by insertion
3351 // order.
3352 PhiNodeSet AllPhiNodes;
3353 // Tracks newly created Select nodes.
3354 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
3355
3356public:
3357 SimplificationTracker(const SimplifyQuery &sq)
3358 : SQ(sq) {}
3359
3360 Value *Get(Value *V) {
3361 do {
3362 auto SV = Storage.find(V);
3363 if (SV == Storage.end())
3364 return V;
3365 V = SV->second;
3366 } while (true);
3367 }
3368
3369 Value *Simplify(Value *Val) {
3370 SmallVector<Value *, 32> WorkList;
3371 SmallPtrSet<Value *, 32> Visited;
3372 WorkList.push_back(Val);
3373 while (!WorkList.empty()) {
3374 auto *P = WorkList.pop_back_val();
3375 if (!Visited.insert(P).second)
3376 continue;
3377 if (auto *PI = dyn_cast<Instruction>(P))
3378 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
3379 for (auto *U : PI->users())
3380 WorkList.push_back(cast<Value>(U));
3381 Put(PI, V);
3382 PI->replaceAllUsesWith(V);
3383 if (auto *PHI = dyn_cast<PHINode>(PI))
3384 AllPhiNodes.erase(PHI);
3385 if (auto *Select = dyn_cast<SelectInst>(PI))
3386 AllSelectNodes.erase(Select);
3387 PI->eraseFromParent();
3388 }
3389 }
3390 return Get(Val);
3391 }
3392
3393 void Put(Value *From, Value *To) {
3394 Storage.insert({ From, To });
3395 }
3396
3397 void ReplacePhi(PHINode *From, PHINode *To) {
3398 Value* OldReplacement = Get(From);
3399 while (OldReplacement != From) {
3400 From = To;
3401 To = dyn_cast<PHINode>(OldReplacement);
3402 OldReplacement = Get(From);
3403 }
3404 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.\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3404, __extension__ __PRETTY_FUNCTION__))
;
3405 Put(From, To);
3406 From->replaceAllUsesWith(To);
3407 AllPhiNodes.erase(From);
3408 From->eraseFromParent();
3409 }
3410
3411 PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
3412
3413 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
3414
3415 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
3416
3417 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
3418
3419 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
3420
3421 void destroyNewNodes(Type *CommonType) {
3422 // For safe erasing, replace the uses with dummy value first.
3423 auto *Dummy = UndefValue::get(CommonType);
3424 for (auto *I : AllPhiNodes) {
3425 I->replaceAllUsesWith(Dummy);
3426 I->eraseFromParent();
3427 }
3428 AllPhiNodes.clear();
3429 for (auto *I : AllSelectNodes) {
3430 I->replaceAllUsesWith(Dummy);
3431 I->eraseFromParent();
3432 }
3433 AllSelectNodes.clear();
3434 }
3435};
3436
3437/// A helper class for combining addressing modes.
3438class AddressingModeCombiner {
3439 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
3440 typedef std::pair<PHINode *, PHINode *> PHIPair;
3441
3442private:
3443 /// The addressing modes we've collected.
3444 SmallVector<ExtAddrMode, 16> AddrModes;
3445
3446 /// The field in which the AddrModes differ, when we have more than one.
3447 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
3448
3449 /// Are the AddrModes that we have all just equal to their original values?
3450 bool AllAddrModesTrivial = true;
3451
3452 /// Common Type for all different fields in addressing modes.
3453 Type *CommonType;
3454
3455 /// SimplifyQuery for simplifyInstruction utility.
3456 const SimplifyQuery &SQ;
3457
3458 /// Original Address.
3459 Value *Original;
3460
3461public:
3462 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
3463 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
3464
3465 /// Get the combined AddrMode
3466 const ExtAddrMode &getAddrMode() const {
3467 return AddrModes[0];
3468 }
3469
3470 /// Add a new AddrMode if it's compatible with the AddrModes we already
3471 /// have.
3472 /// \return True iff we succeeded in doing so.
3473 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
3474 // Take note of if we have any non-trivial AddrModes, as we need to detect
3475 // when all AddrModes are trivial as then we would introduce a phi or select
3476 // which just duplicates what's already there.
3477 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
3478
3479 // If this is the first addrmode then everything is fine.
3480 if (AddrModes.empty()) {
3481 AddrModes.emplace_back(NewAddrMode);
3482 return true;
3483 }
3484
3485 // Figure out how different this is from the other address modes, which we
3486 // can do just by comparing against the first one given that we only care
3487 // about the cumulative difference.
3488 ExtAddrMode::FieldName ThisDifferentField =
3489 AddrModes[0].compare(NewAddrMode);
3490 if (DifferentField == ExtAddrMode::NoField)
3491 DifferentField = ThisDifferentField;
3492 else if (DifferentField != ThisDifferentField)
3493 DifferentField = ExtAddrMode::MultipleFields;
3494
3495 // If NewAddrMode differs in more than one dimension we cannot handle it.
3496 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
3497
3498 // If Scale Field is different then we reject.
3499 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
3500
3501 // We also must reject the case when base offset is different and
3502 // scale reg is not null, we cannot handle this case due to merge of
3503 // different offsets will be used as ScaleReg.
3504 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
3505 !NewAddrMode.ScaledReg);
3506
3507 // We also must reject the case when GV is different and BaseReg installed
3508 // due to we want to use base reg as a merge of GV values.
3509 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
3510 !NewAddrMode.HasBaseReg);
3511
3512 // Even if NewAddMode is the same we still need to collect it due to
3513 // original value is different. And later we will need all original values
3514 // as anchors during finding the common Phi node.
3515 if (CanHandle)
3516 AddrModes.emplace_back(NewAddrMode);
3517 else
3518 AddrModes.clear();
3519
3520 return CanHandle;
3521 }
3522
3523 /// Combine the addressing modes we've collected into a single
3524 /// addressing mode.
3525 /// \return True iff we successfully combined them or we only had one so
3526 /// didn't need to combine them anyway.
3527 bool combineAddrModes() {
3528 // If we have no AddrModes then they can't be combined.
3529 if (AddrModes.size() == 0)
3530 return false;
3531
3532 // A single AddrMode can trivially be combined.
3533 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
3534 return true;
3535
3536 // If the AddrModes we collected are all just equal to the value they are
3537 // derived from then combining them wouldn't do anything useful.
3538 if (AllAddrModesTrivial)
3539 return false;
3540
3541 if (!addrModeCombiningAllowed())
3542 return false;
3543
3544 // Build a map between <original value, basic block where we saw it> to
3545 // value of base register.
3546 // Bail out if there is no common type.
3547 FoldAddrToValueMapping Map;
3548 if (!initializeMap(Map))
3549 return false;
3550
3551 Value *CommonValue = findCommon(Map);
3552 if (CommonValue)
3553 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
3554 return CommonValue != nullptr;
3555 }
3556
3557private:
3558 /// Initialize Map with anchor values. For address seen
3559 /// we set the value of different field saw in this address.
3560 /// At the same time we find a common type for different field we will
3561 /// use to create new Phi/Select nodes. Keep it in CommonType field.
3562 /// Return false if there is no common type found.
3563 bool initializeMap(FoldAddrToValueMapping &Map) {
3564 // Keep track of keys where the value is null. We will need to replace it
3565 // with constant null when we know the common type.
3566 SmallVector<Value *, 2> NullValue;
3567 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
3568 for (auto &AM : AddrModes) {
3569 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
3570 if (DV) {
3571 auto *Type = DV->getType();
3572 if (CommonType && CommonType != Type)
3573 return false;
3574 CommonType = Type;
3575 Map[AM.OriginalValue] = DV;
3576 } else {
3577 NullValue.push_back(AM.OriginalValue);
3578 }
3579 }
3580 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3580, __extension__ __PRETTY_FUNCTION__))
;
3581 for (auto *V : NullValue)
3582 Map[V] = Constant::getNullValue(CommonType);
3583 return true;
3584 }
3585
3586 /// We have mapping between value A and other value B where B was a field in
3587 /// addressing mode represented by A. Also we have an original value C
3588 /// representing an address we start with. Traversing from C through phi and
3589 /// selects we ended up with A's in a map. This utility function tries to find
3590 /// a value V which is a field in addressing mode C and traversing through phi
3591 /// nodes and selects we will end up in corresponded values B in a map.
3592 /// The utility will create a new Phi/Selects if needed.
3593 // The simple example looks as follows:
3594 // BB1:
3595 // p1 = b1 + 40
3596 // br cond BB2, BB3
3597 // BB2:
3598 // p2 = b2 + 40
3599 // br BB3
3600 // BB3:
3601 // p = phi [p1, BB1], [p2, BB2]
3602 // v = load p
3603 // Map is
3604 // p1 -> b1
3605 // p2 -> b2
3606 // Request is
3607 // p -> ?
3608 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
3609 Value *findCommon(FoldAddrToValueMapping &Map) {
3610 // Tracks the simplification of newly created phi nodes. The reason we use
3611 // this mapping is because we will add new created Phi nodes in AddrToBase.
3612 // Simplification of Phi nodes is recursive, so some Phi node may
3613 // be simplified after we added it to AddrToBase. In reality this
3614 // simplification is possible only if original phi/selects were not
3615 // simplified yet.
3616 // Using this mapping we can find the current value in AddrToBase.
3617 SimplificationTracker ST(SQ);
3618
3619 // First step, DFS to create PHI nodes for all intermediate blocks.
3620 // Also fill traverse order for the second step.
3621 SmallVector<Value *, 32> TraverseOrder;
3622 InsertPlaceholders(Map, TraverseOrder, ST);
3623
3624 // Second Step, fill new nodes by merged values and simplify if possible.
3625 FillPlaceholders(Map, TraverseOrder, ST);
3626
3627 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3628 ST.destroyNewNodes(CommonType);
3629 return nullptr;
3630 }
3631
3632 // Now we'd like to match New Phi nodes to existed ones.
3633 unsigned PhiNotMatchedCount = 0;
3634 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3635 ST.destroyNewNodes(CommonType);
3636 return nullptr;
3637 }
3638
3639 auto *Result = ST.Get(Map.find(Original)->second);
3640 if (Result) {
3641 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3642 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
3643 }
3644 return Result;
3645 }
3646
3647 /// Try to match PHI node to Candidate.
3648 /// Matcher tracks the matched Phi nodes.
3649 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
3650 SmallSetVector<PHIPair, 8> &Matcher,
3651 PhiNodeSet &PhiNodesToMatch) {
3652 SmallVector<PHIPair, 8> WorkList;
3653 Matcher.insert({ PHI, Candidate });
3654 SmallSet<PHINode *, 8> MatchedPHIs;
3655 MatchedPHIs.insert(PHI);
3656 WorkList.push_back({ PHI, Candidate });
3657 SmallSet<PHIPair, 8> Visited;
3658 while (!WorkList.empty()) {
3659 auto Item = WorkList.pop_back_val();
3660 if (!Visited.insert(Item).second)
3661 continue;
3662 // We iterate over all incoming values to Phi to compare them.
3663 // If values are different and both of them Phi and the first one is a
3664 // Phi we added (subject to match) and both of them is in the same basic
3665 // block then we can match our pair if values match. So we state that
3666 // these values match and add it to work list to verify that.
3667 for (auto B : Item.first->blocks()) {
3668 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3669 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3670 if (FirstValue == SecondValue)
3671 continue;
3672
3673 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3674 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3675
3676 // One of them is not Phi or
3677 // The first one is not Phi node from the set we'd like to match or
3678 // Phi nodes from different basic blocks then
3679 // we will not be able to match.
3680 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3681 FirstPhi->getParent() != SecondPhi->getParent())
3682 return false;
3683
3684 // If we already matched them then continue.
3685 if (Matcher.count({ FirstPhi, SecondPhi }))
3686 continue;
3687 // So the values are different and does not match. So we need them to
3688 // match. (But we register no more than one match per PHI node, so that
3689 // we won't later try to replace them twice.)
3690 if (MatchedPHIs.insert(FirstPhi).second)
3691 Matcher.insert({ FirstPhi, SecondPhi });
3692 // But me must check it.
3693 WorkList.push_back({ FirstPhi, SecondPhi });
3694 }
3695 }
3696 return true;
3697 }
3698
3699 /// For the given set of PHI nodes (in the SimplificationTracker) try
3700 /// to find their equivalents.
3701 /// Returns false if this matching fails and creation of new Phi is disabled.
3702 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
3703 unsigned &PhiNotMatchedCount) {
3704 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3705 // order, so the replacements (ReplacePhi) are also done in a deterministic
3706 // order.
3707 SmallSetVector<PHIPair, 8> Matched;
3708 SmallPtrSet<PHINode *, 8> WillNotMatch;
3709 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
3710 while (PhiNodesToMatch.size()) {
3711 PHINode *PHI = *PhiNodesToMatch.begin();
3712
3713 // Add us, if no Phi nodes in the basic block we do not match.
3714 WillNotMatch.clear();
3715 WillNotMatch.insert(PHI);
3716
3717 // Traverse all Phis until we found equivalent or fail to do that.
3718 bool IsMatched = false;
3719 for (auto &P : PHI->getParent()->phis()) {
3720 // Skip new Phi nodes.
3721 if (PhiNodesToMatch.count(&P))
3722 continue;
3723 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3724 break;
3725 // If it does not match, collect all Phi nodes from matcher.
3726 // if we end up with no match, them all these Phi nodes will not match
3727 // later.
3728 for (auto M : Matched)
3729 WillNotMatch.insert(M.first);
3730 Matched.clear();
3731 }
3732 if (IsMatched) {
3733 // Replace all matched values and erase them.
3734 for (auto MV : Matched)
3735 ST.ReplacePhi(MV.first, MV.second);
3736 Matched.clear();
3737 continue;
3738 }
3739 // If we are not allowed to create new nodes then bail out.
3740 if (!AllowNewPhiNodes)
3741 return false;
3742 // Just remove all seen values in matcher. They will not match anything.
3743 PhiNotMatchedCount += WillNotMatch.size();
3744 for (auto *P : WillNotMatch)
3745 PhiNodesToMatch.erase(P);
3746 }
3747 return true;
3748 }
3749 /// Fill the placeholders with values from predecessors and simplify them.
3750 void FillPlaceholders(FoldAddrToValueMapping &Map,
3751 SmallVectorImpl<Value *> &TraverseOrder,
3752 SimplificationTracker &ST) {
3753 while (!TraverseOrder.empty()) {
3754 Value *Current = TraverseOrder.pop_back_val();
3755 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!!!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3755, __extension__ __PRETTY_FUNCTION__))
;
3756 Value *V = Map[Current];
3757
3758 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3759 // CurrentValue also must be Select.
3760 auto *CurrentSelect = cast<SelectInst>(Current);
3761 auto *TrueValue = CurrentSelect->getTrueValue();
3762 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3762, __extension__ __PRETTY_FUNCTION__))
;
3763 Select->setTrueValue(ST.Get(Map[TrueValue]));
3764 auto *FalseValue = CurrentSelect->getFalseValue();
3765 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3765, __extension__ __PRETTY_FUNCTION__))
;
3766 Select->setFalseValue(ST.Get(Map[FalseValue]));
3767 } else {
3768 // Must be a Phi node then.
3769 auto *PHI = cast<PHINode>(V);
3770 // Fill the Phi node with values from predecessors.
3771 for (auto *B : predecessors(PHI->getParent())) {
3772 Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
3773 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!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3773, __extension__ __PRETTY_FUNCTION__))
;
3774 PHI->addIncoming(ST.Get(Map[PV]), B);
3775 }
3776 }
3777 Map[Current] = ST.Simplify(V);
3778 }
3779 }
3780
3781 /// Starting from original value recursively iterates over def-use chain up to
3782 /// known ending values represented in a map. For each traversed phi/select
3783 /// inserts a placeholder Phi or Select.
3784 /// Reports all new created Phi/Select nodes by adding them to set.
3785 /// Also reports and order in what values have been traversed.
3786 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3787 SmallVectorImpl<Value *> &TraverseOrder,
3788 SimplificationTracker &ST) {
3789 SmallVector<Value *, 32> Worklist;
3790 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3791, __extension__ __PRETTY_FUNCTION__))
3791 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3791, __extension__ __PRETTY_FUNCTION__))
;
3792 auto *Dummy = UndefValue::get(CommonType);
3793 Worklist.push_back(Original);
3794 while (!Worklist.empty()) {
3795 Value *Current = Worklist.pop_back_val();
3796 // if it is already visited or it is an ending value then skip it.
3797 if (Map.find(Current) != Map.end())
3798 continue;
3799 TraverseOrder.push_back(Current);
3800
3801 // CurrentValue must be a Phi node or select. All others must be covered
3802 // by anchors.
3803 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
3804 // Is it OK to get metadata from OrigSelect?!
3805 // Create a Select placeholder with dummy value.
3806 SelectInst *Select = SelectInst::Create(
3807 CurrentSelect->getCondition(), Dummy, Dummy,
3808 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
3809 Map[Current] = Select;
3810 ST.insertNewSelect(Select);
3811 // We are interested in True and False values.
3812 Worklist.push_back(CurrentSelect->getTrueValue());
3813 Worklist.push_back(CurrentSelect->getFalseValue());
3814 } else {
3815 // It must be a Phi node then.
3816 PHINode *CurrentPhi = cast<PHINode>(Current);
3817 unsigned PredCount = CurrentPhi->getNumIncomingValues();
3818 PHINode *PHI =
3819 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
3820 Map[Current] = PHI;
3821 ST.insertNewPhi(PHI);
3822 append_range(Worklist, CurrentPhi->incoming_values());
3823 }
3824 }
3825 }
3826
3827 bool addrModeCombiningAllowed() {
3828 if (DisableComplexAddrModes)
3829 return false;
3830 switch (DifferentField) {
3831 default:
3832 return false;
3833 case ExtAddrMode::BaseRegField:
3834 return AddrSinkCombineBaseReg;
3835 case ExtAddrMode::BaseGVField:
3836 return AddrSinkCombineBaseGV;
3837 case ExtAddrMode::BaseOffsField:
3838 return AddrSinkCombineBaseOffs;
3839 case ExtAddrMode::ScaledRegField:
3840 return AddrSinkCombineScaledReg;
3841 }
3842 }
3843};
3844} // end anonymous namespace
3845
3846/// Try adding ScaleReg*Scale to the current addressing mode.
3847/// Return true and update AddrMode if this addr mode is legal for the target,
3848/// false if not.
3849bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
3850 unsigned Depth) {
3851 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3852 // mode. Just process that directly.
3853 if (Scale == 1)
3854 return matchAddr(ScaleReg, Depth);
3855
3856 // If the scale is 0, it takes nothing to add this.
3857 if (Scale == 0)
3858 return true;
3859
3860 // If we already have a scale of this value, we can add to it, otherwise, we
3861 // need an available scale field.
3862 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3863 return false;
3864
3865 ExtAddrMode TestAddrMode = AddrMode;
3866
3867 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3868 // [A+B + A*7] -> [B+A*8].
3869 TestAddrMode.Scale += Scale;
3870 TestAddrMode.ScaledReg = ScaleReg;
3871
3872 // If the new address isn't legal, bail out.
3873 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
3874 return false;
3875
3876 // It was legal, so commit it.
3877 AddrMode = TestAddrMode;
3878
3879 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3880 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3881 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
3882 // go any further: we can reuse it and cannot eliminate it.
3883 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
3884 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3885 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
3886 !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
3887 TestAddrMode.InBounds = false;
3888 TestAddrMode.ScaledReg = AddLHS;
3889 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
3890
3891 // If this addressing mode is legal, commit it and remember that we folded
3892 // this instruction.
3893 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
3894 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3895 AddrMode = TestAddrMode;
3896 return true;
3897 }
3898 // Restore status quo.
3899 TestAddrMode = AddrMode;
3900 }
3901
3902 // If this is an add recurrence with a constant step, return the increment
3903 // instruction and the canonicalized step.
3904 auto GetConstantStep = [this](const Value * V)
3905 ->Optional<std::pair<Instruction *, APInt> > {
3906 auto *PN = dyn_cast<PHINode>(V);
3907 if (!PN)
3908 return None;
3909 auto IVInc = getIVIncrement(PN, &LI);
3910 if (!IVInc)
3911 return None;
3912 // TODO: The result of the intrinsics above is two-compliment. However when
3913 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
3914 // If it has nuw or nsw flags, we need to make sure that these flags are
3915 // inferrable at the point of memory instruction. Otherwise we are replacing
3916 // well-defined two-compliment computation with poison. Currently, to avoid
3917 // potentially complex analysis needed to prove this, we reject such cases.
3918 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
3919 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
3920 return None;
3921 if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
3922 return std::make_pair(IVInc->first, ConstantStep->getValue());
3923 return None;
3924 };
3925
3926 // Try to account for the following special case:
3927 // 1. ScaleReg is an inductive variable;
3928 // 2. We use it with non-zero offset;
3929 // 3. IV's increment is available at the point of memory instruction.
3930 //
3931 // In this case, we may reuse the IV increment instead of the IV Phi to
3932 // achieve the following advantages:
3933 // 1. If IV step matches the offset, we will have no need in the offset;
3934 // 2. Even if they don't match, we will reduce the overlap of living IV
3935 // and IV increment, that will potentially lead to better register
3936 // assignment.
3937 if (AddrMode.BaseOffs) {
3938 if (auto IVStep = GetConstantStep(ScaleReg)) {
3939 Instruction *IVInc = IVStep->first;
3940 // The following assert is important to ensure a lack of infinite loops.
3941 // This transforms is (intentionally) the inverse of the one just above.
3942 // If they don't agree on the definition of an increment, we'd alternate
3943 // back and forth indefinitely.
3944 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 3944, __extension__ __PRETTY_FUNCTION__))
;
3945 APInt Step = IVStep->second;
3946 APInt Offset = Step * AddrMode.Scale;
3947 if (Offset.isSignedIntN(64)) {
3948 TestAddrMode.InBounds = false;
3949 TestAddrMode.ScaledReg = IVInc;
3950 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
3951 // If this addressing mode is legal, commit it..
3952 // (Note that we defer the (expensive) domtree base legality check
3953 // to the very last possible point.)
3954 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
3955 getDTFn().dominates(IVInc, MemoryInst)) {
3956 AddrModeInsts.push_back(cast<Instruction>(IVInc));
3957 AddrMode = TestAddrMode;
3958 return true;
3959 }
3960 // Restore status quo.
3961 TestAddrMode = AddrMode;
3962 }
3963 }
3964 }
3965
3966 // Otherwise, just return what we have.
3967 return true;
3968}
3969
3970/// This is a little filter, which returns true if an addressing computation
3971/// involving I might be folded into a load/store accessing it.
3972/// This doesn't need to be perfect, but needs to accept at least
3973/// the set of instructions that MatchOperationAddr can.
3974static bool MightBeFoldableInst(Instruction *I) {
3975 switch (I->getOpcode()) {
3976 case Instruction::BitCast:
3977 case Instruction::AddrSpaceCast:
3978 // Don't touch identity bitcasts.
3979 if (I->getType() == I->getOperand(0)->getType())
3980 return false;
3981 return I->getType()->isIntOrPtrTy();
3982 case Instruction::PtrToInt:
3983 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3984 return true;
3985 case Instruction::IntToPtr:
3986 // We know the input is intptr_t, so this is foldable.
3987 return true;
3988 case Instruction::Add:
3989 return true;
3990 case Instruction::Mul:
3991 case Instruction::Shl:
3992 // Can only handle X*C and X << C.
3993 return isa<ConstantInt>(I->getOperand(1));
3994 case Instruction::GetElementPtr:
3995 return true;
3996 default:
3997 return false;
3998 }
3999}
4000
4001/// Check whether or not \p Val is a legal instruction for \p TLI.
4002/// \note \p Val is assumed to be the product of some type promotion.
4003/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4004/// to be legal, as the non-promoted value would have had the same state.
4005static bool isPromotedInstructionLegal(const TargetLowering &TLI,
4006 const DataLayout &DL, Value *Val) {
4007 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4008 if (!PromotedInst)
4009 return false;
4010 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
4011 // If the ISDOpcode is undefined, it was undefined before the promotion.
4012 if (!ISDOpcode)
4013 return true;
4014 // Otherwise, check if the promoted instruction is legal or not.
4015 return TLI.isOperationLegalOrCustom(
4016 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
4017}
4018
4019namespace {
4020
4021/// Hepler class to perform type promotion.
4022class TypePromotionHelper {
4023 /// Utility function to add a promoted instruction \p ExtOpnd to
4024 /// \p PromotedInsts and record the type of extension we have seen.
4025 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4026 Instruction *ExtOpnd,
4027 bool IsSExt) {
4028 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4029 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
4030 if (It != PromotedInsts.end()) {
4031 // If the new extension is same as original, the information in
4032 // PromotedInsts[ExtOpnd] is still correct.
4033 if (It->second.getInt() == ExtTy)
4034 return;
4035
4036 // Now the new extension is different from old extension, we make
4037 // the type information invalid by setting extension type to
4038 // BothExtension.
4039 ExtTy = BothExtension;
4040 }
4041 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4042 }
4043
4044 /// Utility function to query the original type of instruction \p Opnd
4045 /// with a matched extension type. If the extension doesn't match, we
4046 /// cannot use the information we had on the original type.
4047 /// BothExtension doesn't match any extension type.
4048 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4049 Instruction *Opnd,
4050 bool IsSExt) {
4051 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4052 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
4053 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4054 return It->second.getPointer();
4055 return nullptr;
4056 }
4057
4058 /// Utility function to check whether or not a sign or zero extension
4059 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4060 /// either using the operands of \p Inst or promoting \p Inst.
4061 /// The type of the extension is defined by \p IsSExt.
4062 /// In other words, check if:
4063 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4064 /// #1 Promotion applies:
4065 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4066 /// #2 Operand reuses:
4067 /// ext opnd1 to ConsideredExtType.
4068 /// \p PromotedInsts maps the instructions to their type before promotion.
4069 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4070 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4071
4072 /// Utility function to determine if \p OpIdx should be promoted when
4073 /// promoting \p Inst.
4074 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4075 return !(isa<SelectInst>(Inst) && OpIdx == 0);
4076 }
4077
4078 /// Utility function to promote the operand of \p Ext when this
4079 /// operand is a promotable trunc or sext or zext.
4080 /// \p PromotedInsts maps the instructions to their type before promotion.
4081 /// \p CreatedInstsCost[out] contains the cost of all instructions
4082 /// created to promote the operand of Ext.
4083 /// Newly added extensions are inserted in \p Exts.
4084 /// Newly added truncates are inserted in \p Truncs.
4085 /// Should never be called directly.
4086 /// \return The promoted value which is used instead of Ext.
4087 static Value *promoteOperandForTruncAndAnyExt(
4088 Instruction *Ext, TypePromotionTransaction &TPT,
4089 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4090 SmallVectorImpl<Instruction *> *Exts,
4091 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4092
4093 /// Utility function to promote the operand of \p Ext when this
4094 /// operand is promotable and is not a supported trunc or sext.
4095 /// \p PromotedInsts maps the instructions to their type before promotion.
4096 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4097 /// created to promote the operand of Ext.
4098 /// Newly added extensions are inserted in \p Exts.
4099 /// Newly added truncates are inserted in \p Truncs.
4100 /// Should never be called directly.
4101 /// \return The promoted value which is used instead of Ext.
4102 static Value *promoteOperandForOther(Instruction *Ext,
4103 TypePromotionTransaction &TPT,
4104 InstrToOrigTy &PromotedInsts,
4105 unsigned &CreatedInstsCost,
4106 SmallVectorImpl<Instruction *> *Exts,
4107 SmallVectorImpl<Instruction *> *Truncs,
4108 const TargetLowering &TLI, bool IsSExt);
4109
4110 /// \see promoteOperandForOther.
4111 static Value *signExtendOperandForOther(
4112 Instruction *Ext, TypePromotionTransaction &TPT,
4113 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4114 SmallVectorImpl<Instruction *> *Exts,
4115 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4116 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4117 Exts, Truncs, TLI, true);
4118 }
4119
4120 /// \see promoteOperandForOther.
4121 static Value *zeroExtendOperandForOther(
4122 Instruction *Ext, TypePromotionTransaction &TPT,
4123 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4124 SmallVectorImpl<Instruction *> *Exts,
4125 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4126 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4127 Exts, Truncs, TLI, false);
4128 }
4129
4130public:
4131 /// Type for the utility function that promotes the operand of Ext.
4132 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4133 InstrToOrigTy &PromotedInsts,
4134 unsigned &CreatedInstsCost,
4135 SmallVectorImpl<Instruction *> *Exts,
4136 SmallVectorImpl<Instruction *> *Truncs,
4137 const TargetLowering &TLI);
4138
4139 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4140 /// action to promote the operand of \p Ext instead of using Ext.
4141 /// \return NULL if no promotable action is possible with the current
4142 /// sign extension.
4143 /// \p InsertedInsts keeps track of all the instructions inserted by the
4144 /// other CodeGenPrepare optimizations. This information is important
4145 /// because we do not want to promote these instructions as CodeGenPrepare
4146 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4147 /// \p PromotedInsts maps the instructions to their type before promotion.
4148 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4149 const TargetLowering &TLI,
4150 const InstrToOrigTy &PromotedInsts);
4151};
4152
4153} // end anonymous namespace
4154
4155bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4156 Type *ConsideredExtType,
4157 const InstrToOrigTy &PromotedInsts,
4158 bool IsSExt) {
4159 // The promotion helper does not know how to deal with vector types yet.
4160 // To be able to fix that, we would need to fix the places where we
4161 // statically extend, e.g., constants and such.
4162 if (Inst->getType()->isVectorTy())
4163 return false;
4164
4165 // We can always get through zext.
4166 if (isa<ZExtInst>(Inst))
4167 return true;
4168
4169 // sext(sext) is ok too.
4170 if (IsSExt && isa<SExtInst>(Inst))
4171 return true;
4172
4173 // We can get through binary operator, if it is legal. In other words, the
4174 // binary operator must have a nuw or nsw flag.
4175 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
4176 if (isa_and_nonnull<OverflowingBinaryOperator>(BinOp) &&
4177 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4178 (IsSExt && BinOp->hasNoSignedWrap())))
4179 return true;
4180
4181 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4182 if ((Inst->getOpcode() == Instruction::And ||
4183 Inst->getOpcode() == Instruction::Or))
4184 return true;
4185
4186 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4187 if (Inst->getOpcode() == Instruction::Xor) {
4188 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
4189 // Make sure it is not a NOT.
4190 if (Cst && !Cst->getValue().isAllOnesValue())
4191 return true;
4192 }
4193
4194 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4195 // It may change a poisoned value into a regular value, like
4196 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4197 // poisoned value regular value
4198 // It should be OK since undef covers valid value.
4199 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4200 return true;
4201
4202 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4203 // It may change a poisoned value into a regular value, like
4204 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4205 // poisoned value regular value
4206 // It should be OK since undef covers valid value.
4207 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4208 const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
4209 if (ExtInst->hasOneUse()) {
4210 const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
4211 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4212 const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
4213 if (Cst &&
4214 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
4215 return true;
4216 }
4217 }
4218 }
4219
4220 // Check if we can do the following simplification.
4221 // ext(trunc(opnd)) --> ext(opnd)
4222 if (!isa<TruncInst>(Inst))
4223 return false;
4224
4225 Value *OpndVal = Inst->getOperand(0);
4226 // Check if we can use this operand in the extension.
4227 // If the type is larger than the result type of the extension, we cannot.
4228 if (!OpndVal->getType()->isIntegerTy() ||
4229 OpndVal->getType()->getIntegerBitWidth() >
4230 ConsideredExtType->getIntegerBitWidth())
4231 return false;
4232
4233 // If the operand of the truncate is not an instruction, we will not have
4234 // any information on the dropped bits.
4235 // (Actually we could for constant but it is not worth the extra logic).
4236 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
4237 if (!Opnd)
4238 return false;
4239
4240 // Check if the source of the type is narrow enough.
4241 // I.e., check that trunc just drops extended bits of the same kind of
4242 // the extension.
4243 // #1 get the type of the operand and check the kind of the extended bits.
4244 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4245 if (OpndType)
4246 ;
4247 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
4248 OpndType = Opnd->getOperand(0)->getType();
4249 else
4250 return false;
4251
4252 // #2 check that the truncate just drops extended bits.
4253 return Inst->getType()->getIntegerBitWidth() >=
4254 OpndType->getIntegerBitWidth();
4255}
4256
4257TypePromotionHelper::Action TypePromotionHelper::getAction(
4258 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4259 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4260 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 4261, __extension__ __PRETTY_FUNCTION__))
4261 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 4261, __extension__ __PRETTY_FUNCTION__))
;
4262 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
4263 Type *ExtTy = Ext->getType();
4264 bool IsSExt = isa<SExtInst>(Ext);
4265 // If the operand of the extension is not an instruction, we cannot
4266 // get through.
4267 // If it, check we can get through.
4268 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
4269 return nullptr;
4270
4271 // Do not promote if the operand has been added by codegenprepare.
4272 // Otherwise, it means we are undoing an optimization that is likely to be
4273 // redone, thus causing potential infinite loop.
4274 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
4275 return nullptr;
4276
4277 // SExt or Trunc instructions.
4278 // Return the related handler.
4279 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
4280 isa<ZExtInst>(ExtOpnd))
4281 return promoteOperandForTruncAndAnyExt;
4282
4283 // Regular instruction.
4284 // Abort early if we will have to insert non-free instructions.
4285 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
4286 return nullptr;
4287 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4288}
4289
4290Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4291 Instruction *SExt, TypePromotionTransaction &TPT,
4292 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4293 SmallVectorImpl<Instruction *> *Exts,
4294 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4295 // By construction, the operand of SExt is an instruction. Otherwise we cannot
4296 // get through it and this method should not be called.
4297 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
4298 Value *ExtVal = SExt;
4299 bool HasMergedNonFreeExt = false;
4300 if (isa<ZExtInst>(SExtOpnd)) {
4301 // Replace s|zext(zext(opnd))
4302 // => zext(opnd).
4303 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
4304 Value *ZExt =
4305 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
4306 TPT.replaceAllUsesWith(SExt, ZExt);
4307 TPT.eraseInstruction(SExt);
4308 ExtVal = ZExt;
4309 } else {
4310 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
4311 // => z|sext(opnd).
4312 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
4313 }
4314 CreatedInstsCost = 0;
4315
4316 // Remove dead code.
4317 if (SExtOpnd->use_empty())
4318 TPT.eraseInstruction(SExtOpnd);
4319
4320 // Check if the extension is still needed.
4321 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
4322 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
4323 if (ExtInst) {
4324 if (Exts)
4325 Exts->push_back(ExtInst);
4326 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
4327 }
4328 return ExtVal;
4329 }
4330
4331 // At this point we have: ext ty opnd to ty.
4332 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
4333 Value *NextVal = ExtInst->getOperand(0);
4334 TPT.eraseInstruction(ExtInst, NextVal);
4335 return NextVal;
4336}
4337
4338Value *TypePromotionHelper::promoteOperandForOther(
4339 Instruction *Ext, TypePromotionTransaction &TPT,
4340 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4341 SmallVectorImpl<Instruction *> *Exts,
4342 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
4343 bool IsSExt) {
4344 // By construction, the operand of Ext is an instruction. Otherwise we cannot
4345 // get through it and this method should not be called.
4346 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
4347 CreatedInstsCost = 0;
4348 if (!ExtOpnd->hasOneUse()) {
4349 // ExtOpnd will be promoted.
4350 // All its uses, but Ext, will need to use a truncated value of the
4351 // promoted version.
4352 // Create the truncate now.
4353 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
4354 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
4355 // Insert it just after the definition.
4356 ITrunc->moveAfter(ExtOpnd);
4357 if (Truncs)
4358 Truncs->push_back(ITrunc);
4359 }
4360
4361 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
4362 // Restore the operand of Ext (which has been replaced by the previous call
4363 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
4364 TPT.setOperand(Ext, 0, ExtOpnd);
4365 }
4366
4367 // Get through the Instruction:
4368 // 1. Update its type.
4369 // 2. Replace the uses of Ext by Inst.
4370 // 3. Extend each operand that needs to be extended.
4371
4372 // Remember the original type of the instruction before promotion.
4373 // This is useful to know that the high bits are sign extended bits.
4374 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
4375 // Step #1.
4376 TPT.mutateType(ExtOpnd, Ext->getType());
4377 // Step #2.
4378 TPT.replaceAllUsesWith(Ext, ExtOpnd);
4379 // Step #3.
4380 Instruction *ExtForOpnd = Ext;
4381
4382 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Propagate Ext to operands\n"
; } } while (false)
;
4383 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
4384 ++OpIdx) {
4385 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
)
;
4386 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
4387 !shouldExtOperand(ExtOpnd, OpIdx)) {
4388 LLVM_DEBUG(dbgs() << "No need to propagate\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "No need to propagate\n"
; } } while (false)
;
4389 continue;
4390 }
4391 // Check if we can statically extend the operand.
4392 Value *Opnd = ExtOpnd->getOperand(OpIdx);
4393 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
4394 LLVM_DEBUG(dbgs() << "Statically extend\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Statically extend\n"; }
} while (false)
;
4395 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
4396 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
4397 : Cst->getValue().zext(BitWidth);
4398 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
4399 continue;
4400 }
4401 // UndefValue are typed, so we have to statically sign extend them.
4402 if (isa<UndefValue>(Opnd)) {
4403 LLVM_DEBUG(dbgs() << "Statically extend\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Statically extend\n"; }
} while (false)
;
4404 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
4405 continue;
4406 }
4407
4408 // Otherwise we have to explicitly sign extend the operand.
4409 // Check if Ext was reused to extend an operand.
4410 if (!ExtForOpnd) {
4411 // If yes, create a new one.
4412 LLVM_DEBUG(dbgs() << "More operands to ext\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "More operands to ext\n"
; } } while (false)
;
4413 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
4414 : TPT.createZExt(Ext, Opnd, Ext->getType());
4415 if (!isa<Instruction>(ValForExtOpnd)) {
4416 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
4417 continue;
4418 }
4419 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
4420 }
4421 if (Exts)
4422 Exts->push_back(ExtForOpnd);
4423 TPT.setOperand(ExtForOpnd, 0, Opnd);
4424
4425 // Move the sign extension before the insertion point.
4426 TPT.moveBefore(ExtForOpnd, ExtOpnd);
4427 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
4428 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
4429 // If more sext are required, new instructions will have to be created.
4430 ExtForOpnd = nullptr;
4431 }
4432 if (ExtForOpnd == Ext) {
4433 LLVM_DEBUG(dbgs() << "Extension is useless now\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "Extension is useless now\n"
; } } while (false)
;
4434 TPT.eraseInstruction(Ext);
4435 }
4436 return ExtOpnd;
4437}
4438
4439/// Check whether or not promoting an instruction to a wider type is profitable.
4440/// \p NewCost gives the cost of extension instructions created by the
4441/// promotion.
4442/// \p OldCost gives the cost of extension instructions before the promotion
4443/// plus the number of instructions that have been
4444/// matched in the addressing mode the promotion.
4445/// \p PromotedOperand is the value that has been promoted.
4446/// \return True if the promotion is profitable, false otherwise.
4447bool AddressingModeMatcher::isPromotionProfitable(
4448 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
4449 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCostdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "OldCost: " << OldCost
<< "\tNewCost: " << NewCost << '\n'; } } while
(false)
4450 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "OldCost: " << OldCost
<< "\tNewCost: " << NewCost << '\n'; } } while
(false)
;
4451 // The cost of the new extensions is greater than the cost of the
4452 // old extension plus what we folded.
4453 // This is not profitable.
4454 if (NewCost > OldCost)
4455 return false;
4456 if (NewCost < OldCost)
4457 return true;
4458 // The promotion is neutral but it may help folding the sign extension in
4459 // loads for instance.
4460 // Check that we did not create an illegal instruction.
4461 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
4462}
4463
4464/// Given an instruction or constant expr, see if we can fold the operation
4465/// into the addressing mode. If so, update the addressing mode and return
4466/// true, otherwise return false without modifying AddrMode.
4467/// If \p MovedAway is not NULL, it contains the information of whether or
4468/// not AddrInst has to be folded into the addressing mode on success.
4469/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
4470/// because it has been moved away.
4471/// Thus AddrInst must not be added in the matched instructions.
4472/// This state can happen when AddrInst is a sext, since it may be moved away.
4473/// Therefore, AddrInst may not be valid when MovedAway is true and it must
4474/// not be referenced anymore.
4475bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
4476 unsigned Depth,
4477 bool *MovedAway) {
4478 // Avoid exponential behavior on extremely deep expression trees.
4479 if (Depth >= 5) return false;
4480
4481 // By default, all matched instructions stay in place.
4482 if (MovedAway)
4483 *MovedAway = false;
4484
4485 switch (Opcode) {
4486 case Instruction::PtrToInt:
4487 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4488 return matchAddr(AddrInst->getOperand(0), Depth);
4489 case Instruction::IntToPtr: {
4490 auto AS = AddrInst->getType()->getPointerAddressSpace();
4491 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
4492 // This inttoptr is a no-op if the integer type is pointer sized.
4493 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
4494 return matchAddr(AddrInst->getOperand(0), Depth);
4495 return false;
4496 }
4497 case Instruction::BitCast:
4498 // BitCast is always a noop, and we can handle it as long as it is
4499 // int->int or pointer->pointer (we don't want int<->fp or something).
4500 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
4501 // Don't touch identity bitcasts. These were probably put here by LSR,
4502 // and we don't want to mess around with them. Assume it knows what it
4503 // is doing.
4504 AddrInst->getOperand(0)->getType() != AddrInst->getType())
4505 return matchAddr(AddrInst->getOperand(0), Depth);
4506 return false;
4507 case Instruction::AddrSpaceCast: {
4508 unsigned SrcAS
4509 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
4510 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
4511 if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS))
4512 return matchAddr(AddrInst->getOperand(0), Depth);
4513 return false;
4514 }
4515 case Instruction::Add: {
4516 // Check to see if we can merge in the RHS then the LHS. If so, we win.
4517 ExtAddrMode BackupAddrMode = AddrMode;
4518 unsigned OldSize = AddrModeInsts.size();
4519 // Start a transaction at this point.
4520 // The LHS may match but not the RHS.
4521 // Therefore, we need a higher level restoration point to undo partially
4522 // matched operation.
4523 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4524 TPT.getRestorationPoint();
4525
4526 AddrMode.InBounds = false;
4527 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
4528 matchAddr(AddrInst->getOperand(0), Depth+1))
4529 return true;
4530
4531 // Restore the old addr mode info.
4532 AddrMode = BackupAddrMode;
4533 AddrModeInsts.resize(OldSize);
4534 TPT.rollback(LastKnownGood);
4535
4536 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
4537 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
4538 matchAddr(AddrInst->getOperand(1), Depth+1))
4539 return true;
4540
4541 // Otherwise we definitely can't merge the ADD in.
4542 AddrMode = BackupAddrMode;
4543 AddrModeInsts.resize(OldSize);
4544 TPT.rollback(LastKnownGood);
4545 break;
4546 }
4547 //case Instruction::Or:
4548 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
4549 //break;
4550 case Instruction::Mul:
4551 case Instruction::Shl: {
4552 // Can only handle X*C and X << C.
4553 AddrMode.InBounds = false;
4554 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
4555 if (!RHS || RHS->getBitWidth() > 64)
4556 return false;
4557 int64_t Scale = RHS->getSExtValue();
4558 if (Opcode == Instruction::Shl)
4559 Scale = 1LL << Scale;
4560
4561 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
4562 }
4563 case Instruction::GetElementPtr: {
4564 // Scan the GEP. We check it if it contains constant offsets and at most
4565 // one variable offset.
4566 int VariableOperand = -1;
4567 unsigned VariableScale = 0;
4568
4569 int64_t ConstantOffset = 0;
4570 gep_type_iterator GTI = gep_type_begin(AddrInst);
4571 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
4572 if (StructType *STy = GTI.getStructTypeOrNull()) {
4573 const StructLayout *SL = DL.getStructLayout(STy);
4574 unsigned Idx =
4575 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
4576 ConstantOffset += SL->getElementOffset(Idx);
4577 } else {
4578 TypeSize TS = DL.getTypeAllocSize(GTI.getIndexedType());
4579 if (TS.isNonZero()) {
4580 // The optimisations below currently only work for fixed offsets.
4581 if (TS.isScalable())
4582 return false;
4583 int64_t TypeSize = TS.getFixedSize();
4584 if (ConstantInt *CI =
4585 dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
4586 const APInt &CVal = CI->getValue();
4587 if (CVal.getMinSignedBits() <= 64) {
4588 ConstantOffset += CVal.getSExtValue() * TypeSize;
4589 continue;
4590 }
4591 }
4592 // We only allow one variable index at the moment.
4593 if (VariableOperand != -1)
4594 return false;
4595
4596 // Remember the variable index.
4597 VariableOperand = i;
4598 VariableScale = TypeSize;
4599 }
4600 }
4601 }
4602
4603 // A common case is for the GEP to only do a constant offset. In this case,
4604 // just add it to the disp field and check validity.
4605 if (VariableOperand == -1) {
4606 AddrMode.BaseOffs += ConstantOffset;
4607 if (ConstantOffset == 0 ||
4608 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
4609 // Check to see if we can fold the base pointer in too.
4610 if (matchAddr(AddrInst->getOperand(0), Depth+1)) {
4611 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4612 AddrMode.InBounds = false;
4613 return true;
4614 }
4615 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4616 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4617 ConstantOffset > 0) {
4618 // Record GEPs with non-zero offsets as candidates for splitting in the
4619 // event that the offset cannot fit into the r+i addressing mode.
4620 // Simple and common case that only one GEP is used in calculating the
4621 // address for the memory access.
4622 Value *Base = AddrInst->getOperand(0);
4623 auto *BaseI = dyn_cast<Instruction>(Base);
4624 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4625 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4626 (BaseI && !isa<CastInst>(BaseI) &&
4627 !isa<GetElementPtrInst>(BaseI))) {
4628 // Make sure the parent block allows inserting non-PHI instructions
4629 // before the terminator.
4630 BasicBlock *Parent =
4631 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
4632 if (!Parent->getTerminator()->isEHPad())
4633 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4634 }
4635 }
4636 AddrMode.BaseOffs -= ConstantOffset;
4637 return false;
4638 }
4639
4640 // Save the valid addressing mode in case we can't match.
4641 ExtAddrMode BackupAddrMode = AddrMode;
4642 unsigned OldSize = AddrModeInsts.size();
4643
4644 // See if the scale and offset amount is valid for this target.
4645 AddrMode.BaseOffs += ConstantOffset;
4646 if (!cast<GEPOperator>(AddrInst)->isInBounds())
4647 AddrMode.InBounds = false;
4648
4649 // Match the base operand of the GEP.
4650 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
4651 // If it couldn't be matched, just stuff the value in a register.
4652 if (AddrMode.HasBaseReg) {
4653 AddrMode = BackupAddrMode;
4654 AddrModeInsts.resize(OldSize);
4655 return false;
4656 }
4657 AddrMode.HasBaseReg = true;
4658 AddrMode.BaseReg = AddrInst->getOperand(0);
4659 }
4660
4661 // Match the remaining variable portion of the GEP.
4662 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
4663 Depth)) {
4664 // If it couldn't be matched, try stuffing the base into a register
4665 // instead of matching it, and retrying the match of the scale.
4666 AddrMode = BackupAddrMode;
4667 AddrModeInsts.resize(OldSize);
4668 if (AddrMode.HasBaseReg)
4669 return false;
4670 AddrMode.HasBaseReg = true;
4671 AddrMode.BaseReg = AddrInst->getOperand(0);
4672 AddrMode.BaseOffs += ConstantOffset;
4673 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
4674 VariableScale, Depth)) {
4675 // If even that didn't work, bail.
4676 AddrMode = BackupAddrMode;
4677 AddrModeInsts.resize(OldSize);
4678 return false;
4679 }
4680 }
4681
4682 return true;
4683 }
4684 case Instruction::SExt:
4685 case Instruction::ZExt: {
4686 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4687 if (!Ext)
4688 return false;
4689
4690 // Try to move this ext out of the way of the addressing mode.
4691 // Ask for a method for doing so.
4692 TypePromotionHelper::Action TPH =
4693 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
4694 if (!TPH)
4695 return false;
4696
4697 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4698 TPT.getRestorationPoint();
4699 unsigned CreatedInstsCost = 0;
4700 unsigned ExtCost = !TLI.isExtFree(Ext);
4701 Value *PromotedOperand =
4702 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
4703 // SExt has been moved away.
4704 // Thus either it will be rematched later in the recursive calls or it is
4705 // gone. Anyway, we must not fold it into the addressing mode at this point.
4706 // E.g.,
4707 // op = add opnd, 1
4708 // idx = ext op
4709 // addr = gep base, idx
4710 // is now:
4711 // promotedOpnd = ext opnd <- no match here
4712 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4713 // addr = gep base, op <- match
4714 if (MovedAway)
4715 *MovedAway = true;
4716
4717 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 4718, __extension__ __PRETTY_FUNCTION__))
4718 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 4718, __extension__ __PRETTY_FUNCTION__))
;
4719
4720 ExtAddrMode BackupAddrMode = AddrMode;
4721 unsigned OldSize = AddrModeInsts.size();
4722
4723 if (!matchAddr(PromotedOperand, Depth) ||
4724 // The total of the new cost is equal to the cost of the created
4725 // instructions.
4726 // The total of the old cost is equal to the cost of the extension plus
4727 // what we have saved in the addressing mode.
4728 !isPromotionProfitable(CreatedInstsCost,
4729 ExtCost + (AddrModeInsts.size() - OldSize),
4730 PromotedOperand)) {
4731 AddrMode = BackupAddrMode;
4732 AddrModeInsts.resize(OldSize);
4733 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)
;
4734 TPT.rollback(LastKnownGood);
4735 return false;
4736 }
4737 return true;
4738 }
4739 }
4740 return false;
4741}
4742
4743/// If we can, try to add the value of 'Addr' into the current addressing mode.
4744/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4745/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4746/// for the target.
4747///
4748bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
4749 // Start a transaction at this point that we will rollback if the matching
4750 // fails.
4751 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4752 TPT.getRestorationPoint();
4753 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4754 if (CI->getValue().isSignedIntN(64)) {
4755 // Fold in immediates if legal for the target.
4756 AddrMode.BaseOffs += CI->getSExtValue();
4757 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4758 return true;
4759 AddrMode.BaseOffs -= CI->getSExtValue();
4760 }
4761 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4762 // If this is a global variable, try to fold it into the addressing mode.
4763 if (!AddrMode.BaseGV) {
4764 AddrMode.BaseGV = GV;
4765 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4766 return true;
4767 AddrMode.BaseGV = nullptr;
4768 }
4769 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4770 ExtAddrMode BackupAddrMode = AddrMode;
4771 unsigned OldSize = AddrModeInsts.size();
4772
4773 // Check to see if it is possible to fold this operation.
4774 bool MovedAway = false;
4775 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
4776 // This instruction may have been moved away. If so, there is nothing
4777 // to check here.
4778 if (MovedAway)
4779 return true;
4780 // Okay, it's possible to fold this. Check to see if it is actually
4781 // *profitable* to do so. We use a simple cost model to avoid increasing
4782 // register pressure too much.
4783 if (I->hasOneUse() ||
4784 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
4785 AddrModeInsts.push_back(I);
4786 return true;
4787 }
4788
4789 // It isn't profitable to do this, roll back.
4790 //cerr << "NOT FOLDING: " << *I;
4791 AddrMode = BackupAddrMode;
4792 AddrModeInsts.resize(OldSize);
4793 TPT.rollback(LastKnownGood);
4794 }
4795 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
4796 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
4797 return true;
4798 TPT.rollback(LastKnownGood);
4799 } else if (isa<ConstantPointerNull>(Addr)) {
4800 // Null pointer gets folded without affecting the addressing mode.
4801 return true;
4802 }
4803
4804 // Worse case, the target should support [reg] addressing modes. :)
4805 if (!AddrMode.HasBaseReg) {
4806 AddrMode.HasBaseReg = true;
4807 AddrMode.BaseReg = Addr;
4808 // Still check for legality in case the target supports [imm] but not [i+r].
4809 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4810 return true;
4811 AddrMode.HasBaseReg = false;
4812 AddrMode.BaseReg = nullptr;
4813 }
4814
4815 // If the base register is already taken, see if we can do [r+r].
4816 if (AddrMode.Scale == 0) {
4817 AddrMode.Scale = 1;
4818 AddrMode.ScaledReg = Addr;
4819 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
4820 return true;
4821 AddrMode.Scale = 0;
4822 AddrMode.ScaledReg = nullptr;
4823 }
4824 // Couldn't match.
4825 TPT.rollback(LastKnownGood);
4826 return false;
4827}
4828
4829/// Check to see if all uses of OpVal by the specified inline asm call are due
4830/// to memory operands. If so, return true, otherwise return false.
4831static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
4832 const TargetLowering &TLI,
4833 const TargetRegisterInfo &TRI) {
4834 const Function *F = CI->getFunction();
4835 TargetLowering::AsmOperandInfoVector TargetConstraints =
4836 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, *CI);
4837
4838 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4839 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
4840
4841 // Compute the constraint code and ConstraintType to use.
4842 TLI.ComputeConstraintToUse(OpInfo, SDValue());
4843
4844 // If this asm operand is our Value*, and if it isn't an indirect memory
4845 // operand, we can't fold it!
4846 if (OpInfo.CallOperandVal == OpVal &&
4847 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4848 !OpInfo.isIndirect))
4849 return false;
4850 }
4851
4852 return true;
4853}
4854
4855// Max number of memory uses to look at before aborting the search to conserve
4856// compile time.
4857static constexpr int MaxMemoryUsesToScan = 20;
4858
4859/// Recursively walk all the uses of I until we find a memory use.
4860/// If we find an obviously non-foldable instruction, return true.
4861/// Add accessed addresses and types to MemoryUses.
4862static bool FindAllMemoryUses(
4863 Instruction *I, SmallVectorImpl<std::pair<Value *, Type *>> &MemoryUses,
4864 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4865 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
4866 BlockFrequencyInfo *BFI, int SeenInsts = 0) {
4867 // If we already considered this instruction, we're done.
4868 if (!ConsideredInsts.insert(I).second)
4869 return false;
4870
4871 // If this is an obviously unfoldable instruction, bail out.
4872 if (!MightBeFoldableInst(I))
4873 return true;
4874
4875 // Loop over all the uses, recursively processing them.
4876 for (Use &U : I->uses()) {
4877 // Conservatively return true if we're seeing a large number or a deep chain
4878 // of users. This avoids excessive compilation times in pathological cases.
4879 if (SeenInsts++ >= MaxMemoryUsesToScan)
4880 return true;
4881
4882 Instruction *UserI = cast<Instruction>(U.getUser());
4883 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4884 MemoryUses.push_back({U.get(), LI->getType()});
4885 continue;
4886 }
4887
4888 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4889 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
4890 return true; // Storing addr, not into addr.
4891 MemoryUses.push_back({U.get(), SI->getValueOperand()->getType()});
4892 continue;
4893 }
4894
4895 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4896 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
4897 return true; // Storing addr, not into addr.
4898 MemoryUses.push_back({U.get(), RMW->getValOperand()->getType()});
4899 continue;
4900 }
4901
4902 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4903 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
4904 return true; // Storing addr, not into addr.
4905 MemoryUses.push_back({U.get(), CmpX->getCompareOperand()->getType()});
4906 continue;
4907 }
4908
4909 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
4910 if (CI->hasFnAttr(Attribute::Cold)) {
4911 // If this is a cold call, we can sink the addressing calculation into
4912 // the cold path. See optimizeCallInst
4913 bool OptForSize = OptSize ||
4914 llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
4915 if (!OptForSize)
4916 continue;
4917 }
4918
4919 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
4920 if (!IA) return true;
4921
4922 // If this is a memory operand, we're cool, otherwise bail out.
4923 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
4924 return true;
4925 continue;
4926 }
4927
4928 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
4929 PSI, BFI, SeenInsts))
4930 return true;
4931 }
4932
4933 return false;
4934}
4935
4936/// Return true if Val is already known to be live at the use site that we're
4937/// folding it into. If so, there is no cost to include it in the addressing
4938/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4939/// instruction already.
4940bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
4941 Value *KnownLive2) {
4942 // If Val is either of the known-live values, we know it is live!
4943 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
4944 return true;
4945
4946 // All values other than instructions and arguments (e.g. constants) are live.
4947 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
4948
4949 // If Val is a constant sized alloca in the entry block, it is live, this is
4950 // true because it is just a reference to the stack/frame pointer, which is
4951 // live for the whole function.
4952 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4953 if (AI->isStaticAlloca())
4954 return true;
4955
4956 // Check to see if this value is already used in the memory instruction's
4957 // block. If so, it's already live into the block at the very least, so we
4958 // can reasonably fold it.
4959 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4960}
4961
4962/// It is possible for the addressing mode of the machine to fold the specified
4963/// instruction into a load or store that ultimately uses it.
4964/// However, the specified instruction has multiple uses.
4965/// Given this, it may actually increase register pressure to fold it
4966/// into the load. For example, consider this code:
4967///
4968/// X = ...
4969/// Y = X+1
4970/// use(Y) -> nonload/store
4971/// Z = Y+1
4972/// load Z
4973///
4974/// In this case, Y has multiple uses, and can be folded into the load of Z
4975/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4976/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4977/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4978/// number of computations either.
4979///
4980/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4981/// X was live across 'load Z' for other reasons, we actually *would* want to
4982/// fold the addressing mode in the Z case. This would make Y die earlier.
4983bool AddressingModeMatcher::
4984isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
4985 ExtAddrMode &AMAfter) {
4986 if (IgnoreProfitability) return true;
4987
4988 // AMBefore is the addressing mode before this instruction was folded into it,
4989 // and AMAfter is the addressing mode after the instruction was folded. Get
4990 // the set of registers referenced by AMAfter and subtract out those
4991 // referenced by AMBefore: this is the set of values which folding in this
4992 // address extends the lifetime of.
4993 //
4994 // Note that there are only two potential values being referenced here,
4995 // BaseReg and ScaleReg (global addresses are always available, as are any
4996 // folded immediates).
4997 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
4998
4999 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5000 // lifetime wasn't extended by adding this instruction.
5001 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5002 BaseReg = nullptr;
5003 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
5004 ScaledReg = nullptr;
5005
5006 // If folding this instruction (and it's subexprs) didn't extend any live
5007 // ranges, we're ok with it.
5008 if (!BaseReg && !ScaledReg)
5009 return true;
5010
5011 // If all uses of this instruction can have the address mode sunk into them,
5012 // we can remove the addressing mode and effectively trade one live register
5013 // for another (at worst.) In this context, folding an addressing mode into
5014 // the use is just a particularly nice way of sinking it.
5015 SmallVector<std::pair<Value *, Type *>, 16> MemoryUses;
5016 SmallPtrSet<Instruction*, 16> ConsideredInsts;
5017 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5018 PSI, BFI))
5019 return false; // Has a non-memory, non-foldable use!
5020
5021 // Now that we know that all uses of this instruction are part of a chain of
5022 // computation involving only operations that could theoretically be folded
5023 // into a memory use, loop over each of these memory operation uses and see
5024 // if they could *actually* fold the instruction. The assumption is that
5025 // addressing modes are cheap and that duplicating the computation involved
5026 // many times is worthwhile, even on a fastpath. For sinking candidates
5027 // (i.e. cold call sites), this serves as a way to prevent excessive code
5028 // growth since most architectures have some reasonable small and fast way to
5029 // compute an effective address. (i.e LEA on x86)
5030 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
5031 for (const std::pair<Value *, Type *> &Pair : MemoryUses) {
5032 Value *Address = Pair.first;
5033 Type *AddressAccessTy = Pair.second;
5034 unsigned AS = Address->getType()->getPointerAddressSpace();
5035
5036 // Do a match against the root of this address, ignoring profitability. This
5037 // will tell us if the addressing mode for the memory operation will
5038 // *actually* cover the shared instruction.
5039 ExtAddrMode Result;
5040 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5041 0);
5042 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5043 TPT.getRestorationPoint();
5044 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5045 AddressAccessTy, AS, MemoryInst, Result,
5046 InsertedInsts, PromotedInsts, TPT,
5047 LargeOffsetGEP, OptSize, PSI, BFI);
5048 Matcher.IgnoreProfitability = true;
5049 bool Success = Matcher.matchAddr(Address, 0);
5050 (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*?\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 5050, __extension__ __PRETTY_FUNCTION__))
;
5051
5052 // The match was to check the profitability, the changes made are not
5053 // part of the original matcher. Therefore, they should be dropped
5054 // otherwise the original matcher will not present the right state.
5055 TPT.rollback(LastKnownGood);
5056
5057 // If the match didn't cover I, then it won't be shared by it.
5058 if (!is_contained(MatchedAddrModeInsts, I))
5059 return false;
5060
5061 MatchedAddrModeInsts.clear();
5062 }
5063
5064 return true;
5065}
5066
5067/// Return true if the specified values are defined in a
5068/// different basic block than BB.
5069static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5070 if (Instruction *I = dyn_cast<Instruction>(V))
5071 return I->getParent() != BB;
5072 return false;
5073}
5074
5075/// Sink addressing mode computation immediate before MemoryInst if doing so
5076/// can be done without increasing register pressure. The need for the
5077/// register pressure constraint means this can end up being an all or nothing
5078/// decision for all uses of the same addressing computation.
5079///
5080/// Load and Store Instructions often have addressing modes that can do
5081/// significant amounts of computation. As such, instruction selection will try
5082/// to get the load or store to do as much computation as possible for the
5083/// program. The problem is that isel can only see within a single block. As
5084/// such, we sink as much legal addressing mode work into the block as possible.
5085///
5086/// This method is used to optimize both load/store and inline asms with memory
5087/// operands. It's also used to sink addressing computations feeding into cold
5088/// call sites into their (cold) basic block.
5089///
5090/// The motivation for handling sinking into cold blocks is that doing so can
5091/// both enable other address mode sinking (by satisfying the register pressure
5092/// constraint above), and reduce register pressure globally (by removing the
5093/// addressing mode computation from the fast path entirely.).
5094bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5095 Type *AccessTy, unsigned AddrSpace) {
5096 Value *Repl = Addr;
5097
5098 // Try to collapse single-value PHI nodes. This is necessary to undo
5099 // unprofitable PRE transformations.
5100 SmallVector<Value*, 8> worklist;
5101 SmallPtrSet<Value*, 16> Visited;
5102 worklist.push_back(Addr);
5103
5104 // Use a worklist to iteratively look through PHI and select nodes, and
5105 // ensure that the addressing mode obtained from the non-PHI/select roots of
5106 // the graph are compatible.
5107 bool PhiOrSelectSeen = false;
5108 SmallVector<Instruction*, 16> AddrModeInsts;
5109 const SimplifyQuery SQ(*DL, TLInfo);
5110 AddressingModeCombiner AddrModes(SQ, Addr);
5111 TypePromotionTransaction TPT(RemovedInsts);
5112 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5113 TPT.getRestorationPoint();
5114 while (!worklist.empty()) {
5115 Value *V = worklist.pop_back_val();
5116
5117 // We allow traversing cyclic Phi nodes.
5118 // In case of success after this loop we ensure that traversing through
5119 // Phi nodes ends up with all cases to compute address of the form
5120 // BaseGV + Base + Scale * Index + Offset
5121 // where Scale and Offset are constans and BaseGV, Base and Index
5122 // are exactly the same Values in all cases.
5123 // It means that BaseGV, Scale and Offset dominate our memory instruction
5124 // and have the same value as they had in address computation represented
5125 // as Phi. So we can safely sink address computation to memory instruction.
5126 if (!Visited.insert(V).second)
5127 continue;
5128
5129 // For a PHI node, push all of its incoming values.
5130 if (PHINode *P = dyn_cast<PHINode>(V)) {
5131 append_range(worklist, P->incoming_values());
5132 PhiOrSelectSeen = true;
5133 continue;
5134 }
5135 // Similar for select.
5136 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
5137 worklist.push_back(SI->getFalseValue());
5138 worklist.push_back(SI->getTrueValue());
5139 PhiOrSelectSeen = true;
5140 continue;
5141 }
5142
5143 // For non-PHIs, determine the addressing mode being computed. Note that
5144 // the result may differ depending on what other uses our candidate
5145 // addressing instructions might have.
5146 AddrModeInsts.clear();
5147 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5148 0);
5149 // Defer the query (and possible computation of) the dom tree to point of
5150 // actual use. It's expected that most address matches don't actually need
5151 // the domtree.
5152 auto getDTFn = [MemoryInst, this]() -> const DominatorTree & {
5153 Function *F = MemoryInst->getParent()->getParent();
5154 return this->getDT(*F);
5155 };
5156 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5157 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
5158 *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5159 BFI.get());
5160
5161 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5162 if (GEP && !NewGEPBases.count(GEP)) {
5163 // If splitting the underlying data structure can reduce the offset of a
5164 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5165 // previously split data structures.
5166 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
5167 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
5168 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
5169 }
5170
5171 NewAddrMode.OriginalValue = V;
5172 if (!AddrModes.addNewAddrMode(NewAddrMode))
5173 break;
5174 }
5175
5176 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5177 // or we have multiple but either couldn't combine them or combining them
5178 // wouldn't do anything useful, bail out now.
5179 if (!AddrModes.combineAddrModes()) {
5180 TPT.rollback(LastKnownGood);
5181 return false;
5182 }
5183 bool Modified = TPT.commit();
5184
5185 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5186 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5187
5188 // If all the instructions matched are already in this BB, don't do anything.
5189 // If we saw a Phi node then it is not local definitely, and if we saw a select
5190 // then we want to push the address calculation past it even if it's already
5191 // in this BB.
5192 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
5193 return IsNonLocalValue(V, MemoryInst->getParent());
5194 })) {
5195 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrModedo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: Found local addrmode: "
<< AddrMode << "\n"; } } while (false)
5196 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: Found local addrmode: "
<< AddrMode << "\n"; } } while (false)
;
5197 return Modified;
5198 }
5199
5200 // Insert this computation right after this user. Since our caller is
5201 // scanning from the top of the BB to the bottom, reuse of the expr are
5202 // guaranteed to happen later.
5203 IRBuilder<> Builder(MemoryInst);
5204
5205 // Now that we determined the addressing expression we want to use and know
5206 // that we have to sink it into this block. Check to see if we have already
5207 // done this for some other load/store instr in this block. If so, reuse
5208 // the computation. Before attempting reuse, check if the address is valid
5209 // as it may have been erased.
5210
5211 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5212
5213 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
5214 if (SunkAddr) {
5215 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)
5216 << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: Reusing nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
;
5217 if (SunkAddr->getType() != Addr->getType())
5218 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
5219 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
5220 SubtargetInfo->addrSinkUsingGEPs())) {
5221 // By default, we use the GEP-based method when AA is used later. This
5222 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
5223 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)
5224 << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
;
5225 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5226 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
5227
5228 // First, find the pointer.
5229 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
5230 ResultPtr = AddrMode.BaseReg;
5231 AddrMode.BaseReg = nullptr;
5232 }
5233
5234 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
5235 // We can't add more than one pointer together, nor can we scale a
5236 // pointer (both of which seem meaningless).
5237 if (ResultPtr || AddrMode.Scale != 1)
5238 return Modified;
5239
5240 ResultPtr = AddrMode.ScaledReg;
5241 AddrMode.Scale = 0;
5242 }
5243
5244 // It is only safe to sign extend the BaseReg if we know that the math
5245 // required to create it did not overflow before we extend it. Since
5246 // the original IR value was tossed in favor of a constant back when
5247 // the AddrMode was created we need to bail out gracefully if widths
5248 // do not match instead of extending it.
5249 //
5250 // (See below for code to add the scale.)
5251 if (AddrMode.Scale) {
5252 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
5253 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
5254 cast<IntegerType>(ScaledRegTy)->getBitWidth())
5255 return Modified;
5256 }
5257
5258 if (AddrMode.BaseGV) {
5259 if (ResultPtr)
5260 return Modified;
5261
5262 ResultPtr = AddrMode.BaseGV;
5263 }
5264
5265 // If the real base value actually came from an inttoptr, then the matcher
5266 // will look through it and provide only the integer value. In that case,
5267 // use it here.
5268 if (!DL->isNonIntegralPointerType(Addr->getType())) {
5269 if (!ResultPtr && AddrMode.BaseReg) {
5270 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
5271 "sunkaddr");
5272 AddrMode.BaseReg = nullptr;
5273 } else if (!ResultPtr && AddrMode.Scale == 1) {
5274 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
5275 "sunkaddr");
5276 AddrMode.Scale = 0;
5277 }
5278 }
5279
5280 if (!ResultPtr &&
5281 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
5282 SunkAddr = Constant::getNullValue(Addr->getType());
5283 } else if (!ResultPtr) {
5284 return Modified;
5285 } else {
5286 Type *I8PtrTy =
5287 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
5288 Type *I8Ty = Builder.getInt8Ty();
5289
5290 // Start with the base register. Do this first so that subsequent address
5291 // matching finds it last, which will prevent it from trying to match it
5292 // as the scaled value in case it happens to be a mul. That would be
5293 // problematic if we've sunk a different mul for the scale, because then
5294 // we'd end up sinking both muls.
5295 if (AddrMode.BaseReg) {
5296 Value *V = AddrMode.BaseReg;
5297 if (V->getType() != IntPtrTy)
5298 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
5299
5300 ResultIndex = V;
5301 }
5302
5303 // Add the scale value.
5304 if (AddrMode.Scale) {
5305 Value *V = AddrMode.ScaledReg;
5306 if (V->getType() == IntPtrTy) {
5307 // done.
5308 } else {
5309 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 5311, __extension__ __PRETTY_FUNCTION__))
5310 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 5311, __extension__ __PRETTY_FUNCTION__))
5311 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 5311, __extension__ __PRETTY_FUNCTION__))
;
5312 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
5313 }
5314
5315 if (AddrMode.Scale != 1)
5316 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
5317 "sunkaddr");
5318 if (ResultIndex)
5319 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
5320 else
5321 ResultIndex = V;
5322 }
5323
5324 // Add in the Base Offset if present.
5325 if (AddrMode.BaseOffs) {
5326 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
5327 if (ResultIndex) {
5328 // We need to add this separately from the scale above to help with
5329 // SDAG consecutive load/store merging.
5330 if (ResultPtr->getType() != I8PtrTy)
5331 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
5332 ResultPtr =
5333 AddrMode.InBounds
5334 ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
5335 "sunkaddr")
5336 : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
5337 }
5338
5339 ResultIndex = V;
5340 }
5341
5342 if (!ResultIndex) {
5343 SunkAddr = ResultPtr;
5344 } else {
5345 if (ResultPtr->getType() != I8PtrTy)
5346 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
5347 SunkAddr =
5348 AddrMode.InBounds
5349 ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
5350 "sunkaddr")
5351 : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
5352 }
5353
5354 if (SunkAddr->getType() != Addr->getType())
5355 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
5356 }
5357 } else {
5358 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
5359 // non-integral pointers, so in that case bail out now.
5360 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
5361 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
5362 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
5363 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
5364 if (DL->isNonIntegralPointerType(Addr->getType()) ||
5365 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
5366 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
5367 (AddrMode.BaseGV &&
5368 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
5369 return Modified;
5370
5371 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)
5372 << " for " << *MemoryInst << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("codegenprepare")) { dbgs() << "CGP: SINKING nonlocal addrmode: "
<< AddrMode << " for " << *MemoryInst <<
"\n"; } } while (false)
;
5373 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5374 Value *Result = nullptr;
5375
5376 // Start with the base register. Do this first so that subsequent address
5377 // matching finds it last, which will prevent it from trying to match it
5378 // as the scaled value in case it happens to be a mul. That would be
5379 // problematic if we've sunk a different mul for the scale, because then
5380 // we'd end up sinking both muls.
5381 if (AddrMode.BaseReg) {
5382 Value *V = AddrMode.BaseReg;
5383 if (V->getType()->isPointerTy())
5384 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
5385 if (V->getType() != IntPtrTy)
5386 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
5387 Result = V;
5388 }
5389
5390 // Add the scale value.
5391 if (AddrMode.Scale) {
5392 Value *V = AddrMode.ScaledReg;
5393 if (V->getType() == IntPtrTy) {
5394 // done.
5395 } else if (V->getType()->isPointerTy()) {
5396 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
5397 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
5398 cast<IntegerType>(V->getType())->getBitWidth()) {
5399 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
5400 } else {
5401 // It is only safe to sign extend the BaseReg if we know that the math
5402 // required to create it did not overflow before we extend it. Since
5403 // the original IR value was tossed in favor of a constant back when
5404 // the AddrMode was created we need to bail out gracefully if widths
5405 // do not match instead of extending it.
5406 Instruction *I = dyn_cast_or_null<Instruction>(Result);
5407 if (I && (Result != AddrMode.BaseReg))
5408 I->eraseFromParent();
5409 return Modified;
5410 }
5411 if (AddrMode.Scale != 1)
5412 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
5413 "sunkaddr");
5414 if (Result)
5415 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5416 else
5417 Result = V;
5418 }
5419
5420 // Add in the BaseGV if present.
5421 if (AddrMode.BaseGV) {
5422 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
5423 if (Result)
5424 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5425 else
5426 Result = V;
5427 }
5428
5429 // Add in the Base Offset if present.
5430 if (AddrMode.BaseOffs) {
5431 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
5432 if (Result)
5433 Result = Builder.CreateAdd(Result, V, "sunkaddr");
5434 else
5435 Result = V;
5436 }
5437
5438 if (!Result)
5439 SunkAddr = Constant::getNullValue(Addr->getType());
5440 else
5441 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
5442 }
5443
5444 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
5445 // Store the newly computed address into the cache. In the case we reused a
5446 // value, this should be idempotent.
5447 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
5448
5449 // If we have no uses, recursively delete the value and all dead instructions
5450 // using it.
5451 if (Repl->use_empty()) {
5452 resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
5453 RecursivelyDeleteTriviallyDeadInstructions(
5454 Repl, TLInfo, nullptr,
5455 [&](Value *V) { removeAllAssertingVHReferences(V); });
5456 });
5457 }
5458 ++NumMemoryInsts;
5459 return true;
5460}
5461
5462/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
5463/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
5464/// only handle a 2 operand GEP in the same basic block or a splat constant
5465/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
5466/// index.
5467///
5468/// If the existing GEP has a vector base pointer that is splat, we can look
5469/// through the splat to find the scalar pointer. If we can't find a scalar
5470/// pointer there's nothing we can do.
5471///
5472/// If we have a GEP with more than 2 indices where the middle indices are all
5473/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
5474///
5475/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
5476/// followed by a GEP with an all zeroes vector index. This will enable
5477/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
5478/// zero index.
5479bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
5480 Value *Ptr) {
5481 Value *NewAddr;
5482
5483 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
5484 // Don't optimize GEPs that don't have indices.
5485 if (!GEP->hasIndices())
5486 return false;
5487
5488 // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
5489 // FIXME: We should support this by sinking the GEP.
5490 if (MemoryInst->getParent() != GEP->getParent())
5491 return false;
5492
5493 SmallVector<Value *, 2> Ops(GEP->operands());
5494
5495 bool RewriteGEP = false;
5496
5497 if (Ops[0]->getType()->isVectorTy()) {
5498 Ops[0] = getSplatValue(Ops[0]);
5499 if (!Ops[0])
5500 return false;
5501 RewriteGEP = true;
5502 }
5503
5504 unsigned FinalIndex = Ops.size() - 1;
5505
5506 // Ensure all but the last index is 0.
5507 // FIXME: This isn't strictly required. All that's required is that they are
5508 // all scalars or splats.
5509 for (unsigned i = 1; i < FinalIndex; ++i) {
5510 auto *C = dyn_cast<Constant>(Ops[i]);
5511 if (!C)
5512 return false;
5513 if (isa<VectorType>(C->getType()))
5514 C = C->getSplatValue();
5515 auto *CI = dyn_cast_or_null<ConstantInt>(C);
5516 if (!CI || !CI->isZero())
5517 return false;
5518 // Scalarize the index if needed.
5519 Ops[i] = CI;
5520 }
5521
5522 // Try to scalarize the final index.
5523 if (Ops[FinalIndex]->getType()->isVectorTy()) {
5524 if (Value *V = getSplatValue(Ops[FinalIndex])) {
5525 auto *C = dyn_cast<ConstantInt>(V);
5526 // Don't scalarize all zeros vector.
5527 if (!C || !C->isZero()) {
5528 Ops[FinalIndex] = V;
5529 RewriteGEP = true;
5530 }
5531 }
5532 }
5533
5534 // If we made any changes or the we have extra operands, we need to generate
5535 // new instructions.
5536 if (!RewriteGEP && Ops.size() == 2)
5537 return false;
5538
5539 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5540
5541 IRBuilder<> Builder(MemoryInst);
5542
5543 Type *SourceTy = GEP->getSourceElementType();
5544 Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType());
5545
5546 // If the final index isn't a vector, emit a scalar GEP containing all ops
5547 // and a vector GEP with all zeroes final index.
5548 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
5549 NewAddr = Builder.CreateGEP(SourceTy, Ops[0],
5550 makeArrayRef(Ops).drop_front());
5551 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
5552 auto *SecondTy = GetElementPtrInst::getIndexedType(
5553 SourceTy, makeArrayRef(Ops).drop_front());
5554 NewAddr =
5555 Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy));
5556 } else {
5557 Value *Base = Ops[0];
5558 Value *Index = Ops[FinalIndex];
5559
5560 // Create a scalar GEP if there are more than 2 operands.
5561 if (Ops.size() != 2) {
5562 // Replace the last index with 0.
5563 Ops[FinalIndex] = Constant::getNullValue(ScalarIndexTy);
5564 Base = Builder.CreateGEP(SourceTy, Base,
5565 makeArrayRef(Ops).drop_front());
5566 SourceTy = GetElementPtrInst::getIndexedType(
5567 SourceTy, makeArrayRef(Ops).drop_front());
5568 }
5569
5570 // Now create the GEP with scalar pointer and vector index.
5571 NewAddr = Builder.CreateGEP(SourceTy, Base, Index);
5572 }
5573 } else if (!isa<Constant>(Ptr)) {
5574 // Not a GEP, maybe its a splat and we can create a GEP to enable
5575 // SelectionDAGBuilder to use it as a uniform base.
5576 Value *V = getSplatValue(Ptr);
5577 if (!V)
5578 return false;
5579
5580 auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
5581
5582 IRBuilder<> Builder(MemoryInst);
5583
5584 // Emit a vector GEP with a scalar pointer and all 0s vector index.
5585 Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType());
5586 auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
5587 Type *ScalarTy;
5588 if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
5589 Intrinsic::masked_gather) {
5590 ScalarTy = MemoryInst->getType()->getScalarType();
5591 } else {
5592 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"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 5593, __extension__ __PRETTY_FUNCTION__))
5593 Intrinsic::masked_scatter)(static_cast <bool> (cast<IntrinsicInst>(MemoryInst
)->getIntrinsicID() == Intrinsic::masked_scatter) ? void (
0) : __assert_fail ("cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() == Intrinsic::masked_scatter"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 5593, __extension__ __PRETTY_FUNCTION__))
;
5594 ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType();
5595 }
5596 NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy));
5597 } else {
5598 // Constant, SelectionDAGBuilder knows to check if its a splat.
5599 return false;
5600 }
5601
5602 MemoryInst->replaceUsesOfWith(Ptr, NewAddr);
5603
5604 // If we have no uses, recursively delete the value and all dead instructions
5605 // using it.
5606 if (Ptr->use_empty())
5607 RecursivelyDeleteTriviallyDeadInstructions(
5608 Ptr, TLInfo, nullptr,
5609 [&](Value *V) { removeAllAssertingVHReferences(V); });
5610
5611 return true;
5612}
5613
5614/// If there are any memory operands, use OptimizeMemoryInst to sink their
5615/// address computing into the block when possible / profitable.
5616bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
5617 bool MadeChange = false;
5618
5619 const TargetRegisterInfo *TRI =
5620 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
5621 TargetLowering::AsmOperandInfoVector TargetConstraints =
5622 TLI->ParseConstraints(*DL, TRI, *CS);
5623 unsigned ArgNo = 0;
5624 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5625 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
5626
5627 // Compute the constraint code and ConstraintType to use.
5628 TLI->ComputeConstraintToUse(OpInfo, SDValue());
5629
5630 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5631 OpInfo.isIndirect) {
5632 Value *OpVal = CS->getArgOperand(ArgNo++);
5633 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
5634 } else if (OpInfo.Type == InlineAsm::isInput)
5635 ArgNo++;
5636 }
5637
5638 return MadeChange;
5639}
5640
5641/// Check if all the uses of \p Val are equivalent (or free) zero or
5642/// sign extensions.
5643static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
5644 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 5644, __extension__ __PRETTY_FUNCTION__))
;
5645 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
5646 bool IsSExt = isa<SExtInst>(FirstUser);
5647 Type *ExtTy = FirstUser->getType();
5648 for (const User *U : Val->users()) {
5649 const Instruction *UI = cast<Instruction>(U);
5650 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
5651 return false;
5652 Type *CurTy = UI->getType();
5653 // Same input and output types: Same instruction after CSE.
5654 if (CurTy == ExtTy)
5655 continue;
5656
5657 // If IsSExt is true, we are in this situation:
5658 // a = Val
5659 // b = sext ty1 a to ty2
5660 // c = sext ty1 a to ty3
5661 // Assuming ty2 is shorter than ty3, this could be turned into:
5662 // a = Val
5663 // b = sext ty1 a to ty2
5664 // c = sext ty2 b to ty3
5665 // However, the last sext is not free.
5666 if (IsSExt)
5667 return false;
5668
5669 // This is a ZExt, maybe this is free to extend from one type to another.
5670 // In that case, we would not account for a different use.
5671 Type *NarrowTy;
5672 Type *LargeTy;
5673 if (ExtTy->getScalarType()->getIntegerBitWidth() >
5674 CurTy->getScalarType()->getIntegerBitWidth()) {
5675 NarrowTy = CurTy;
5676 LargeTy = ExtTy;
5677 } else {
5678 NarrowTy = ExtTy;
5679 LargeTy = CurTy;
5680 }
5681
5682 if (!TLI.isZExtFree(NarrowTy, LargeTy))
5683 return false;
5684 }
5685 // All uses are the same or can be derived from one another for free.
5686 return true;
5687}
5688
5689/// Try to speculatively promote extensions in \p Exts and continue
5690/// promoting through newly promoted operands recursively as far as doing so is
5691/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
5692/// When some promotion happened, \p TPT contains the proper state to revert
5693/// them.
5694///
5695/// \return true if some promotion happened, false otherwise.
5696bool CodeGenPrepare::tryToPromoteExts(
5697 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
5698 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
5699 unsigned CreatedInstsCost) {
5700 bool Promoted = false;
5701
5702 // Iterate over all the extensions to try to promote them.
5703 for (auto *I : Exts) {
5704 // Early check if we directly have ext(load).
5705 if (isa<LoadInst>(I->getOperand(0))) {
5706 ProfitablyMovedExts.push_back(I);
5707 continue;
5708 }
5709
5710 // Check whether or not we want to do any promotion. The reason we have
5711 // this check inside the for loop is to catch the case where an extension
5712 // is directly fed by a load because in such case the extension can be moved
5713 // up without any promotion on its operands.
5714 if (!TLI->enableExtLdPromotion() || DisableExtLdPromotion)
5715 return false;
5716
5717 // Get the action to perform the promotion.
5718 TypePromotionHelper::Action TPH =
5719 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
5720 // Check if we can promote.
5721 if (!TPH) {
5722 // Save the current extension as we cannot move up through its operand.
5723 ProfitablyMovedExts.push_back(I);
5724 continue;
5725 }
5726
5727 // Save the current state.
5728 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5729 TPT.getRestorationPoint();
5730 SmallVector<Instruction *, 4> NewExts;
5731 unsigned NewCreatedInstsCost = 0;
5732 unsigned ExtCost = !TLI->isExtFree(I);
5733 // Promote.
5734 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
5735 &NewExts, nullptr, *TLI);
5736 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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 5737, __extension__ __PRETTY_FUNCTION__))
5737 "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\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/CodeGen/CodeGenPrepare.cpp"
, 5737, __extension__ __PRETTY_FUNCTION__))
;
5738
5739 // We would be able to merge only one extension in a load.
5740 // Therefore, if we have more than 1 new extension we heuristically
5741 // cut this search path, because it means we degrade the code quality.
5742 // With exactly 2, the transformation is neutral, because we will merge
5743 // one extension but leave one. However, we optimistically keep going,
5744 // because the new extension may be removed too.
5745 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
5746 // FIXME: It would be possible to propagate a negative value instead of
5747 // conservatively ceiling it to 0.
5748 TotalCreatedInstsCost =
5749 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
5750 if (!StressExtLdPromotion &&
5751 (TotalCreatedInstsCost > 1 ||
5752 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
5753 // This promotion is not profitable, rollback to the previous state, and
5754 // save the current extension in ProfitablyMovedExts as the latest
5755 // speculative promotion turned out to be unprofitable.
5756 TPT.rollback(LastKnownGood);
5757 ProfitablyMovedExts.push_back(I);
5758 continue;
5759 }
5760 // Continue promoting NewExts as far as doing so is profitable.
5761 SmallVector<Instruction *, 2> NewlyMovedExts;
5762 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
5763 bool NewPromoted = false;
5764 for (auto *ExtInst : NewlyMovedExts) {
5765 Instruction *MovedExt = cast<Instruction>(ExtInst);
5766 Value *ExtOperand = MovedExt->getOperand(0);
5767 // If we have reached to a load, we need this extra profitability check
5768 // as it could potentially be merged into an ext(load).
5769 if (isa<LoadInst>(ExtOperand) &&
5770 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5771 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
5772 continue;
5773