Bug Summary

File:build/source/llvm/lib/CodeGen/CodeGenPrepare.cpp
Warning:line 2468, 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 -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name CodeGenPrepare.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/CodeGen -I /build/source/llvm/lib/CodeGen -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1679915782 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-03-27-130437-16335-1 -x c++ /build/source/llvm/lib/CodeGen/CodeGenPrepare.cpp

/build/source/llvm/lib/CodeGen/CodeGenPrepare.cpp

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