Bug Summary

File:llvm/lib/CodeGen/CodeGenPrepare.cpp
Warning:line 2336, 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 -fhalf-no-semantic-interposition -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-13~++20210308111132+66e3a4abe99c/build-llvm/lib/CodeGen -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/build-llvm/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2021-03-08-182450-10039-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210308111132+66e3a4abe99c/llvm/lib/CodeGen/CodeGenPrepare.cpp

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