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/CodeGen/CodeGenPrepare.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/PointerIntPair.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/Statistic.h"
25#include "llvm/Analysis/BlockFrequencyInfo.h"
26#include "llvm/Analysis/BranchProbabilityInfo.h"
27#include "llvm/Analysis/DomTreeUpdater.h"
28#include "llvm/Analysis/FloatingPointPredicateUtils.h"
29#include "llvm/Analysis/InstructionSimplify.h"
30#include "llvm/Analysis/LoopInfo.h"
31#include "llvm/Analysis/ProfileSummaryInfo.h"
32#include "llvm/Analysis/ScalarEvolutionExpressions.h"
33#include "llvm/Analysis/TargetLibraryInfo.h"
34#include "llvm/Analysis/TargetTransformInfo.h"
35#include "llvm/Analysis/ValueTracking.h"
36#include "llvm/Analysis/VectorUtils.h"
37#include "llvm/CodeGen/Analysis.h"
38#include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
39#include "llvm/CodeGen/ISDOpcodes.h"
40#include "llvm/CodeGen/SelectionDAGNodes.h"
41#include "llvm/CodeGen/TargetLowering.h"
42#include "llvm/CodeGen/TargetPassConfig.h"
43#include "llvm/CodeGen/TargetSubtargetInfo.h"
44#include "llvm/CodeGen/ValueTypes.h"
45#include "llvm/CodeGenTypes/MachineValueType.h"
46#include "llvm/Config/llvm-config.h"
47#include "llvm/IR/Argument.h"
48#include "llvm/IR/Attributes.h"
49#include "llvm/IR/BasicBlock.h"
50#include "llvm/IR/CFG.h"
51#include "llvm/IR/Constant.h"
52#include "llvm/IR/Constants.h"
53#include "llvm/IR/DataLayout.h"
54#include "llvm/IR/DebugInfo.h"
55#include "llvm/IR/DerivedTypes.h"
56#include "llvm/IR/Dominators.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/GetElementPtrTypeIterator.h"
59#include "llvm/IR/GlobalValue.h"
60#include "llvm/IR/GlobalVariable.h"
61#include "llvm/IR/IRBuilder.h"
62#include "llvm/IR/InlineAsm.h"
63#include "llvm/IR/InstrTypes.h"
64#include "llvm/IR/Instruction.h"
65#include "llvm/IR/Instructions.h"
66#include "llvm/IR/IntrinsicInst.h"
67#include "llvm/IR/Intrinsics.h"
68#include "llvm/IR/IntrinsicsAArch64.h"
69#include "llvm/IR/LLVMContext.h"
70#include "llvm/IR/MDBuilder.h"
71#include "llvm/IR/Module.h"
72#include "llvm/IR/Operator.h"
73#include "llvm/IR/PatternMatch.h"
74#include "llvm/IR/ProfDataUtils.h"
75#include "llvm/IR/Statepoint.h"
76#include "llvm/IR/Type.h"
77#include "llvm/IR/Use.h"
78#include "llvm/IR/User.h"
79#include "llvm/IR/Value.h"
80#include "llvm/IR/ValueHandle.h"
81#include "llvm/IR/ValueMap.h"
82#include "llvm/InitializePasses.h"
83#include "llvm/Pass.h"
84#include "llvm/Support/BlockFrequency.h"
85#include "llvm/Support/BranchProbability.h"
86#include "llvm/Support/Casting.h"
87#include "llvm/Support/CommandLine.h"
88#include "llvm/Support/Compiler.h"
89#include "llvm/Support/Debug.h"
90#include "llvm/Support/ErrorHandling.h"
91#include "llvm/Support/raw_ostream.h"
92#include "llvm/Target/TargetMachine.h"
93#include "llvm/Target/TargetOptions.h"
94#include "llvm/Transforms/Utils/BasicBlockUtils.h"
95#include "llvm/Transforms/Utils/BypassSlowDivision.h"
96#include "llvm/Transforms/Utils/Local.h"
97#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
98#include "llvm/Transforms/Utils/SizeOpts.h"
99#include <algorithm>
100#include <cassert>
101#include <cstdint>
102#include <iterator>
103#include <limits>
104#include <memory>
105#include <optional>
106#include <utility>
107#include <vector>
108
109using namespace llvm;
110using namespace llvm::PatternMatch;
111
112#define DEBUG_TYPE "codegenprepare"
113
114STATISTIC(NumBlocksElim, "Number of blocks eliminated");
115STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
116STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
117STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
118 "sunken Cmps");
119STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
120 "of sunken Casts");
121STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
122 "computations were sunk");
123STATISTIC(NumMemoryInstsPhiCreated,
124 "Number of phis created when address "
125 "computations were sunk to memory instructions");
126STATISTIC(NumMemoryInstsSelectCreated,
127 "Number of select created when address "
128 "computations were sunk to memory instructions");
129STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
130STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
131STATISTIC(NumAndsAdded,
132 "Number of and mask instructions added to form ext loads");
133STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
134STATISTIC(NumRetsDup, "Number of return instructions duplicated");
135STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
136STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
137STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
138
139static cl::opt<bool> DisableBranchOpts(
140 "disable-cgp-branch-opts", cl::Hidden, cl::init(Val: false),
141 cl::desc("Disable branch optimizations in CodeGenPrepare"));
142
143static cl::opt<bool>
144 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(Val: false),
145 cl::desc("Disable GC optimizations in CodeGenPrepare"));
146
147static cl::opt<bool>
148 DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden,
149 cl::init(Val: false),
150 cl::desc("Disable select to branch conversion."));
151
152static cl::opt<bool>
153 AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(Val: true),
154 cl::desc("Address sinking in CGP using GEPs."));
155
156static cl::opt<bool>
157 EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(Val: true),
158 cl::desc("Enable sinking and/cmp into branches."));
159
160static cl::opt<bool> DisableStoreExtract(
161 "disable-cgp-store-extract", cl::Hidden, cl::init(Val: false),
162 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
163
164static cl::opt<bool> StressStoreExtract(
165 "stress-cgp-store-extract", cl::Hidden, cl::init(Val: false),
166 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
167
168static cl::opt<bool> DisableExtLdPromotion(
169 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(Val: false),
170 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
171 "CodeGenPrepare"));
172
173static cl::opt<bool> StressExtLdPromotion(
174 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(Val: false),
175 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
176 "optimization in CodeGenPrepare"));
177
178static cl::opt<bool> DisablePreheaderProtect(
179 "disable-preheader-prot", cl::Hidden, cl::init(Val: false),
180 cl::desc("Disable protection against removing loop preheaders"));
181
182static cl::opt<bool> ProfileGuidedSectionPrefix(
183 "profile-guided-section-prefix", cl::Hidden, cl::init(Val: true),
184 cl::desc("Use profile info to add section prefix for hot/cold functions"));
185
186static cl::opt<bool> ProfileUnknownInSpecialSection(
187 "profile-unknown-in-special-section", cl::Hidden,
188 cl::desc("In profiling mode like sampleFDO, if a function doesn't have "
189 "profile, we cannot tell the function is cold for sure because "
190 "it may be a function newly added without ever being sampled. "
191 "With the flag enabled, compiler can put such profile unknown "
192 "functions into a special section, so runtime system can choose "
193 "to handle it in a different way than .text section, to save "
194 "RAM for example. "));
195
196static cl::opt<bool> BBSectionsGuidedSectionPrefix(
197 "bbsections-guided-section-prefix", cl::Hidden, cl::init(Val: true),
198 cl::desc("Use the basic-block-sections profile to determine the text "
199 "section prefix for hot functions. Functions with "
200 "basic-block-sections profile will be placed in `.text.hot` "
201 "regardless of their FDO profile info. Other functions won't be "
202 "impacted, i.e., their prefixes will be decided by FDO/sampleFDO "
203 "profiles."));
204
205static cl::opt<uint64_t> FreqRatioToSkipMerge(
206 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(Val: 2),
207 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
208 "(frequency of destination block) is greater than this ratio"));
209
210static cl::opt<bool> ForceSplitStore(
211 "force-split-store", cl::Hidden, cl::init(Val: false),
212 cl::desc("Force store splitting no matter what the target query says."));
213
214static cl::opt<bool> EnableTypePromotionMerge(
215 "cgp-type-promotion-merge", cl::Hidden,
216 cl::desc("Enable merging of redundant sexts when one is dominating"
217 " the other."),
218 cl::init(Val: true));
219
220static cl::opt<bool> DisableComplexAddrModes(
221 "disable-complex-addr-modes", cl::Hidden, cl::init(Val: false),
222 cl::desc("Disables combining addressing modes with different parts "
223 "in optimizeMemoryInst."));
224
225static cl::opt<bool>
226 AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(Val: false),
227 cl::desc("Allow creation of Phis in Address sinking."));
228
229static cl::opt<bool> AddrSinkNewSelects(
230 "addr-sink-new-select", cl::Hidden, cl::init(Val: true),
231 cl::desc("Allow creation of selects in Address sinking."));
232
233static cl::opt<bool> AddrSinkCombineBaseReg(
234 "addr-sink-combine-base-reg", cl::Hidden, cl::init(Val: true),
235 cl::desc("Allow combining of BaseReg field in Address sinking."));
236
237static cl::opt<bool> AddrSinkCombineBaseGV(
238 "addr-sink-combine-base-gv", cl::Hidden, cl::init(Val: true),
239 cl::desc("Allow combining of BaseGV field in Address sinking."));
240
241static cl::opt<bool> AddrSinkCombineBaseOffs(
242 "addr-sink-combine-base-offs", cl::Hidden, cl::init(Val: true),
243 cl::desc("Allow combining of BaseOffs field in Address sinking."));
244
245static cl::opt<bool> AddrSinkCombineScaledReg(
246 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(Val: true),
247 cl::desc("Allow combining of ScaledReg field in Address sinking."));
248
249static cl::opt<bool>
250 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
251 cl::init(Val: true),
252 cl::desc("Enable splitting large offset of GEP."));
253
254static cl::opt<bool> EnableICMP_EQToICMP_ST(
255 "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(Val: false),
256 cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
257
258static cl::opt<bool>
259 VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(Val: false),
260 cl::desc("Enable BFI update verification for "
261 "CodeGenPrepare."));
262
263static cl::opt<bool>
264 OptimizePhiTypes("cgp-optimize-phi-types", cl::Hidden, cl::init(Val: true),
265 cl::desc("Enable converting phi types in CodeGenPrepare"));
266
267static cl::opt<unsigned>
268 HugeFuncThresholdInCGPP("cgpp-huge-func", cl::init(Val: 10000), cl::Hidden,
269 cl::desc("Least BB number of huge function."));
270
271static cl::opt<unsigned>
272 MaxAddressUsersToScan("cgp-max-address-users-to-scan", cl::init(Val: 100),
273 cl::Hidden,
274 cl::desc("Max number of address users to look at"));
275
276static cl::opt<bool>
277 DisableDeletePHIs("disable-cgp-delete-phis", cl::Hidden, cl::init(Val: false),
278 cl::desc("Disable elimination of dead PHI nodes."));
279
280namespace {
281
282enum ExtType {
283 ZeroExtension, // Zero extension has been seen.
284 SignExtension, // Sign extension has been seen.
285 BothExtension // This extension type is used if we saw sext after
286 // ZeroExtension had been set, or if we saw zext after
287 // SignExtension had been set. It makes the type
288 // information of a promoted instruction invalid.
289};
290
291enum ModifyDT {
292 NotModifyDT, // Not Modify any DT.
293 ModifyBBDT, // Modify the Basic Block Dominator Tree.
294 ModifyInstDT // Modify the Instruction Dominator in a Basic Block,
295 // This usually means we move/delete/insert instruction
296 // in a Basic Block. So we should re-iterate instructions
297 // in such Basic Block.
298};
299
300using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
301using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
302using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
303using SExts = SmallVector<Instruction *, 16>;
304using ValueToSExts = MapVector<Value *, SExts>;
305
306class TypePromotionTransaction;
307
308class CodeGenPrepare {
309 friend class CodeGenPrepareLegacyPass;
310 const TargetMachine *TM = nullptr;
311 const TargetSubtargetInfo *SubtargetInfo = nullptr;
312 const TargetLowering *TLI = nullptr;
313 const TargetRegisterInfo *TRI = nullptr;
314 const TargetTransformInfo *TTI = nullptr;
315 const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
316 const TargetLibraryInfo *TLInfo = nullptr;
317 DomTreeUpdater *DTU = nullptr;
318 LoopInfo *LI = nullptr;
319 BlockFrequencyInfo *BFI;
320 BranchProbabilityInfo *BPI;
321 ProfileSummaryInfo *PSI = nullptr;
322
323 /// As we scan instructions optimizing them, this is the next instruction
324 /// to optimize. Transforms that can invalidate this should update it.
325 BasicBlock::iterator CurInstIterator;
326
327 /// Keeps track of non-local addresses that have been sunk into a block.
328 /// This allows us to avoid inserting duplicate code for blocks with
329 /// multiple load/stores of the same address. The usage of WeakTrackingVH
330 /// enables SunkAddrs to be treated as a cache whose entries can be
331 /// invalidated if a sunken address computation has been erased.
332 ValueMap<Value *, WeakTrackingVH> SunkAddrs;
333
334 /// Keeps track of all instructions inserted for the current function.
335 SetOfInstrs InsertedInsts;
336
337 /// Keeps track of the type of the related instruction before their
338 /// promotion for the current function.
339 InstrToOrigTy PromotedInsts;
340
341 /// Keep track of instructions removed during promotion.
342 SetOfInstrs RemovedInsts;
343
344 /// Keep track of sext chains based on their initial value.
345 DenseMap<Value *, Instruction *> SeenChainsForSExt;
346
347 /// Keep track of GEPs accessing the same data structures such as structs or
348 /// arrays that are candidates to be split later because of their large
349 /// size.
350 MapVector<AssertingVH<Value>,
351 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
352 LargeOffsetGEPMap;
353
354 /// Keep track of new GEP base after splitting the GEPs having large offset.
355 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
356
357 /// Map serial numbers to Large offset GEPs.
358 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
359
360 /// Keep track of SExt promoted.
361 ValueToSExts ValToSExtendedUses;
362
363 /// True if the function has the OptSize attribute.
364 bool OptSize;
365
366 /// DataLayout for the Function being processed.
367 const DataLayout *DL = nullptr;
368
369public:
370 CodeGenPrepare() = default;
371 CodeGenPrepare(const TargetMachine *TM) : TM(TM){};
372 /// If encounter huge function, we need to limit the build time.
373 bool IsHugeFunc = false;
374
375 /// FreshBBs is like worklist, it collected the updated BBs which need
376 /// to be optimized again.
377 /// Note: Consider building time in this pass, when a BB updated, we need
378 /// to insert such BB into FreshBBs for huge function.
379 SmallPtrSet<BasicBlock *, 32> FreshBBs;
380
381 void releaseMemory() {
382 // Clear per function information.
383 InsertedInsts.clear();
384 PromotedInsts.clear();
385 FreshBBs.clear();
386 }
387
388 bool run(Function &F, FunctionAnalysisManager &AM);
389
390private:
391 template <typename F>
392 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
393 // Substituting can cause recursive simplifications, which can invalidate
394 // our iterator. Use a WeakTrackingVH to hold onto it in case this
395 // happens.
396 Value *CurValue = &*CurInstIterator;
397 WeakTrackingVH IterHandle(CurValue);
398
399 f();
400
401 // If the iterator instruction was recursively deleted, start over at the
402 // start of the block.
403 if (IterHandle != CurValue) {
404 CurInstIterator = BB->begin();
405 SunkAddrs.clear();
406 }
407 }
408
409 // Get the DominatorTree, updating it if necessary.
410 DominatorTree &getDT() { return DTU->getDomTree(); }
411
412 void removeAllAssertingVHReferences(Value *V);
413 bool eliminateAssumptions(Function &F);
414 bool eliminateFallThrough(Function &F);
415 bool eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI);
416 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
417 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
418 bool eliminateMostlyEmptyBlock(BasicBlock *BB);
419 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
420 bool isPreheader);
421 bool makeBitReverse(Instruction &I);
422 bool optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT);
423 bool optimizeInst(Instruction *I, ModifyDT &ModifiedDT);
424 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, Type *AccessTy,
425 unsigned AddrSpace);
426 bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
427 bool optimizeMulWithOverflow(Instruction *I, bool IsSigned,
428 ModifyDT &ModifiedDT);
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 fixupDbgVariableRecord(DbgVariableRecord &I);
444 bool fixupDbgVariableRecordsOnInst(Instruction &I);
445 bool placeDbgValues(Function &F);
446 bool placePseudoProbes(Function &F);
447 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
448 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
449 bool tryToPromoteExts(TypePromotionTransaction &TPT,
450 const SmallVectorImpl<Instruction *> &Exts,
451 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
452 unsigned CreatedInstsCost = 0);
453 bool mergeSExts(Function &F);
454 bool splitLargeGEPOffsets();
455 bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
456 SmallPtrSetImpl<Instruction *> &DeletedInstrs);
457 bool optimizePhiTypes(Function &F);
458 bool performAddressTypePromotion(
459 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
460 bool HasPromoted, TypePromotionTransaction &TPT,
461 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
462 bool splitBranchCondition(Function &F);
463 bool simplifyOffsetableRelocate(GCStatepointInst &I);
464
465 bool tryToSinkFreeOperands(Instruction *I);
466 bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, Value *Arg1,
467 CmpInst *Cmp, Intrinsic::ID IID);
468 bool optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT);
469 bool optimizeURem(Instruction *Rem);
470 bool combineToUSubWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
471 bool combineToUAddWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
472 bool unfoldPowerOf2Test(CmpInst *Cmp);
473 void verifyBFIUpdates(Function &F);
474 bool _run(Function &F);
475};
476
477class CodeGenPrepareLegacyPass : public FunctionPass {
478public:
479 static char ID; // Pass identification, replacement for typeid
480
481 CodeGenPrepareLegacyPass() : FunctionPass(ID) {}
482
483 bool runOnFunction(Function &F) override;
484
485 StringRef getPassName() const override { return "CodeGen Prepare"; }
486
487 void getAnalysisUsage(AnalysisUsage &AU) const override {
488 // FIXME: When we can selectively preserve passes, preserve the domtree.
489 AU.addRequired<ProfileSummaryInfoWrapperPass>();
490 AU.addRequired<TargetLibraryInfoWrapperPass>();
491 AU.addRequired<TargetPassConfig>();
492 AU.addRequired<TargetTransformInfoWrapperPass>();
493 AU.addRequired<DominatorTreeWrapperPass>();
494 AU.addRequired<LoopInfoWrapperPass>();
495 AU.addRequired<BranchProbabilityInfoWrapperPass>();
496 AU.addRequired<BlockFrequencyInfoWrapperPass>();
497 AU.addUsedIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
498 }
499};
500
501} // end anonymous namespace
502
503char CodeGenPrepareLegacyPass::ID = 0;
504
505bool CodeGenPrepareLegacyPass::runOnFunction(Function &F) {
506 if (skipFunction(F))
507 return false;
508 auto TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
509 CodeGenPrepare CGP(TM);
510 CGP.DL = &F.getDataLayout();
511 CGP.SubtargetInfo = TM->getSubtargetImpl(F);
512 CGP.TLI = CGP.SubtargetInfo->getTargetLowering();
513 CGP.TRI = CGP.SubtargetInfo->getRegisterInfo();
514 CGP.TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
515 CGP.TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
516 CGP.LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
517 CGP.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
518 CGP.BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
519 CGP.PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
520 auto BBSPRWP =
521 getAnalysisIfAvailable<BasicBlockSectionsProfileReaderWrapperPass>();
522 CGP.BBSectionsProfileReader = BBSPRWP ? &BBSPRWP->getBBSPR() : nullptr;
523 DomTreeUpdater DTUpdater(
524 &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
525 DomTreeUpdater::UpdateStrategy::Lazy);
526 CGP.DTU = &DTUpdater;
527
528 return CGP._run(F);
529}
530
531INITIALIZE_PASS_BEGIN(CodeGenPrepareLegacyPass, DEBUG_TYPE,
532 "Optimize for code generation", false, false)
533INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReaderWrapperPass)
534INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
535INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
536INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
537INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
538INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
539INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
540INITIALIZE_PASS_END(CodeGenPrepareLegacyPass, DEBUG_TYPE,
541 "Optimize for code generation", false, false)
542
543FunctionPass *llvm::createCodeGenPrepareLegacyPass() {
544 return new CodeGenPrepareLegacyPass();
545}
546
547PreservedAnalyses CodeGenPreparePass::run(Function &F,
548 FunctionAnalysisManager &AM) {
549 CodeGenPrepare CGP(TM);
550
551 bool Changed = CGP.run(F, AM);
552 if (!Changed)
553 return PreservedAnalyses::all();
554
555 PreservedAnalyses PA;
556 PA.preserve<TargetLibraryAnalysis>();
557 PA.preserve<TargetIRAnalysis>();
558 return PA;
559}
560
561bool CodeGenPrepare::run(Function &F, FunctionAnalysisManager &AM) {
562 DL = &F.getDataLayout();
563 SubtargetInfo = TM->getSubtargetImpl(F);
564 TLI = SubtargetInfo->getTargetLowering();
565 TRI = SubtargetInfo->getRegisterInfo();
566 TLInfo = &AM.getResult<TargetLibraryAnalysis>(IR&: F);
567 TTI = &AM.getResult<TargetIRAnalysis>(IR&: F);
568 LI = &AM.getResult<LoopAnalysis>(IR&: F);
569 BPI = &AM.getResult<BranchProbabilityAnalysis>(IR&: F);
570 BFI = &AM.getResult<BlockFrequencyAnalysis>(IR&: F);
571 auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(IR&: F);
572 PSI = MAMProxy.getCachedResult<ProfileSummaryAnalysis>(IR&: *F.getParent());
573 if (!PSI)
574 reportFatalUsageError(reason: "this pass requires the profile-summary module "
575 "analysis to be available");
576 BBSectionsProfileReader =
577 AM.getCachedResult<BasicBlockSectionsProfileReaderAnalysis>(IR&: F);
578 DomTreeUpdater DTUpdater(&AM.getResult<DominatorTreeAnalysis>(IR&: F),
579 DomTreeUpdater::UpdateStrategy::Lazy);
580 DTU = &DTUpdater;
581 return _run(F);
582}
583
584bool CodeGenPrepare::_run(Function &F) {
585 bool EverMadeChange = false;
586
587 OptSize = F.hasOptSize();
588 // Use the basic-block-sections profile to promote hot functions to .text.hot
589 // if requested.
590 if (BBSectionsGuidedSectionPrefix && BBSectionsProfileReader &&
591 BBSectionsProfileReader->isFunctionHot(FuncName: F.getName())) {
592 (void)F.setSectionPrefix("hot");
593 } else if (ProfileGuidedSectionPrefix) {
594 // The hot attribute overwrites profile count based hotness while profile
595 // counts based hotness overwrite the cold attribute.
596 // This is a conservative behabvior.
597 if (F.hasFnAttribute(Kind: Attribute::Hot) ||
598 PSI->isFunctionHotInCallGraph(F: &F, BFI&: *BFI))
599 (void)F.setSectionPrefix("hot");
600 // If PSI shows this function is not hot, we will placed the function
601 // into unlikely section if (1) PSI shows this is a cold function, or
602 // (2) the function has a attribute of cold.
603 else if (PSI->isFunctionColdInCallGraph(F: &F, BFI&: *BFI) ||
604 F.hasFnAttribute(Kind: Attribute::Cold))
605 (void)F.setSectionPrefix("unlikely");
606 else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() &&
607 PSI->isFunctionHotnessUnknown(F))
608 (void)F.setSectionPrefix("unknown");
609 }
610
611 /// This optimization identifies DIV instructions that can be
612 /// profitably bypassed and carried out with a shorter, faster divide.
613 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
614 const DenseMap<unsigned int, unsigned int> &BypassWidths =
615 TLI->getBypassSlowDivWidths();
616 BasicBlock *BB = &*F.begin();
617 while (BB != nullptr) {
618 // bypassSlowDivision may create new BBs, but we don't want to reapply the
619 // optimization to those blocks.
620 BasicBlock *Next = BB->getNextNode();
621 if (!llvm::shouldOptimizeForSize(BB, PSI, BFI))
622 EverMadeChange |= bypassSlowDivision(BB, BypassWidth: BypassWidths, DTU, LI);
623 BB = Next;
624 }
625 }
626
627 // Get rid of @llvm.assume builtins before attempting to eliminate empty
628 // blocks, since there might be blocks that only contain @llvm.assume calls
629 // (plus arguments that we can get rid of).
630 EverMadeChange |= eliminateAssumptions(F);
631
632 auto resetLoopInfo = [this]() {
633 LI->releaseMemory();
634 LI->analyze(DomTree: DTU->getDomTree());
635 };
636
637 // Eliminate blocks that contain only PHI nodes and an
638 // unconditional branch.
639 bool ResetLI = false;
640 EverMadeChange |= eliminateMostlyEmptyBlocks(F, ResetLI);
641 if (ResetLI)
642 resetLoopInfo();
643
644 if (!DisableBranchOpts)
645 EverMadeChange |= splitBranchCondition(F);
646
647 // Split some critical edges where one of the sources is an indirect branch,
648 // to help generate sane code for PHIs involving such edges.
649 bool Split = SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true,
650 BPI, BFI, DTU);
651 EverMadeChange |= Split;
652 if (Split)
653 resetLoopInfo();
654
655#ifndef NDEBUG
656 if (VerifyDomInfo)
657 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
658 "Incorrect DominatorTree updates in CGP");
659
660 if (VerifyLoopInfo)
661 LI->verify(getDT());
662#endif
663
664 // If we are optimzing huge function, we need to consider the build time.
665 // Because the basic algorithm's complex is near O(N!).
666 IsHugeFunc = F.size() > HugeFuncThresholdInCGPP;
667
668 bool MadeChange = true;
669 bool FuncIterated = false;
670 while (MadeChange) {
671 MadeChange = false;
672
673 // This is required because optimizeBlock() calls getDT() inside the loop
674 // below, which flushes pending updates and may delete dead blocks, leading
675 // to iterator invalidation.
676 DTU->flush();
677
678 for (BasicBlock &BB : llvm::make_early_inc_range(Range&: F)) {
679 if (FuncIterated && !FreshBBs.contains(Ptr: &BB))
680 continue;
681
682 ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
683 bool Changed = optimizeBlock(BB, ModifiedDT&: ModifiedDTOnIteration);
684
685 MadeChange |= Changed;
686 if (IsHugeFunc) {
687 // If the BB is updated, it may still has chance to be optimized.
688 // This usually happen at sink optimization.
689 // For example:
690 //
691 // bb0:
692 // %and = and i32 %a, 4
693 // %cmp = icmp eq i32 %and, 0
694 //
695 // If the %cmp sink to other BB, the %and will has chance to sink.
696 if (Changed)
697 FreshBBs.insert(Ptr: &BB);
698 else if (FuncIterated)
699 FreshBBs.erase(Ptr: &BB);
700 } else {
701 // For small/normal functions, we restart BB iteration if the dominator
702 // tree of the Function was changed.
703 if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
704 break;
705 }
706 }
707 // We have iterated all the BB in the (only work for huge) function.
708 FuncIterated = IsHugeFunc;
709
710 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
711 MadeChange |= mergeSExts(F);
712 if (!LargeOffsetGEPMap.empty())
713 MadeChange |= splitLargeGEPOffsets();
714 MadeChange |= optimizePhiTypes(F);
715
716 if (MadeChange)
717 eliminateFallThrough(F);
718
719#ifndef NDEBUG
720 if (VerifyDomInfo)
721 assert(getDT().verify(DominatorTree::VerificationLevel::Fast) &&
722 "Incorrect DominatorTree updates in CGP");
723
724 if (VerifyLoopInfo)
725 LI->verify(getDT());
726#endif
727
728 // Really free removed instructions during promotion.
729 for (Instruction *I : RemovedInsts)
730 I->deleteValue();
731
732 EverMadeChange |= MadeChange;
733 SeenChainsForSExt.clear();
734 ValToSExtendedUses.clear();
735 RemovedInsts.clear();
736 LargeOffsetGEPMap.clear();
737 LargeOffsetGEPID.clear();
738 }
739
740 NewGEPBases.clear();
741 SunkAddrs.clear();
742
743 // LoopInfo is not needed anymore and ConstantFoldTerminator can break it.
744 LI = nullptr;
745
746 if (!DisableBranchOpts) {
747 MadeChange = false;
748 // Use a set vector to get deterministic iteration order. The order the
749 // blocks are removed may affect whether or not PHI nodes in successors
750 // are removed.
751 SmallSetVector<BasicBlock *, 8> WorkList;
752 for (BasicBlock &BB : F) {
753 SmallVector<BasicBlock *, 2> Successors(successors(BB: &BB));
754 MadeChange |= ConstantFoldTerminator(BB: &BB, DeleteDeadConditions: true, TLI: nullptr, DTU);
755 if (!MadeChange)
756 continue;
757
758 for (BasicBlock *Succ : Successors)
759 if (pred_empty(BB: Succ))
760 WorkList.insert(X: Succ);
761 }
762
763 // Delete the dead blocks and any of their dead successors.
764 MadeChange |= !WorkList.empty();
765 while (!WorkList.empty()) {
766 BasicBlock *BB = WorkList.pop_back_val();
767 SmallVector<BasicBlock *, 2> Successors(successors(BB));
768
769 DeleteDeadBlock(BB, DTU);
770
771 for (BasicBlock *Succ : Successors)
772 if (pred_empty(BB: Succ))
773 WorkList.insert(X: Succ);
774 }
775
776 // Flush pending DT updates in order to finalise deletion of dead blocks.
777 DTU->flush();
778
779 // Merge pairs of basic blocks with unconditional branches, connected by
780 // a single edge.
781 if (EverMadeChange || MadeChange)
782 MadeChange |= eliminateFallThrough(F);
783
784 EverMadeChange |= MadeChange;
785 }
786
787 if (!DisableGCOpts) {
788 SmallVector<GCStatepointInst *, 2> Statepoints;
789 for (BasicBlock &BB : F)
790 for (Instruction &I : BB)
791 if (auto *SP = dyn_cast<GCStatepointInst>(Val: &I))
792 Statepoints.push_back(Elt: SP);
793 for (auto &I : Statepoints)
794 EverMadeChange |= simplifyOffsetableRelocate(I&: *I);
795 }
796
797 // Do this last to clean up use-before-def scenarios introduced by other
798 // preparatory transforms.
799 EverMadeChange |= placeDbgValues(F);
800 EverMadeChange |= placePseudoProbes(F);
801
802#ifndef NDEBUG
803 if (VerifyBFIUpdates)
804 verifyBFIUpdates(F);
805#endif
806
807 return EverMadeChange;
808}
809
810bool CodeGenPrepare::eliminateAssumptions(Function &F) {
811 bool MadeChange = false;
812 for (BasicBlock &BB : F) {
813 CurInstIterator = BB.begin();
814 while (CurInstIterator != BB.end()) {
815 Instruction *I = &*(CurInstIterator++);
816 if (auto *Assume = dyn_cast<AssumeInst>(Val: I)) {
817 MadeChange = true;
818 Value *Operand = Assume->getOperand(i_nocapture: 0);
819 Assume->eraseFromParent();
820
821 resetIteratorIfInvalidatedWhileCalling(BB: &BB, f: [&]() {
822 RecursivelyDeleteTriviallyDeadInstructions(V: Operand, TLI: TLInfo, MSSAU: nullptr);
823 });
824 }
825 }
826 }
827 return MadeChange;
828}
829
830/// An instruction is about to be deleted, so remove all references to it in our
831/// GEP-tracking data strcutures.
832void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
833 LargeOffsetGEPMap.erase(Key: V);
834 NewGEPBases.erase(V);
835
836 auto GEP = dyn_cast<GetElementPtrInst>(Val: V);
837 if (!GEP)
838 return;
839
840 LargeOffsetGEPID.erase(Val: GEP);
841
842 auto VecI = LargeOffsetGEPMap.find(Key: GEP->getPointerOperand());
843 if (VecI == LargeOffsetGEPMap.end())
844 return;
845
846 auto &GEPVector = VecI->second;
847 llvm::erase_if(C&: GEPVector, P: [=](auto &Elt) { return Elt.first == GEP; });
848
849 if (GEPVector.empty())
850 LargeOffsetGEPMap.erase(Iterator: VecI);
851}
852
853// Verify BFI has been updated correctly by recomputing BFI and comparing them.
854[[maybe_unused]] void CodeGenPrepare::verifyBFIUpdates(Function &F) {
855 DominatorTree NewDT(F);
856 LoopInfo NewLI(NewDT);
857 BranchProbabilityInfo NewBPI(F, NewLI, TLInfo);
858 BlockFrequencyInfo NewBFI(F, NewBPI, NewLI);
859 NewBFI.verifyMatch(Other&: *BFI);
860}
861
862/// Merge basic blocks which are connected by a single edge, where one of the
863/// basic blocks has a single successor pointing to the other basic block,
864/// which has a single predecessor.
865bool CodeGenPrepare::eliminateFallThrough(Function &F) {
866 bool Changed = false;
867 SmallPtrSet<BasicBlock *, 8> Preds;
868 // Scan all of the blocks in the function, except for the entry block.
869 for (auto &Block : llvm::drop_begin(RangeOrContainer&: F)) {
870 auto *BB = &Block;
871 if (DTU->isBBPendingDeletion(DelBB: BB))
872 continue;
873 // If the destination block has a single pred, then this is a trivial
874 // edge, just collapse it.
875 BasicBlock *SinglePred = BB->getSinglePredecessor();
876
877 // Don't merge if BB's address is taken.
878 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
879 continue;
880
881 if (isa<UncondBrInst>(Val: SinglePred->getTerminator())) {
882 Changed = true;
883 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
884
885 // Merge BB into SinglePred and delete it.
886 MergeBlockIntoPredecessor(BB, DTU, LI);
887 Preds.insert(Ptr: SinglePred);
888
889 if (IsHugeFunc) {
890 // Update FreshBBs to optimize the merged BB.
891 FreshBBs.insert(Ptr: SinglePred);
892 FreshBBs.erase(Ptr: BB);
893 }
894 }
895 }
896
897 // (Repeatedly) merging blocks into their predecessors can create redundant
898 // debug intrinsics.
899 for (auto *Pred : Preds)
900 if (!DTU->isBBPendingDeletion(DelBB: Pred))
901 RemoveRedundantDbgInstrs(BB: Pred);
902
903 return Changed;
904}
905
906/// Find a destination block from BB if BB is mergeable empty block.
907BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
908 // If this block doesn't end with an uncond branch, ignore it.
909 UncondBrInst *BI = dyn_cast<UncondBrInst>(Val: BB->getTerminator());
910 if (!BI)
911 return nullptr;
912
913 // If the instruction before the branch (skipping debug info) isn't a phi
914 // node, then other stuff is happening here.
915 BasicBlock::iterator BBI = BI->getIterator();
916 if (BBI != BB->begin()) {
917 --BBI;
918 if (!isa<PHINode>(Val: BBI))
919 return nullptr;
920 }
921
922 // Do not break infinite loops.
923 BasicBlock *DestBB = BI->getSuccessor();
924 if (DestBB == BB)
925 return nullptr;
926
927 if (!canMergeBlocks(BB, DestBB))
928 DestBB = nullptr;
929
930 return DestBB;
931}
932
933/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
934/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
935/// edges in ways that are non-optimal for isel. Start by eliminating these
936/// blocks so we can split them the way we want them.
937bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F, bool &ResetLI) {
938 SmallPtrSet<BasicBlock *, 16> Preheaders;
939 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
940 while (!LoopList.empty()) {
941 Loop *L = LoopList.pop_back_val();
942 llvm::append_range(C&: LoopList, R&: *L);
943 if (BasicBlock *Preheader = L->getLoopPreheader())
944 Preheaders.insert(Ptr: Preheader);
945 }
946
947 ResetLI = false;
948 bool MadeChange = false;
949 SmallPtrSet<PHINode *, 32> KnownNonDeadPHIs;
950 // Note that this intentionally skips the entry block.
951 for (auto &Block : llvm::drop_begin(RangeOrContainer&: F)) {
952 // Delete phi nodes that could block deleting other empty blocks.
953 if (!DisableDeletePHIs)
954 MadeChange |= DeleteDeadPHIs(BB: &Block, TLI: TLInfo, MSSAU: nullptr, KnownNonDeadPHIs: &KnownNonDeadPHIs);
955 }
956
957 for (auto &Block : llvm::drop_begin(RangeOrContainer&: F)) {
958 auto *BB = &Block;
959 if (DTU->isBBPendingDeletion(DelBB: BB))
960 continue;
961 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
962 if (!DestBB ||
963 !isMergingEmptyBlockProfitable(BB, DestBB, isPreheader: Preheaders.count(Ptr: BB)))
964 continue;
965
966 ResetLI |= eliminateMostlyEmptyBlock(BB);
967 MadeChange = true;
968 }
969 return MadeChange;
970}
971
972bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
973 BasicBlock *DestBB,
974 bool isPreheader) {
975 // Do not delete loop preheaders if doing so would create a critical edge.
976 // Loop preheaders can be good locations to spill registers. If the
977 // preheader is deleted and we create a critical edge, registers may be
978 // spilled in the loop body instead.
979 if (!DisablePreheaderProtect && isPreheader &&
980 !(BB->getSinglePredecessor() &&
981 BB->getSinglePredecessor()->getSingleSuccessor()))
982 return false;
983
984 // Skip merging if the block's successor is also a successor to any callbr
985 // that leads to this block.
986 // FIXME: Is this really needed? Is this a correctness issue?
987 for (BasicBlock *Pred : predecessors(BB)) {
988 if (isa<CallBrInst>(Val: Pred->getTerminator()) &&
989 llvm::is_contained(Range: successors(BB: Pred), Element: DestBB))
990 return false;
991 }
992
993 // Try to skip merging if the unique predecessor of BB is terminated by a
994 // switch or indirect branch instruction, and BB is used as an incoming block
995 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
996 // add COPY instructions in the predecessor of BB instead of BB (if it is not
997 // merged). Note that the critical edge created by merging such blocks wont be
998 // split in MachineSink because the jump table is not analyzable. By keeping
999 // such empty block (BB), ISel will place COPY instructions in BB, not in the
1000 // predecessor of BB.
1001 BasicBlock *Pred = BB->getUniquePredecessor();
1002 if (!Pred || !(isa<SwitchInst>(Val: Pred->getTerminator()) ||
1003 isa<IndirectBrInst>(Val: Pred->getTerminator())))
1004 return true;
1005
1006 if (BB->getTerminator() != &*BB->getFirstNonPHIOrDbg())
1007 return true;
1008
1009 // We use a simple cost heuristic which determine skipping merging is
1010 // profitable if the cost of skipping merging is less than the cost of
1011 // merging : Cost(skipping merging) < Cost(merging BB), where the
1012 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
1013 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
1014 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
1015 // Freq(Pred) / Freq(BB) > 2.
1016 // Note that if there are multiple empty blocks sharing the same incoming
1017 // value for the PHIs in the DestBB, we consider them together. In such
1018 // case, Cost(merging BB) will be the sum of their frequencies.
1019
1020 if (!isa<PHINode>(Val: DestBB->begin()))
1021 return true;
1022
1023 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
1024
1025 // Find all other incoming blocks from which incoming values of all PHIs in
1026 // DestBB are the same as the ones from BB.
1027 for (BasicBlock *DestBBPred : predecessors(BB: DestBB)) {
1028 if (DestBBPred == BB)
1029 continue;
1030
1031 if (llvm::all_of(Range: DestBB->phis(), P: [&](const PHINode &DestPN) {
1032 return DestPN.getIncomingValueForBlock(BB) ==
1033 DestPN.getIncomingValueForBlock(BB: DestBBPred);
1034 }))
1035 SameIncomingValueBBs.insert(Ptr: DestBBPred);
1036 }
1037
1038 // See if all BB's incoming values are same as the value from Pred. In this
1039 // case, no reason to skip merging because COPYs are expected to be place in
1040 // Pred already.
1041 if (SameIncomingValueBBs.count(Ptr: Pred))
1042 return true;
1043
1044 BlockFrequency PredFreq = BFI->getBlockFreq(BB: Pred);
1045 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
1046
1047 for (auto *SameValueBB : SameIncomingValueBBs)
1048 if (SameValueBB->getUniquePredecessor() == Pred &&
1049 DestBB == findDestBlockOfMergeableEmptyBlock(BB: SameValueBB))
1050 BBFreq += BFI->getBlockFreq(BB: SameValueBB);
1051
1052 std::optional<BlockFrequency> Limit = BBFreq.mul(Factor: FreqRatioToSkipMerge);
1053 return !Limit || PredFreq <= *Limit;
1054}
1055
1056/// Return true if we can merge BB into DestBB if there is a single
1057/// unconditional branch between them, and BB contains no other non-phi
1058/// instructions.
1059bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
1060 const BasicBlock *DestBB) const {
1061 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
1062 // the successor. If there are more complex condition (e.g. preheaders),
1063 // don't mess around with them.
1064 for (const PHINode &PN : BB->phis()) {
1065 for (const User *U : PN.users()) {
1066 const Instruction *UI = cast<Instruction>(Val: U);
1067 if (UI->getParent() != DestBB || !isa<PHINode>(Val: UI))
1068 return false;
1069 // If User is inside DestBB block and it is a PHINode then check
1070 // incoming value. If incoming value is not from BB then this is
1071 // a complex condition (e.g. preheaders) we want to avoid here.
1072 if (UI->getParent() == DestBB) {
1073 if (const PHINode *UPN = dyn_cast<PHINode>(Val: UI))
1074 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
1075 Instruction *Insn = dyn_cast<Instruction>(Val: UPN->getIncomingValue(i: I));
1076 if (Insn && Insn->getParent() == BB &&
1077 Insn->getParent() != UPN->getIncomingBlock(i: I))
1078 return false;
1079 }
1080 }
1081 }
1082 }
1083
1084 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
1085 // and DestBB may have conflicting incoming values for the block. If so, we
1086 // can't merge the block.
1087 const PHINode *DestBBPN = dyn_cast<PHINode>(Val: DestBB->begin());
1088 if (!DestBBPN)
1089 return true; // no conflict.
1090
1091 // Collect the preds of BB.
1092 SmallPtrSet<const BasicBlock *, 16> BBPreds;
1093 if (const PHINode *BBPN = dyn_cast<PHINode>(Val: BB->begin())) {
1094 // It is faster to get preds from a PHI than with pred_iterator.
1095 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1096 BBPreds.insert(Ptr: BBPN->getIncomingBlock(i));
1097 } else {
1098 BBPreds.insert_range(R: predecessors(BB));
1099 }
1100
1101 // Walk the preds of DestBB.
1102 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
1103 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
1104 if (BBPreds.count(Ptr: Pred)) { // Common predecessor?
1105 for (const PHINode &PN : DestBB->phis()) {
1106 const Value *V1 = PN.getIncomingValueForBlock(BB: Pred);
1107 const Value *V2 = PN.getIncomingValueForBlock(BB);
1108
1109 // If V2 is a phi node in BB, look up what the mapped value will be.
1110 if (const PHINode *V2PN = dyn_cast<PHINode>(Val: V2))
1111 if (V2PN->getParent() == BB)
1112 V2 = V2PN->getIncomingValueForBlock(BB: Pred);
1113
1114 // If there is a conflict, bail out.
1115 if (V1 != V2)
1116 return false;
1117 }
1118 }
1119 }
1120
1121 return true;
1122}
1123
1124/// Replace all old uses with new ones, and push the updated BBs into FreshBBs.
1125static void replaceAllUsesWith(Value *Old, Value *New,
1126 SmallPtrSet<BasicBlock *, 32> &FreshBBs,
1127 bool IsHuge) {
1128 auto *OldI = dyn_cast<Instruction>(Val: Old);
1129 if (OldI) {
1130 for (Value::user_iterator UI = OldI->user_begin(), E = OldI->user_end();
1131 UI != E; ++UI) {
1132 Instruction *User = cast<Instruction>(Val: *UI);
1133 if (IsHuge)
1134 FreshBBs.insert(Ptr: User->getParent());
1135 }
1136 }
1137 Old->replaceAllUsesWith(V: New);
1138}
1139
1140/// Eliminate a basic block that has only phi's and an unconditional branch in
1141/// it.
1142/// Indicate that the LoopInfo was modified only if it wasn't updated.
1143bool CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
1144 UncondBrInst *BI = cast<UncondBrInst>(Val: BB->getTerminator());
1145 BasicBlock *DestBB = BI->getSuccessor();
1146
1147 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
1148 << *BB << *DestBB);
1149
1150 // If the destination block has a single pred, then this is a trivial edge,
1151 // just collapse it.
1152 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
1153 if (SinglePred != DestBB) {
1154 assert(SinglePred == BB &&
1155 "Single predecessor not the same as predecessor");
1156 // Merge DestBB into SinglePred/BB and delete it.
1157 MergeBlockIntoPredecessor(BB: DestBB, DTU, LI);
1158 // Note: BB(=SinglePred) will not be deleted on this path.
1159 // DestBB(=its single successor) is the one that was deleted.
1160 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
1161
1162 if (IsHugeFunc) {
1163 // Update FreshBBs to optimize the merged BB.
1164 FreshBBs.insert(Ptr: SinglePred);
1165 FreshBBs.erase(Ptr: DestBB);
1166 }
1167 return false;
1168 }
1169 }
1170
1171 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
1172 // to handle the new incoming edges it is about to have.
1173 for (PHINode &PN : DestBB->phis()) {
1174 // Remove the incoming value for BB, and remember it.
1175 Value *InVal = PN.removeIncomingValue(BB, DeletePHIIfEmpty: false);
1176
1177 // Two options: either the InVal is a phi node defined in BB or it is some
1178 // value that dominates BB.
1179 PHINode *InValPhi = dyn_cast<PHINode>(Val: InVal);
1180 if (InValPhi && InValPhi->getParent() == BB) {
1181 // Add all of the input values of the input PHI as inputs of this phi.
1182 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
1183 PN.addIncoming(V: InValPhi->getIncomingValue(i),
1184 BB: InValPhi->getIncomingBlock(i));
1185 } else {
1186 // Otherwise, add one instance of the dominating value for each edge that
1187 // we will be adding.
1188 if (PHINode *BBPN = dyn_cast<PHINode>(Val: BB->begin())) {
1189 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
1190 PN.addIncoming(V: InVal, BB: BBPN->getIncomingBlock(i));
1191 } else {
1192 for (BasicBlock *Pred : predecessors(BB))
1193 PN.addIncoming(V: InVal, BB: Pred);
1194 }
1195 }
1196 }
1197
1198 // Preserve loop Metadata.
1199 if (BI->hasMetadata(KindID: LLVMContext::MD_loop)) {
1200 for (auto *Pred : predecessors(BB))
1201 Pred->getTerminator()->copyMetadata(SrcInst: *BI, WL: LLVMContext::MD_loop);
1202 }
1203
1204 // The PHIs are now updated, change everything that refers to BB to use
1205 // DestBB and remove BB.
1206 SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
1207 SmallPtrSet<BasicBlock *, 8> SeenPreds;
1208 SmallPtrSet<BasicBlock *, 8> PredOfDestBB(llvm::from_range,
1209 predecessors(BB: DestBB));
1210 for (auto *Pred : predecessors(BB)) {
1211 if (!PredOfDestBB.contains(Ptr: Pred)) {
1212 if (SeenPreds.insert(Ptr: Pred).second)
1213 DTUpdates.push_back(Elt: {DominatorTree::Insert, Pred, DestBB});
1214 }
1215 }
1216 SeenPreds.clear();
1217 for (auto *Pred : predecessors(BB)) {
1218 if (SeenPreds.insert(Ptr: Pred).second)
1219 DTUpdates.push_back(Elt: {DominatorTree::Delete, Pred, BB});
1220 }
1221 DTUpdates.push_back(Elt: {DominatorTree::Delete, BB, DestBB});
1222 BB->replaceAllUsesWith(V: DestBB);
1223 DTU->applyUpdates(Updates: DTUpdates);
1224 DTU->deleteBB(DelBB: BB);
1225 ++NumBlocksElim;
1226
1227 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
1228 return true;
1229}
1230
1231// Computes a map of base pointer relocation instructions to corresponding
1232// derived pointer relocation instructions given a vector of all relocate calls
1233static void computeBaseDerivedRelocateMap(
1234 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
1235 MapVector<GCRelocateInst *, SmallVector<GCRelocateInst *, 0>>
1236 &RelocateInstMap) {
1237 // Collect information in two maps: one primarily for locating the base object
1238 // while filling the second map; the second map is the final structure holding
1239 // a mapping between Base and corresponding Derived relocate calls
1240 MapVector<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
1241 for (auto *ThisRelocate : AllRelocateCalls) {
1242 auto K = std::make_pair(x: ThisRelocate->getBasePtrIndex(),
1243 y: ThisRelocate->getDerivedPtrIndex());
1244 RelocateIdxMap.insert(KV: std::make_pair(x&: K, y&: ThisRelocate));
1245 }
1246 for (auto &Item : RelocateIdxMap) {
1247 std::pair<unsigned, unsigned> Key = Item.first;
1248 if (Key.first == Key.second)
1249 // Base relocation: nothing to insert
1250 continue;
1251
1252 GCRelocateInst *I = Item.second;
1253 auto BaseKey = std::make_pair(x&: Key.first, y&: Key.first);
1254
1255 // We're iterating over RelocateIdxMap so we cannot modify it.
1256 auto MaybeBase = RelocateIdxMap.find(Key: BaseKey);
1257 if (MaybeBase == RelocateIdxMap.end())
1258 // TODO: We might want to insert a new base object relocate and gep off
1259 // that, if there are enough derived object relocates.
1260 continue;
1261
1262 RelocateInstMap[MaybeBase->second].push_back(Elt: I);
1263 }
1264}
1265
1266// Accepts a GEP and extracts the operands into a vector provided they're all
1267// small integer constants
1268static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1269 SmallVectorImpl<Value *> &OffsetV) {
1270 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1271 // Only accept small constant integer operands
1272 auto *Op = dyn_cast<ConstantInt>(Val: GEP->getOperand(i_nocapture: i));
1273 if (!Op || Op->getZExtValue() > 20)
1274 return false;
1275 }
1276
1277 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1278 OffsetV.push_back(Elt: GEP->getOperand(i_nocapture: i));
1279 return true;
1280}
1281
1282// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1283// replace, computes a replacement, and affects it.
1284static bool
1285simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1286 const SmallVectorImpl<GCRelocateInst *> &Targets) {
1287 bool MadeChange = false;
1288 // We must ensure the relocation of derived pointer is defined after
1289 // relocation of base pointer. If we find a relocation corresponding to base
1290 // defined earlier than relocation of base then we move relocation of base
1291 // right before found relocation. We consider only relocation in the same
1292 // basic block as relocation of base. Relocations from other basic block will
1293 // be skipped by optimization and we do not care about them.
1294 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1295 &*R != RelocatedBase; ++R)
1296 if (auto *RI = dyn_cast<GCRelocateInst>(Val&: R))
1297 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1298 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1299 RelocatedBase->moveBefore(InsertPos: RI->getIterator());
1300 MadeChange = true;
1301 break;
1302 }
1303
1304 for (GCRelocateInst *ToReplace : Targets) {
1305 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
1306 "Not relocating a derived object of the original base object");
1307 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
1308 // A duplicate relocate call. TODO: coalesce duplicates.
1309 continue;
1310 }
1311
1312 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1313 // Base and derived relocates are in different basic blocks.
1314 // In this case transform is only valid when base dominates derived
1315 // relocate. However it would be too expensive to check dominance
1316 // for each such relocate, so we skip the whole transformation.
1317 continue;
1318 }
1319
1320 Value *Base = ToReplace->getBasePtr();
1321 auto *Derived = dyn_cast<GetElementPtrInst>(Val: ToReplace->getDerivedPtr());
1322 if (!Derived || Derived->getPointerOperand() != Base)
1323 continue;
1324
1325 SmallVector<Value *, 2> OffsetV;
1326 if (!getGEPSmallConstantIntOffsetV(GEP: Derived, OffsetV))
1327 continue;
1328
1329 // Create a Builder and replace the target callsite with a gep
1330 assert(RelocatedBase->getNextNode() &&
1331 "Should always have one since it's not a terminator");
1332
1333 // Insert after RelocatedBase
1334 IRBuilder<> Builder(RelocatedBase->getNextNode());
1335 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
1336
1337 // If gc_relocate does not match the actual type, cast it to the right type.
1338 // In theory, there must be a bitcast after gc_relocate if the type does not
1339 // match, and we should reuse it to get the derived pointer. But it could be
1340 // cases like this:
1341 // bb1:
1342 // ...
1343 // %g1 = call coldcc i8 addrspace(1)*
1344 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1345 //
1346 // bb2:
1347 // ...
1348 // %g2 = call coldcc i8 addrspace(1)*
1349 // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
1350 //
1351 // merge:
1352 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1353 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1354 //
1355 // In this case, we can not find the bitcast any more. So we insert a new
1356 // bitcast no matter there is already one or not. In this way, we can handle
1357 // all cases, and the extra bitcast should be optimized away in later
1358 // passes.
1359 Value *ActualRelocatedBase = RelocatedBase;
1360 if (RelocatedBase->getType() != Base->getType()) {
1361 ActualRelocatedBase =
1362 Builder.CreateBitCast(V: RelocatedBase, DestTy: Base->getType());
1363 }
1364 Value *Replacement =
1365 Builder.CreateGEP(Ty: Derived->getSourceElementType(), Ptr: ActualRelocatedBase,
1366 IdxList: ArrayRef(OffsetV));
1367 Replacement->takeName(V: ToReplace);
1368 // If the newly generated derived pointer's type does not match the original
1369 // derived pointer's type, cast the new derived pointer to match it. Same
1370 // reasoning as above.
1371 Value *ActualReplacement = Replacement;
1372 if (Replacement->getType() != ToReplace->getType()) {
1373 ActualReplacement =
1374 Builder.CreateBitCast(V: Replacement, DestTy: ToReplace->getType());
1375 }
1376 ToReplace->replaceAllUsesWith(V: ActualReplacement);
1377 ToReplace->eraseFromParent();
1378
1379 MadeChange = true;
1380 }
1381 return MadeChange;
1382}
1383
1384// Turns this:
1385//
1386// %base = ...
1387// %ptr = gep %base + 15
1388// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1389// %base' = relocate(%tok, i32 4, i32 4)
1390// %ptr' = relocate(%tok, i32 4, i32 5)
1391// %val = load %ptr'
1392//
1393// into this:
1394//
1395// %base = ...
1396// %ptr = gep %base + 15
1397// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1398// %base' = gc.relocate(%tok, i32 4, i32 4)
1399// %ptr' = gep %base' + 15
1400// %val = load %ptr'
1401bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
1402 bool MadeChange = false;
1403 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
1404 for (auto *U : I.users())
1405 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(Val: U))
1406 // Collect all the relocate calls associated with a statepoint
1407 AllRelocateCalls.push_back(Elt: Relocate);
1408
1409 // We need at least one base pointer relocation + one derived pointer
1410 // relocation to mangle
1411 if (AllRelocateCalls.size() < 2)
1412 return false;
1413
1414 // RelocateInstMap is a mapping from the base relocate instruction to the
1415 // corresponding derived relocate instructions
1416 MapVector<GCRelocateInst *, SmallVector<GCRelocateInst *, 0>> RelocateInstMap;
1417 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1418 if (RelocateInstMap.empty())
1419 return false;
1420
1421 for (auto &Item : RelocateInstMap)
1422 // Item.first is the RelocatedBase to offset against
1423 // Item.second is the vector of Targets to replace
1424 MadeChange = simplifyRelocatesOffABase(RelocatedBase: Item.first, Targets: Item.second);
1425 return MadeChange;
1426}
1427
1428/// Sink the specified cast instruction into its user blocks.
1429static bool SinkCast(CastInst *CI) {
1430 BasicBlock *DefBB = CI->getParent();
1431
1432 /// InsertedCasts - Only insert a cast in each block once.
1433 DenseMap<BasicBlock *, CastInst *> InsertedCasts;
1434
1435 bool MadeChange = false;
1436 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
1437 UI != E;) {
1438 Use &TheUse = UI.getUse();
1439 Instruction *User = cast<Instruction>(Val: *UI);
1440
1441 // Figure out which BB this cast is used in. For PHI's this is the
1442 // appropriate predecessor block.
1443 BasicBlock *UserBB = User->getParent();
1444 if (PHINode *PN = dyn_cast<PHINode>(Val: User)) {
1445 UserBB = PN->getIncomingBlock(U: TheUse);
1446 }
1447
1448 // Preincrement use iterator so we don't invalidate it.
1449 ++UI;
1450
1451 // The first insertion point of a block containing an EH pad is after the
1452 // pad. If the pad is the user, we cannot sink the cast past the pad.
1453 if (User->isEHPad())
1454 continue;
1455
1456 // If the block selected to receive the cast is an EH pad that does not
1457 // allow non-PHI instructions before the terminator, we can't sink the
1458 // cast.
1459 if (UserBB->getTerminator()->isEHPad())
1460 continue;
1461
1462 // If this user is in the same block as the cast, don't change the cast.
1463 if (UserBB == DefBB)
1464 continue;
1465
1466 // If we have already inserted a cast into this block, use it.
1467 CastInst *&InsertedCast = InsertedCasts[UserBB];
1468
1469 if (!InsertedCast) {
1470 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1471 assert(InsertPt != UserBB->end());
1472 InsertedCast = cast<CastInst>(Val: CI->clone());
1473 InsertedCast->insertBefore(BB&: *UserBB, InsertPos: InsertPt);
1474 }
1475
1476 // Replace a use of the cast with a use of the new cast.
1477 TheUse = InsertedCast;
1478 MadeChange = true;
1479 ++NumCastUses;
1480 }
1481
1482 // If we removed all uses, nuke the cast.
1483 if (CI->use_empty()) {
1484 salvageDebugInfo(I&: *CI);
1485 CI->eraseFromParent();
1486 MadeChange = true;
1487 }
1488
1489 return MadeChange;
1490}
1491
1492/// If the specified cast instruction is a noop copy (e.g. it's casting from
1493/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1494/// reduce the number of virtual registers that must be created and coalesced.
1495///
1496/// Return true if any changes are made.
1497static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1498 const DataLayout &DL) {
1499 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1500 // than sinking only nop casts, but is helpful on some platforms.
1501 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(Val: CI)) {
1502 if (!TLI.isFreeAddrSpaceCast(SrcAS: ASC->getSrcAddressSpace(),
1503 DestAS: ASC->getDestAddressSpace()))
1504 return false;
1505 }
1506
1507 // If this is a noop copy,
1508 EVT SrcVT = TLI.getValueType(DL, Ty: CI->getOperand(i_nocapture: 0)->getType());
1509 EVT DstVT = TLI.getValueType(DL, Ty: CI->getType());
1510
1511 // This is an fp<->int conversion?
1512 if (SrcVT.isInteger() != DstVT.isInteger())
1513 return false;
1514
1515 // If this is an extension, it will be a zero or sign extension, which
1516 // isn't a noop.
1517 if (SrcVT.bitsLT(VT: DstVT))
1518 return false;
1519
1520 // If these values will be promoted, find out what they will be promoted
1521 // to. This helps us consider truncates on PPC as noop copies when they
1522 // are.
1523 if (TLI.getTypeAction(Context&: CI->getContext(), VT: SrcVT) ==
1524 TargetLowering::TypePromoteInteger)
1525 SrcVT = TLI.getTypeToTransformTo(Context&: CI->getContext(), VT: SrcVT);
1526 if (TLI.getTypeAction(Context&: CI->getContext(), VT: DstVT) ==
1527 TargetLowering::TypePromoteInteger)
1528 DstVT = TLI.getTypeToTransformTo(Context&: CI->getContext(), VT: DstVT);
1529
1530 // If, after promotion, these are the same types, this is a noop copy.
1531 if (SrcVT != DstVT)
1532 return false;
1533
1534 return SinkCast(CI);
1535}
1536
1537// Match a simple increment by constant operation. Note that if a sub is
1538// matched, the step is negated (as if the step had been canonicalized to
1539// an add, even though we leave the instruction alone.)
1540static bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
1541 Constant *&Step) {
1542 if (match(V: IVInc, P: m_Add(L: m_Instruction(I&: LHS), R: m_Constant(C&: Step))) ||
1543 match(V: IVInc, P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::uadd_with_overflow>(
1544 Ops: m_Instruction(I&: LHS), Ops: m_Constant(C&: Step)))))
1545 return true;
1546 if (match(V: IVInc, P: m_Sub(L: m_Instruction(I&: LHS), R: m_Constant(C&: Step))) ||
1547 match(V: IVInc, P: m_ExtractValue<0>(V: m_Intrinsic<Intrinsic::usub_with_overflow>(
1548 Ops: m_Instruction(I&: LHS), Ops: m_Constant(C&: Step))))) {
1549 Step = ConstantExpr::getNeg(C: Step);
1550 return true;
1551 }
1552 return false;
1553}
1554
1555/// If given \p PN is an inductive variable with value IVInc coming from the
1556/// backedge, and on each iteration it gets increased by Step, return pair
1557/// <IVInc, Step>. Otherwise, return std::nullopt.
1558static std::optional<std::pair<Instruction *, Constant *>>
1559getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
1560 const Loop *L = LI->getLoopFor(BB: PN->getParent());
1561 if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
1562 return std::nullopt;
1563 auto *IVInc =
1564 dyn_cast<Instruction>(Val: PN->getIncomingValueForBlock(BB: L->getLoopLatch()));
1565 if (!IVInc || LI->getLoopFor(BB: IVInc->getParent()) != L)
1566 return std::nullopt;
1567 Instruction *LHS = nullptr;
1568 Constant *Step = nullptr;
1569 if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
1570 return std::make_pair(x&: IVInc, y&: Step);
1571 return std::nullopt;
1572}
1573
1574static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
1575 auto *I = dyn_cast<Instruction>(Val: V);
1576 if (!I)
1577 return false;
1578 Instruction *LHS = nullptr;
1579 Constant *Step = nullptr;
1580 if (!matchIncrement(IVInc: I, LHS, Step))
1581 return false;
1582 if (auto *PN = dyn_cast<PHINode>(Val: LHS))
1583 if (auto IVInc = getIVIncrement(PN, LI))
1584 return IVInc->first == I;
1585 return false;
1586}
1587
1588bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
1589 Value *Arg0, Value *Arg1,
1590 CmpInst *Cmp,
1591 Intrinsic::ID IID) {
1592 auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
1593 if (!isIVIncrement(V: BO, LI))
1594 return false;
1595 const Loop *L = LI->getLoopFor(BB: BO->getParent());
1596 assert(L && "L should not be null after isIVIncrement()");
1597 // Do not risk on moving increment into a child loop.
1598 if (LI->getLoopFor(BB: Cmp->getParent()) != L)
1599 return false;
1600
1601 // Finally, we need to ensure that the insert point will dominate all
1602 // existing uses of the increment.
1603
1604 auto &DT = getDT();
1605 if (DT.dominates(A: Cmp->getParent(), B: BO->getParent()))
1606 // If we're moving up the dom tree, all uses are trivially dominated.
1607 // (This is the common case for code produced by LSR.)
1608 return true;
1609
1610 // Otherwise, special case the single use in the phi recurrence.
1611 return BO->hasOneUse() && DT.dominates(A: Cmp->getParent(), B: L->getLoopLatch());
1612 };
1613 if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
1614 // We used to use a dominator tree here to allow multi-block optimization.
1615 // But that was problematic because:
1616 // 1. It could cause a perf regression by hoisting the math op into the
1617 // critical path.
1618 // 2. It could cause a perf regression by creating a value that was live
1619 // across multiple blocks and increasing register pressure.
1620 // 3. Use of a dominator tree could cause large compile-time regression.
1621 // This is because we recompute the DT on every change in the main CGP
1622 // run-loop. The recomputing is probably unnecessary in many cases, so if
1623 // that was fixed, using a DT here would be ok.
1624 //
1625 // There is one important particular case we still want to handle: if BO is
1626 // the IV increment. Important properties that make it profitable:
1627 // - We can speculate IV increment anywhere in the loop (as long as the
1628 // indvar Phi is its only user);
1629 // - Upon computing Cmp, we effectively compute something equivalent to the
1630 // IV increment (despite it loops differently in the IR). So moving it up
1631 // to the cmp point does not really increase register pressure.
1632 return false;
1633 }
1634
1635 // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
1636 if (BO->getOpcode() == Instruction::Add &&
1637 IID == Intrinsic::usub_with_overflow) {
1638 assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
1639 Arg1 = ConstantExpr::getNeg(C: cast<Constant>(Val: Arg1));
1640 }
1641
1642 // Insert at the first instruction of the pair.
1643 Instruction *InsertPt = nullptr;
1644 for (Instruction &Iter : *Cmp->getParent()) {
1645 // If BO is an XOR, it is not guaranteed that it comes after both inputs to
1646 // the overflow intrinsic are defined.
1647 if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
1648 InsertPt = &Iter;
1649 break;
1650 }
1651 }
1652 assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
1653
1654 IRBuilder<> Builder(InsertPt);
1655 Value *MathOV = Builder.CreateBinaryIntrinsic(ID: IID, LHS: Arg0, RHS: Arg1);
1656 if (BO->getOpcode() != Instruction::Xor) {
1657 Value *Math = Builder.CreateExtractValue(Agg: MathOV, Idxs: 0, Name: "math");
1658 replaceAllUsesWith(Old: BO, New: Math, FreshBBs, IsHuge: IsHugeFunc);
1659 } else
1660 assert(BO->hasOneUse() &&
1661 "Patterns with XOr should use the BO only in the compare");
1662 Value *OV = Builder.CreateExtractValue(Agg: MathOV, Idxs: 1, Name: "ov");
1663 replaceAllUsesWith(Old: Cmp, New: OV, FreshBBs, IsHuge: IsHugeFunc);
1664 Cmp->eraseFromParent();
1665 BO->eraseFromParent();
1666 return true;
1667}
1668
1669/// Match special-case patterns that check for unsigned add overflow.
1670static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
1671 BinaryOperator *&Add) {
1672 // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
1673 // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
1674 Value *A = Cmp->getOperand(i_nocapture: 0), *B = Cmp->getOperand(i_nocapture: 1);
1675
1676 // We are not expecting non-canonical/degenerate code. Just bail out.
1677 if (isa<Constant>(Val: A))
1678 return false;
1679
1680 ICmpInst::Predicate Pred = Cmp->getPredicate();
1681 if (Pred == ICmpInst::ICMP_EQ && match(V: B, P: m_AllOnes()))
1682 B = ConstantInt::get(Ty: B->getType(), V: 1);
1683 else if (Pred == ICmpInst::ICMP_NE && match(V: B, P: m_ZeroInt()))
1684 B = Constant::getAllOnesValue(Ty: B->getType());
1685 else
1686 return false;
1687
1688 // Check the users of the variable operand of the compare looking for an add
1689 // with the adjusted constant.
1690 for (User *U : A->users()) {
1691 if (match(V: U, P: m_Add(L: m_Specific(V: A), R: m_Specific(V: B)))) {
1692 Add = cast<BinaryOperator>(Val: U);
1693 return true;
1694 }
1695 }
1696 return false;
1697}
1698
1699/// Try to combine the compare into a call to the llvm.uadd.with.overflow
1700/// intrinsic. Return true if any changes were made.
1701bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
1702 ModifyDT &ModifiedDT) {
1703 bool EdgeCase = false;
1704 Value *A, *B;
1705 BinaryOperator *Add;
1706 if (!match(V: Cmp, P: m_UAddWithOverflow(L: m_Value(V&: A), R: m_Value(V&: B), S: m_BinOp(I&: Add)))) {
1707 if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add))
1708 return false;
1709 // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
1710 A = Add->getOperand(i_nocapture: 0);
1711 B = Add->getOperand(i_nocapture: 1);
1712 EdgeCase = true;
1713 }
1714
1715 if (!TLI->shouldFormOverflowOp(Opcode: ISD::UADDO,
1716 VT: TLI->getValueType(DL: *DL, Ty: Add->getType()),
1717 MathUsed: Add->hasNUsesOrMore(N: EdgeCase ? 1 : 2)))
1718 return false;
1719
1720 // We don't want to move around uses of condition values this late, so we
1721 // check if it is legal to create the call to the intrinsic in the basic
1722 // block containing the icmp.
1723 if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
1724 return false;
1725
1726 if (!replaceMathCmpWithIntrinsic(BO: Add, Arg0: A, Arg1: B, Cmp,
1727 IID: Intrinsic::uadd_with_overflow))
1728 return false;
1729
1730 // Reset callers - do not crash by iterating over a dead instruction.
1731 ModifiedDT = ModifyDT::ModifyInstDT;
1732 return true;
1733}
1734
1735bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
1736 ModifyDT &ModifiedDT) {
1737 // We are not expecting non-canonical/degenerate code. Just bail out.
1738 Value *A = Cmp->getOperand(i_nocapture: 0), *B = Cmp->getOperand(i_nocapture: 1);
1739 if (isa<Constant>(Val: A) && isa<Constant>(Val: B))
1740 return false;
1741
1742 // Convert (A u> B) to (A u< B) to simplify pattern matching.
1743 ICmpInst::Predicate Pred = Cmp->getPredicate();
1744 if (Pred == ICmpInst::ICMP_UGT) {
1745 std::swap(a&: A, b&: B);
1746 Pred = ICmpInst::ICMP_ULT;
1747 }
1748 // Convert special-case: (A == 0) is the same as (A u< 1).
1749 if (Pred == ICmpInst::ICMP_EQ && match(V: B, P: m_ZeroInt())) {
1750 B = ConstantInt::get(Ty: B->getType(), V: 1);
1751 Pred = ICmpInst::ICMP_ULT;
1752 }
1753 // Convert special-case: (A != 0) is the same as (0 u< A).
1754 if (Pred == ICmpInst::ICMP_NE && match(V: B, P: m_ZeroInt())) {
1755 std::swap(a&: A, b&: B);
1756 Pred = ICmpInst::ICMP_ULT;
1757 }
1758 if (Pred != ICmpInst::ICMP_ULT)
1759 return false;
1760
1761 // Walk the users of a variable operand of a compare looking for a subtract or
1762 // add with that same operand. Also match the 2nd operand of the compare to
1763 // the add/sub, but that may be a negated constant operand of an add.
1764 Value *CmpVariableOperand = isa<Constant>(Val: A) ? B : A;
1765 BinaryOperator *Sub = nullptr;
1766 for (User *U : CmpVariableOperand->users()) {
1767 // A - B, A u< B --> usubo(A, B)
1768 if (match(V: U, P: m_Sub(L: m_Specific(V: A), R: m_Specific(V: B)))) {
1769 Sub = cast<BinaryOperator>(Val: U);
1770 break;
1771 }
1772
1773 // A + (-C), A u< C (canonicalized form of (sub A, C))
1774 const APInt *CmpC, *AddC;
1775 if (match(V: U, P: m_Add(L: m_Specific(V: A), R: m_APInt(Res&: AddC))) &&
1776 match(V: B, P: m_APInt(Res&: CmpC)) && *AddC == -(*CmpC)) {
1777 Sub = cast<BinaryOperator>(Val: U);
1778 break;
1779 }
1780 }
1781 if (!Sub)
1782 return false;
1783
1784 if (!TLI->shouldFormOverflowOp(Opcode: ISD::USUBO,
1785 VT: TLI->getValueType(DL: *DL, Ty: Sub->getType()),
1786 MathUsed: Sub->hasNUsesOrMore(N: 1)))
1787 return false;
1788
1789 // We don't want to move around uses of condition values this late, so we
1790 // check if it is legal to create the call to the intrinsic in the basic
1791 // block containing the icmp.
1792 if (Sub->getParent() != Cmp->getParent() && !Sub->hasOneUse())
1793 return false;
1794
1795 if (!replaceMathCmpWithIntrinsic(BO: Sub, Arg0: Sub->getOperand(i_nocapture: 0), Arg1: Sub->getOperand(i_nocapture: 1),
1796 Cmp, IID: Intrinsic::usub_with_overflow))
1797 return false;
1798
1799 // Reset callers - do not crash by iterating over a dead instruction.
1800 ModifiedDT = ModifyDT::ModifyInstDT;
1801 return true;
1802}
1803
1804// Decanonicalizes icmp+ctpop power-of-two test if ctpop is slow.
1805// The same transformation exists in DAG combiner, but we repeat it here because
1806// DAG builder can break the pattern by moving icmp into a successor block.
1807bool CodeGenPrepare::unfoldPowerOf2Test(CmpInst *Cmp) {
1808 CmpPredicate Pred;
1809 Value *X;
1810 const APInt *C;
1811
1812 // (icmp (ctpop x), c)
1813 if (!match(V: Cmp, P: m_ICmp(Pred, L: m_Ctpop(Op0: m_Value(V&: X)), R: m_APIntAllowPoison(Res&: C))))
1814 return false;
1815
1816 // We're only interested in "is power of 2 [or zero]" patterns.
1817 bool IsStrictlyPowerOf2Test = ICmpInst::isEquality(P: Pred) && *C == 1;
1818 bool IsPowerOf2OrZeroTest = (Pred == CmpInst::ICMP_ULT && *C == 2) ||
1819 (Pred == CmpInst::ICMP_UGT && *C == 1);
1820 if (!IsStrictlyPowerOf2Test && !IsPowerOf2OrZeroTest)
1821 return false;
1822
1823 // Some targets have better codegen for `ctpop(x) u</u>= 2/1`than for
1824 // `ctpop(x) ==/!= 1`. If ctpop is fast, only try changing the comparison,
1825 // and otherwise expand ctpop into a few simple instructions.
1826 Type *OpTy = X->getType();
1827 if (TLI->isCtpopFast(VT: TLI->getValueType(DL: *DL, Ty: OpTy))) {
1828 // Look for `ctpop(x) ==/!= 1`, where `ctpop(x)` is known to be non-zero.
1829 if (!IsStrictlyPowerOf2Test || !isKnownNonZero(V: Cmp->getOperand(i_nocapture: 0), Q: *DL))
1830 return false;
1831
1832 // ctpop(x) == 1 -> ctpop(x) u< 2
1833 // ctpop(x) != 1 -> ctpop(x) u> 1
1834 if (Pred == ICmpInst::ICMP_EQ) {
1835 Cmp->setOperand(i_nocapture: 1, Val_nocapture: ConstantInt::get(Ty: OpTy, V: 2));
1836 Cmp->setPredicate(ICmpInst::ICMP_ULT);
1837 } else {
1838 Cmp->setPredicate(ICmpInst::ICMP_UGT);
1839 }
1840 return true;
1841 }
1842
1843 Value *NewCmp;
1844 if (IsPowerOf2OrZeroTest ||
1845 (IsStrictlyPowerOf2Test && isKnownNonZero(V: Cmp->getOperand(i_nocapture: 0), Q: *DL))) {
1846 // ctpop(x) u< 2 -> (x & (x - 1)) == 0
1847 // ctpop(x) u> 1 -> (x & (x - 1)) != 0
1848 IRBuilder<> Builder(Cmp);
1849 Value *Sub = Builder.CreateAdd(LHS: X, RHS: Constant::getAllOnesValue(Ty: OpTy));
1850 Value *And = Builder.CreateAnd(LHS: X, RHS: Sub);
1851 CmpInst::Predicate NewPred =
1852 (Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_EQ)
1853 ? CmpInst::ICMP_EQ
1854 : CmpInst::ICMP_NE;
1855 NewCmp = Builder.CreateICmp(P: NewPred, LHS: And, RHS: ConstantInt::getNullValue(Ty: OpTy));
1856 } else {
1857 // ctpop(x) == 1 -> (x ^ (x - 1)) u> (x - 1)
1858 // ctpop(x) != 1 -> (x ^ (x - 1)) u<= (x - 1)
1859 IRBuilder<> Builder(Cmp);
1860 Value *Sub = Builder.CreateAdd(LHS: X, RHS: Constant::getAllOnesValue(Ty: OpTy));
1861 Value *Xor = Builder.CreateXor(LHS: X, RHS: Sub);
1862 CmpInst::Predicate NewPred =
1863 Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
1864 NewCmp = Builder.CreateICmp(P: NewPred, LHS: Xor, RHS: Sub);
1865 }
1866
1867 Cmp->replaceAllUsesWith(V: NewCmp);
1868 RecursivelyDeleteTriviallyDeadInstructions(V: Cmp);
1869 return true;
1870}
1871
1872/// Sink the given CmpInst into user blocks to reduce the number of virtual
1873/// registers that must be created and coalesced. This is a clear win except on
1874/// targets with multiple condition code registers (PowerPC), where it might
1875/// lose; some adjustment may be wanted there.
1876///
1877/// Return true if any changes are made.
1878static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI,
1879 const DataLayout &DL) {
1880 if (TLI.hasMultipleConditionRegisters(VT: EVT::getEVT(Ty: Cmp->getType())))
1881 return false;
1882
1883 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
1884 if (TLI.useSoftFloat() && isa<FCmpInst>(Val: Cmp))
1885 return false;
1886
1887 bool UsedInPhiOrCurrentBlock = any_of(Range: Cmp->users(), P: [Cmp](User *U) {
1888 return isa<PHINode>(Val: U) ||
1889 cast<Instruction>(Val: U)->getParent() == Cmp->getParent();
1890 });
1891
1892 // Avoid sinking larger than legal integer comparisons unless its ONLY used in
1893 // another BB.
1894 if (UsedInPhiOrCurrentBlock && Cmp->getOperand(i_nocapture: 0)->getType()->isIntegerTy() &&
1895 Cmp->getOperand(i_nocapture: 0)->getType()->getScalarSizeInBits() >
1896 DL.getLargestLegalIntTypeSizeInBits())
1897 return false;
1898
1899 // Only insert a cmp in each block once.
1900 DenseMap<BasicBlock *, CmpInst *> InsertedCmps;
1901
1902 bool MadeChange = false;
1903 for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
1904 UI != E;) {
1905 Use &TheUse = UI.getUse();
1906 Instruction *User = cast<Instruction>(Val: *UI);
1907
1908 // Preincrement use iterator so we don't invalidate it.
1909 ++UI;
1910
1911 // Don't bother for PHI nodes.
1912 if (isa<PHINode>(Val: User))
1913 continue;
1914
1915 // Figure out which BB this cmp is used in.
1916 BasicBlock *UserBB = User->getParent();
1917 BasicBlock *DefBB = Cmp->getParent();
1918
1919 // If this user is in the same block as the cmp, don't change the cmp.
1920 if (UserBB == DefBB)
1921 continue;
1922
1923 // If we have already inserted a cmp into this block, use it.
1924 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1925
1926 if (!InsertedCmp) {
1927 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1928 assert(InsertPt != UserBB->end());
1929 InsertedCmp = CmpInst::Create(Op: Cmp->getOpcode(), Pred: Cmp->getPredicate(),
1930 S1: Cmp->getOperand(i_nocapture: 0), S2: Cmp->getOperand(i_nocapture: 1), Name: "");
1931 InsertedCmp->insertBefore(BB&: *UserBB, InsertPos: InsertPt);
1932 // Propagate the debug info.
1933 InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
1934 }
1935
1936 // Replace a use of the cmp with a use of the new cmp.
1937 TheUse = InsertedCmp;
1938 MadeChange = true;
1939 ++NumCmpUses;
1940 }
1941
1942 // If we removed all uses, nuke the cmp.
1943 if (Cmp->use_empty()) {
1944 Cmp->eraseFromParent();
1945 MadeChange = true;
1946 }
1947
1948 return MadeChange;
1949}
1950
1951/// For pattern like:
1952///
1953/// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
1954/// ...
1955/// DomBB:
1956/// ...
1957/// br DomCond, TrueBB, CmpBB
1958/// CmpBB: (with DomBB being the single predecessor)
1959/// ...
1960/// Cmp = icmp eq CmpOp0, CmpOp1
1961/// ...
1962///
1963/// It would use two comparison on targets that lowering of icmp sgt/slt is
1964/// different from lowering of icmp eq (PowerPC). This function try to convert
1965/// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
1966/// After that, DomCond and Cmp can use the same comparison so reduce one
1967/// comparison.
1968///
1969/// Return true if any changes are made.
1970static bool foldICmpWithDominatingICmp(CmpInst *Cmp,
1971 const TargetLowering &TLI) {
1972 if (!EnableICMP_EQToICMP_ST && TLI.isEqualityCmpFoldedWithSignedCmp())
1973 return false;
1974
1975 ICmpInst::Predicate Pred = Cmp->getPredicate();
1976 if (Pred != ICmpInst::ICMP_EQ)
1977 return false;
1978
1979 // If icmp eq has users other than CondBrInst and SelectInst, converting it to
1980 // icmp slt/sgt would introduce more redundant LLVM IR.
1981 for (User *U : Cmp->users()) {
1982 if (isa<CondBrInst>(Val: U))
1983 continue;
1984 if (isa<SelectInst>(Val: U) && cast<SelectInst>(Val: U)->getCondition() == Cmp)
1985 continue;
1986 return false;
1987 }
1988
1989 // This is a cheap/incomplete check for dominance - just match a single
1990 // predecessor with a conditional branch.
1991 BasicBlock *CmpBB = Cmp->getParent();
1992 BasicBlock *DomBB = CmpBB->getSinglePredecessor();
1993 if (!DomBB)
1994 return false;
1995
1996 // We want to ensure that the only way control gets to the comparison of
1997 // interest is that a less/greater than comparison on the same operands is
1998 // false.
1999 Value *DomCond;
2000 BasicBlock *TrueBB, *FalseBB;
2001 if (!match(V: DomBB->getTerminator(), P: m_Br(C: m_Value(V&: DomCond), T&: TrueBB, F&: FalseBB)))
2002 return false;
2003 if (CmpBB != FalseBB)
2004 return false;
2005
2006 Value *CmpOp0 = Cmp->getOperand(i_nocapture: 0), *CmpOp1 = Cmp->getOperand(i_nocapture: 1);
2007 CmpPredicate DomPred;
2008 if (!match(V: DomCond, P: m_ICmp(Pred&: DomPred, L: m_Specific(V: CmpOp0), R: m_Specific(V: CmpOp1))))
2009 return false;
2010 if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
2011 return false;
2012
2013 // Convert the equality comparison to the opposite of the dominating
2014 // comparison and swap the direction for all branch/select users.
2015 // We have conceptually converted:
2016 // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
2017 // to
2018 // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
2019 // And similarly for branches.
2020 for (User *U : Cmp->users()) {
2021 if (auto *BI = dyn_cast<CondBrInst>(Val: U)) {
2022 BI->swapSuccessors();
2023 continue;
2024 }
2025 if (auto *SI = dyn_cast<SelectInst>(Val: U)) {
2026 // Swap operands
2027 SI->swapValues();
2028 SI->swapProfMetadata();
2029 continue;
2030 }
2031 llvm_unreachable("Must be a branch or a select");
2032 }
2033 Cmp->setPredicate(CmpInst::getSwappedPredicate(pred: DomPred));
2034 return true;
2035}
2036
2037/// Many architectures use the same instruction for both subtract and cmp. Try
2038/// to swap cmp operands to match subtract operations to allow for CSE.
2039static bool swapICmpOperandsToExposeCSEOpportunities(CmpInst *Cmp) {
2040 Value *Op0 = Cmp->getOperand(i_nocapture: 0);
2041 Value *Op1 = Cmp->getOperand(i_nocapture: 1);
2042 if (!Op0->getType()->isIntegerTy() || isa<Constant>(Val: Op0) ||
2043 isa<Constant>(Val: Op1) || Op0 == Op1)
2044 return false;
2045
2046 // If a subtract already has the same operands as a compare, swapping would be
2047 // bad. If a subtract has the same operands as a compare but in reverse order,
2048 // then swapping is good.
2049 int GoodToSwap = 0;
2050 unsigned NumInspected = 0;
2051 for (const User *U : Op0->users()) {
2052 // Avoid walking many users.
2053 if (++NumInspected > 128)
2054 return false;
2055 if (match(V: U, P: m_Sub(L: m_Specific(V: Op1), R: m_Specific(V: Op0))))
2056 GoodToSwap++;
2057 else if (match(V: U, P: m_Sub(L: m_Specific(V: Op0), R: m_Specific(V: Op1))))
2058 GoodToSwap--;
2059 }
2060
2061 if (GoodToSwap > 0) {
2062 Cmp->swapOperands();
2063 return true;
2064 }
2065 return false;
2066}
2067
2068static bool foldFCmpToFPClassTest(CmpInst *Cmp, const TargetLowering &TLI,
2069 const DataLayout &DL) {
2070 FCmpInst *FCmp = dyn_cast<FCmpInst>(Val: Cmp);
2071 if (!FCmp)
2072 return false;
2073
2074 // Don't fold if the target offers free fabs and the predicate is legal.
2075 EVT VT = TLI.getValueType(DL, Ty: Cmp->getOperand(i_nocapture: 0)->getType());
2076 if (TLI.isFAbsFree(VT) &&
2077 TLI.isCondCodeLegal(CC: getFCmpCondCode(Pred: FCmp->getPredicate()),
2078 VT: VT.getSimpleVT()))
2079 return false;
2080
2081 // Reverse the canonicalization if it is a FP class test
2082 auto ShouldReverseTransform = [](FPClassTest ClassTest) {
2083 return ClassTest == fcInf || ClassTest == (fcInf | fcNan);
2084 };
2085 auto [ClassVal, ClassTest] =
2086 fcmpToClassTest(Pred: FCmp->getPredicate(), F: *FCmp->getParent()->getParent(),
2087 LHS: FCmp->getOperand(i_nocapture: 0), RHS: FCmp->getOperand(i_nocapture: 1));
2088 if (!ClassVal)
2089 return false;
2090
2091 if (!ShouldReverseTransform(ClassTest) && !ShouldReverseTransform(~ClassTest))
2092 return false;
2093
2094 IRBuilder<> Builder(Cmp);
2095 Value *IsFPClass = Builder.createIsFPClass(FPNum: ClassVal, Test: ClassTest);
2096 Cmp->replaceAllUsesWith(V: IsFPClass);
2097 RecursivelyDeleteTriviallyDeadInstructions(V: Cmp);
2098 return true;
2099}
2100
2101static bool isRemOfLoopIncrementWithLoopInvariant(
2102 Instruction *Rem, const LoopInfo *LI, Value *&RemAmtOut, Value *&AddInstOut,
2103 Value *&AddOffsetOut, PHINode *&LoopIncrPNOut) {
2104 Value *Incr, *RemAmt;
2105 // NB: If RemAmt is a power of 2 it *should* have been transformed by now.
2106 if (!match(V: Rem, P: m_URem(L: m_Value(V&: Incr), R: m_Value(V&: RemAmt))))
2107 return false;
2108
2109 Value *AddInst, *AddOffset;
2110 // Find out loop increment PHI.
2111 PHINode *PN = dyn_cast<PHINode>(Val: Incr);
2112 if (PN != nullptr) {
2113 AddInst = nullptr;
2114 AddOffset = nullptr;
2115 } else {
2116 // Search through a NUW add on top of the loop increment.
2117 if (!match(V: Incr, P: m_c_NUWAdd(L: m_Phi(PN), R: m_Value(V&: AddOffset))))
2118 return false;
2119 AddInst = Incr;
2120 }
2121
2122 if (!PN)
2123 return false;
2124
2125 // This isn't strictly necessary, what we really need is one increment and any
2126 // amount of initial values all being the same.
2127 if (PN->getNumIncomingValues() != 2)
2128 return false;
2129
2130 // Only trivially analyzable loops.
2131 Loop *L = LI->getLoopFor(BB: PN->getParent());
2132 if (!L || !L->getLoopPreheader() || !L->getLoopLatch())
2133 return false;
2134
2135 // Req that the remainder is in the loop
2136 if (!L->contains(Inst: Rem))
2137 return false;
2138
2139 // Only works if the remainder amount is a loop invaraint
2140 if (!L->isLoopInvariant(V: RemAmt))
2141 return false;
2142
2143 // Only works if the AddOffset is a loop invaraint
2144 if (AddOffset && !L->isLoopInvariant(V: AddOffset))
2145 return false;
2146
2147 // Is the PHI a loop increment?
2148 auto LoopIncrInfo = getIVIncrement(PN, LI);
2149 if (!LoopIncrInfo)
2150 return false;
2151
2152 // We need remainder_amount % increment_amount to be zero. Increment of one
2153 // satisfies that without any special logic and is overwhelmingly the common
2154 // case.
2155 if (!match(V: LoopIncrInfo->second, P: m_One()))
2156 return false;
2157
2158 // Need the increment to not overflow.
2159 if (!match(V: LoopIncrInfo->first, P: m_c_NUWAdd(L: m_Specific(V: PN), R: m_Value())))
2160 return false;
2161
2162 // Set output variables.
2163 RemAmtOut = RemAmt;
2164 LoopIncrPNOut = PN;
2165 AddInstOut = AddInst;
2166 AddOffsetOut = AddOffset;
2167
2168 return true;
2169}
2170
2171// Try to transform:
2172//
2173// for(i = Start; i < End; ++i)
2174// Rem = (i nuw+ IncrLoopInvariant) u% RemAmtLoopInvariant;
2175//
2176// ->
2177//
2178// Rem = (Start nuw+ IncrLoopInvariant) % RemAmtLoopInvariant;
2179// for(i = Start; i < End; ++i, ++rem)
2180// Rem = rem == RemAmtLoopInvariant ? 0 : Rem;
2181static bool foldURemOfLoopIncrement(Instruction *Rem, const DataLayout *DL,
2182 const LoopInfo *LI,
2183 SmallPtrSet<BasicBlock *, 32> &FreshBBs,
2184 bool IsHuge) {
2185 Value *AddOffset, *RemAmt, *AddInst;
2186 PHINode *LoopIncrPN;
2187 if (!isRemOfLoopIncrementWithLoopInvariant(Rem, LI, RemAmtOut&: RemAmt, AddInstOut&: AddInst,
2188 AddOffsetOut&: AddOffset, LoopIncrPNOut&: LoopIncrPN))
2189 return false;
2190
2191 // Only non-constant remainder as the extra IV is probably not profitable
2192 // in that case.
2193 //
2194 // Potential TODO(1): `urem` of a const ends up as `mul` + `shift` + `add`. If
2195 // we can rule out register pressure and ensure this `urem` is executed each
2196 // iteration, its probably profitable to handle the const case as well.
2197 //
2198 // Potential TODO(2): Should we have a check for how "nested" this remainder
2199 // operation is? The new code runs every iteration so if the remainder is
2200 // guarded behind unlikely conditions this might not be worth it.
2201 if (match(V: RemAmt, P: m_ImmConstant()))
2202 return false;
2203
2204 Loop *L = LI->getLoopFor(BB: LoopIncrPN->getParent());
2205 Value *Start = LoopIncrPN->getIncomingValueForBlock(BB: L->getLoopPreheader());
2206 // If we have add create initial value for remainder.
2207 // The logic here is:
2208 // (urem (add nuw Start, IncrLoopInvariant), RemAmtLoopInvariant
2209 //
2210 // Only proceed if the expression simplifies (otherwise we can't fully
2211 // optimize out the urem).
2212 if (AddInst) {
2213 assert(AddOffset && "We found an add but missing values");
2214 // Without dom-condition/assumption cache we aren't likely to get much out
2215 // of a context instruction.
2216 Start = simplifyAddInst(LHS: Start, RHS: AddOffset,
2217 IsNSW: match(V: AddInst, P: m_NSWAdd(L: m_Value(), R: m_Value())),
2218 /*IsNUW=*/true, Q: *DL);
2219 if (!Start)
2220 return false;
2221 }
2222
2223 // If we can't fully optimize out the `rem`, skip this transform.
2224 Start = simplifyURemInst(LHS: Start, RHS: RemAmt, Q: *DL);
2225 if (!Start)
2226 return false;
2227
2228 // Create new remainder with induction variable.
2229 Type *Ty = Rem->getType();
2230 IRBuilder<> Builder(Rem->getContext());
2231
2232 Builder.SetInsertPoint(LoopIncrPN);
2233 PHINode *NewRem = Builder.CreatePHI(Ty, NumReservedValues: 2);
2234
2235 Builder.SetInsertPoint(cast<Instruction>(
2236 Val: LoopIncrPN->getIncomingValueForBlock(BB: L->getLoopLatch())));
2237 // `(add (urem x, y), 1)` is always nuw.
2238 Value *RemAdd = Builder.CreateNUWAdd(LHS: NewRem, RHS: ConstantInt::get(Ty, V: 1));
2239 Value *RemCmp = Builder.CreateICmp(P: ICmpInst::ICMP_EQ, LHS: RemAdd, RHS: RemAmt);
2240 Value *RemSel =
2241 Builder.CreateSelect(C: RemCmp, True: Constant::getNullValue(Ty), False: RemAdd);
2242
2243 NewRem->addIncoming(V: Start, BB: L->getLoopPreheader());
2244 NewRem->addIncoming(V: RemSel, BB: L->getLoopLatch());
2245
2246 // Insert all touched BBs.
2247 FreshBBs.insert(Ptr: LoopIncrPN->getParent());
2248 FreshBBs.insert(Ptr: L->getLoopLatch());
2249 FreshBBs.insert(Ptr: Rem->getParent());
2250 if (AddInst)
2251 FreshBBs.insert(Ptr: cast<Instruction>(Val: AddInst)->getParent());
2252 replaceAllUsesWith(Old: Rem, New: NewRem, FreshBBs, IsHuge);
2253 Rem->eraseFromParent();
2254 if (AddInst && AddInst->use_empty())
2255 cast<Instruction>(Val: AddInst)->eraseFromParent();
2256 return true;
2257}
2258
2259bool CodeGenPrepare::optimizeURem(Instruction *Rem) {
2260 if (foldURemOfLoopIncrement(Rem, DL, LI, FreshBBs, IsHuge: IsHugeFunc))
2261 return true;
2262 return false;
2263}
2264
2265bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
2266 if (sinkCmpExpression(Cmp, TLI: *TLI, DL: *DL))
2267 return true;
2268
2269 if (combineToUAddWithOverflow(Cmp, ModifiedDT))
2270 return true;
2271
2272 if (combineToUSubWithOverflow(Cmp, ModifiedDT))
2273 return true;
2274
2275 if (unfoldPowerOf2Test(Cmp))
2276 return true;
2277
2278 if (foldICmpWithDominatingICmp(Cmp, TLI: *TLI))
2279 return true;
2280
2281 if (swapICmpOperandsToExposeCSEOpportunities(Cmp))
2282 return true;
2283
2284 if (foldFCmpToFPClassTest(Cmp, TLI: *TLI, DL: *DL))
2285 return true;
2286
2287 return false;
2288}
2289
2290/// Duplicate and sink the given 'and' instruction into user blocks where it is
2291/// used in a compare to allow isel to generate better code for targets where
2292/// this operation can be combined.
2293///
2294/// Return true if any changes are made.
2295static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI,
2296 SetOfInstrs &InsertedInsts) {
2297 // Double-check that we're not trying to optimize an instruction that was
2298 // already optimized by some other part of this pass.
2299 assert(!InsertedInsts.count(AndI) &&
2300 "Attempting to optimize already optimized and instruction");
2301 (void)InsertedInsts;
2302
2303 // Nothing to do for single use in same basic block.
2304 if (AndI->hasOneUse() &&
2305 AndI->getParent() == cast<Instruction>(Val: *AndI->user_begin())->getParent())
2306 return false;
2307
2308 // Try to avoid cases where sinking/duplicating is likely to increase register
2309 // pressure.
2310 if (!isa<ConstantInt>(Val: AndI->getOperand(i: 0)) &&
2311 !isa<ConstantInt>(Val: AndI->getOperand(i: 1)) &&
2312 AndI->getOperand(i: 0)->hasOneUse() && AndI->getOperand(i: 1)->hasOneUse())
2313 return false;
2314
2315 for (auto *U : AndI->users()) {
2316 Instruction *User = cast<Instruction>(Val: U);
2317
2318 // Only sink 'and' feeding icmp with 0.
2319 if (!isa<ICmpInst>(Val: User))
2320 return false;
2321
2322 auto *CmpC = dyn_cast<ConstantInt>(Val: User->getOperand(i: 1));
2323 if (!CmpC || !CmpC->isZero())
2324 return false;
2325 }
2326
2327 if (!TLI.isMaskAndCmp0FoldingBeneficial(AndI: *AndI))
2328 return false;
2329
2330 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
2331 LLVM_DEBUG(AndI->getParent()->dump());
2332
2333 // Push the 'and' into the same block as the icmp 0. There should only be
2334 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
2335 // others, so we don't need to keep track of which BBs we insert into.
2336 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
2337 UI != E;) {
2338 Use &TheUse = UI.getUse();
2339 Instruction *User = cast<Instruction>(Val: *UI);
2340
2341 // Preincrement use iterator so we don't invalidate it.
2342 ++UI;
2343
2344 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
2345
2346 // Keep the 'and' in the same place if the use is already in the same block.
2347 Instruction *InsertPt =
2348 User->getParent() == AndI->getParent() ? AndI : User;
2349 Instruction *InsertedAnd = BinaryOperator::Create(
2350 Op: Instruction::And, S1: AndI->getOperand(i: 0), S2: AndI->getOperand(i: 1), Name: "",
2351 InsertBefore: InsertPt->getIterator());
2352 // Propagate the debug info.
2353 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
2354
2355 // Replace a use of the 'and' with a use of the new 'and'.
2356 TheUse = InsertedAnd;
2357 ++NumAndUses;
2358 LLVM_DEBUG(User->getParent()->dump());
2359 }
2360
2361 // We removed all uses, nuke the and.
2362 AndI->eraseFromParent();
2363 return true;
2364}
2365
2366/// Check if the candidates could be combined with a shift instruction, which
2367/// includes:
2368/// 1. Truncate instruction
2369/// 2. And instruction and the imm is a mask of the low bits:
2370/// imm & (imm+1) == 0
2371static bool isExtractBitsCandidateUse(Instruction *User) {
2372 if (!isa<TruncInst>(Val: User)) {
2373 if (User->getOpcode() != Instruction::And ||
2374 !isa<ConstantInt>(Val: User->getOperand(i: 1)))
2375 return false;
2376
2377 const APInt &Cimm = cast<ConstantInt>(Val: User->getOperand(i: 1))->getValue();
2378
2379 if ((Cimm & (Cimm + 1)).getBoolValue())
2380 return false;
2381 }
2382 return true;
2383}
2384
2385/// Sink both shift and truncate instruction to the use of truncate's BB.
2386static bool
2387SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
2388 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
2389 const TargetLowering &TLI, const DataLayout &DL) {
2390 BasicBlock *UserBB = User->getParent();
2391 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
2392 auto *TruncI = cast<TruncInst>(Val: User);
2393 bool MadeChange = false;
2394
2395 for (Value::user_iterator TruncUI = TruncI->user_begin(),
2396 TruncE = TruncI->user_end();
2397 TruncUI != TruncE;) {
2398
2399 Use &TruncTheUse = TruncUI.getUse();
2400 Instruction *TruncUser = cast<Instruction>(Val: *TruncUI);
2401 // Preincrement use iterator so we don't invalidate it.
2402
2403 ++TruncUI;
2404
2405 int ISDOpcode = TLI.InstructionOpcodeToISD(Opcode: TruncUser->getOpcode());
2406 if (!ISDOpcode)
2407 continue;
2408
2409 // If the use is actually a legal node, there will not be an
2410 // implicit truncate.
2411 // FIXME: always querying the result type is just an
2412 // approximation; some nodes' legality is determined by the
2413 // operand or other means. There's no good way to find out though.
2414 if (TLI.isOperationLegalOrCustom(
2415 Op: ISDOpcode, VT: TLI.getValueType(DL, Ty: TruncUser->getType(), AllowUnknown: true)))
2416 continue;
2417
2418 // Don't bother for PHI nodes.
2419 if (isa<PHINode>(Val: TruncUser))
2420 continue;
2421
2422 BasicBlock *TruncUserBB = TruncUser->getParent();
2423
2424 if (UserBB == TruncUserBB)
2425 continue;
2426
2427 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
2428 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
2429
2430 if (!InsertedShift && !InsertedTrunc) {
2431 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
2432 assert(InsertPt != TruncUserBB->end());
2433 // Sink the shift
2434 if (ShiftI->getOpcode() == Instruction::AShr)
2435 InsertedShift =
2436 BinaryOperator::CreateAShr(V1: ShiftI->getOperand(i_nocapture: 0), V2: CI, Name: "");
2437 else
2438 InsertedShift =
2439 BinaryOperator::CreateLShr(V1: ShiftI->getOperand(i_nocapture: 0), V2: CI, Name: "");
2440 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2441 InsertedShift->insertBefore(BB&: *TruncUserBB, InsertPos: InsertPt);
2442
2443 // Sink the trunc
2444 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
2445 TruncInsertPt++;
2446 // It will go ahead of any debug-info.
2447 TruncInsertPt.setHeadBit(true);
2448 assert(TruncInsertPt != TruncUserBB->end());
2449
2450 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), S: InsertedShift,
2451 Ty: TruncI->getType(), Name: "");
2452 InsertedTrunc->insertBefore(BB&: *TruncUserBB, InsertPos: TruncInsertPt);
2453 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
2454
2455 MadeChange = true;
2456
2457 TruncTheUse = InsertedTrunc;
2458 }
2459 }
2460 return MadeChange;
2461}
2462
2463/// Sink the shift *right* instruction into user blocks if the uses could
2464/// potentially be combined with this shift instruction and generate BitExtract
2465/// instruction. It will only be applied if the architecture supports BitExtract
2466/// instruction. Here is an example:
2467/// BB1:
2468/// %x.extract.shift = lshr i64 %arg1, 32
2469/// BB2:
2470/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
2471/// ==>
2472///
2473/// BB2:
2474/// %x.extract.shift.1 = lshr i64 %arg1, 32
2475/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
2476///
2477/// CodeGen will recognize the pattern in BB2 and generate BitExtract
2478/// instruction.
2479/// Return true if any changes are made.
2480static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
2481 const TargetLowering &TLI,
2482 const DataLayout &DL) {
2483 BasicBlock *DefBB = ShiftI->getParent();
2484
2485 /// Only insert instructions in each block once.
2486 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
2487
2488 bool shiftIsLegal = TLI.isTypeLegal(VT: TLI.getValueType(DL, Ty: ShiftI->getType()));
2489
2490 bool MadeChange = false;
2491 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
2492 UI != E;) {
2493 Use &TheUse = UI.getUse();
2494 Instruction *User = cast<Instruction>(Val: *UI);
2495 // Preincrement use iterator so we don't invalidate it.
2496 ++UI;
2497
2498 // Don't bother for PHI nodes.
2499 if (isa<PHINode>(Val: User))
2500 continue;
2501
2502 if (!isExtractBitsCandidateUse(User))
2503 continue;
2504
2505 BasicBlock *UserBB = User->getParent();
2506
2507 if (UserBB == DefBB) {
2508 // If the shift and truncate instruction are in the same BB. The use of
2509 // the truncate(TruncUse) may still introduce another truncate if not
2510 // legal. In this case, we would like to sink both shift and truncate
2511 // instruction to the BB of TruncUse.
2512 // for example:
2513 // BB1:
2514 // i64 shift.result = lshr i64 opnd, imm
2515 // trunc.result = trunc shift.result to i16
2516 //
2517 // BB2:
2518 // ----> We will have an implicit truncate here if the architecture does
2519 // not have i16 compare.
2520 // cmp i16 trunc.result, opnd2
2521 //
2522 if (isa<TruncInst>(Val: User) &&
2523 shiftIsLegal
2524 // If the type of the truncate is legal, no truncate will be
2525 // introduced in other basic blocks.
2526 && (!TLI.isTypeLegal(VT: TLI.getValueType(DL, Ty: User->getType()))))
2527 MadeChange =
2528 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
2529
2530 continue;
2531 }
2532 // If we have already inserted a shift into this block, use it.
2533 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
2534
2535 if (!InsertedShift) {
2536 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2537 assert(InsertPt != UserBB->end());
2538
2539 if (ShiftI->getOpcode() == Instruction::AShr)
2540 InsertedShift =
2541 BinaryOperator::CreateAShr(V1: ShiftI->getOperand(i_nocapture: 0), V2: CI, Name: "");
2542 else
2543 InsertedShift =
2544 BinaryOperator::CreateLShr(V1: ShiftI->getOperand(i_nocapture: 0), V2: CI, Name: "");
2545 InsertedShift->insertBefore(BB&: *UserBB, InsertPos: InsertPt);
2546 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
2547
2548 MadeChange = true;
2549 }
2550
2551 // Replace a use of the shift with a use of the new shift.
2552 TheUse = InsertedShift;
2553 }
2554
2555 // If we removed all uses, or there are none, nuke the shift.
2556 if (ShiftI->use_empty()) {
2557 salvageDebugInfo(I&: *ShiftI);
2558 ShiftI->eraseFromParent();
2559 MadeChange = true;
2560 }
2561
2562 return MadeChange;
2563}
2564
2565/// If counting leading or trailing zeros is an expensive operation and a zero
2566/// input is defined, add a check for zero to avoid calling the intrinsic.
2567///
2568/// We want to transform:
2569/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2570///
2571/// into:
2572/// entry:
2573/// %cmpz = icmp eq i64 %A, 0
2574/// br i1 %cmpz, label %cond.end, label %cond.false
2575/// cond.false:
2576/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2577/// br label %cond.end
2578/// cond.end:
2579/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2580///
2581/// If the transform is performed, return true and set ModifiedDT to true.
2582static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2583 DomTreeUpdater *DTU, LoopInfo *LI,
2584 const TargetLowering *TLI,
2585 const DataLayout *DL, ModifyDT &ModifiedDT,
2586 SmallPtrSet<BasicBlock *, 32> &FreshBBs,
2587 bool IsHugeFunc) {
2588 // If a zero input is undefined, it doesn't make sense to despeculate that.
2589 if (match(V: CountZeros->getOperand(i_nocapture: 1), P: m_One()))
2590 return false;
2591
2592 // If it's cheap to speculate, there's nothing to do.
2593 Type *Ty = CountZeros->getType();
2594 auto IntrinsicID = CountZeros->getIntrinsicID();
2595 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
2596 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
2597 return false;
2598
2599 // Only handle scalar cases. Anything else requires too much work.
2600 unsigned SizeInBits = Ty->getScalarSizeInBits();
2601 if (Ty->isVectorTy())
2602 return false;
2603
2604 // Bail if the value is never zero.
2605 Use &Op = CountZeros->getOperandUse(i: 0);
2606 if (isKnownNonZero(V: Op, Q: *DL))
2607 return false;
2608
2609 // The intrinsic will be sunk behind a compare against zero and branch.
2610 BasicBlock *StartBlock = CountZeros->getParent();
2611 BasicBlock *CallBlock = SplitBlock(Old: StartBlock, SplitPt: CountZeros, DTU, LI,
2612 /* MSSAU */ nullptr, BBName: "cond.false");
2613 if (IsHugeFunc)
2614 FreshBBs.insert(Ptr: CallBlock);
2615
2616 // Create another block after the count zero intrinsic. A PHI will be added
2617 // in this block to select the result of the intrinsic or the bit-width
2618 // constant if the input to the intrinsic is zero.
2619 BasicBlock::iterator SplitPt = std::next(x: BasicBlock::iterator(CountZeros));
2620 // Any debug-info after CountZeros should not be included.
2621 SplitPt.setHeadBit(true);
2622 BasicBlock *EndBlock = SplitBlock(Old: CallBlock, SplitPt: &*SplitPt, DTU, LI,
2623 /* MSSAU */ nullptr, BBName: "cond.end");
2624 if (IsHugeFunc)
2625 FreshBBs.insert(Ptr: EndBlock);
2626
2627 // Set up a builder to create a compare, conditional branch, and PHI.
2628 IRBuilder<> Builder(CountZeros->getContext());
2629 Builder.SetInsertPoint(StartBlock->getTerminator());
2630 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2631
2632 // Replace the unconditional branch that was created by the first split with
2633 // a compare against zero and a conditional branch.
2634 Value *Zero = Constant::getNullValue(Ty);
2635 // Avoid introducing branch on poison. This also replaces the ctz operand.
2636 if (!isGuaranteedNotToBeUndefOrPoison(V: Op))
2637 Op = Builder.CreateFreeze(V: Op, Name: Op->getName() + ".fr");
2638 Value *Cmp = Builder.CreateICmpEQ(LHS: Op, RHS: Zero, Name: "cmpz");
2639 Builder.CreateCondBr(Cond: Cmp, True: EndBlock, False: CallBlock);
2640 StartBlock->getTerminator()->eraseFromParent();
2641 DTU->applyUpdates(Updates: {{DominatorTree::Insert, StartBlock, EndBlock}});
2642
2643 // Create a PHI in the end block to select either the output of the intrinsic
2644 // or the bit width of the operand.
2645 Builder.SetInsertPoint(TheBB: EndBlock, IP: EndBlock->begin());
2646 PHINode *PN = Builder.CreatePHI(Ty, NumReservedValues: 2, Name: "ctz");
2647 replaceAllUsesWith(Old: CountZeros, New: PN, FreshBBs, IsHuge: IsHugeFunc);
2648 Value *BitWidth = Builder.getInt(AI: APInt(SizeInBits, SizeInBits));
2649 PN->addIncoming(V: BitWidth, BB: StartBlock);
2650 PN->addIncoming(V: CountZeros, BB: CallBlock);
2651
2652 // We are explicitly handling the zero case, so we can set the intrinsic's
2653 // undefined zero argument to 'true'. This will also prevent reprocessing the
2654 // intrinsic; we only despeculate when a zero input is defined.
2655 CountZeros->setArgOperand(i: 1, v: Builder.getTrue());
2656 ModifiedDT = ModifyDT::ModifyBBDT;
2657 return true;
2658}
2659
2660bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
2661 BasicBlock *BB = CI->getParent();
2662
2663 // Sink address computing for memory operands into the block.
2664 if (CI->isInlineAsm() && optimizeInlineAsmInst(CS: CI))
2665 return true;
2666
2667 // Align the pointer arguments to this call if the target thinks it's a good
2668 // idea
2669 unsigned MinSize;
2670 Align PrefAlign;
2671 if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
2672 for (auto &Arg : CI->args()) {
2673 // We want to align both objects whose address is used directly and
2674 // objects whose address is used in casts and GEPs, though it only makes
2675 // sense for GEPs if the offset is a multiple of the desired alignment and
2676 // if size - offset meets the size threshold.
2677 if (!Arg->getType()->isPointerTy())
2678 continue;
2679 APInt Offset(DL->getIndexSizeInBits(
2680 AS: cast<PointerType>(Val: Arg->getType())->getAddressSpace()),
2681 0);
2682 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(DL: *DL, Offset);
2683 uint64_t Offset2 = Offset.getLimitedValue();
2684 if (!isAligned(Lhs: PrefAlign, SizeInBytes: Offset2))
2685 continue;
2686 AllocaInst *AI;
2687 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign) {
2688 std::optional<TypeSize> AllocaSize = AI->getAllocationSize(DL: *DL);
2689 if (AllocaSize && AllocaSize->getKnownMinValue() >= MinSize + Offset2)
2690 AI->setAlignment(PrefAlign);
2691 }
2692 // Global variables can only be aligned if they are defined in this
2693 // object (i.e. they are uniquely initialized in this object), and
2694 // over-aligning global variables that have an explicit section is
2695 // forbidden.
2696 GlobalVariable *GV;
2697 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
2698 GV->getPointerAlignment(DL: *DL) < PrefAlign &&
2699 GV->getGlobalSize(DL: *DL) >= MinSize + Offset2)
2700 GV->setAlignment(PrefAlign);
2701 }
2702 }
2703 // If this is a memcpy (or similar) then we may be able to improve the
2704 // alignment.
2705 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Val: CI)) {
2706 Align DestAlign = getKnownAlignment(V: MI->getDest(), DL: *DL);
2707 MaybeAlign MIDestAlign = MI->getDestAlign();
2708 if (!MIDestAlign || DestAlign > *MIDestAlign)
2709 MI->setDestAlignment(DestAlign);
2710 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(Val: MI)) {
2711 MaybeAlign MTISrcAlign = MTI->getSourceAlign();
2712 Align SrcAlign = getKnownAlignment(V: MTI->getSource(), DL: *DL);
2713 if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
2714 MTI->setSourceAlignment(SrcAlign);
2715 }
2716 }
2717
2718 // If we have a cold call site, try to sink addressing computation into the
2719 // cold block. This interacts with our handling for loads and stores to
2720 // ensure that we can fold all uses of a potential addressing computation
2721 // into their uses. TODO: generalize this to work over profiling data
2722 if (CI->hasFnAttr(Kind: Attribute::Cold) &&
2723 !llvm::shouldOptimizeForSize(BB, PSI, BFI))
2724 for (auto &Arg : CI->args()) {
2725 if (!Arg->getType()->isPointerTy())
2726 continue;
2727 unsigned AS = Arg->getType()->getPointerAddressSpace();
2728 if (optimizeMemoryInst(MemoryInst: CI, Addr: Arg, AccessTy: Arg->getType(), AddrSpace: AS))
2729 return true;
2730 }
2731
2732 IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: CI);
2733 if (II) {
2734 switch (II->getIntrinsicID()) {
2735 default:
2736 break;
2737 case Intrinsic::assume:
2738 llvm_unreachable("llvm.assume should have been removed already");
2739 case Intrinsic::allow_runtime_check:
2740 case Intrinsic::allow_ubsan_check:
2741 case Intrinsic::experimental_widenable_condition: {
2742 // Give up on future widening opportunities so that we can fold away dead
2743 // paths and merge blocks before going into block-local instruction
2744 // selection.
2745 if (II->use_empty()) {
2746 II->eraseFromParent();
2747 return true;
2748 }
2749 Constant *RetVal = ConstantInt::getTrue(Context&: II->getContext());
2750 resetIteratorIfInvalidatedWhileCalling(BB, f: [&]() {
2751 replaceAndRecursivelySimplify(I: CI, SimpleV: RetVal, TLI: TLInfo, DT: nullptr);
2752 });
2753 return true;
2754 }
2755 case Intrinsic::objectsize:
2756 llvm_unreachable("llvm.objectsize.* should have been lowered already");
2757 case Intrinsic::is_constant:
2758 llvm_unreachable("llvm.is.constant.* should have been lowered already");
2759 case Intrinsic::aarch64_stlxr:
2760 case Intrinsic::aarch64_stxr: {
2761 ZExtInst *ExtVal = dyn_cast<ZExtInst>(Val: CI->getArgOperand(i: 0));
2762 if (!ExtVal || !ExtVal->hasOneUse() ||
2763 ExtVal->getParent() == CI->getParent())
2764 return false;
2765 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2766 ExtVal->moveBefore(InsertPos: CI->getIterator());
2767 // Mark this instruction as "inserted by CGP", so that other
2768 // optimizations don't touch it.
2769 InsertedInsts.insert(Ptr: ExtVal);
2770 return true;
2771 }
2772
2773 case Intrinsic::launder_invariant_group:
2774 case Intrinsic::strip_invariant_group: {
2775 Value *ArgVal = II->getArgOperand(i: 0);
2776 auto it = LargeOffsetGEPMap.find(Key: II);
2777 if (it != LargeOffsetGEPMap.end()) {
2778 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
2779 // Make sure not to have to deal with iterator invalidation
2780 // after possibly adding ArgVal to LargeOffsetGEPMap.
2781 auto GEPs = std::move(it->second);
2782 LargeOffsetGEPMap[ArgVal].append(in_start: GEPs.begin(), in_end: GEPs.end());
2783 LargeOffsetGEPMap.erase(Key: II);
2784 }
2785
2786 replaceAllUsesWith(Old: II, New: ArgVal, FreshBBs, IsHuge: IsHugeFunc);
2787 II->eraseFromParent();
2788 return true;
2789 }
2790 case Intrinsic::cttz:
2791 case Intrinsic::ctlz:
2792 // If counting zeros is expensive, try to avoid it.
2793 return despeculateCountZeros(CountZeros: II, DTU, LI, TLI, DL, ModifiedDT, FreshBBs,
2794 IsHugeFunc);
2795 case Intrinsic::fshl:
2796 case Intrinsic::fshr:
2797 return optimizeFunnelShift(Fsh: II);
2798 case Intrinsic::masked_gather:
2799 return optimizeGatherScatterInst(MemoryInst: II, Ptr: II->getArgOperand(i: 0));
2800 case Intrinsic::masked_scatter:
2801 return optimizeGatherScatterInst(MemoryInst: II, Ptr: II->getArgOperand(i: 1));
2802 case Intrinsic::masked_load:
2803 // Treat v1X masked load as load X type.
2804 if (auto *VT = dyn_cast<FixedVectorType>(Val: II->getType())) {
2805 if (VT->getNumElements() == 1) {
2806 Value *PtrVal = II->getArgOperand(i: 0);
2807 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2808 if (optimizeMemoryInst(MemoryInst: II, Addr: PtrVal, AccessTy: VT->getElementType(), AddrSpace: AS))
2809 return true;
2810 }
2811 }
2812 return false;
2813 case Intrinsic::masked_store:
2814 // Treat v1X masked store as store X type.
2815 if (auto *VT =
2816 dyn_cast<FixedVectorType>(Val: II->getArgOperand(i: 0)->getType())) {
2817 if (VT->getNumElements() == 1) {
2818 Value *PtrVal = II->getArgOperand(i: 1);
2819 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2820 if (optimizeMemoryInst(MemoryInst: II, Addr: PtrVal, AccessTy: VT->getElementType(), AddrSpace: AS))
2821 return true;
2822 }
2823 }
2824 return false;
2825 case Intrinsic::umul_with_overflow:
2826 return optimizeMulWithOverflow(I: II, /*IsSigned=*/false, ModifiedDT);
2827 case Intrinsic::smul_with_overflow:
2828 return optimizeMulWithOverflow(I: II, /*IsSigned=*/true, ModifiedDT);
2829 }
2830
2831 SmallVector<Value *, 2> PtrOps;
2832 Type *AccessTy;
2833 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2834 while (!PtrOps.empty()) {
2835 Value *PtrVal = PtrOps.pop_back_val();
2836 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2837 if (optimizeMemoryInst(MemoryInst: II, Addr: PtrVal, AccessTy, AddrSpace: AS))
2838 return true;
2839 }
2840 }
2841
2842 // From here on out we're working with named functions.
2843 auto *Callee = CI->getCalledFunction();
2844 if (!Callee)
2845 return false;
2846
2847 // Lower all default uses of _chk calls. This is very similar
2848 // to what InstCombineCalls does, but here we are only lowering calls
2849 // to fortified library functions (e.g. __memcpy_chk) that have the default
2850 // "don't know" as the objectsize. Anything else should be left alone.
2851 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
2852 IRBuilder<> Builder(CI);
2853 if (Value *V = Simplifier.optimizeCall(CI, B&: Builder)) {
2854 replaceAllUsesWith(Old: CI, New: V, FreshBBs, IsHuge: IsHugeFunc);
2855 CI->eraseFromParent();
2856 return true;
2857 }
2858
2859 // SCCP may have propagated, among other things, C++ static variables across
2860 // calls. If this happens to be the case, we may want to undo it in order to
2861 // avoid redundant pointer computation of the constant, as the function method
2862 // returning the constant needs to be executed anyways.
2863 auto GetUniformReturnValue = [](const Function *F) -> GlobalVariable * {
2864 if (!F->getReturnType()->isPointerTy())
2865 return nullptr;
2866
2867 GlobalVariable *UniformValue = nullptr;
2868 for (auto &BB : *F) {
2869 if (auto *RI = dyn_cast<ReturnInst>(Val: BB.getTerminator())) {
2870 if (auto *V = dyn_cast<GlobalVariable>(Val: RI->getReturnValue())) {
2871 if (!UniformValue)
2872 UniformValue = V;
2873 else if (V != UniformValue)
2874 return nullptr;
2875 } else {
2876 return nullptr;
2877 }
2878 }
2879 }
2880
2881 return UniformValue;
2882 };
2883
2884 if (Callee->hasExactDefinition()) {
2885 if (GlobalVariable *RV = GetUniformReturnValue(Callee)) {
2886 bool MadeChange = false;
2887 for (Use &U : make_early_inc_range(Range: RV->uses())) {
2888 auto *I = dyn_cast<Instruction>(Val: U.getUser());
2889 if (!I || I->getParent() != CI->getParent()) {
2890 // Limit to the same basic block to avoid extending the call-site live
2891 // range, which otherwise could increase register pressure.
2892 continue;
2893 }
2894 if (CI->comesBefore(Other: I)) {
2895 U.set(CI);
2896 MadeChange = true;
2897 }
2898 }
2899
2900 return MadeChange;
2901 }
2902 }
2903
2904 return false;
2905}
2906
2907static bool isIntrinsicOrLFToBeTailCalled(const TargetLibraryInfo *TLInfo,
2908 const CallInst *CI) {
2909 assert(CI && CI->use_empty());
2910
2911 if (const auto *II = dyn_cast<IntrinsicInst>(Val: CI))
2912 switch (II->getIntrinsicID()) {
2913 case Intrinsic::memset:
2914 case Intrinsic::memcpy:
2915 case Intrinsic::memmove:
2916 return true;
2917 default:
2918 return false;
2919 }
2920
2921 LibFunc LF;
2922 Function *Callee = CI->getCalledFunction();
2923 if (Callee && TLInfo && TLInfo->getLibFunc(FDecl: *Callee, F&: LF))
2924 switch (LF) {
2925 case LibFunc_strcpy:
2926 case LibFunc_strncpy:
2927 case LibFunc_strcat:
2928 case LibFunc_strncat:
2929 return true;
2930 default:
2931 return false;
2932 }
2933
2934 return false;
2935}
2936
2937/// Look for opportunities to duplicate return instructions to the predecessor
2938/// to enable tail call optimizations. The case it is currently looking for is
2939/// the following one. Known intrinsics or library function that may be tail
2940/// called are taken into account as well.
2941/// @code
2942/// bb0:
2943/// %tmp0 = tail call i32 @f0()
2944/// br label %return
2945/// bb1:
2946/// %tmp1 = tail call i32 @f1()
2947/// br label %return
2948/// bb2:
2949/// %tmp2 = tail call i32 @f2()
2950/// br label %return
2951/// return:
2952/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2953/// ret i32 %retval
2954/// @endcode
2955///
2956/// =>
2957///
2958/// @code
2959/// bb0:
2960/// %tmp0 = tail call i32 @f0()
2961/// ret i32 %tmp0
2962/// bb1:
2963/// %tmp1 = tail call i32 @f1()
2964/// ret i32 %tmp1
2965/// bb2:
2966/// %tmp2 = tail call i32 @f2()
2967/// ret i32 %tmp2
2968/// @endcode
2969bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
2970 ModifyDT &ModifiedDT) {
2971 if (!BB->getTerminator())
2972 return false;
2973
2974 ReturnInst *RetI = dyn_cast<ReturnInst>(Val: BB->getTerminator());
2975 if (!RetI)
2976 return false;
2977
2978 assert(LI->getLoopFor(BB) == nullptr && "A return block cannot be in a loop");
2979
2980 PHINode *PN = nullptr;
2981 ExtractValueInst *EVI = nullptr;
2982 BitCastInst *BCI = nullptr;
2983 Value *V = RetI->getReturnValue();
2984 if (V) {
2985 BCI = dyn_cast<BitCastInst>(Val: V);
2986 if (BCI)
2987 V = BCI->getOperand(i_nocapture: 0);
2988
2989 EVI = dyn_cast<ExtractValueInst>(Val: V);
2990 if (EVI) {
2991 V = EVI->getOperand(i_nocapture: 0);
2992 if (!llvm::all_of(Range: EVI->indices(), P: equal_to(Arg: 0)))
2993 return false;
2994 }
2995
2996 PN = dyn_cast<PHINode>(Val: V);
2997 }
2998
2999 if (PN && PN->getParent() != BB)
3000 return false;
3001
3002 auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
3003 const BitCastInst *BC = dyn_cast<BitCastInst>(Val: Inst);
3004 if (BC && BC->hasOneUse())
3005 Inst = BC->user_back();
3006
3007 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: Inst))
3008 return II->getIntrinsicID() == Intrinsic::lifetime_end;
3009 return false;
3010 };
3011
3012 SmallVector<const IntrinsicInst *, 4> FakeUses;
3013
3014 auto isFakeUse = [&FakeUses](const Instruction *Inst) {
3015 if (auto *II = dyn_cast<IntrinsicInst>(Val: Inst);
3016 II && II->getIntrinsicID() == Intrinsic::fake_use) {
3017 // Record the instruction so it can be preserved when the exit block is
3018 // removed. Do not preserve the fake use that uses the result of the
3019 // PHI instruction.
3020 // Do not copy fake uses that use the result of a PHI node.
3021 // FIXME: If we do want to copy the fake use into the return blocks, we
3022 // have to figure out which of the PHI node operands to use for each
3023 // copy.
3024 if (!isa<PHINode>(Val: II->getOperand(i_nocapture: 0))) {
3025 FakeUses.push_back(Elt: II);
3026 }
3027 return true;
3028 }
3029
3030 return false;
3031 };
3032
3033 // Make sure there are no instructions between the first instruction
3034 // and return.
3035 BasicBlock::const_iterator BI = BB->getFirstNonPHIIt();
3036 // Skip over pseudo-probes and the bitcast.
3037 while (&*BI == BCI || &*BI == EVI || isa<PseudoProbeInst>(Val: BI) ||
3038 isLifetimeEndOrBitCastFor(&*BI) || isFakeUse(&*BI))
3039 BI = std::next(x: BI);
3040 if (&*BI != RetI)
3041 return false;
3042
3043 // Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
3044 // call.
3045 auto MayBePermittedAsTailCall = [&](const auto *CI) {
3046 return TLI->mayBeEmittedAsTailCall(CI) &&
3047 attributesPermitTailCall(BB->getParent(), CI, RetI, *TLI);
3048 };
3049
3050 SmallVector<BasicBlock *, 4> TailCallBBs;
3051 // Record the call instructions so we can insert any fake uses
3052 // that need to be preserved before them.
3053 SmallVector<CallInst *, 4> CallInsts;
3054 if (PN) {
3055 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
3056 // Look through bitcasts.
3057 Value *IncomingVal = PN->getIncomingValue(i: I)->stripPointerCasts();
3058 CallInst *CI = dyn_cast<CallInst>(Val: IncomingVal);
3059 BasicBlock *PredBB = PN->getIncomingBlock(i: I);
3060 // Make sure the phi value is indeed produced by the tail call.
3061 if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
3062 MayBePermittedAsTailCall(CI)) {
3063 TailCallBBs.push_back(Elt: PredBB);
3064 CallInsts.push_back(Elt: CI);
3065 } else {
3066 // Consider the cases in which the phi value is indirectly produced by
3067 // the tail call, for example when encountering memset(), memmove(),
3068 // strcpy(), whose return value may have been optimized out. In such
3069 // cases, the value needs to be the first function argument.
3070 //
3071 // bb0:
3072 // tail call void @llvm.memset.p0.i64(ptr %0, i8 0, i64 %1)
3073 // br label %return
3074 // return:
3075 // %phi = phi ptr [ %0, %bb0 ], [ %2, %entry ]
3076 if (PredBB && PredBB->getSingleSuccessor() == BB)
3077 CI = dyn_cast_or_null<CallInst>(
3078 Val: PredBB->getTerminator()->getPrevNode());
3079
3080 if (CI && CI->use_empty() &&
3081 isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
3082 IncomingVal == CI->getArgOperand(i: 0) &&
3083 MayBePermittedAsTailCall(CI)) {
3084 TailCallBBs.push_back(Elt: PredBB);
3085 CallInsts.push_back(Elt: CI);
3086 }
3087 }
3088 }
3089 } else {
3090 SmallPtrSet<BasicBlock *, 4> VisitedBBs;
3091 for (BasicBlock *Pred : predecessors(BB)) {
3092 if (!VisitedBBs.insert(Ptr: Pred).second)
3093 continue;
3094 if (Instruction *I = Pred->rbegin()->getPrevNode()) {
3095 CallInst *CI = dyn_cast<CallInst>(Val: I);
3096 if (CI && CI->use_empty() && MayBePermittedAsTailCall(CI)) {
3097 // Either we return void or the return value must be the first
3098 // argument of a known intrinsic or library function.
3099 if (!V || isa<UndefValue>(Val: V) ||
3100 (isIntrinsicOrLFToBeTailCalled(TLInfo, CI) &&
3101 V == CI->getArgOperand(i: 0))) {
3102 TailCallBBs.push_back(Elt: Pred);
3103 CallInsts.push_back(Elt: CI);
3104 }
3105 }
3106 }
3107 }
3108 }
3109
3110 bool Changed = false;
3111 for (auto const &TailCallBB : TailCallBBs) {
3112 // Make sure the call instruction is followed by an unconditional branch to
3113 // the return block.
3114 UncondBrInst *BI = dyn_cast<UncondBrInst>(Val: TailCallBB->getTerminator());
3115 if (!BI || BI->getSuccessor() != BB)
3116 continue;
3117
3118 // Duplicate the return into TailCallBB.
3119 (void)FoldReturnIntoUncondBranch(RI: RetI, BB, Pred: TailCallBB, DTU);
3120 assert(!VerifyBFIUpdates ||
3121 BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
3122 BFI->setBlockFreq(BB,
3123 Freq: (BFI->getBlockFreq(BB) - BFI->getBlockFreq(BB: TailCallBB)));
3124 ModifiedDT = ModifyDT::ModifyBBDT;
3125 Changed = true;
3126 ++NumRetsDup;
3127 }
3128
3129 // If we eliminated all predecessors of the block, delete the block now.
3130 if (Changed && !BB->hasAddressTaken() && pred_empty(BB)) {
3131 // Copy the fake uses found in the original return block to all blocks
3132 // that contain tail calls.
3133 for (auto *CI : CallInsts) {
3134 for (auto const *FakeUse : FakeUses) {
3135 auto *ClonedInst = FakeUse->clone();
3136 ClonedInst->insertBefore(InsertPos: CI->getIterator());
3137 }
3138 }
3139 DTU->deleteBB(DelBB: BB);
3140 }
3141
3142 return Changed;
3143}
3144
3145//===----------------------------------------------------------------------===//
3146// Memory Optimization
3147//===----------------------------------------------------------------------===//
3148
3149namespace {
3150
3151/// This is an extended version of TargetLowering::AddrMode
3152/// which holds actual Value*'s for register values.
3153struct ExtAddrMode : public TargetLowering::AddrMode {
3154 Value *BaseReg = nullptr;
3155 Value *ScaledReg = nullptr;
3156 Value *OriginalValue = nullptr;
3157 bool InBounds = true;
3158
3159 enum FieldName {
3160 NoField = 0x00,
3161 BaseRegField = 0x01,
3162 BaseGVField = 0x02,
3163 BaseOffsField = 0x04,
3164 ScaledRegField = 0x08,
3165 ScaleField = 0x10,
3166 MultipleFields = 0xff
3167 };
3168
3169 ExtAddrMode() = default;
3170
3171 void print(raw_ostream &OS) const;
3172 void dump() const;
3173
3174 // Replace From in ExtAddrMode with To.
3175 // E.g., SExt insts may be promoted and deleted. We should replace them with
3176 // the promoted values.
3177 void replaceWith(Value *From, Value *To) {
3178 if (ScaledReg == From)
3179 ScaledReg = To;
3180 }
3181
3182 FieldName compare(const ExtAddrMode &other) {
3183 // First check that the types are the same on each field, as differing types
3184 // is something we can't cope with later on.
3185 if (BaseReg && other.BaseReg &&
3186 BaseReg->getType() != other.BaseReg->getType())
3187 return MultipleFields;
3188 if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
3189 return MultipleFields;
3190 if (ScaledReg && other.ScaledReg &&
3191 ScaledReg->getType() != other.ScaledReg->getType())
3192 return MultipleFields;
3193
3194 // Conservatively reject 'inbounds' mismatches.
3195 if (InBounds != other.InBounds)
3196 return MultipleFields;
3197
3198 // Check each field to see if it differs.
3199 unsigned Result = NoField;
3200 if (BaseReg != other.BaseReg)
3201 Result |= BaseRegField;
3202 if (BaseGV != other.BaseGV)
3203 Result |= BaseGVField;
3204 if (BaseOffs != other.BaseOffs)
3205 Result |= BaseOffsField;
3206 if (ScaledReg != other.ScaledReg)
3207 Result |= ScaledRegField;
3208 // Don't count 0 as being a different scale, because that actually means
3209 // unscaled (which will already be counted by having no ScaledReg).
3210 if (Scale && other.Scale && Scale != other.Scale)
3211 Result |= ScaleField;
3212
3213 if (llvm::popcount(Value: Result) > 1)
3214 return MultipleFields;
3215 else
3216 return static_cast<FieldName>(Result);
3217 }
3218
3219 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
3220 // with no offset.
3221 bool isTrivial() {
3222 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
3223 // trivial if at most one of these terms is nonzero, except that BaseGV and
3224 // BaseReg both being zero actually means a null pointer value, which we
3225 // consider to be 'non-zero' here.
3226 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
3227 }
3228
3229 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
3230 switch (Field) {
3231 default:
3232 return nullptr;
3233 case BaseRegField:
3234 return BaseReg;
3235 case BaseGVField:
3236 return BaseGV;
3237 case ScaledRegField:
3238 return ScaledReg;
3239 case BaseOffsField:
3240 return ConstantInt::getSigned(Ty: IntPtrTy, V: BaseOffs);
3241 }
3242 }
3243
3244 void SetCombinedField(FieldName Field, Value *V,
3245 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
3246 switch (Field) {
3247 default:
3248 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
3249 break;
3250 case ExtAddrMode::BaseRegField:
3251 BaseReg = V;
3252 break;
3253 case ExtAddrMode::BaseGVField:
3254 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
3255 // in the BaseReg field.
3256 assert(BaseReg == nullptr);
3257 BaseReg = V;
3258 BaseGV = nullptr;
3259 break;
3260 case ExtAddrMode::ScaledRegField:
3261 ScaledReg = V;
3262 // If we have a mix of scaled and unscaled addrmodes then we want scale
3263 // to be the scale and not zero.
3264 if (!Scale)
3265 for (const ExtAddrMode &AM : AddrModes)
3266 if (AM.Scale) {
3267 Scale = AM.Scale;
3268 break;
3269 }
3270 break;
3271 case ExtAddrMode::BaseOffsField:
3272 // The offset is no longer a constant, so it goes in ScaledReg with a
3273 // scale of 1.
3274 assert(ScaledReg == nullptr);
3275 ScaledReg = V;
3276 Scale = 1;
3277 BaseOffs = 0;
3278 break;
3279 }
3280 }
3281};
3282
3283#ifndef NDEBUG
3284static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
3285 AM.print(OS);
3286 return OS;
3287}
3288#endif
3289
3290#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3291void ExtAddrMode::print(raw_ostream &OS) const {
3292 bool NeedPlus = false;
3293 OS << "[";
3294 if (InBounds)
3295 OS << "inbounds ";
3296 if (BaseGV) {
3297 OS << "GV:";
3298 BaseGV->printAsOperand(OS, /*PrintType=*/false);
3299 NeedPlus = true;
3300 }
3301
3302 if (BaseOffs) {
3303 OS << (NeedPlus ? " + " : "") << BaseOffs;
3304 NeedPlus = true;
3305 }
3306
3307 if (BaseReg) {
3308 OS << (NeedPlus ? " + " : "") << "Base:";
3309 BaseReg->printAsOperand(OS, /*PrintType=*/false);
3310 NeedPlus = true;
3311 }
3312 if (Scale) {
3313 OS << (NeedPlus ? " + " : "") << Scale << "*";
3314 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
3315 }
3316
3317 OS << ']';
3318}
3319
3320LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
3321 print(dbgs());
3322 dbgs() << '\n';
3323}
3324#endif
3325
3326} // end anonymous namespace
3327
3328namespace {
3329
3330/// This class provides transaction based operation on the IR.
3331/// Every change made through this class is recorded in the internal state and
3332/// can be undone (rollback) until commit is called.
3333/// CGP does not check if instructions could be speculatively executed when
3334/// moved. Preserving the original location would pessimize the debugging
3335/// experience, as well as negatively impact the quality of sample PGO.
3336class TypePromotionTransaction {
3337 /// This represents the common interface of the individual transaction.
3338 /// Each class implements the logic for doing one specific modification on
3339 /// the IR via the TypePromotionTransaction.
3340 class TypePromotionAction {
3341 protected:
3342 /// The Instruction modified.
3343 Instruction *Inst;
3344
3345 public:
3346 /// Constructor of the action.
3347 /// The constructor performs the related action on the IR.
3348 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
3349
3350 virtual ~TypePromotionAction() = default;
3351
3352 /// Undo the modification done by this action.
3353 /// When this method is called, the IR must be in the same state as it was
3354 /// before this action was applied.
3355 /// \pre Undoing the action works if and only if the IR is in the exact same
3356 /// state as it was directly after this action was applied.
3357 virtual void undo() = 0;
3358
3359 /// Advocate every change made by this action.
3360 /// When the results on the IR of the action are to be kept, it is important
3361 /// to call this function, otherwise hidden information may be kept forever.
3362 virtual void commit() {
3363 // Nothing to be done, this action is not doing anything.
3364 }
3365 };
3366
3367 /// Utility to remember the position of an instruction.
3368 class InsertionHandler {
3369 /// Position of an instruction.
3370 /// Either an instruction:
3371 /// - Is the first in a basic block: BB is used.
3372 /// - Has a previous instruction: PrevInst is used.
3373 struct {
3374 BasicBlock::iterator PrevInst;
3375 BasicBlock *BB;
3376 } Point;
3377 std::optional<DbgRecord::self_iterator> BeforeDbgRecord = std::nullopt;
3378
3379 /// Remember whether or not the instruction had a previous instruction.
3380 bool HasPrevInstruction;
3381
3382 public:
3383 /// Record the position of \p Inst.
3384 InsertionHandler(Instruction *Inst) {
3385 HasPrevInstruction = (Inst != &*(Inst->getParent()->begin()));
3386 BasicBlock *BB = Inst->getParent();
3387
3388 // Record where we would have to re-insert the instruction in the sequence
3389 // of DbgRecords, if we ended up reinserting.
3390 BeforeDbgRecord = Inst->getDbgReinsertionPosition();
3391
3392 if (HasPrevInstruction) {
3393 Point.PrevInst = std::prev(x: Inst->getIterator());
3394 } else {
3395 Point.BB = BB;
3396 }
3397 }
3398
3399 /// Insert \p Inst at the recorded position.
3400 void insert(Instruction *Inst) {
3401 if (HasPrevInstruction) {
3402 if (Inst->getParent())
3403 Inst->removeFromParent();
3404 Inst->insertAfter(InsertPos: Point.PrevInst);
3405 } else {
3406 BasicBlock::iterator Position = Point.BB->getFirstInsertionPt();
3407 if (Inst->getParent())
3408 Inst->moveBefore(BB&: *Point.BB, I: Position);
3409 else
3410 Inst->insertBefore(BB&: *Point.BB, InsertPos: Position);
3411 }
3412
3413 Inst->getParent()->reinsertInstInDbgRecords(I: Inst, Pos: BeforeDbgRecord);
3414 }
3415 };
3416
3417 /// Move an instruction before another.
3418 class InstructionMoveBefore : public TypePromotionAction {
3419 /// Original position of the instruction.
3420 InsertionHandler Position;
3421
3422 public:
3423 /// Move \p Inst before \p Before.
3424 InstructionMoveBefore(Instruction *Inst, BasicBlock::iterator Before)
3425 : TypePromotionAction(Inst), Position(Inst) {
3426 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
3427 << "\n");
3428 Inst->moveBefore(InsertPos: Before);
3429 }
3430
3431 /// Move the instruction back to its original position.
3432 void undo() override {
3433 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
3434 Position.insert(Inst);
3435 }
3436 };
3437
3438 /// Set the operand of an instruction with a new value.
3439 class OperandSetter : public TypePromotionAction {
3440 /// Original operand of the instruction.
3441 Value *Origin;
3442
3443 /// Index of the modified instruction.
3444 unsigned Idx;
3445
3446 public:
3447 /// Set \p Idx operand of \p Inst with \p NewVal.
3448 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
3449 : TypePromotionAction(Inst), Idx(Idx) {
3450 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
3451 << "for:" << *Inst << "\n"
3452 << "with:" << *NewVal << "\n");
3453 Origin = Inst->getOperand(i: Idx);
3454 Inst->setOperand(i: Idx, Val: NewVal);
3455 }
3456
3457 /// Restore the original value of the instruction.
3458 void undo() override {
3459 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
3460 << "for: " << *Inst << "\n"
3461 << "with: " << *Origin << "\n");
3462 Inst->setOperand(i: Idx, Val: Origin);
3463 }
3464 };
3465
3466 /// Hide the operands of an instruction.
3467 /// Do as if this instruction was not using any of its operands.
3468 class OperandsHider : public TypePromotionAction {
3469 /// The list of original operands.
3470 SmallVector<Value *, 4> OriginalValues;
3471
3472 public:
3473 /// Remove \p Inst from the uses of the operands of \p Inst.
3474 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
3475 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
3476 unsigned NumOpnds = Inst->getNumOperands();
3477 OriginalValues.reserve(N: NumOpnds);
3478 for (unsigned It = 0; It < NumOpnds; ++It) {
3479 // Save the current operand.
3480 Value *Val = Inst->getOperand(i: It);
3481 OriginalValues.push_back(Elt: Val);
3482 // Set a dummy one.
3483 // We could use OperandSetter here, but that would imply an overhead
3484 // that we are not willing to pay.
3485 Inst->setOperand(i: It, Val: PoisonValue::get(T: Val->getType()));
3486 }
3487 }
3488
3489 /// Restore the original list of uses.
3490 void undo() override {
3491 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
3492 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
3493 Inst->setOperand(i: It, Val: OriginalValues[It]);
3494 }
3495 };
3496
3497 /// Build a truncate instruction.
3498 class TruncBuilder : public TypePromotionAction {
3499 Value *Val;
3500
3501 public:
3502 /// Build a truncate instruction of \p Opnd producing a \p Ty
3503 /// result.
3504 /// trunc Opnd to Ty.
3505 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
3506 IRBuilder<> Builder(Opnd);
3507 Builder.SetCurrentDebugLocation(DebugLoc());
3508 Val = Builder.CreateTrunc(V: Opnd, DestTy: Ty, Name: "promoted");
3509 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
3510 }
3511
3512 /// Get the built value.
3513 Value *getBuiltValue() { return Val; }
3514
3515 /// Remove the built instruction.
3516 void undo() override {
3517 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
3518 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3519 IVal->eraseFromParent();
3520 }
3521 };
3522
3523 /// Build a sign extension instruction.
3524 class SExtBuilder : public TypePromotionAction {
3525 Value *Val;
3526
3527 public:
3528 /// Build a sign extension instruction of \p Opnd producing a \p Ty
3529 /// result.
3530 /// sext Opnd to Ty.
3531 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3532 : TypePromotionAction(InsertPt) {
3533 IRBuilder<> Builder(InsertPt);
3534 Val = Builder.CreateSExt(V: Opnd, DestTy: Ty, Name: "promoted");
3535 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
3536 }
3537
3538 /// Get the built value.
3539 Value *getBuiltValue() { return Val; }
3540
3541 /// Remove the built instruction.
3542 void undo() override {
3543 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
3544 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3545 IVal->eraseFromParent();
3546 }
3547 };
3548
3549 /// Build a zero extension instruction.
3550 class ZExtBuilder : public TypePromotionAction {
3551 Value *Val;
3552
3553 public:
3554 /// Build a zero extension instruction of \p Opnd producing a \p Ty
3555 /// result.
3556 /// zext Opnd to Ty.
3557 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
3558 : TypePromotionAction(InsertPt) {
3559 IRBuilder<> Builder(InsertPt);
3560 Builder.SetCurrentDebugLocation(DebugLoc());
3561 Val = Builder.CreateZExt(V: Opnd, DestTy: Ty, Name: "promoted");
3562 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
3563 }
3564
3565 /// Get the built value.
3566 Value *getBuiltValue() { return Val; }
3567
3568 /// Remove the built instruction.
3569 void undo() override {
3570 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
3571 if (Instruction *IVal = dyn_cast<Instruction>(Val))
3572 IVal->eraseFromParent();
3573 }
3574 };
3575
3576 /// Mutate an instruction to another type.
3577 class TypeMutator : public TypePromotionAction {
3578 /// Record the original type.
3579 Type *OrigTy;
3580
3581 public:
3582 /// Mutate the type of \p Inst into \p NewTy.
3583 TypeMutator(Instruction *Inst, Type *NewTy)
3584 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
3585 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
3586 << "\n");
3587 Inst->mutateType(Ty: NewTy);
3588 }
3589
3590 /// Mutate the instruction back to its original type.
3591 void undo() override {
3592 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
3593 << "\n");
3594 Inst->mutateType(Ty: OrigTy);
3595 }
3596 };
3597
3598 /// Replace the uses of an instruction by another instruction.
3599 class UsesReplacer : public TypePromotionAction {
3600 /// Helper structure to keep track of the replaced uses.
3601 struct InstructionAndIdx {
3602 /// The instruction using the instruction.
3603 Instruction *Inst;
3604
3605 /// The index where this instruction is used for Inst.
3606 unsigned Idx;
3607
3608 InstructionAndIdx(Instruction *Inst, unsigned Idx)
3609 : Inst(Inst), Idx(Idx) {}
3610 };
3611
3612 /// Keep track of the original uses (pair Instruction, Index).
3613 SmallVector<InstructionAndIdx, 4> OriginalUses;
3614 /// Keep track of the debug users.
3615 SmallVector<DbgVariableRecord *, 1> DbgVariableRecords;
3616
3617 /// Keep track of the new value so that we can undo it by replacing
3618 /// instances of the new value with the original value.
3619 Value *New;
3620
3621 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
3622
3623 public:
3624 /// Replace all the use of \p Inst by \p New.
3625 UsesReplacer(Instruction *Inst, Value *New)
3626 : TypePromotionAction(Inst), New(New) {
3627 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
3628 << "\n");
3629 // Record the original uses.
3630 for (Use &U : Inst->uses()) {
3631 Instruction *UserI = cast<Instruction>(Val: U.getUser());
3632 OriginalUses.push_back(Elt: InstructionAndIdx(UserI, U.getOperandNo()));
3633 }
3634 // Record the debug uses separately. They are not in the instruction's
3635 // use list, but they are replaced by RAUW.
3636 findDbgValues(V: Inst, DbgVariableRecords);
3637
3638 // Now, we can replace the uses.
3639 Inst->replaceAllUsesWith(V: New);
3640 }
3641
3642 /// Reassign the original uses of Inst to Inst.
3643 void undo() override {
3644 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
3645 for (InstructionAndIdx &Use : OriginalUses)
3646 Use.Inst->setOperand(i: Use.Idx, Val: Inst);
3647 // RAUW has replaced all original uses with references to the new value,
3648 // including the debug uses. Since we are undoing the replacements,
3649 // the original debug uses must also be reinstated to maintain the
3650 // correctness and utility of debug value records.
3651 for (DbgVariableRecord *DVR : DbgVariableRecords)
3652 DVR->replaceVariableLocationOp(OldValue: New, NewValue: Inst);
3653 }
3654 };
3655
3656 /// Remove an instruction from the IR.
3657 class InstructionRemover : public TypePromotionAction {
3658 /// Original position of the instruction.
3659 InsertionHandler Inserter;
3660
3661 /// Helper structure to hide all the link to the instruction. In other
3662 /// words, this helps to do as if the instruction was removed.
3663 OperandsHider Hider;
3664
3665 /// Keep track of the uses replaced, if any.
3666 UsesReplacer *Replacer = nullptr;
3667
3668 /// Keep track of instructions removed.
3669 SetOfInstrs &RemovedInsts;
3670
3671 public:
3672 /// Remove all reference of \p Inst and optionally replace all its
3673 /// uses with New.
3674 /// \p RemovedInsts Keep track of the instructions removed by this Action.
3675 /// \pre If !Inst->use_empty(), then New != nullptr
3676 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
3677 Value *New = nullptr)
3678 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
3679 RemovedInsts(RemovedInsts) {
3680 if (New)
3681 Replacer = new UsesReplacer(Inst, New);
3682 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
3683 RemovedInsts.insert(Ptr: Inst);
3684 /// The instructions removed here will be freed after completing
3685 /// optimizeBlock() for all blocks as we need to keep track of the
3686 /// removed instructions during promotion.
3687 Inst->removeFromParent();
3688 }
3689
3690 ~InstructionRemover() override { delete Replacer; }
3691
3692 InstructionRemover &operator=(const InstructionRemover &other) = delete;
3693 InstructionRemover(const InstructionRemover &other) = delete;
3694
3695 /// Resurrect the instruction and reassign it to the proper uses if
3696 /// new value was provided when build this action.
3697 void undo() override {
3698 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
3699 Inserter.insert(Inst);
3700 if (Replacer)
3701 Replacer->undo();
3702 Hider.undo();
3703 RemovedInsts.erase(Ptr: Inst);
3704 }
3705 };
3706
3707public:
3708 /// Restoration point.
3709 /// The restoration point is a pointer to an action instead of an iterator
3710 /// because the iterator may be invalidated but not the pointer.
3711 using ConstRestorationPt = const TypePromotionAction *;
3712
3713 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
3714 : RemovedInsts(RemovedInsts) {}
3715
3716 /// Advocate every changes made in that transaction. Return true if any change
3717 /// happen.
3718 bool commit();
3719
3720 /// Undo all the changes made after the given point.
3721 void rollback(ConstRestorationPt Point);
3722
3723 /// Get the current restoration point.
3724 ConstRestorationPt getRestorationPoint() const;
3725
3726 /// \name API for IR modification with state keeping to support rollback.
3727 /// @{
3728 /// Same as Instruction::setOperand.
3729 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
3730
3731 /// Same as Instruction::eraseFromParent.
3732 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
3733
3734 /// Same as Value::replaceAllUsesWith.
3735 void replaceAllUsesWith(Instruction *Inst, Value *New);
3736
3737 /// Same as Value::mutateType.
3738 void mutateType(Instruction *Inst, Type *NewTy);
3739
3740 /// Same as IRBuilder::createTrunc.
3741 Value *createTrunc(Instruction *Opnd, Type *Ty);
3742
3743 /// Same as IRBuilder::createSExt.
3744 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
3745
3746 /// Same as IRBuilder::createZExt.
3747 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
3748
3749private:
3750 /// The ordered list of actions made so far.
3751 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
3752
3753 using CommitPt =
3754 SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
3755
3756 SetOfInstrs &RemovedInsts;
3757};
3758
3759} // end anonymous namespace
3760
3761void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
3762 Value *NewVal) {
3763 Actions.push_back(Elt: std::make_unique<TypePromotionTransaction::OperandSetter>(
3764 args&: Inst, args&: Idx, args&: NewVal));
3765}
3766
3767void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
3768 Value *NewVal) {
3769 Actions.push_back(
3770 Elt: std::make_unique<TypePromotionTransaction::InstructionRemover>(
3771 args&: Inst, args&: RemovedInsts, args&: NewVal));
3772}
3773
3774void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
3775 Value *New) {
3776 Actions.push_back(
3777 Elt: std::make_unique<TypePromotionTransaction::UsesReplacer>(args&: Inst, args&: New));
3778}
3779
3780void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
3781 Actions.push_back(
3782 Elt: std::make_unique<TypePromotionTransaction::TypeMutator>(args&: Inst, args&: NewTy));
3783}
3784
3785Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
3786 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
3787 Value *Val = Ptr->getBuiltValue();
3788 Actions.push_back(Elt: std::move(Ptr));
3789 return Val;
3790}
3791
3792Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
3793 Type *Ty) {
3794 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
3795 Value *Val = Ptr->getBuiltValue();
3796 Actions.push_back(Elt: std::move(Ptr));
3797 return Val;
3798}
3799
3800Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
3801 Type *Ty) {
3802 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
3803 Value *Val = Ptr->getBuiltValue();
3804 Actions.push_back(Elt: std::move(Ptr));
3805 return Val;
3806}
3807
3808TypePromotionTransaction::ConstRestorationPt
3809TypePromotionTransaction::getRestorationPoint() const {
3810 return !Actions.empty() ? Actions.back().get() : nullptr;
3811}
3812
3813bool TypePromotionTransaction::commit() {
3814 for (std::unique_ptr<TypePromotionAction> &Action : Actions)
3815 Action->commit();
3816 bool Modified = !Actions.empty();
3817 Actions.clear();
3818 return Modified;
3819}
3820
3821void TypePromotionTransaction::rollback(
3822 TypePromotionTransaction::ConstRestorationPt Point) {
3823 while (!Actions.empty() && Point != Actions.back().get()) {
3824 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
3825 Curr->undo();
3826 }
3827}
3828
3829namespace {
3830
3831/// A helper class for matching addressing modes.
3832///
3833/// This encapsulates the logic for matching the target-legal addressing modes.
3834class AddressingModeMatcher {
3835 SmallVectorImpl<Instruction *> &AddrModeInsts;
3836 const TargetLowering &TLI;
3837 const TargetRegisterInfo &TRI;
3838 const DataLayout &DL;
3839 const LoopInfo &LI;
3840 const std::function<const DominatorTree &()> getDTFn;
3841
3842 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
3843 /// the memory instruction that we're computing this address for.
3844 Type *AccessTy;
3845 unsigned AddrSpace;
3846 Instruction *MemoryInst;
3847
3848 /// This is the addressing mode that we're building up. This is
3849 /// part of the return value of this addressing mode matching stuff.
3850 ExtAddrMode &AddrMode;
3851
3852 /// The instructions inserted by other CodeGenPrepare optimizations.
3853 const SetOfInstrs &InsertedInsts;
3854
3855 /// A map from the instructions to their type before promotion.
3856 InstrToOrigTy &PromotedInsts;
3857
3858 /// The ongoing transaction where every action should be registered.
3859 TypePromotionTransaction &TPT;
3860
3861 // A GEP which has too large offset to be folded into the addressing mode.
3862 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
3863
3864 /// This is set to true when we should not do profitability checks.
3865 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
3866 bool IgnoreProfitability;
3867
3868 /// True if we are optimizing for size.
3869 bool OptSize = false;
3870
3871 ProfileSummaryInfo *PSI;
3872 BlockFrequencyInfo *BFI;
3873
3874 AddressingModeMatcher(
3875 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
3876 const TargetRegisterInfo &TRI, const LoopInfo &LI,
3877 const std::function<const DominatorTree &()> getDTFn, Type *AT,
3878 unsigned AS, Instruction *MI, ExtAddrMode &AM,
3879 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
3880 TypePromotionTransaction &TPT,
3881 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3882 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
3883 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
3884 DL(MI->getDataLayout()), LI(LI), getDTFn(getDTFn),
3885 AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
3886 InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
3887 LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
3888 IgnoreProfitability = false;
3889 }
3890
3891public:
3892 /// Find the maximal addressing mode that a load/store of V can fold,
3893 /// give an access type of AccessTy. This returns a list of involved
3894 /// instructions in AddrModeInsts.
3895 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
3896 /// optimizations.
3897 /// \p PromotedInsts maps the instructions to their type before promotion.
3898 /// \p The ongoing transaction where every action should be registered.
3899 static ExtAddrMode
3900 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
3901 SmallVectorImpl<Instruction *> &AddrModeInsts,
3902 const TargetLowering &TLI, const LoopInfo &LI,
3903 const std::function<const DominatorTree &()> getDTFn,
3904 const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
3905 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
3906 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
3907 bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
3908 ExtAddrMode Result;
3909
3910 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, LI, getDTFn,
3911 AccessTy, AS, MemoryInst, Result,
3912 InsertedInsts, PromotedInsts, TPT,
3913 LargeOffsetGEP, OptSize, PSI, BFI)
3914 .matchAddr(Addr: V, Depth: 0);
3915 (void)Success;
3916 assert(Success && "Couldn't select *anything*?");
3917 return Result;
3918 }
3919
3920private:
3921 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3922 bool matchAddr(Value *Addr, unsigned Depth);
3923 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
3924 bool *MovedAway = nullptr);
3925 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
3926 ExtAddrMode &AMBefore,
3927 ExtAddrMode &AMAfter);
3928 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3929 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
3930 Value *PromotedOperand) const;
3931};
3932
3933class PhiNodeSet;
3934
3935/// An iterator for PhiNodeSet.
3936class PhiNodeSetIterator {
3937 PhiNodeSet *const Set;
3938 size_t CurrentIndex = 0;
3939
3940public:
3941 /// The constructor. Start should point to either a valid element, or be equal
3942 /// to the size of the underlying SmallVector of the PhiNodeSet.
3943 PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
3944 PHINode *operator*() const;
3945 PhiNodeSetIterator &operator++();
3946 bool operator==(const PhiNodeSetIterator &RHS) const;
3947 bool operator!=(const PhiNodeSetIterator &RHS) const;
3948};
3949
3950/// Keeps a set of PHINodes.
3951///
3952/// This is a minimal set implementation for a specific use case:
3953/// It is very fast when there are very few elements, but also provides good
3954/// performance when there are many. It is similar to SmallPtrSet, but also
3955/// provides iteration by insertion order, which is deterministic and stable
3956/// across runs. It is also similar to SmallSetVector, but provides removing
3957/// elements in O(1) time. This is achieved by not actually removing the element
3958/// from the underlying vector, so comes at the cost of using more memory, but
3959/// that is fine, since PhiNodeSets are used as short lived objects.
3960class PhiNodeSet {
3961 friend class PhiNodeSetIterator;
3962
3963 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
3964 using iterator = PhiNodeSetIterator;
3965
3966 /// Keeps the elements in the order of their insertion in the underlying
3967 /// vector. To achieve constant time removal, it never deletes any element.
3968 SmallVector<PHINode *, 32> NodeList;
3969
3970 /// Keeps the elements in the underlying set implementation. This (and not the
3971 /// NodeList defined above) is the source of truth on whether an element
3972 /// is actually in the collection.
3973 MapType NodeMap;
3974
3975 /// Points to the first valid (not deleted) element when the set is not empty
3976 /// and the value is not zero. Equals to the size of the underlying vector
3977 /// when the set is empty. When the value is 0, as in the beginning, the
3978 /// first element may or may not be valid.
3979 size_t FirstValidElement = 0;
3980
3981public:
3982 /// Inserts a new element to the collection.
3983 /// \returns true if the element is actually added, i.e. was not in the
3984 /// collection before the operation.
3985 bool insert(PHINode *Ptr) {
3986 if (NodeMap.insert(KV: std::make_pair(x&: Ptr, y: NodeList.size())).second) {
3987 NodeList.push_back(Elt: Ptr);
3988 return true;
3989 }
3990 return false;
3991 }
3992
3993 /// Removes the element from the collection.
3994 /// \returns whether the element is actually removed, i.e. was in the
3995 /// collection before the operation.
3996 bool erase(PHINode *Ptr) {
3997 if (NodeMap.erase(Val: Ptr)) {
3998 SkipRemovedElements(CurrentIndex&: FirstValidElement);
3999 return true;
4000 }
4001 return false;
4002 }
4003
4004 /// Removes all elements and clears the collection.
4005 void clear() {
4006 NodeMap.clear();
4007 NodeList.clear();
4008 FirstValidElement = 0;
4009 }
4010
4011 /// \returns an iterator that will iterate the elements in the order of
4012 /// insertion.
4013 iterator begin() {
4014 if (FirstValidElement == 0)
4015 SkipRemovedElements(CurrentIndex&: FirstValidElement);
4016 return PhiNodeSetIterator(this, FirstValidElement);
4017 }
4018
4019 /// \returns an iterator that points to the end of the collection.
4020 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
4021
4022 /// Returns the number of elements in the collection.
4023 size_t size() const { return NodeMap.size(); }
4024
4025 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
4026 size_t count(PHINode *Ptr) const { return NodeMap.count(Val: Ptr); }
4027
4028private:
4029 /// Updates the CurrentIndex so that it will point to a valid element.
4030 ///
4031 /// If the element of NodeList at CurrentIndex is valid, it does not
4032 /// change it. If there are no more valid elements, it updates CurrentIndex
4033 /// to point to the end of the NodeList.
4034 void SkipRemovedElements(size_t &CurrentIndex) {
4035 while (CurrentIndex < NodeList.size()) {
4036 auto it = NodeMap.find(Val: NodeList[CurrentIndex]);
4037 // If the element has been deleted and added again later, NodeMap will
4038 // point to a different index, so CurrentIndex will still be invalid.
4039 if (it != NodeMap.end() && it->second == CurrentIndex)
4040 break;
4041 ++CurrentIndex;
4042 }
4043 }
4044};
4045
4046PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
4047 : Set(Set), CurrentIndex(Start) {}
4048
4049PHINode *PhiNodeSetIterator::operator*() const {
4050 assert(CurrentIndex < Set->NodeList.size() &&
4051 "PhiNodeSet access out of range");
4052 return Set->NodeList[CurrentIndex];
4053}
4054
4055PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
4056 assert(CurrentIndex < Set->NodeList.size() &&
4057 "PhiNodeSet access out of range");
4058 ++CurrentIndex;
4059 Set->SkipRemovedElements(CurrentIndex);
4060 return *this;
4061}
4062
4063bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
4064 return CurrentIndex == RHS.CurrentIndex;
4065}
4066
4067bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
4068 return !((*this) == RHS);
4069}
4070
4071/// Keep track of simplification of Phi nodes.
4072/// Accept the set of all phi nodes and erase phi node from this set
4073/// if it is simplified.
4074class SimplificationTracker {
4075 DenseMap<Value *, Value *> Storage;
4076 // Tracks newly created Phi nodes. The elements are iterated by insertion
4077 // order.
4078 PhiNodeSet AllPhiNodes;
4079 // Tracks newly created Select nodes.
4080 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
4081
4082public:
4083 Value *Get(Value *V) {
4084 do {
4085 auto SV = Storage.find(Val: V);
4086 if (SV == Storage.end())
4087 return V;
4088 V = SV->second;
4089 } while (true);
4090 }
4091
4092 void Put(Value *From, Value *To) { Storage.insert(KV: {From, To}); }
4093
4094 void ReplacePhi(PHINode *From, PHINode *To) {
4095 Value *OldReplacement = Get(V: From);
4096 while (OldReplacement != From) {
4097 From = To;
4098 To = dyn_cast<PHINode>(Val: OldReplacement);
4099 OldReplacement = Get(V: From);
4100 }
4101 assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
4102 Put(From, To);
4103 From->replaceAllUsesWith(V: To);
4104 AllPhiNodes.erase(Ptr: From);
4105 From->eraseFromParent();
4106 }
4107
4108 PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
4109
4110 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(Ptr: PN); }
4111
4112 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(Ptr: SI); }
4113
4114 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
4115
4116 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
4117
4118 void destroyNewNodes(Type *CommonType) {
4119 // For safe erasing, replace the uses with dummy value first.
4120 auto *Dummy = PoisonValue::get(T: CommonType);
4121 for (auto *I : AllPhiNodes) {
4122 I->replaceAllUsesWith(V: Dummy);
4123 I->eraseFromParent();
4124 }
4125 AllPhiNodes.clear();
4126 for (auto *I : AllSelectNodes) {
4127 I->replaceAllUsesWith(V: Dummy);
4128 I->eraseFromParent();
4129 }
4130 AllSelectNodes.clear();
4131 }
4132};
4133
4134/// A helper class for combining addressing modes.
4135class AddressingModeCombiner {
4136 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
4137 typedef std::pair<PHINode *, PHINode *> PHIPair;
4138
4139private:
4140 /// The addressing modes we've collected.
4141 SmallVector<ExtAddrMode, 16> AddrModes;
4142
4143 /// The field in which the AddrModes differ, when we have more than one.
4144 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
4145
4146 /// Are the AddrModes that we have all just equal to their original values?
4147 bool AllAddrModesTrivial = true;
4148
4149 /// Common Type for all different fields in addressing modes.
4150 Type *CommonType = nullptr;
4151
4152 const DataLayout &DL;
4153
4154 /// Original Address.
4155 Value *Original;
4156
4157 /// Common value among addresses
4158 Value *CommonValue = nullptr;
4159
4160public:
4161 AddressingModeCombiner(const DataLayout &DL, Value *OriginalValue)
4162 : DL(DL), Original(OriginalValue) {}
4163
4164 ~AddressingModeCombiner() { eraseCommonValueIfDead(); }
4165
4166 /// Get the combined AddrMode
4167 const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
4168
4169 /// Add a new AddrMode if it's compatible with the AddrModes we already
4170 /// have.
4171 /// \return True iff we succeeded in doing so.
4172 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
4173 // Take note of if we have any non-trivial AddrModes, as we need to detect
4174 // when all AddrModes are trivial as then we would introduce a phi or select
4175 // which just duplicates what's already there.
4176 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
4177
4178 // If this is the first addrmode then everything is fine.
4179 if (AddrModes.empty()) {
4180 AddrModes.emplace_back(Args&: NewAddrMode);
4181 return true;
4182 }
4183
4184 // Figure out how different this is from the other address modes, which we
4185 // can do just by comparing against the first one given that we only care
4186 // about the cumulative difference.
4187 ExtAddrMode::FieldName ThisDifferentField =
4188 AddrModes[0].compare(other: NewAddrMode);
4189 if (DifferentField == ExtAddrMode::NoField)
4190 DifferentField = ThisDifferentField;
4191 else if (DifferentField != ThisDifferentField)
4192 DifferentField = ExtAddrMode::MultipleFields;
4193
4194 // If NewAddrMode differs in more than one dimension we cannot handle it.
4195 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
4196
4197 // If Scale Field is different then we reject.
4198 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
4199
4200 // We also must reject the case when base offset is different and
4201 // scale reg is not null, we cannot handle this case due to merge of
4202 // different offsets will be used as ScaleReg.
4203 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
4204 !NewAddrMode.ScaledReg);
4205
4206 // We also must reject the case when GV is different and BaseReg installed
4207 // due to we want to use base reg as a merge of GV values.
4208 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
4209 !NewAddrMode.HasBaseReg);
4210
4211 // Even if NewAddMode is the same we still need to collect it due to
4212 // original value is different. And later we will need all original values
4213 // as anchors during finding the common Phi node.
4214 if (CanHandle)
4215 AddrModes.emplace_back(Args&: NewAddrMode);
4216 else
4217 AddrModes.clear();
4218
4219 return CanHandle;
4220 }
4221
4222 /// Combine the addressing modes we've collected into a single
4223 /// addressing mode.
4224 /// \return True iff we successfully combined them or we only had one so
4225 /// didn't need to combine them anyway.
4226 bool combineAddrModes() {
4227 // If we have no AddrModes then they can't be combined.
4228 if (AddrModes.size() == 0)
4229 return false;
4230
4231 // A single AddrMode can trivially be combined.
4232 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
4233 return true;
4234
4235 // If the AddrModes we collected are all just equal to the value they are
4236 // derived from then combining them wouldn't do anything useful.
4237 if (AllAddrModesTrivial)
4238 return false;
4239
4240 if (!addrModeCombiningAllowed())
4241 return false;
4242
4243 // Build a map between <original value, basic block where we saw it> to
4244 // value of base register.
4245 // Bail out if there is no common type.
4246 FoldAddrToValueMapping Map;
4247 if (!initializeMap(Map))
4248 return false;
4249
4250 CommonValue = findCommon(Map);
4251 if (CommonValue)
4252 AddrModes[0].SetCombinedField(Field: DifferentField, V: CommonValue, AddrModes);
4253 return CommonValue != nullptr;
4254 }
4255
4256private:
4257 /// `CommonValue` may be a placeholder inserted by us.
4258 /// If the placeholder is not used, we should remove this dead instruction.
4259 void eraseCommonValueIfDead() {
4260 if (CommonValue && CommonValue->use_empty())
4261 if (Instruction *CommonInst = dyn_cast<Instruction>(Val: CommonValue))
4262 CommonInst->eraseFromParent();
4263 }
4264
4265 /// Initialize Map with anchor values. For address seen
4266 /// we set the value of different field saw in this address.
4267 /// At the same time we find a common type for different field we will
4268 /// use to create new Phi/Select nodes. Keep it in CommonType field.
4269 /// Return false if there is no common type found.
4270 bool initializeMap(FoldAddrToValueMapping &Map) {
4271 // Keep track of keys where the value is null. We will need to replace it
4272 // with constant null when we know the common type.
4273 SmallVector<Value *, 2> NullValue;
4274 Type *IntPtrTy = DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
4275 for (auto &AM : AddrModes) {
4276 Value *DV = AM.GetFieldAsValue(Field: DifferentField, IntPtrTy);
4277 if (DV) {
4278 auto *Type = DV->getType();
4279 if (CommonType && CommonType != Type)
4280 return false;
4281 CommonType = Type;
4282 Map[AM.OriginalValue] = DV;
4283 } else {
4284 NullValue.push_back(Elt: AM.OriginalValue);
4285 }
4286 }
4287 assert(CommonType && "At least one non-null value must be!");
4288 for (auto *V : NullValue)
4289 Map[V] = Constant::getNullValue(Ty: CommonType);
4290 return true;
4291 }
4292
4293 /// We have mapping between value A and other value B where B was a field in
4294 /// addressing mode represented by A. Also we have an original value C
4295 /// representing an address we start with. Traversing from C through phi and
4296 /// selects we ended up with A's in a map. This utility function tries to find
4297 /// a value V which is a field in addressing mode C and traversing through phi
4298 /// nodes and selects we will end up in corresponded values B in a map.
4299 /// The utility will create a new Phi/Selects if needed.
4300 // The simple example looks as follows:
4301 // BB1:
4302 // p1 = b1 + 40
4303 // br cond BB2, BB3
4304 // BB2:
4305 // p2 = b2 + 40
4306 // br BB3
4307 // BB3:
4308 // p = phi [p1, BB1], [p2, BB2]
4309 // v = load p
4310 // Map is
4311 // p1 -> b1
4312 // p2 -> b2
4313 // Request is
4314 // p -> ?
4315 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
4316 Value *findCommon(FoldAddrToValueMapping &Map) {
4317 // Tracks the simplification of newly created phi nodes. The reason we use
4318 // this mapping is because we will add new created Phi nodes in AddrToBase.
4319 // Simplification of Phi nodes is recursive, so some Phi node may
4320 // be simplified after we added it to AddrToBase. In reality this
4321 // simplification is possible only if original phi/selects were not
4322 // simplified yet.
4323 // Using this mapping we can find the current value in AddrToBase.
4324 SimplificationTracker ST;
4325
4326 // First step, DFS to create PHI nodes for all intermediate blocks.
4327 // Also fill traverse order for the second step.
4328 SmallVector<Value *, 32> TraverseOrder;
4329 InsertPlaceholders(Map, TraverseOrder, ST);
4330
4331 // Second Step, fill new nodes by merged values and simplify if possible.
4332 FillPlaceholders(Map, TraverseOrder, ST);
4333
4334 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
4335 ST.destroyNewNodes(CommonType);
4336 return nullptr;
4337 }
4338
4339 // Now we'd like to match New Phi nodes to existed ones.
4340 unsigned PhiNotMatchedCount = 0;
4341 if (!MatchPhiSet(ST, AllowNewPhiNodes: AddrSinkNewPhis, PhiNotMatchedCount)) {
4342 ST.destroyNewNodes(CommonType);
4343 return nullptr;
4344 }
4345
4346 auto *Result = ST.Get(V: Map.find(Val: Original)->second);
4347 if (Result) {
4348 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
4349 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
4350 }
4351 return Result;
4352 }
4353
4354 /// Try to match PHI node to Candidate.
4355 /// Matcher tracks the matched Phi nodes.
4356 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
4357 SmallSetVector<PHIPair, 8> &Matcher,
4358 PhiNodeSet &PhiNodesToMatch) {
4359 SmallVector<PHIPair, 8> WorkList;
4360 Matcher.insert(X: {PHI, Candidate});
4361 SmallPtrSet<PHINode *, 8> MatchedPHIs;
4362 MatchedPHIs.insert(Ptr: PHI);
4363 WorkList.push_back(Elt: {PHI, Candidate});
4364 SmallSet<PHIPair, 8> Visited;
4365 while (!WorkList.empty()) {
4366 auto Item = WorkList.pop_back_val();
4367 if (!Visited.insert(V: Item).second)
4368 continue;
4369 // We iterate over all incoming values to Phi to compare them.
4370 // If values are different and both of them Phi and the first one is a
4371 // Phi we added (subject to match) and both of them is in the same basic
4372 // block then we can match our pair if values match. So we state that
4373 // these values match and add it to work list to verify that.
4374 for (auto *B : Item.first->blocks()) {
4375 Value *FirstValue = Item.first->getIncomingValueForBlock(BB: B);
4376 Value *SecondValue = Item.second->getIncomingValueForBlock(BB: B);
4377 if (FirstValue == SecondValue)
4378 continue;
4379
4380 PHINode *FirstPhi = dyn_cast<PHINode>(Val: FirstValue);
4381 PHINode *SecondPhi = dyn_cast<PHINode>(Val: SecondValue);
4382
4383 // One of them is not Phi or
4384 // The first one is not Phi node from the set we'd like to match or
4385 // Phi nodes from different basic blocks then
4386 // we will not be able to match.
4387 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(Ptr: FirstPhi) ||
4388 FirstPhi->getParent() != SecondPhi->getParent())
4389 return false;
4390
4391 // If we already matched them then continue.
4392 if (Matcher.count(key: {FirstPhi, SecondPhi}))
4393 continue;
4394 // So the values are different and does not match. So we need them to
4395 // match. (But we register no more than one match per PHI node, so that
4396 // we won't later try to replace them twice.)
4397 if (MatchedPHIs.insert(Ptr: FirstPhi).second)
4398 Matcher.insert(X: {FirstPhi, SecondPhi});
4399 // But me must check it.
4400 WorkList.push_back(Elt: {FirstPhi, SecondPhi});
4401 }
4402 }
4403 return true;
4404 }
4405
4406 /// For the given set of PHI nodes (in the SimplificationTracker) try
4407 /// to find their equivalents.
4408 /// Returns false if this matching fails and creation of new Phi is disabled.
4409 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
4410 unsigned &PhiNotMatchedCount) {
4411 // Matched and PhiNodesToMatch iterate their elements in a deterministic
4412 // order, so the replacements (ReplacePhi) are also done in a deterministic
4413 // order.
4414 SmallSetVector<PHIPair, 8> Matched;
4415 SmallPtrSet<PHINode *, 8> WillNotMatch;
4416 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
4417 while (PhiNodesToMatch.size()) {
4418 PHINode *PHI = *PhiNodesToMatch.begin();
4419
4420 // Add us, if no Phi nodes in the basic block we do not match.
4421 WillNotMatch.clear();
4422 WillNotMatch.insert(Ptr: PHI);
4423
4424 // Traverse all Phis until we found equivalent or fail to do that.
4425 bool IsMatched = false;
4426 for (auto &P : PHI->getParent()->phis()) {
4427 // Skip new Phi nodes.
4428 if (PhiNodesToMatch.count(Ptr: &P))
4429 continue;
4430 if ((IsMatched = MatchPhiNode(PHI, Candidate: &P, Matcher&: Matched, PhiNodesToMatch)))
4431 break;
4432 // If it does not match, collect all Phi nodes from matcher.
4433 // if we end up with no match, them all these Phi nodes will not match
4434 // later.
4435 WillNotMatch.insert_range(R: llvm::make_first_range(c&: Matched));
4436 Matched.clear();
4437 }
4438 if (IsMatched) {
4439 // Replace all matched values and erase them.
4440 for (auto MV : Matched)
4441 ST.ReplacePhi(From: MV.first, To: MV.second);
4442 Matched.clear();
4443 continue;
4444 }
4445 // If we are not allowed to create new nodes then bail out.
4446 if (!AllowNewPhiNodes)
4447 return false;
4448 // Just remove all seen values in matcher. They will not match anything.
4449 PhiNotMatchedCount += WillNotMatch.size();
4450 for (auto *P : WillNotMatch)
4451 PhiNodesToMatch.erase(Ptr: P);
4452 }
4453 return true;
4454 }
4455 /// Fill the placeholders with values from predecessors and simplify them.
4456 void FillPlaceholders(FoldAddrToValueMapping &Map,
4457 SmallVectorImpl<Value *> &TraverseOrder,
4458 SimplificationTracker &ST) {
4459 while (!TraverseOrder.empty()) {
4460 Value *Current = TraverseOrder.pop_back_val();
4461 assert(Map.contains(Current) && "No node to fill!!!");
4462 Value *V = Map[Current];
4463
4464 if (SelectInst *Select = dyn_cast<SelectInst>(Val: V)) {
4465 // CurrentValue also must be Select.
4466 auto *CurrentSelect = cast<SelectInst>(Val: Current);
4467 auto *TrueValue = CurrentSelect->getTrueValue();
4468 assert(Map.contains(TrueValue) && "No True Value!");
4469 Select->setTrueValue(ST.Get(V: Map[TrueValue]));
4470 auto *FalseValue = CurrentSelect->getFalseValue();
4471 assert(Map.contains(FalseValue) && "No False Value!");
4472 Select->setFalseValue(ST.Get(V: Map[FalseValue]));
4473 } else {
4474 // Must be a Phi node then.
4475 auto *PHI = cast<PHINode>(Val: V);
4476 // Fill the Phi node with values from predecessors.
4477 for (auto *B : predecessors(BB: PHI->getParent())) {
4478 Value *PV = cast<PHINode>(Val: Current)->getIncomingValueForBlock(BB: B);
4479 assert(Map.contains(PV) && "No predecessor Value!");
4480 PHI->addIncoming(V: ST.Get(V: Map[PV]), BB: B);
4481 }
4482 }
4483 }
4484 }
4485
4486 /// Starting from original value recursively iterates over def-use chain up to
4487 /// known ending values represented in a map. For each traversed phi/select
4488 /// inserts a placeholder Phi or Select.
4489 /// Reports all new created Phi/Select nodes by adding them to set.
4490 /// Also reports and order in what values have been traversed.
4491 void InsertPlaceholders(FoldAddrToValueMapping &Map,
4492 SmallVectorImpl<Value *> &TraverseOrder,
4493 SimplificationTracker &ST) {
4494 SmallVector<Value *, 32> Worklist;
4495 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
4496 "Address must be a Phi or Select node");
4497 auto *Dummy = PoisonValue::get(T: CommonType);
4498 Worklist.push_back(Elt: Original);
4499 while (!Worklist.empty()) {
4500 Value *Current = Worklist.pop_back_val();
4501 // if it is already visited or it is an ending value then skip it.
4502 if (Map.contains(Val: Current))
4503 continue;
4504 TraverseOrder.push_back(Elt: Current);
4505
4506 // CurrentValue must be a Phi node or select. All others must be covered
4507 // by anchors.
4508 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Val: Current)) {
4509 // Is it OK to get metadata from OrigSelect?!
4510 // Create a Select placeholder with dummy value.
4511 SelectInst *Select =
4512 SelectInst::Create(C: CurrentSelect->getCondition(), S1: Dummy, S2: Dummy,
4513 NameStr: CurrentSelect->getName(),
4514 InsertBefore: CurrentSelect->getIterator(), MDFrom: CurrentSelect);
4515 Map[Current] = Select;
4516 ST.insertNewSelect(SI: Select);
4517 // We are interested in True and False values.
4518 Worklist.push_back(Elt: CurrentSelect->getTrueValue());
4519 Worklist.push_back(Elt: CurrentSelect->getFalseValue());
4520 } else {
4521 // It must be a Phi node then.
4522 PHINode *CurrentPhi = cast<PHINode>(Val: Current);
4523 unsigned PredCount = CurrentPhi->getNumIncomingValues();
4524 PHINode *PHI =
4525 PHINode::Create(Ty: CommonType, NumReservedValues: PredCount, NameStr: "sunk_phi", InsertBefore: CurrentPhi->getIterator());
4526 Map[Current] = PHI;
4527 ST.insertNewPhi(PN: PHI);
4528 append_range(C&: Worklist, R: CurrentPhi->incoming_values());
4529 }
4530 }
4531 }
4532
4533 bool addrModeCombiningAllowed() {
4534 if (DisableComplexAddrModes)
4535 return false;
4536 switch (DifferentField) {
4537 default:
4538 return false;
4539 case ExtAddrMode::BaseRegField:
4540 return AddrSinkCombineBaseReg;
4541 case ExtAddrMode::BaseGVField:
4542 return AddrSinkCombineBaseGV;
4543 case ExtAddrMode::BaseOffsField:
4544 return AddrSinkCombineBaseOffs;
4545 case ExtAddrMode::ScaledRegField:
4546 return AddrSinkCombineScaledReg;
4547 }
4548 }
4549};
4550} // end anonymous namespace
4551
4552/// Try adding ScaleReg*Scale to the current addressing mode.
4553/// Return true and update AddrMode if this addr mode is legal for the target,
4554/// false if not.
4555bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
4556 unsigned Depth) {
4557 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
4558 // mode. Just process that directly.
4559 if (Scale == 1)
4560 return matchAddr(Addr: ScaleReg, Depth);
4561
4562 // If the scale is 0, it takes nothing to add this.
4563 if (Scale == 0)
4564 return true;
4565
4566 // If we already have a scale of this value, we can add to it, otherwise, we
4567 // need an available scale field.
4568 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
4569 return false;
4570
4571 ExtAddrMode TestAddrMode = AddrMode;
4572
4573 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
4574 // [A+B + A*7] -> [B+A*8].
4575 TestAddrMode.Scale += Scale;
4576 TestAddrMode.ScaledReg = ScaleReg;
4577
4578 // If the new address isn't legal, bail out.
4579 if (!TLI.isLegalAddressingMode(DL, AM: TestAddrMode, Ty: AccessTy, AddrSpace))
4580 return false;
4581
4582 // It was legal, so commit it.
4583 AddrMode = TestAddrMode;
4584
4585 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
4586 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
4587 // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
4588 // go any further: we can reuse it and cannot eliminate it.
4589 ConstantInt *CI = nullptr;
4590 Value *AddLHS = nullptr;
4591 if (isa<Instruction>(Val: ScaleReg) && // not a constant expr.
4592 match(V: ScaleReg, P: m_Add(L: m_Value(V&: AddLHS), R: m_ConstantInt(CI))) &&
4593 !isIVIncrement(V: ScaleReg, LI: &LI) && CI->getValue().isSignedIntN(N: 64)) {
4594 TestAddrMode.InBounds = false;
4595 TestAddrMode.ScaledReg = AddLHS;
4596 TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
4597
4598 // If this addressing mode is legal, commit it and remember that we folded
4599 // this instruction.
4600 if (TLI.isLegalAddressingMode(DL, AM: TestAddrMode, Ty: AccessTy, AddrSpace)) {
4601 AddrModeInsts.push_back(Elt: cast<Instruction>(Val: ScaleReg));
4602 AddrMode = TestAddrMode;
4603 return true;
4604 }
4605 // Restore status quo.
4606 TestAddrMode = AddrMode;
4607 }
4608
4609 // If this is an add recurrence with a constant step, return the increment
4610 // instruction and the canonicalized step.
4611 auto GetConstantStep =
4612 [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
4613 auto *PN = dyn_cast<PHINode>(Val: V);
4614 if (!PN)
4615 return std::nullopt;
4616 auto IVInc = getIVIncrement(PN, LI: &LI);
4617 if (!IVInc)
4618 return std::nullopt;
4619 // TODO: The result of the intrinsics above is two-complement. However when
4620 // IV inc is expressed as add or sub, iv.next is potentially a poison value.
4621 // If it has nuw or nsw flags, we need to make sure that these flags are
4622 // inferrable at the point of memory instruction. Otherwise we are replacing
4623 // well-defined two-complement computation with poison. Currently, to avoid
4624 // potentially complex analysis needed to prove this, we reject such cases.
4625 if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(Val: IVInc->first))
4626 if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
4627 return std::nullopt;
4628 if (auto *ConstantStep = dyn_cast<ConstantInt>(Val: IVInc->second))
4629 return std::make_pair(x&: IVInc->first, y: ConstantStep->getValue());
4630 return std::nullopt;
4631 };
4632
4633 // Try to account for the following special case:
4634 // 1. ScaleReg is an inductive variable;
4635 // 2. We use it with non-zero offset;
4636 // 3. IV's increment is available at the point of memory instruction.
4637 //
4638 // In this case, we may reuse the IV increment instead of the IV Phi to
4639 // achieve the following advantages:
4640 // 1. If IV step matches the offset, we will have no need in the offset;
4641 // 2. Even if they don't match, we will reduce the overlap of living IV
4642 // and IV increment, that will potentially lead to better register
4643 // assignment.
4644 if (AddrMode.BaseOffs) {
4645 if (auto IVStep = GetConstantStep(ScaleReg)) {
4646 Instruction *IVInc = IVStep->first;
4647 // The following assert is important to ensure a lack of infinite loops.
4648 // This transforms is (intentionally) the inverse of the one just above.
4649 // If they don't agree on the definition of an increment, we'd alternate
4650 // back and forth indefinitely.
4651 assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
4652 APInt Step = IVStep->second;
4653 APInt Offset = Step * AddrMode.Scale;
4654 if (Offset.isSignedIntN(N: 64)) {
4655 TestAddrMode.InBounds = false;
4656 TestAddrMode.ScaledReg = IVInc;
4657 TestAddrMode.BaseOffs -= Offset.getLimitedValue();
4658 // If this addressing mode is legal, commit it..
4659 // (Note that we defer the (expensive) domtree base legality check
4660 // to the very last possible point.)
4661 if (TLI.isLegalAddressingMode(DL, AM: TestAddrMode, Ty: AccessTy, AddrSpace) &&
4662 getDTFn().dominates(Def: IVInc, User: MemoryInst)) {
4663 AddrModeInsts.push_back(Elt: cast<Instruction>(Val: IVInc));
4664 AddrMode = TestAddrMode;
4665 return true;
4666 }
4667 // Restore status quo.
4668 TestAddrMode = AddrMode;
4669 }
4670 }
4671 }
4672
4673 // Otherwise, just return what we have.
4674 return true;
4675}
4676
4677/// This is a little filter, which returns true if an addressing computation
4678/// involving I might be folded into a load/store accessing it.
4679/// This doesn't need to be perfect, but needs to accept at least
4680/// the set of instructions that MatchOperationAddr can.
4681static bool MightBeFoldableInst(Instruction *I) {
4682 switch (I->getOpcode()) {
4683 case Instruction::BitCast:
4684 case Instruction::AddrSpaceCast:
4685 // Don't touch identity bitcasts.
4686 if (I->getType() == I->getOperand(i: 0)->getType())
4687 return false;
4688 return I->getType()->isIntOrPtrTy();
4689 case Instruction::PtrToInt:
4690 // PtrToInt is always a noop, as we know that the int type is pointer sized.
4691 return true;
4692 case Instruction::IntToPtr:
4693 // We know the input is intptr_t, so this is foldable.
4694 return true;
4695 case Instruction::Add:
4696 return true;
4697 case Instruction::Mul:
4698 case Instruction::Shl:
4699 // Can only handle X*C and X << C.
4700 return isa<ConstantInt>(Val: I->getOperand(i: 1));
4701 case Instruction::GetElementPtr:
4702 return true;
4703 default:
4704 return false;
4705 }
4706}
4707
4708/// Check whether or not \p Val is a legal instruction for \p TLI.
4709/// \note \p Val is assumed to be the product of some type promotion.
4710/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
4711/// to be legal, as the non-promoted value would have had the same state.
4712static bool isPromotedInstructionLegal(const TargetLowering &TLI,
4713 const DataLayout &DL, Value *Val) {
4714 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
4715 if (!PromotedInst)
4716 return false;
4717 int ISDOpcode = TLI.InstructionOpcodeToISD(Opcode: PromotedInst->getOpcode());
4718 // If the ISDOpcode is undefined, it was undefined before the promotion.
4719 if (!ISDOpcode)
4720 return true;
4721 // Otherwise, check if the promoted instruction is legal or not.
4722 return TLI.isOperationLegalOrCustom(
4723 Op: ISDOpcode, VT: TLI.getValueType(DL, Ty: PromotedInst->getType()));
4724}
4725
4726namespace {
4727
4728/// Hepler class to perform type promotion.
4729class TypePromotionHelper {
4730 /// Utility function to add a promoted instruction \p ExtOpnd to
4731 /// \p PromotedInsts and record the type of extension we have seen.
4732 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
4733 Instruction *ExtOpnd, bool IsSExt) {
4734 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4735 auto [It, Inserted] = PromotedInsts.try_emplace(Key: ExtOpnd);
4736 if (!Inserted) {
4737 // If the new extension is same as original, the information in
4738 // PromotedInsts[ExtOpnd] is still correct.
4739 if (It->second.getInt() == ExtTy)
4740 return;
4741
4742 // Now the new extension is different from old extension, we make
4743 // the type information invalid by setting extension type to
4744 // BothExtension.
4745 ExtTy = BothExtension;
4746 }
4747 It->second = TypeIsSExt(ExtOpnd->getType(), ExtTy);
4748 }
4749
4750 /// Utility function to query the original type of instruction \p Opnd
4751 /// with a matched extension type. If the extension doesn't match, we
4752 /// cannot use the information we had on the original type.
4753 /// BothExtension doesn't match any extension type.
4754 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
4755 Instruction *Opnd, bool IsSExt) {
4756 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
4757 InstrToOrigTy::const_iterator It = PromotedInsts.find(Val: Opnd);
4758 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
4759 return It->second.getPointer();
4760 return nullptr;
4761 }
4762
4763 /// Utility function to check whether or not a sign or zero extension
4764 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
4765 /// either using the operands of \p Inst or promoting \p Inst.
4766 /// The type of the extension is defined by \p IsSExt.
4767 /// In other words, check if:
4768 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
4769 /// #1 Promotion applies:
4770 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
4771 /// #2 Operand reuses:
4772 /// ext opnd1 to ConsideredExtType.
4773 /// \p PromotedInsts maps the instructions to their type before promotion.
4774 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
4775 const InstrToOrigTy &PromotedInsts, bool IsSExt);
4776
4777 /// Utility function to determine if \p OpIdx should be promoted when
4778 /// promoting \p Inst.
4779 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
4780 return !(isa<SelectInst>(Val: Inst) && OpIdx == 0);
4781 }
4782
4783 /// Utility function to promote the operand of \p Ext when this
4784 /// operand is a promotable trunc or sext or zext.
4785 /// \p PromotedInsts maps the instructions to their type before promotion.
4786 /// \p CreatedInstsCost[out] contains the cost of all instructions
4787 /// created to promote the operand of Ext.
4788 /// Newly added extensions are inserted in \p Exts.
4789 /// Newly added truncates are inserted in \p Truncs.
4790 /// Should never be called directly.
4791 /// \return The promoted value which is used instead of Ext.
4792 static Value *promoteOperandForTruncAndAnyExt(
4793 Instruction *Ext, TypePromotionTransaction &TPT,
4794 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4795 SmallVectorImpl<Instruction *> *Exts,
4796 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
4797
4798 /// Utility function to promote the operand of \p Ext when this
4799 /// operand is promotable and is not a supported trunc or sext.
4800 /// \p PromotedInsts maps the instructions to their type before promotion.
4801 /// \p CreatedInstsCost[out] contains the cost of all the instructions
4802 /// created to promote the operand of Ext.
4803 /// Newly added extensions are inserted in \p Exts.
4804 /// Newly added truncates are inserted in \p Truncs.
4805 /// Should never be called directly.
4806 /// \return The promoted value which is used instead of Ext.
4807 static Value *promoteOperandForOther(Instruction *Ext,
4808 TypePromotionTransaction &TPT,
4809 InstrToOrigTy &PromotedInsts,
4810 unsigned &CreatedInstsCost,
4811 SmallVectorImpl<Instruction *> *Exts,
4812 SmallVectorImpl<Instruction *> *Truncs,
4813 const TargetLowering &TLI, bool IsSExt);
4814
4815 /// \see promoteOperandForOther.
4816 static Value *signExtendOperandForOther(
4817 Instruction *Ext, TypePromotionTransaction &TPT,
4818 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4819 SmallVectorImpl<Instruction *> *Exts,
4820 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4821 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4822 Exts, Truncs, TLI, IsSExt: true);
4823 }
4824
4825 /// \see promoteOperandForOther.
4826 static Value *zeroExtendOperandForOther(
4827 Instruction *Ext, TypePromotionTransaction &TPT,
4828 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4829 SmallVectorImpl<Instruction *> *Exts,
4830 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
4831 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
4832 Exts, Truncs, TLI, IsSExt: false);
4833 }
4834
4835public:
4836 /// Type for the utility function that promotes the operand of Ext.
4837 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
4838 InstrToOrigTy &PromotedInsts,
4839 unsigned &CreatedInstsCost,
4840 SmallVectorImpl<Instruction *> *Exts,
4841 SmallVectorImpl<Instruction *> *Truncs,
4842 const TargetLowering &TLI);
4843
4844 /// Given a sign/zero extend instruction \p Ext, return the appropriate
4845 /// action to promote the operand of \p Ext instead of using Ext.
4846 /// \return NULL if no promotable action is possible with the current
4847 /// sign extension.
4848 /// \p InsertedInsts keeps track of all the instructions inserted by the
4849 /// other CodeGenPrepare optimizations. This information is important
4850 /// because we do not want to promote these instructions as CodeGenPrepare
4851 /// will reinsert them later. Thus creating an infinite loop: create/remove.
4852 /// \p PromotedInsts maps the instructions to their type before promotion.
4853 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
4854 const TargetLowering &TLI,
4855 const InstrToOrigTy &PromotedInsts);
4856};
4857
4858} // end anonymous namespace
4859
4860bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
4861 Type *ConsideredExtType,
4862 const InstrToOrigTy &PromotedInsts,
4863 bool IsSExt) {
4864 // The promotion helper does not know how to deal with vector types yet.
4865 // To be able to fix that, we would need to fix the places where we
4866 // statically extend, e.g., constants and such.
4867 if (Inst->getType()->isVectorTy())
4868 return false;
4869
4870 // We can always get through zext.
4871 if (isa<ZExtInst>(Val: Inst))
4872 return true;
4873
4874 // sext(sext) is ok too.
4875 if (IsSExt && isa<SExtInst>(Val: Inst))
4876 return true;
4877
4878 // We can get through binary operator, if it is legal. In other words, the
4879 // binary operator must have a nuw or nsw flag.
4880 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: Inst))
4881 if (isa<OverflowingBinaryOperator>(Val: BinOp) &&
4882 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
4883 (IsSExt && BinOp->hasNoSignedWrap())))
4884 return true;
4885
4886 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
4887 if ((Inst->getOpcode() == Instruction::And ||
4888 Inst->getOpcode() == Instruction::Or))
4889 return true;
4890
4891 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
4892 if (Inst->getOpcode() == Instruction::Xor) {
4893 // Make sure it is not a NOT.
4894 if (const auto *Cst = dyn_cast<ConstantInt>(Val: Inst->getOperand(i: 1)))
4895 if (!Cst->getValue().isAllOnes())
4896 return true;
4897 }
4898
4899 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
4900 // It may change a poisoned value into a regular value, like
4901 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
4902 // poisoned value regular value
4903 // It should be OK since undef covers valid value.
4904 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
4905 return true;
4906
4907 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
4908 // It may change a poisoned value into a regular value, like
4909 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
4910 // poisoned value regular value
4911 // It should be OK since undef covers valid value.
4912 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
4913 const auto *ExtInst = cast<const Instruction>(Val: *Inst->user_begin());
4914 if (ExtInst->hasOneUse()) {
4915 const auto *AndInst = dyn_cast<const Instruction>(Val: *ExtInst->user_begin());
4916 if (AndInst && AndInst->getOpcode() == Instruction::And) {
4917 const auto *Cst = dyn_cast<ConstantInt>(Val: AndInst->getOperand(i: 1));
4918 if (Cst &&
4919 Cst->getValue().isIntN(N: Inst->getType()->getIntegerBitWidth()))
4920 return true;
4921 }
4922 }
4923 }
4924
4925 // Check if we can do the following simplification.
4926 // ext(trunc(opnd)) --> ext(opnd)
4927 if (!isa<TruncInst>(Val: Inst))
4928 return false;
4929
4930 Value *OpndVal = Inst->getOperand(i: 0);
4931 // Check if we can use this operand in the extension.
4932 // If the type is larger than the result type of the extension, we cannot.
4933 if (!OpndVal->getType()->isIntegerTy() ||
4934 OpndVal->getType()->getIntegerBitWidth() >
4935 ConsideredExtType->getIntegerBitWidth())
4936 return false;
4937
4938 // If the operand of the truncate is not an instruction, we will not have
4939 // any information on the dropped bits.
4940 // (Actually we could for constant but it is not worth the extra logic).
4941 Instruction *Opnd = dyn_cast<Instruction>(Val: OpndVal);
4942 if (!Opnd)
4943 return false;
4944
4945 // Check if the source of the type is narrow enough.
4946 // I.e., check that trunc just drops extended bits of the same kind of
4947 // the extension.
4948 // #1 get the type of the operand and check the kind of the extended bits.
4949 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
4950 if (OpndType)
4951 ;
4952 else if ((IsSExt && isa<SExtInst>(Val: Opnd)) || (!IsSExt && isa<ZExtInst>(Val: Opnd)))
4953 OpndType = Opnd->getOperand(i: 0)->getType();
4954 else
4955 return false;
4956
4957 // #2 check that the truncate just drops extended bits.
4958 return Inst->getType()->getIntegerBitWidth() >=
4959 OpndType->getIntegerBitWidth();
4960}
4961
4962TypePromotionHelper::Action TypePromotionHelper::getAction(
4963 Instruction *Ext, const SetOfInstrs &InsertedInsts,
4964 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
4965 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4966 "Unexpected instruction type");
4967 Instruction *ExtOpnd = dyn_cast<Instruction>(Val: Ext->getOperand(i: 0));
4968 Type *ExtTy = Ext->getType();
4969 bool IsSExt = isa<SExtInst>(Val: Ext);
4970 // If the operand of the extension is not an instruction, we cannot
4971 // get through.
4972 // If it, check we can get through.
4973 if (!ExtOpnd || !canGetThrough(Inst: ExtOpnd, ConsideredExtType: ExtTy, PromotedInsts, IsSExt))
4974 return nullptr;
4975
4976 // Do not promote if the operand has been added by codegenprepare.
4977 // Otherwise, it means we are undoing an optimization that is likely to be
4978 // redone, thus causing potential infinite loop.
4979 if (isa<TruncInst>(Val: ExtOpnd) && InsertedInsts.count(Ptr: ExtOpnd))
4980 return nullptr;
4981
4982 // SExt or Trunc instructions.
4983 // Return the related handler.
4984 if (isa<SExtInst>(Val: ExtOpnd) || isa<TruncInst>(Val: ExtOpnd) ||
4985 isa<ZExtInst>(Val: ExtOpnd))
4986 return promoteOperandForTruncAndAnyExt;
4987
4988 // Regular instruction.
4989 // Abort early if we will have to insert non-free instructions.
4990 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(FromTy: ExtTy, ToTy: ExtOpnd->getType()))
4991 return nullptr;
4992 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
4993}
4994
4995Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
4996 Instruction *SExt, TypePromotionTransaction &TPT,
4997 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
4998 SmallVectorImpl<Instruction *> *Exts,
4999 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
5000 // By construction, the operand of SExt is an instruction. Otherwise we cannot
5001 // get through it and this method should not be called.
5002 Instruction *SExtOpnd = cast<Instruction>(Val: SExt->getOperand(i: 0));
5003 Value *ExtVal = SExt;
5004 bool HasMergedNonFreeExt = false;
5005 if (isa<ZExtInst>(Val: SExtOpnd)) {
5006 // Replace s|zext(zext(opnd))
5007 // => zext(opnd).
5008 HasMergedNonFreeExt = !TLI.isExtFree(I: SExtOpnd);
5009 Value *ZExt =
5010 TPT.createZExt(Inst: SExt, Opnd: SExtOpnd->getOperand(i: 0), Ty: SExt->getType());
5011 TPT.replaceAllUsesWith(Inst: SExt, New: ZExt);
5012 TPT.eraseInstruction(Inst: SExt);
5013 ExtVal = ZExt;
5014 } else {
5015 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
5016 // => z|sext(opnd).
5017 TPT.setOperand(Inst: SExt, Idx: 0, NewVal: SExtOpnd->getOperand(i: 0));
5018 }
5019 CreatedInstsCost = 0;
5020
5021 // Remove dead code.
5022 if (SExtOpnd->use_empty())
5023 TPT.eraseInstruction(Inst: SExtOpnd);
5024
5025 // Check if the extension is still needed.
5026 Instruction *ExtInst = dyn_cast<Instruction>(Val: ExtVal);
5027 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(i: 0)->getType()) {
5028 if (ExtInst) {
5029 if (Exts)
5030 Exts->push_back(Elt: ExtInst);
5031 CreatedInstsCost = !TLI.isExtFree(I: ExtInst) && !HasMergedNonFreeExt;
5032 }
5033 return ExtVal;
5034 }
5035
5036 // At this point we have: ext ty opnd to ty.
5037 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
5038 Value *NextVal = ExtInst->getOperand(i: 0);
5039 TPT.eraseInstruction(Inst: ExtInst, NewVal: NextVal);
5040 return NextVal;
5041}
5042
5043Value *TypePromotionHelper::promoteOperandForOther(
5044 Instruction *Ext, TypePromotionTransaction &TPT,
5045 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
5046 SmallVectorImpl<Instruction *> *Exts,
5047 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
5048 bool IsSExt) {
5049 // By construction, the operand of Ext is an instruction. Otherwise we cannot
5050 // get through it and this method should not be called.
5051 Instruction *ExtOpnd = cast<Instruction>(Val: Ext->getOperand(i: 0));
5052 CreatedInstsCost = 0;
5053 if (!ExtOpnd->hasOneUse()) {
5054 // ExtOpnd will be promoted.
5055 // All its uses, but Ext, will need to use a truncated value of the
5056 // promoted version.
5057 // Create the truncate now.
5058 Value *Trunc = TPT.createTrunc(Opnd: Ext, Ty: ExtOpnd->getType());
5059 if (Instruction *ITrunc = dyn_cast<Instruction>(Val: Trunc)) {
5060 // Insert it just after the definition.
5061 ITrunc->moveAfter(MovePos: ExtOpnd);
5062 if (Truncs)
5063 Truncs->push_back(Elt: ITrunc);
5064 }
5065
5066 TPT.replaceAllUsesWith(Inst: ExtOpnd, New: Trunc);
5067 // Restore the operand of Ext (which has been replaced by the previous call
5068 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
5069 TPT.setOperand(Inst: Ext, Idx: 0, NewVal: ExtOpnd);
5070 }
5071
5072 // Get through the Instruction:
5073 // 1. Update its type.
5074 // 2. Replace the uses of Ext by Inst.
5075 // 3. Extend each operand that needs to be extended.
5076
5077 // Remember the original type of the instruction before promotion.
5078 // This is useful to know that the high bits are sign extended bits.
5079 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
5080 // Step #1.
5081 TPT.mutateType(Inst: ExtOpnd, NewTy: Ext->getType());
5082 // Step #2.
5083 TPT.replaceAllUsesWith(Inst: Ext, New: ExtOpnd);
5084 // Step #3.
5085 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
5086 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
5087 ++OpIdx) {
5088 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
5089 if (ExtOpnd->getOperand(i: OpIdx)->getType() == Ext->getType() ||
5090 !shouldExtOperand(Inst: ExtOpnd, OpIdx)) {
5091 LLVM_DEBUG(dbgs() << "No need to propagate\n");
5092 continue;
5093 }
5094 // Check if we can statically extend the operand.
5095 Value *Opnd = ExtOpnd->getOperand(i: OpIdx);
5096 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Val: Opnd)) {
5097 LLVM_DEBUG(dbgs() << "Statically extend\n");
5098 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
5099 APInt CstVal = IsSExt ? Cst->getValue().sext(width: BitWidth)
5100 : Cst->getValue().zext(width: BitWidth);
5101 TPT.setOperand(Inst: ExtOpnd, Idx: OpIdx, NewVal: ConstantInt::get(Ty: Ext->getType(), V: CstVal));
5102 continue;
5103 }
5104 // UndefValue are typed, so we have to statically sign extend them.
5105 if (isa<UndefValue>(Val: Opnd)) {
5106 LLVM_DEBUG(dbgs() << "Statically extend\n");
5107 TPT.setOperand(Inst: ExtOpnd, Idx: OpIdx, NewVal: UndefValue::get(T: Ext->getType()));
5108 continue;
5109 }
5110
5111 // Otherwise we have to explicitly sign extend the operand.
5112 Value *ValForExtOpnd = IsSExt
5113 ? TPT.createSExt(Inst: ExtOpnd, Opnd, Ty: Ext->getType())
5114 : TPT.createZExt(Inst: ExtOpnd, Opnd, Ty: Ext->getType());
5115 TPT.setOperand(Inst: ExtOpnd, Idx: OpIdx, NewVal: ValForExtOpnd);
5116 Instruction *InstForExtOpnd = dyn_cast<Instruction>(Val: ValForExtOpnd);
5117 if (!InstForExtOpnd)
5118 continue;
5119
5120 if (Exts)
5121 Exts->push_back(Elt: InstForExtOpnd);
5122
5123 CreatedInstsCost += !TLI.isExtFree(I: InstForExtOpnd);
5124 }
5125 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
5126 TPT.eraseInstruction(Inst: Ext);
5127 return ExtOpnd;
5128}
5129
5130/// Check whether or not promoting an instruction to a wider type is profitable.
5131/// \p NewCost gives the cost of extension instructions created by the
5132/// promotion.
5133/// \p OldCost gives the cost of extension instructions before the promotion
5134/// plus the number of instructions that have been
5135/// matched in the addressing mode the promotion.
5136/// \p PromotedOperand is the value that has been promoted.
5137/// \return True if the promotion is profitable, false otherwise.
5138bool AddressingModeMatcher::isPromotionProfitable(
5139 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
5140 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
5141 << '\n');
5142 // The cost of the new extensions is greater than the cost of the
5143 // old extension plus what we folded.
5144 // This is not profitable.
5145 if (NewCost > OldCost)
5146 return false;
5147 if (NewCost < OldCost)
5148 return true;
5149 // The promotion is neutral but it may help folding the sign extension in
5150 // loads for instance.
5151 // Check that we did not create an illegal instruction.
5152 return isPromotedInstructionLegal(TLI, DL, Val: PromotedOperand);
5153}
5154
5155/// Given an instruction or constant expr, see if we can fold the operation
5156/// into the addressing mode. If so, update the addressing mode and return
5157/// true, otherwise return false without modifying AddrMode.
5158/// If \p MovedAway is not NULL, it contains the information of whether or
5159/// not AddrInst has to be folded into the addressing mode on success.
5160/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
5161/// because it has been moved away.
5162/// Thus AddrInst must not be added in the matched instructions.
5163/// This state can happen when AddrInst is a sext, since it may be moved away.
5164/// Therefore, AddrInst may not be valid when MovedAway is true and it must
5165/// not be referenced anymore.
5166bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
5167 unsigned Depth,
5168 bool *MovedAway) {
5169 // Avoid exponential behavior on extremely deep expression trees.
5170 if (Depth >= 5)
5171 return false;
5172
5173 // By default, all matched instructions stay in place.
5174 if (MovedAway)
5175 *MovedAway = false;
5176
5177 switch (Opcode) {
5178 case Instruction::PtrToInt:
5179 // PtrToInt is always a noop, as we know that the int type is pointer sized.
5180 return matchAddr(Addr: AddrInst->getOperand(i: 0), Depth);
5181 case Instruction::IntToPtr: {
5182 auto AS = AddrInst->getType()->getPointerAddressSpace();
5183 auto PtrTy = MVT::getIntegerVT(BitWidth: DL.getPointerSizeInBits(AS));
5184 // This inttoptr is a no-op if the integer type is pointer sized.
5185 if (TLI.getValueType(DL, Ty: AddrInst->getOperand(i: 0)->getType()) == PtrTy)
5186 return matchAddr(Addr: AddrInst->getOperand(i: 0), Depth);
5187 return false;
5188 }
5189 case Instruction::BitCast:
5190 // BitCast is always a noop, and we can handle it as long as it is
5191 // int->int or pointer->pointer (we don't want int<->fp or something).
5192 if (AddrInst->getOperand(i: 0)->getType()->isIntOrPtrTy() &&
5193 // Don't touch identity bitcasts. These were probably put here by LSR,
5194 // and we don't want to mess around with them. Assume it knows what it
5195 // is doing.
5196 AddrInst->getOperand(i: 0)->getType() != AddrInst->getType())
5197 return matchAddr(Addr: AddrInst->getOperand(i: 0), Depth);
5198 return false;
5199 case Instruction::AddrSpaceCast: {
5200 unsigned SrcAS =
5201 AddrInst->getOperand(i: 0)->getType()->getPointerAddressSpace();
5202 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
5203 if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS))
5204 return matchAddr(Addr: AddrInst->getOperand(i: 0), Depth);
5205 return false;
5206 }
5207 case Instruction::Add: {
5208 // Check to see if we can merge in one operand, then the other. If so, we
5209 // win.
5210 ExtAddrMode BackupAddrMode = AddrMode;
5211 unsigned OldSize = AddrModeInsts.size();
5212 // Start a transaction at this point.
5213 // The LHS may match but not the RHS.
5214 // Therefore, we need a higher level restoration point to undo partially
5215 // matched operation.
5216 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5217 TPT.getRestorationPoint();
5218
5219 // Try to match an integer constant second to increase its chance of ending
5220 // up in `BaseOffs`, resp. decrease its chance of ending up in `BaseReg`.
5221 int First = 0, Second = 1;
5222 if (isa<ConstantInt>(Val: AddrInst->getOperand(i: First))
5223 && !isa<ConstantInt>(Val: AddrInst->getOperand(i: Second)))
5224 std::swap(a&: First, b&: Second);
5225 AddrMode.InBounds = false;
5226 if (matchAddr(Addr: AddrInst->getOperand(i: First), Depth: Depth + 1) &&
5227 matchAddr(Addr: AddrInst->getOperand(i: Second), Depth: Depth + 1))
5228 return true;
5229
5230 // Restore the old addr mode info.
5231 AddrMode = BackupAddrMode;
5232 AddrModeInsts.resize(N: OldSize);
5233 TPT.rollback(Point: LastKnownGood);
5234
5235 // Otherwise this was over-aggressive. Try merging operands in the opposite
5236 // order.
5237 if (matchAddr(Addr: AddrInst->getOperand(i: Second), Depth: Depth + 1) &&
5238 matchAddr(Addr: AddrInst->getOperand(i: First), Depth: Depth + 1))
5239 return true;
5240
5241 // Otherwise we definitely can't merge the ADD in.
5242 AddrMode = BackupAddrMode;
5243 AddrModeInsts.resize(N: OldSize);
5244 TPT.rollback(Point: LastKnownGood);
5245 break;
5246 }
5247 // case Instruction::Or:
5248 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
5249 // break;
5250 case Instruction::Mul:
5251 case Instruction::Shl: {
5252 // Can only handle X*C and X << C.
5253 AddrMode.InBounds = false;
5254 ConstantInt *RHS = dyn_cast<ConstantInt>(Val: AddrInst->getOperand(i: 1));
5255 if (!RHS || RHS->getBitWidth() > 64)
5256 return false;
5257 int64_t Scale = Opcode == Instruction::Shl
5258 ? 1LL << RHS->getLimitedValue(Limit: RHS->getBitWidth() - 1)
5259 : RHS->getSExtValue();
5260
5261 return matchScaledValue(ScaleReg: AddrInst->getOperand(i: 0), Scale, Depth);
5262 }
5263 case Instruction::GetElementPtr: {
5264 // Scan the GEP. We check it if it contains constant offsets and at most
5265 // one variable offset.
5266 int VariableOperand = -1;
5267 unsigned VariableScale = 0;
5268
5269 int64_t ConstantOffset = 0;
5270 gep_type_iterator GTI = gep_type_begin(GEP: AddrInst);
5271 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
5272 if (StructType *STy = GTI.getStructTypeOrNull()) {
5273 const StructLayout *SL = DL.getStructLayout(Ty: STy);
5274 unsigned Idx =
5275 cast<ConstantInt>(Val: AddrInst->getOperand(i))->getZExtValue();
5276 ConstantOffset += SL->getElementOffset(Idx);
5277 } else {
5278 TypeSize TS = GTI.getSequentialElementStride(DL);
5279 if (TS.isNonZero()) {
5280 // The optimisations below currently only work for fixed offsets.
5281 if (TS.isScalable())
5282 return false;
5283 int64_t TypeSize = TS.getFixedValue();
5284 if (ConstantInt *CI =
5285 dyn_cast<ConstantInt>(Val: AddrInst->getOperand(i))) {
5286 const APInt &CVal = CI->getValue();
5287 if (CVal.getSignificantBits() <= 64) {
5288 ConstantOffset += CVal.getSExtValue() * TypeSize;
5289 continue;
5290 }
5291 }
5292 // We only allow one variable index at the moment.
5293 if (VariableOperand != -1)
5294 return false;
5295
5296 // Remember the variable index.
5297 VariableOperand = i;
5298 VariableScale = TypeSize;
5299 }
5300 }
5301 }
5302
5303 // A common case is for the GEP to only do a constant offset. In this case,
5304 // just add it to the disp field and check validity.
5305 if (VariableOperand == -1) {
5306 AddrMode.BaseOffs += ConstantOffset;
5307 if (matchAddr(Addr: AddrInst->getOperand(i: 0), Depth: Depth + 1)) {
5308 if (!cast<GEPOperator>(Val: AddrInst)->isInBounds())
5309 AddrMode.InBounds = false;
5310 return true;
5311 }
5312 AddrMode.BaseOffs -= ConstantOffset;
5313
5314 if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(Val: AddrInst) &&
5315 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
5316 ConstantOffset > 0) {
5317 // Record GEPs with non-zero offsets as candidates for splitting in
5318 // the event that the offset cannot fit into the r+i addressing mode.
5319 // Simple and common case that only one GEP is used in calculating the
5320 // address for the memory access.
5321 Value *Base = AddrInst->getOperand(i: 0);
5322 auto *BaseI = dyn_cast<Instruction>(Val: Base);
5323 auto *GEP = cast<GetElementPtrInst>(Val: AddrInst);
5324 if (isa<Argument>(Val: Base) || isa<GlobalValue>(Val: Base) ||
5325 (BaseI && !isa<CastInst>(Val: BaseI) &&
5326 !isa<GetElementPtrInst>(Val: BaseI))) {
5327 // Make sure the parent block allows inserting non-PHI instructions
5328 // before the terminator.
5329 BasicBlock *Parent = BaseI ? BaseI->getParent()
5330 : &GEP->getFunction()->getEntryBlock();
5331 if (!Parent->getTerminator()->isEHPad())
5332 LargeOffsetGEP = std::make_pair(x&: GEP, y&: ConstantOffset);
5333 }
5334 }
5335
5336 return false;
5337 }
5338
5339 // Save the valid addressing mode in case we can't match.
5340 ExtAddrMode BackupAddrMode = AddrMode;
5341 unsigned OldSize = AddrModeInsts.size();
5342
5343 // See if the scale and offset amount is valid for this target.
5344 AddrMode.BaseOffs += ConstantOffset;
5345 if (!cast<GEPOperator>(Val: AddrInst)->isInBounds())
5346 AddrMode.InBounds = false;
5347
5348 // Match the base operand of the GEP.
5349 if (!matchAddr(Addr: AddrInst->getOperand(i: 0), Depth: Depth + 1)) {
5350 // If it couldn't be matched, just stuff the value in a register.
5351 if (AddrMode.HasBaseReg) {
5352 AddrMode = BackupAddrMode;
5353 AddrModeInsts.resize(N: OldSize);
5354 return false;
5355 }
5356 AddrMode.HasBaseReg = true;
5357 AddrMode.BaseReg = AddrInst->getOperand(i: 0);
5358 }
5359
5360 // Match the remaining variable portion of the GEP.
5361 if (!matchScaledValue(ScaleReg: AddrInst->getOperand(i: VariableOperand), Scale: VariableScale,
5362 Depth)) {
5363 // If it couldn't be matched, try stuffing the base into a register
5364 // instead of matching it, and retrying the match of the scale.
5365 AddrMode = BackupAddrMode;
5366 AddrModeInsts.resize(N: OldSize);
5367 if (AddrMode.HasBaseReg)
5368 return false;
5369 AddrMode.HasBaseReg = true;
5370 AddrMode.BaseReg = AddrInst->getOperand(i: 0);
5371 AddrMode.BaseOffs += ConstantOffset;
5372 if (!matchScaledValue(ScaleReg: AddrInst->getOperand(i: VariableOperand),
5373 Scale: VariableScale, Depth)) {
5374 // If even that didn't work, bail.
5375 AddrMode = BackupAddrMode;
5376 AddrModeInsts.resize(N: OldSize);
5377 return false;
5378 }
5379 }
5380
5381 return true;
5382 }
5383 case Instruction::SExt:
5384 case Instruction::ZExt: {
5385 Instruction *Ext = dyn_cast<Instruction>(Val: AddrInst);
5386 if (!Ext)
5387 return false;
5388
5389 // Try to move this ext out of the way of the addressing mode.
5390 // Ask for a method for doing so.
5391 TypePromotionHelper::Action TPH =
5392 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
5393 if (!TPH)
5394 return false;
5395
5396 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5397 TPT.getRestorationPoint();
5398 unsigned CreatedInstsCost = 0;
5399 unsigned ExtCost = !TLI.isExtFree(I: Ext);
5400 Value *PromotedOperand =
5401 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
5402 // SExt has been moved away.
5403 // Thus either it will be rematched later in the recursive calls or it is
5404 // gone. Anyway, we must not fold it into the addressing mode at this point.
5405 // E.g.,
5406 // op = add opnd, 1
5407 // idx = ext op
5408 // addr = gep base, idx
5409 // is now:
5410 // promotedOpnd = ext opnd <- no match here
5411 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
5412 // addr = gep base, op <- match
5413 if (MovedAway)
5414 *MovedAway = true;
5415
5416 assert(PromotedOperand &&
5417 "TypePromotionHelper should have filtered out those cases");
5418
5419 ExtAddrMode BackupAddrMode = AddrMode;
5420 unsigned OldSize = AddrModeInsts.size();
5421
5422 if (!matchAddr(Addr: PromotedOperand, Depth) ||
5423 // The total of the new cost is equal to the cost of the created
5424 // instructions.
5425 // The total of the old cost is equal to the cost of the extension plus
5426 // what we have saved in the addressing mode.
5427 !isPromotionProfitable(NewCost: CreatedInstsCost,
5428 OldCost: ExtCost + (AddrModeInsts.size() - OldSize),
5429 PromotedOperand)) {
5430 AddrMode = BackupAddrMode;
5431 AddrModeInsts.resize(N: OldSize);
5432 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
5433 TPT.rollback(Point: LastKnownGood);
5434 return false;
5435 }
5436
5437 // SExt has been deleted. Make sure it is not referenced by the AddrMode.
5438 AddrMode.replaceWith(From: Ext, To: PromotedOperand);
5439 return true;
5440 }
5441 case Instruction::Call:
5442 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: AddrInst)) {
5443 if (II->getIntrinsicID() == Intrinsic::threadlocal_address) {
5444 GlobalValue &GV = cast<GlobalValue>(Val&: *II->getArgOperand(i: 0));
5445 if (TLI.addressingModeSupportsTLS(GV))
5446 return matchAddr(Addr: AddrInst->getOperand(i: 0), Depth);
5447 }
5448 }
5449 break;
5450 }
5451 return false;
5452}
5453
5454/// If we can, try to add the value of 'Addr' into the current addressing mode.
5455/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
5456/// unmodified. This assumes that Addr is either a pointer type or intptr_t
5457/// for the target.
5458///
5459bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
5460 // Start a transaction at this point that we will rollback if the matching
5461 // fails.
5462 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5463 TPT.getRestorationPoint();
5464 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val: Addr)) {
5465 if (CI->getValue().isSignedIntN(N: 64)) {
5466 // Check if the addition would result in a signed overflow.
5467 int64_t Result;
5468 bool Overflow =
5469 AddOverflow(X: AddrMode.BaseOffs, Y: CI->getSExtValue(), Result);
5470 if (!Overflow) {
5471 // Fold in immediates if legal for the target.
5472 AddrMode.BaseOffs = Result;
5473 if (TLI.isLegalAddressingMode(DL, AM: AddrMode, Ty: AccessTy, AddrSpace))
5474 return true;
5475 AddrMode.BaseOffs -= CI->getSExtValue();
5476 }
5477 }
5478 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Val: Addr)) {
5479 // If this is a global variable, try to fold it into the addressing mode.
5480 if (!AddrMode.BaseGV) {
5481 AddrMode.BaseGV = GV;
5482 if (TLI.isLegalAddressingMode(DL, AM: AddrMode, Ty: AccessTy, AddrSpace))
5483 return true;
5484 AddrMode.BaseGV = nullptr;
5485 }
5486 } else if (Instruction *I = dyn_cast<Instruction>(Val: Addr)) {
5487 ExtAddrMode BackupAddrMode = AddrMode;
5488 unsigned OldSize = AddrModeInsts.size();
5489
5490 // Check to see if it is possible to fold this operation.
5491 bool MovedAway = false;
5492 if (matchOperationAddr(AddrInst: I, Opcode: I->getOpcode(), Depth, MovedAway: &MovedAway)) {
5493 // This instruction may have been moved away. If so, there is nothing
5494 // to check here.
5495 if (MovedAway)
5496 return true;
5497 // Okay, it's possible to fold this. Check to see if it is actually
5498 // *profitable* to do so. We use a simple cost model to avoid increasing
5499 // register pressure too much.
5500 if (I->hasOneUse() ||
5501 isProfitableToFoldIntoAddressingMode(I, AMBefore&: BackupAddrMode, AMAfter&: AddrMode)) {
5502 AddrModeInsts.push_back(Elt: I);
5503 return true;
5504 }
5505
5506 // It isn't profitable to do this, roll back.
5507 AddrMode = BackupAddrMode;
5508 AddrModeInsts.resize(N: OldSize);
5509 TPT.rollback(Point: LastKnownGood);
5510 }
5511 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Val: Addr)) {
5512 if (matchOperationAddr(AddrInst: CE, Opcode: CE->getOpcode(), Depth))
5513 return true;
5514 TPT.rollback(Point: LastKnownGood);
5515 } else if (isa<ConstantPointerNull>(Val: Addr)) {
5516 // Null pointer gets folded without affecting the addressing mode.
5517 return true;
5518 }
5519
5520 // Worse case, the target should support [reg] addressing modes. :)
5521 if (!AddrMode.HasBaseReg) {
5522 AddrMode.HasBaseReg = true;
5523 AddrMode.BaseReg = Addr;
5524 // Still check for legality in case the target supports [imm] but not [i+r].
5525 if (TLI.isLegalAddressingMode(DL, AM: AddrMode, Ty: AccessTy, AddrSpace))
5526 return true;
5527 AddrMode.HasBaseReg = false;
5528 AddrMode.BaseReg = nullptr;
5529 }
5530
5531 // If the base register is already taken, see if we can do [r+r].
5532 if (AddrMode.Scale == 0) {
5533 AddrMode.Scale = 1;
5534 AddrMode.ScaledReg = Addr;
5535 if (TLI.isLegalAddressingMode(DL, AM: AddrMode, Ty: AccessTy, AddrSpace))
5536 return true;
5537 AddrMode.Scale = 0;
5538 AddrMode.ScaledReg = nullptr;
5539 }
5540 // Couldn't match.
5541 TPT.rollback(Point: LastKnownGood);
5542 return false;
5543}
5544
5545/// Check to see if all uses of OpVal by the specified inline asm call are due
5546/// to memory operands. If so, return true, otherwise return false.
5547static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
5548 const TargetLowering &TLI,
5549 const TargetRegisterInfo &TRI) {
5550 const Function *F = CI->getFunction();
5551 TargetLowering::AsmOperandInfoVector TargetConstraints =
5552 TLI.ParseConstraints(DL: F->getDataLayout(), TRI: &TRI, Call: *CI);
5553
5554 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
5555 // Compute the constraint code and ConstraintType to use.
5556 TLI.ComputeConstraintToUse(OpInfo, Op: SDValue());
5557
5558 // If this asm operand is our Value*, and if it isn't an indirect memory
5559 // operand, we can't fold it! TODO: Also handle C_Address?
5560 if (OpInfo.CallOperandVal == OpVal &&
5561 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
5562 !OpInfo.isIndirect))
5563 return false;
5564 }
5565
5566 return true;
5567}
5568
5569/// Recursively walk all the uses of I until we find a memory use.
5570/// If we find an obviously non-foldable instruction, return true.
5571/// Add accessed addresses and types to MemoryUses.
5572static bool FindAllMemoryUses(
5573 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5574 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
5575 const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
5576 BlockFrequencyInfo *BFI, unsigned &SeenInsts) {
5577 // If we already considered this instruction, we're done.
5578 if (!ConsideredInsts.insert(Ptr: I).second)
5579 return false;
5580
5581 // If this is an obviously unfoldable instruction, bail out.
5582 if (!MightBeFoldableInst(I))
5583 return true;
5584
5585 // Loop over all the uses, recursively processing them.
5586 for (Use &U : I->uses()) {
5587 // Conservatively return true if we're seeing a large number or a deep chain
5588 // of users. This avoids excessive compilation times in pathological cases.
5589 if (SeenInsts++ >= MaxAddressUsersToScan)
5590 return true;
5591
5592 Instruction *UserI = cast<Instruction>(Val: U.getUser());
5593 if (LoadInst *LI = dyn_cast<LoadInst>(Val: UserI)) {
5594 MemoryUses.push_back(Elt: {&U, LI->getType()});
5595 continue;
5596 }
5597
5598 if (StoreInst *SI = dyn_cast<StoreInst>(Val: UserI)) {
5599 if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
5600 return true; // Storing addr, not into addr.
5601 MemoryUses.push_back(Elt: {&U, SI->getValueOperand()->getType()});
5602 continue;
5603 }
5604
5605 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Val: UserI)) {
5606 if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
5607 return true; // Storing addr, not into addr.
5608 MemoryUses.push_back(Elt: {&U, RMW->getValOperand()->getType()});
5609 continue;
5610 }
5611
5612 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Val: UserI)) {
5613 if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
5614 return true; // Storing addr, not into addr.
5615 MemoryUses.push_back(Elt: {&U, CmpX->getCompareOperand()->getType()});
5616 continue;
5617 }
5618
5619 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: UserI)) {
5620 SmallVector<Value *, 2> PtrOps;
5621 Type *AccessTy;
5622 if (!TLI.getAddrModeArguments(II, PtrOps, AccessTy))
5623 return true;
5624
5625 if (!find(Range&: PtrOps, Val: U.get()))
5626 return true;
5627
5628 MemoryUses.push_back(Elt: {&U, AccessTy});
5629 continue;
5630 }
5631
5632 if (CallInst *CI = dyn_cast<CallInst>(Val: UserI)) {
5633 if (CI->hasFnAttr(Kind: Attribute::Cold)) {
5634 // If this is a cold call, we can sink the addressing calculation into
5635 // the cold path. See optimizeCallInst
5636 if (!llvm::shouldOptimizeForSize(BB: CI->getParent(), PSI, BFI))
5637 continue;
5638 }
5639
5640 InlineAsm *IA = dyn_cast<InlineAsm>(Val: CI->getCalledOperand());
5641 if (!IA)
5642 return true;
5643
5644 // If this is a memory operand, we're cool, otherwise bail out.
5645 if (!IsOperandAMemoryOperand(CI, IA, OpVal: I, TLI, TRI))
5646 return true;
5647 continue;
5648 }
5649
5650 if (FindAllMemoryUses(I: UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5651 PSI, BFI, SeenInsts))
5652 return true;
5653 }
5654
5655 return false;
5656}
5657
5658static bool FindAllMemoryUses(
5659 Instruction *I, SmallVectorImpl<std::pair<Use *, Type *>> &MemoryUses,
5660 const TargetLowering &TLI, const TargetRegisterInfo &TRI, bool OptSize,
5661 ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
5662 unsigned SeenInsts = 0;
5663 SmallPtrSet<Instruction *, 16> ConsideredInsts;
5664 return FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
5665 PSI, BFI, SeenInsts);
5666}
5667
5668
5669/// Return true if Val is already known to be live at the use site that we're
5670/// folding it into. If so, there is no cost to include it in the addressing
5671/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
5672/// instruction already.
5673bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
5674 Value *KnownLive1,
5675 Value *KnownLive2) {
5676 // If Val is either of the known-live values, we know it is live!
5677 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
5678 return true;
5679
5680 // All values other than instructions and arguments (e.g. constants) are live.
5681 if (!isa<Instruction>(Val) && !isa<Argument>(Val))
5682 return true;
5683
5684 // If Val is a constant sized alloca in the entry block, it is live, this is
5685 // true because it is just a reference to the stack/frame pointer, which is
5686 // live for the whole function.
5687 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
5688 if (AI->isStaticAlloca())
5689 return true;
5690
5691 // Check to see if this value is already used in the memory instruction's
5692 // block. If so, it's already live into the block at the very least, so we
5693 // can reasonably fold it.
5694 return Val->isUsedInBasicBlock(BB: MemoryInst->getParent());
5695}
5696
5697/// It is possible for the addressing mode of the machine to fold the specified
5698/// instruction into a load or store that ultimately uses it.
5699/// However, the specified instruction has multiple uses.
5700/// Given this, it may actually increase register pressure to fold it
5701/// into the load. For example, consider this code:
5702///
5703/// X = ...
5704/// Y = X+1
5705/// use(Y) -> nonload/store
5706/// Z = Y+1
5707/// load Z
5708///
5709/// In this case, Y has multiple uses, and can be folded into the load of Z
5710/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
5711/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
5712/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
5713/// number of computations either.
5714///
5715/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
5716/// X was live across 'load Z' for other reasons, we actually *would* want to
5717/// fold the addressing mode in the Z case. This would make Y die earlier.
5718bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
5719 Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
5720 if (IgnoreProfitability)
5721 return true;
5722
5723 // AMBefore is the addressing mode before this instruction was folded into it,
5724 // and AMAfter is the addressing mode after the instruction was folded. Get
5725 // the set of registers referenced by AMAfter and subtract out those
5726 // referenced by AMBefore: this is the set of values which folding in this
5727 // address extends the lifetime of.
5728 //
5729 // Note that there are only two potential values being referenced here,
5730 // BaseReg and ScaleReg (global addresses are always available, as are any
5731 // folded immediates).
5732 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
5733
5734 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
5735 // lifetime wasn't extended by adding this instruction.
5736 if (valueAlreadyLiveAtInst(Val: BaseReg, KnownLive1: AMBefore.BaseReg, KnownLive2: AMBefore.ScaledReg))
5737 BaseReg = nullptr;
5738 if (valueAlreadyLiveAtInst(Val: ScaledReg, KnownLive1: AMBefore.BaseReg, KnownLive2: AMBefore.ScaledReg))
5739 ScaledReg = nullptr;
5740
5741 // If folding this instruction (and it's subexprs) didn't extend any live
5742 // ranges, we're ok with it.
5743 if (!BaseReg && !ScaledReg)
5744 return true;
5745
5746 // If all uses of this instruction can have the address mode sunk into them,
5747 // we can remove the addressing mode and effectively trade one live register
5748 // for another (at worst.) In this context, folding an addressing mode into
5749 // the use is just a particularly nice way of sinking it.
5750 SmallVector<std::pair<Use *, Type *>, 16> MemoryUses;
5751 if (FindAllMemoryUses(I, MemoryUses, TLI, TRI, OptSize, PSI, BFI))
5752 return false; // Has a non-memory, non-foldable use!
5753
5754 // Now that we know that all uses of this instruction are part of a chain of
5755 // computation involving only operations that could theoretically be folded
5756 // into a memory use, loop over each of these memory operation uses and see
5757 // if they could *actually* fold the instruction. The assumption is that
5758 // addressing modes are cheap and that duplicating the computation involved
5759 // many times is worthwhile, even on a fastpath. For sinking candidates
5760 // (i.e. cold call sites), this serves as a way to prevent excessive code
5761 // growth since most architectures have some reasonable small and fast way to
5762 // compute an effective address. (i.e LEA on x86)
5763 SmallVector<Instruction *, 32> MatchedAddrModeInsts;
5764 for (const std::pair<Use *, Type *> &Pair : MemoryUses) {
5765 Value *Address = Pair.first->get();
5766 Instruction *UserI = cast<Instruction>(Val: Pair.first->getUser());
5767 Type *AddressAccessTy = Pair.second;
5768 unsigned AS = Address->getType()->getPointerAddressSpace();
5769
5770 // Do a match against the root of this address, ignoring profitability. This
5771 // will tell us if the addressing mode for the memory operation will
5772 // *actually* cover the shared instruction.
5773 ExtAddrMode Result;
5774 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5775 0);
5776 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5777 TPT.getRestorationPoint();
5778 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
5779 AddressAccessTy, AS, UserI, Result,
5780 InsertedInsts, PromotedInsts, TPT,
5781 LargeOffsetGEP, OptSize, PSI, BFI);
5782 Matcher.IgnoreProfitability = true;
5783 bool Success = Matcher.matchAddr(Addr: Address, Depth: 0);
5784 (void)Success;
5785 assert(Success && "Couldn't select *anything*?");
5786
5787 // The match was to check the profitability, the changes made are not
5788 // part of the original matcher. Therefore, they should be dropped
5789 // otherwise the original matcher will not present the right state.
5790 TPT.rollback(Point: LastKnownGood);
5791
5792 // If the match didn't cover I, then it won't be shared by it.
5793 if (!is_contained(Range&: MatchedAddrModeInsts, Element: I))
5794 return false;
5795
5796 MatchedAddrModeInsts.clear();
5797 }
5798
5799 return true;
5800}
5801
5802/// Return true if the specified values are defined in a
5803/// different basic block than BB.
5804static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
5805 if (Instruction *I = dyn_cast<Instruction>(Val: V))
5806 return I->getParent() != BB;
5807 return false;
5808}
5809
5810// Find an insert position of Addr for MemoryInst. We can't guarantee MemoryInst
5811// is the first instruction that will use Addr. So we need to find the first
5812// user of Addr in current BB.
5813static BasicBlock::iterator findInsertPos(Value *Addr, Instruction *MemoryInst,
5814 Value *SunkAddr) {
5815 if (Addr->hasOneUse())
5816 return MemoryInst->getIterator();
5817
5818 // We already have a SunkAddr in current BB, but we may need to insert cast
5819 // instruction after it.
5820 if (SunkAddr) {
5821 if (Instruction *AddrInst = dyn_cast<Instruction>(Val: SunkAddr))
5822 return std::next(x: AddrInst->getIterator());
5823 }
5824
5825 // Find the first user of Addr in current BB.
5826 Instruction *Earliest = MemoryInst;
5827 for (User *U : Addr->users()) {
5828 Instruction *UserInst = dyn_cast<Instruction>(Val: U);
5829 if (UserInst && UserInst->getParent() == MemoryInst->getParent()) {
5830 if (isa<PHINode>(Val: UserInst) || UserInst->isDebugOrPseudoInst())
5831 continue;
5832 if (UserInst->comesBefore(Other: Earliest))
5833 Earliest = UserInst;
5834 }
5835 }
5836 return Earliest->getIterator();
5837}
5838
5839/// Sink addressing mode computation immediate before MemoryInst if doing so
5840/// can be done without increasing register pressure. The need for the
5841/// register pressure constraint means this can end up being an all or nothing
5842/// decision for all uses of the same addressing computation.
5843///
5844/// Load and Store Instructions often have addressing modes that can do
5845/// significant amounts of computation. As such, instruction selection will try
5846/// to get the load or store to do as much computation as possible for the
5847/// program. The problem is that isel can only see within a single block. As
5848/// such, we sink as much legal addressing mode work into the block as possible.
5849///
5850/// This method is used to optimize both load/store and inline asms with memory
5851/// operands. It's also used to sink addressing computations feeding into cold
5852/// call sites into their (cold) basic block.
5853///
5854/// The motivation for handling sinking into cold blocks is that doing so can
5855/// both enable other address mode sinking (by satisfying the register pressure
5856/// constraint above), and reduce register pressure globally (by removing the
5857/// addressing mode computation from the fast path entirely.).
5858bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
5859 Type *AccessTy, unsigned AddrSpace) {
5860 Value *Repl = Addr;
5861
5862 // Try to collapse single-value PHI nodes. This is necessary to undo
5863 // unprofitable PRE transformations.
5864 SmallVector<Value *, 8> worklist;
5865 SmallPtrSet<Value *, 16> Visited;
5866 worklist.push_back(Elt: Addr);
5867
5868 // Use a worklist to iteratively look through PHI and select nodes, and
5869 // ensure that the addressing mode obtained from the non-PHI/select roots of
5870 // the graph are compatible.
5871 bool PhiOrSelectSeen = false;
5872 SmallVector<Instruction *, 16> AddrModeInsts;
5873 AddressingModeCombiner AddrModes(*DL, Addr);
5874 TypePromotionTransaction TPT(RemovedInsts);
5875 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
5876 TPT.getRestorationPoint();
5877 while (!worklist.empty()) {
5878 Value *V = worklist.pop_back_val();
5879
5880 // We allow traversing cyclic Phi nodes.
5881 // In case of success after this loop we ensure that traversing through
5882 // Phi nodes ends up with all cases to compute address of the form
5883 // BaseGV + Base + Scale * Index + Offset
5884 // where Scale and Offset are constans and BaseGV, Base and Index
5885 // are exactly the same Values in all cases.
5886 // It means that BaseGV, Scale and Offset dominate our memory instruction
5887 // and have the same value as they had in address computation represented
5888 // as Phi. So we can safely sink address computation to memory instruction.
5889 if (!Visited.insert(Ptr: V).second)
5890 continue;
5891
5892 // For a PHI node, push all of its incoming values.
5893 if (PHINode *P = dyn_cast<PHINode>(Val: V)) {
5894 append_range(C&: worklist, R: P->incoming_values());
5895 PhiOrSelectSeen = true;
5896 continue;
5897 }
5898 // Similar for select.
5899 if (SelectInst *SI = dyn_cast<SelectInst>(Val: V)) {
5900 worklist.push_back(Elt: SI->getFalseValue());
5901 worklist.push_back(Elt: SI->getTrueValue());
5902 PhiOrSelectSeen = true;
5903 continue;
5904 }
5905
5906 // For non-PHIs, determine the addressing mode being computed. Note that
5907 // the result may differ depending on what other uses our candidate
5908 // addressing instructions might have.
5909 AddrModeInsts.clear();
5910 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
5911 0);
5912 // Defer the query (and possible computation of) the dom tree to point of
5913 // actual use. It's expected that most address matches don't actually need
5914 // the domtree.
5915 auto getDTFn = [this]() -> const DominatorTree & { return getDT(); };
5916 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
5917 V, AccessTy, AS: AddrSpace, MemoryInst, AddrModeInsts, TLI: *TLI, LI: *LI, getDTFn,
5918 TRI: *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
5919 BFI);
5920
5921 GetElementPtrInst *GEP = LargeOffsetGEP.first;
5922 if (GEP && !NewGEPBases.count(V: GEP)) {
5923 // If splitting the underlying data structure can reduce the offset of a
5924 // GEP, collect the GEP. Skip the GEPs that are the new bases of
5925 // previously split data structures.
5926 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(Elt: LargeOffsetGEP);
5927 LargeOffsetGEPID.insert(KV: std::make_pair(x&: GEP, y: LargeOffsetGEPID.size()));
5928 }
5929
5930 NewAddrMode.OriginalValue = V;
5931 if (!AddrModes.addNewAddrMode(NewAddrMode))
5932 break;
5933 }
5934
5935 // Try to combine the AddrModes we've collected. If we couldn't collect any,
5936 // or we have multiple but either couldn't combine them or combining them
5937 // wouldn't do anything useful, bail out now.
5938 if (!AddrModes.combineAddrModes()) {
5939 TPT.rollback(Point: LastKnownGood);
5940 return false;
5941 }
5942 bool Modified = TPT.commit();
5943
5944 // Get the combined AddrMode (or the only AddrMode, if we only had one).
5945 ExtAddrMode AddrMode = AddrModes.getAddrMode();
5946
5947 // If all the instructions matched are already in this BB, don't do anything.
5948 // If we saw a Phi node then it is not local definitely, and if we saw a
5949 // select then we want to push the address calculation past it even if it's
5950 // already in this BB.
5951 if (!PhiOrSelectSeen && none_of(Range&: AddrModeInsts, P: [&](Value *V) {
5952 return IsNonLocalValue(V, BB: MemoryInst->getParent());
5953 })) {
5954 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
5955 << "\n");
5956 return Modified;
5957 }
5958
5959 // Now that we determined the addressing expression we want to use and know
5960 // that we have to sink it into this block. Check to see if we have already
5961 // done this for some other load/store instr in this block. If so, reuse
5962 // the computation. Before attempting reuse, check if the address is valid
5963 // as it may have been erased.
5964
5965 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
5966
5967 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
5968 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
5969
5970 // The current BB may be optimized multiple times, we can't guarantee the
5971 // reuse of Addr happens later, call findInsertPos to find an appropriate
5972 // insert position.
5973 auto InsertPos = findInsertPos(Addr, MemoryInst, SunkAddr);
5974
5975 // TODO: Adjust insert point considering (Base|Scaled)Reg if possible.
5976 if (!SunkAddr) {
5977 auto &DT = getDT();
5978 if ((AddrMode.BaseReg && !DT.dominates(Def: AddrMode.BaseReg, User: &*InsertPos)) ||
5979 (AddrMode.ScaledReg && !DT.dominates(Def: AddrMode.ScaledReg, User: &*InsertPos)))
5980 return Modified;
5981 }
5982
5983 IRBuilder<> Builder(MemoryInst->getParent(), InsertPos);
5984
5985 if (SunkAddr) {
5986 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
5987 << " for " << *MemoryInst << "\n");
5988 if (SunkAddr->getType() != Addr->getType()) {
5989 if (SunkAddr->getType()->getPointerAddressSpace() !=
5990 Addr->getType()->getPointerAddressSpace() &&
5991 !DL->isNonIntegralPointerType(Ty: Addr->getType())) {
5992 // There are two reasons the address spaces might not match: a no-op
5993 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
5994 // ptrtoint/inttoptr pair to ensure we match the original semantics.
5995 // TODO: allow bitcast between different address space pointers with the
5996 // same size.
5997 SunkAddr = Builder.CreatePtrToInt(V: SunkAddr, DestTy: IntPtrTy, Name: "sunkaddr");
5998 SunkAddr =
5999 Builder.CreateIntToPtr(V: SunkAddr, DestTy: Addr->getType(), Name: "sunkaddr");
6000 } else
6001 SunkAddr = Builder.CreatePointerCast(V: SunkAddr, DestTy: Addr->getType());
6002 }
6003 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
6004 SubtargetInfo->addrSinkUsingGEPs())) {
6005 // By default, we use the GEP-based method when AA is used later. This
6006 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
6007 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6008 << " for " << *MemoryInst << "\n");
6009 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
6010
6011 // First, find the pointer.
6012 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
6013 ResultPtr = AddrMode.BaseReg;
6014 AddrMode.BaseReg = nullptr;
6015 }
6016
6017 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
6018 // We can't add more than one pointer together, nor can we scale a
6019 // pointer (both of which seem meaningless).
6020 if (ResultPtr || AddrMode.Scale != 1)
6021 return Modified;
6022
6023 ResultPtr = AddrMode.ScaledReg;
6024 AddrMode.Scale = 0;
6025 }
6026
6027 // It is only safe to sign extend the BaseReg if we know that the math
6028 // required to create it did not overflow before we extend it. Since
6029 // the original IR value was tossed in favor of a constant back when
6030 // the AddrMode was created we need to bail out gracefully if widths
6031 // do not match instead of extending it.
6032 //
6033 // (See below for code to add the scale.)
6034 if (AddrMode.Scale) {
6035 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
6036 if (cast<IntegerType>(Val: IntPtrTy)->getBitWidth() >
6037 cast<IntegerType>(Val: ScaledRegTy)->getBitWidth())
6038 return Modified;
6039 }
6040
6041 GlobalValue *BaseGV = AddrMode.BaseGV;
6042 if (BaseGV != nullptr) {
6043 if (ResultPtr)
6044 return Modified;
6045
6046 if (BaseGV->isThreadLocal()) {
6047 ResultPtr = Builder.CreateThreadLocalAddress(Ptr: BaseGV);
6048 } else {
6049 ResultPtr = BaseGV;
6050 }
6051 }
6052
6053 // If the real base value actually came from an inttoptr, then the matcher
6054 // will look through it and provide only the integer value. In that case,
6055 // use it here.
6056 if (!DL->isNonIntegralPointerType(Ty: Addr->getType())) {
6057 if (!ResultPtr && AddrMode.BaseReg) {
6058 ResultPtr = Builder.CreateIntToPtr(V: AddrMode.BaseReg, DestTy: Addr->getType(),
6059 Name: "sunkaddr");
6060 AddrMode.BaseReg = nullptr;
6061 } else if (!ResultPtr && AddrMode.Scale == 1) {
6062 ResultPtr = Builder.CreateIntToPtr(V: AddrMode.ScaledReg, DestTy: Addr->getType(),
6063 Name: "sunkaddr");
6064 AddrMode.Scale = 0;
6065 }
6066 }
6067
6068 if (!ResultPtr && !AddrMode.BaseReg && !AddrMode.Scale &&
6069 !AddrMode.BaseOffs) {
6070 SunkAddr = Constant::getNullValue(Ty: Addr->getType());
6071 } else if (!ResultPtr) {
6072 return Modified;
6073 } else {
6074 Type *I8PtrTy =
6075 Builder.getPtrTy(AddrSpace: Addr->getType()->getPointerAddressSpace());
6076
6077 // Start with the base register. Do this first so that subsequent address
6078 // matching finds it last, which will prevent it from trying to match it
6079 // as the scaled value in case it happens to be a mul. That would be
6080 // problematic if we've sunk a different mul for the scale, because then
6081 // we'd end up sinking both muls.
6082 if (AddrMode.BaseReg) {
6083 Value *V = AddrMode.BaseReg;
6084 if (V->getType() != IntPtrTy)
6085 V = Builder.CreateIntCast(V, DestTy: IntPtrTy, /*isSigned=*/true, Name: "sunkaddr");
6086
6087 ResultIndex = V;
6088 }
6089
6090 // Add the scale value.
6091 if (AddrMode.Scale) {
6092 Value *V = AddrMode.ScaledReg;
6093 if (V->getType() == IntPtrTy) {
6094 // done.
6095 } else {
6096 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
6097 cast<IntegerType>(V->getType())->getBitWidth() &&
6098 "We can't transform if ScaledReg is too narrow");
6099 V = Builder.CreateTrunc(V, DestTy: IntPtrTy, Name: "sunkaddr");
6100 }
6101
6102 if (AddrMode.Scale != 1)
6103 V = Builder.CreateMul(
6104 LHS: V, RHS: ConstantInt::getSigned(Ty: IntPtrTy, V: AddrMode.Scale), Name: "sunkaddr");
6105 if (ResultIndex)
6106 ResultIndex = Builder.CreateAdd(LHS: ResultIndex, RHS: V, Name: "sunkaddr");
6107 else
6108 ResultIndex = V;
6109 }
6110
6111 // Add in the Base Offset if present.
6112 if (AddrMode.BaseOffs) {
6113 Value *V = ConstantInt::getSigned(Ty: IntPtrTy, V: AddrMode.BaseOffs);
6114 if (ResultIndex) {
6115 // We need to add this separately from the scale above to help with
6116 // SDAG consecutive load/store merging.
6117 if (ResultPtr->getType() != I8PtrTy)
6118 ResultPtr = Builder.CreatePointerCast(V: ResultPtr, DestTy: I8PtrTy);
6119 ResultPtr = Builder.CreatePtrAdd(Ptr: ResultPtr, Offset: ResultIndex, Name: "sunkaddr",
6120 NW: AddrMode.InBounds);
6121 }
6122
6123 ResultIndex = V;
6124 }
6125
6126 if (!ResultIndex) {
6127 auto PtrInst = dyn_cast<Instruction>(Val: ResultPtr);
6128 // We know that we have a pointer without any offsets. If this pointer
6129 // originates from a different basic block than the current one, we
6130 // must be able to recreate it in the current basic block.
6131 // We do not support the recreation of any instructions yet.
6132 if (PtrInst && PtrInst->getParent() != MemoryInst->getParent())
6133 return Modified;
6134 SunkAddr = ResultPtr;
6135 } else {
6136 if (ResultPtr->getType() != I8PtrTy)
6137 ResultPtr = Builder.CreatePointerCast(V: ResultPtr, DestTy: I8PtrTy);
6138 SunkAddr = Builder.CreatePtrAdd(Ptr: ResultPtr, Offset: ResultIndex, Name: "sunkaddr",
6139 NW: AddrMode.InBounds);
6140 }
6141
6142 if (SunkAddr->getType() != Addr->getType()) {
6143 if (SunkAddr->getType()->getPointerAddressSpace() !=
6144 Addr->getType()->getPointerAddressSpace() &&
6145 !DL->isNonIntegralPointerType(Ty: Addr->getType())) {
6146 // There are two reasons the address spaces might not match: a no-op
6147 // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
6148 // ptrtoint/inttoptr pair to ensure we match the original semantics.
6149 // TODO: allow bitcast between different address space pointers with
6150 // the same size.
6151 SunkAddr = Builder.CreatePtrToInt(V: SunkAddr, DestTy: IntPtrTy, Name: "sunkaddr");
6152 SunkAddr =
6153 Builder.CreateIntToPtr(V: SunkAddr, DestTy: Addr->getType(), Name: "sunkaddr");
6154 } else
6155 SunkAddr = Builder.CreatePointerCast(V: SunkAddr, DestTy: Addr->getType());
6156 }
6157 }
6158 } else {
6159 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
6160 // non-integral pointers, so in that case bail out now.
6161 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
6162 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
6163 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(Val: BaseTy);
6164 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(Val: ScaleTy);
6165 if (DL->isNonIntegralPointerType(Ty: Addr->getType()) ||
6166 (BasePtrTy && DL->isNonIntegralPointerType(PT: BasePtrTy)) ||
6167 (ScalePtrTy && DL->isNonIntegralPointerType(PT: ScalePtrTy)) ||
6168 (AddrMode.BaseGV &&
6169 DL->isNonIntegralPointerType(PT: AddrMode.BaseGV->getType())))
6170 return Modified;
6171
6172 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
6173 << " for " << *MemoryInst << "\n");
6174 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
6175 Value *Result = nullptr;
6176
6177 // Start with the base register. Do this first so that subsequent address
6178 // matching finds it last, which will prevent it from trying to match it
6179 // as the scaled value in case it happens to be a mul. That would be
6180 // problematic if we've sunk a different mul for the scale, because then
6181 // we'd end up sinking both muls.
6182 if (AddrMode.BaseReg) {
6183 Value *V = AddrMode.BaseReg;
6184 if (V->getType()->isPointerTy())
6185 V = Builder.CreatePtrToInt(V, DestTy: IntPtrTy, Name: "sunkaddr");
6186 if (V->getType() != IntPtrTy)
6187 V = Builder.CreateIntCast(V, DestTy: IntPtrTy, /*isSigned=*/true, Name: "sunkaddr");
6188 Result = V;
6189 }
6190
6191 // Add the scale value.
6192 if (AddrMode.Scale) {
6193 Value *V = AddrMode.ScaledReg;
6194 if (V->getType() == IntPtrTy) {
6195 // done.
6196 } else if (V->getType()->isPointerTy()) {
6197 V = Builder.CreatePtrToInt(V, DestTy: IntPtrTy, Name: "sunkaddr");
6198 } else if (cast<IntegerType>(Val: IntPtrTy)->getBitWidth() <
6199 cast<IntegerType>(Val: V->getType())->getBitWidth()) {
6200 V = Builder.CreateTrunc(V, DestTy: IntPtrTy, Name: "sunkaddr");
6201 } else {
6202 // It is only safe to sign extend the BaseReg if we know that the math
6203 // required to create it did not overflow before we extend it. Since
6204 // the original IR value was tossed in favor of a constant back when
6205 // the AddrMode was created we need to bail out gracefully if widths
6206 // do not match instead of extending it.
6207 Instruction *I = dyn_cast_or_null<Instruction>(Val: Result);
6208 if (I && (Result != AddrMode.BaseReg))
6209 I->eraseFromParent();
6210 return Modified;
6211 }
6212 if (AddrMode.Scale != 1)
6213 V = Builder.CreateMul(
6214 LHS: V, RHS: ConstantInt::getSigned(Ty: IntPtrTy, V: AddrMode.Scale), Name: "sunkaddr");
6215 if (Result)
6216 Result = Builder.CreateAdd(LHS: Result, RHS: V, Name: "sunkaddr");
6217 else
6218 Result = V;
6219 }
6220
6221 // Add in the BaseGV if present.
6222 GlobalValue *BaseGV = AddrMode.BaseGV;
6223 if (BaseGV != nullptr) {
6224 Value *BaseGVPtr;
6225 if (BaseGV->isThreadLocal()) {
6226 BaseGVPtr = Builder.CreateThreadLocalAddress(Ptr: BaseGV);
6227 } else {
6228 BaseGVPtr = BaseGV;
6229 }
6230 Value *V = Builder.CreatePtrToInt(V: BaseGVPtr, DestTy: IntPtrTy, Name: "sunkaddr");
6231 if (Result)
6232 Result = Builder.CreateAdd(LHS: Result, RHS: V, Name: "sunkaddr");
6233 else
6234 Result = V;
6235 }
6236
6237 // Add in the Base Offset if present.
6238 if (AddrMode.BaseOffs) {
6239 Value *V = ConstantInt::getSigned(Ty: IntPtrTy, V: AddrMode.BaseOffs);
6240 if (Result)
6241 Result = Builder.CreateAdd(LHS: Result, RHS: V, Name: "sunkaddr");
6242 else
6243 Result = V;
6244 }
6245
6246 if (!Result)
6247 SunkAddr = Constant::getNullValue(Ty: Addr->getType());
6248 else
6249 SunkAddr = Builder.CreateIntToPtr(V: Result, DestTy: Addr->getType(), Name: "sunkaddr");
6250 }
6251
6252 MemoryInst->replaceUsesOfWith(From: Repl, To: SunkAddr);
6253 // Store the newly computed address into the cache. In the case we reused a
6254 // value, this should be idempotent.
6255 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
6256
6257 // If we have no uses, recursively delete the value and all dead instructions
6258 // using it.
6259 if (Repl->use_empty()) {
6260 resetIteratorIfInvalidatedWhileCalling(BB: CurInstIterator->getParent(), f: [&]() {
6261 RecursivelyDeleteTriviallyDeadInstructions(
6262 V: Repl, TLI: TLInfo, MSSAU: nullptr,
6263 AboutToDeleteCallback: [&](Value *V) { removeAllAssertingVHReferences(V); });
6264 });
6265 }
6266 ++NumMemoryInsts;
6267 return true;
6268}
6269
6270/// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
6271/// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
6272/// only handle a 2 operand GEP in the same basic block or a splat constant
6273/// vector. The 2 operands to the GEP must have a scalar pointer and a vector
6274/// index.
6275///
6276/// If the existing GEP has a vector base pointer that is splat, we can look
6277/// through the splat to find the scalar pointer. If we can't find a scalar
6278/// pointer there's nothing we can do.
6279///
6280/// If we have a GEP with more than 2 indices where the middle indices are all
6281/// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
6282///
6283/// If the final index isn't a vector or is a splat, we can emit a scalar GEP
6284/// followed by a GEP with an all zeroes vector index. This will enable
6285/// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
6286/// zero index.
6287bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
6288 Value *Ptr) {
6289 Value *NewAddr;
6290
6291 if (const auto *GEP = dyn_cast<GetElementPtrInst>(Val: Ptr)) {
6292 // Don't optimize GEPs that don't have indices.
6293 if (!GEP->hasIndices())
6294 return false;
6295
6296 // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
6297 // FIXME: We should support this by sinking the GEP.
6298 if (MemoryInst->getParent() != GEP->getParent())
6299 return false;
6300
6301 SmallVector<Value *, 2> Ops(GEP->operands());
6302
6303 bool RewriteGEP = false;
6304
6305 if (Ops[0]->getType()->isVectorTy()) {
6306 Ops[0] = getSplatValue(V: Ops[0]);
6307 if (!Ops[0])
6308 return false;
6309 RewriteGEP = true;
6310 }
6311
6312 unsigned FinalIndex = Ops.size() - 1;
6313
6314 // Ensure all but the last index is 0.
6315 // FIXME: This isn't strictly required. All that's required is that they are
6316 // all scalars or splats.
6317 for (unsigned i = 1; i < FinalIndex; ++i) {
6318 auto *C = dyn_cast<Constant>(Val: Ops[i]);
6319 if (!C)
6320 return false;
6321 if (isa<VectorType>(Val: C->getType()))
6322 C = C->getSplatValue();
6323 auto *CI = dyn_cast_or_null<ConstantInt>(Val: C);
6324 if (!CI || !CI->isZero())
6325 return false;
6326 // Scalarize the index if needed.
6327 Ops[i] = CI;
6328 }
6329
6330 // Try to scalarize the final index.
6331 if (Ops[FinalIndex]->getType()->isVectorTy()) {
6332 if (Value *V = getSplatValue(V: Ops[FinalIndex])) {
6333 auto *C = dyn_cast<ConstantInt>(Val: V);
6334 // Don't scalarize all zeros vector.
6335 if (!C || !C->isZero()) {
6336 Ops[FinalIndex] = V;
6337 RewriteGEP = true;
6338 }
6339 }
6340 }
6341
6342 // If we made any changes or the we have extra operands, we need to generate
6343 // new instructions.
6344 if (!RewriteGEP && Ops.size() == 2)
6345 return false;
6346
6347 auto NumElts = cast<VectorType>(Val: Ptr->getType())->getElementCount();
6348
6349 IRBuilder<> Builder(MemoryInst);
6350
6351 Type *SourceTy = GEP->getSourceElementType();
6352 Type *ScalarIndexTy = DL->getIndexType(PtrTy: Ops[0]->getType()->getScalarType());
6353
6354 // If the final index isn't a vector, emit a scalar GEP containing all ops
6355 // and a vector GEP with all zeroes final index.
6356 if (!Ops[FinalIndex]->getType()->isVectorTy()) {
6357 NewAddr = Builder.CreateGEP(Ty: SourceTy, Ptr: Ops[0], IdxList: ArrayRef(Ops).drop_front());
6358 auto *IndexTy = VectorType::get(ElementType: ScalarIndexTy, EC: NumElts);
6359 auto *SecondTy = GetElementPtrInst::getIndexedType(
6360 Ty: SourceTy, IdxList: ArrayRef(Ops).drop_front());
6361 NewAddr =
6362 Builder.CreateGEP(Ty: SecondTy, Ptr: NewAddr, IdxList: Constant::getNullValue(Ty: IndexTy));
6363 } else {
6364 Value *Base = Ops[0];
6365 Value *Index = Ops[FinalIndex];
6366
6367 // Create a scalar GEP if there are more than 2 operands.
6368 if (Ops.size() != 2) {
6369 // Replace the last index with 0.
6370 Ops[FinalIndex] =
6371 Constant::getNullValue(Ty: Ops[FinalIndex]->getType()->getScalarType());
6372 Base = Builder.CreateGEP(Ty: SourceTy, Ptr: Base, IdxList: ArrayRef(Ops).drop_front());
6373 SourceTy = GetElementPtrInst::getIndexedType(
6374 Ty: SourceTy, IdxList: ArrayRef(Ops).drop_front());
6375 }
6376
6377 // Now create the GEP with scalar pointer and vector index.
6378 NewAddr = Builder.CreateGEP(Ty: SourceTy, Ptr: Base, IdxList: Index);
6379 }
6380 } else if (!isa<Constant>(Val: Ptr)) {
6381 // Not a GEP, maybe its a splat and we can create a GEP to enable
6382 // SelectionDAGBuilder to use it as a uniform base.
6383 Value *V = getSplatValue(V: Ptr);
6384 if (!V)
6385 return false;
6386
6387 auto NumElts = cast<VectorType>(Val: Ptr->getType())->getElementCount();
6388
6389 IRBuilder<> Builder(MemoryInst);
6390
6391 // Emit a vector GEP with a scalar pointer and all 0s vector index.
6392 Type *ScalarIndexTy = DL->getIndexType(PtrTy: V->getType()->getScalarType());
6393 auto *IndexTy = VectorType::get(ElementType: ScalarIndexTy, EC: NumElts);
6394 Type *ScalarTy;
6395 if (cast<IntrinsicInst>(Val: MemoryInst)->getIntrinsicID() ==
6396 Intrinsic::masked_gather) {
6397 ScalarTy = MemoryInst->getType()->getScalarType();
6398 } else {
6399 assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
6400 Intrinsic::masked_scatter);
6401 ScalarTy = MemoryInst->getOperand(i: 0)->getType()->getScalarType();
6402 }
6403 NewAddr = Builder.CreateGEP(Ty: ScalarTy, Ptr: V, IdxList: Constant::getNullValue(Ty: IndexTy));
6404 } else {
6405 // Constant, SelectionDAGBuilder knows to check if its a splat.
6406 return false;
6407 }
6408
6409 MemoryInst->replaceUsesOfWith(From: Ptr, To: NewAddr);
6410
6411 // If we have no uses, recursively delete the value and all dead instructions
6412 // using it.
6413 if (Ptr->use_empty())
6414 RecursivelyDeleteTriviallyDeadInstructions(
6415 V: Ptr, TLI: TLInfo, MSSAU: nullptr,
6416 AboutToDeleteCallback: [&](Value *V) { removeAllAssertingVHReferences(V); });
6417
6418 return true;
6419}
6420
6421// This is a helper for CodeGenPrepare::optimizeMulWithOverflow.
6422// Check the pattern we are interested in where there are maximum 2 uses
6423// of the intrinsic which are the extract instructions.
6424static bool matchOverflowPattern(Instruction *&I, ExtractValueInst *&MulExtract,
6425 ExtractValueInst *&OverflowExtract) {
6426 // Bail out if it's more than 2 users:
6427 if (I->hasNUsesOrMore(N: 3))
6428 return false;
6429
6430 for (User *U : I->users()) {
6431 auto *Extract = dyn_cast<ExtractValueInst>(Val: U);
6432 if (!Extract || Extract->getNumIndices() != 1)
6433 return false;
6434
6435 unsigned Index = Extract->getIndices()[0];
6436 if (Index == 0)
6437 MulExtract = Extract;
6438 else if (Index == 1)
6439 OverflowExtract = Extract;
6440 else
6441 return false;
6442 }
6443 return true;
6444}
6445
6446// Rewrite the mul_with_overflow intrinsic by checking if both of the
6447// operands' value ranges are within the legal type. If so, we can optimize the
6448// multiplication algorithm. This code is supposed to be written during the step
6449// of type legalization, but given that we need to reconstruct the IR which is
6450// not doable there, we do it here.
6451// The IR after the optimization will look like:
6452// entry:
6453// if signed:
6454// ( (lhs_lo>>BW-1) ^ lhs_hi) || ( (rhs_lo>>BW-1) ^ rhs_hi) ? overflow,
6455// overflow_no
6456// else:
6457// (lhs_hi != 0) || (rhs_hi != 0) ? overflow, overflow_no
6458// overflow_no:
6459// overflow:
6460// overflow.res:
6461// \returns true if optimization was applied
6462// TODO: This optimization can be further improved to optimize branching on
6463// overflow where the 'overflow_no' BB can branch directly to the false
6464// successor of overflow, but that would add additional complexity so we leave
6465// it for future work.
6466bool CodeGenPrepare::optimizeMulWithOverflow(Instruction *I, bool IsSigned,
6467 ModifyDT &ModifiedDT) {
6468 // Check if target supports this optimization.
6469 if (!TLI->shouldOptimizeMulOverflowWithZeroHighBits(
6470 Context&: I->getContext(),
6471 VT: TLI->getValueType(DL: *DL, Ty: I->getType()->getContainedType(i: 0))))
6472 return false;
6473
6474 ExtractValueInst *MulExtract = nullptr, *OverflowExtract = nullptr;
6475 if (!matchOverflowPattern(I, MulExtract, OverflowExtract))
6476 return false;
6477
6478 // Keep track of the instruction to stop reoptimizing it again.
6479 InsertedInsts.insert(Ptr: I);
6480
6481 Value *LHS = I->getOperand(i: 0);
6482 Value *RHS = I->getOperand(i: 1);
6483 Type *Ty = LHS->getType();
6484 unsigned VTHalfBitWidth = Ty->getScalarSizeInBits() / 2;
6485 Type *LegalTy = Ty->getWithNewBitWidth(NewBitWidth: VTHalfBitWidth);
6486
6487 // New BBs:
6488 BasicBlock *OverflowEntryBB =
6489 splitBlockBefore(Old: I->getParent(), SplitPt: I, DTU, LI, MSSAU: nullptr, BBName: "");
6490 OverflowEntryBB->takeName(V: I->getParent());
6491 // Keep the 'br' instruction that is generated as a result of the split to be
6492 // erased/replaced later.
6493 Instruction *OldTerminator = OverflowEntryBB->getTerminator();
6494 BasicBlock *NoOverflowBB =
6495 BasicBlock::Create(Context&: I->getContext(), Name: "overflow.no", Parent: I->getFunction());
6496 NoOverflowBB->moveAfter(MovePos: OverflowEntryBB);
6497 BasicBlock *OverflowBB =
6498 BasicBlock::Create(Context&: I->getContext(), Name: "overflow", Parent: I->getFunction());
6499 OverflowBB->moveAfter(MovePos: NoOverflowBB);
6500
6501 // BB overflow.entry:
6502 IRBuilder<> Builder(OverflowEntryBB);
6503 // Extract low and high halves of LHS:
6504 Value *LoLHS = Builder.CreateTrunc(V: LHS, DestTy: LegalTy, Name: "lo.lhs");
6505 Value *HiLHS = Builder.CreateLShr(LHS, RHS: VTHalfBitWidth, Name: "lhs.lsr");
6506 HiLHS = Builder.CreateTrunc(V: HiLHS, DestTy: LegalTy, Name: "hi.lhs");
6507
6508 // Extract low and high halves of RHS:
6509 Value *LoRHS = Builder.CreateTrunc(V: RHS, DestTy: LegalTy, Name: "lo.rhs");
6510 Value *HiRHS = Builder.CreateLShr(LHS: RHS, RHS: VTHalfBitWidth, Name: "rhs.lsr");
6511 HiRHS = Builder.CreateTrunc(V: HiRHS, DestTy: LegalTy, Name: "hi.rhs");
6512
6513 Value *IsAnyBitTrue;
6514 if (IsSigned) {
6515 Value *SignLoLHS =
6516 Builder.CreateAShr(LHS: LoLHS, RHS: VTHalfBitWidth - 1, Name: "sign.lo.lhs");
6517 Value *SignLoRHS =
6518 Builder.CreateAShr(LHS: LoRHS, RHS: VTHalfBitWidth - 1, Name: "sign.lo.rhs");
6519 Value *XorLHS = Builder.CreateXor(LHS: HiLHS, RHS: SignLoLHS);
6520 Value *XorRHS = Builder.CreateXor(LHS: HiRHS, RHS: SignLoRHS);
6521 Value *Or = Builder.CreateOr(LHS: XorLHS, RHS: XorRHS, Name: "or.lhs.rhs");
6522 IsAnyBitTrue = Builder.CreateCmp(Pred: ICmpInst::ICMP_NE, LHS: Or,
6523 RHS: ConstantInt::getNullValue(Ty: Or->getType()));
6524 } else {
6525 Value *CmpLHS = Builder.CreateCmp(Pred: ICmpInst::ICMP_NE, LHS: HiLHS,
6526 RHS: ConstantInt::getNullValue(Ty: LegalTy));
6527 Value *CmpRHS = Builder.CreateCmp(Pred: ICmpInst::ICMP_NE, LHS: HiRHS,
6528 RHS: ConstantInt::getNullValue(Ty: LegalTy));
6529 IsAnyBitTrue = Builder.CreateOr(LHS: CmpLHS, RHS: CmpRHS, Name: "or.lhs.rhs");
6530 }
6531 Builder.CreateCondBr(Cond: IsAnyBitTrue, True: OverflowBB, False: NoOverflowBB);
6532
6533 // BB overflow.no:
6534 Builder.SetInsertPoint(NoOverflowBB);
6535 Value *ExtLoLHS, *ExtLoRHS;
6536 if (IsSigned) {
6537 ExtLoLHS = Builder.CreateSExt(V: LoLHS, DestTy: Ty, Name: "lo.lhs.ext");
6538 ExtLoRHS = Builder.CreateSExt(V: LoRHS, DestTy: Ty, Name: "lo.rhs.ext");
6539 } else {
6540 ExtLoLHS = Builder.CreateZExt(V: LoLHS, DestTy: Ty, Name: "lo.lhs.ext");
6541 ExtLoRHS = Builder.CreateZExt(V: LoRHS, DestTy: Ty, Name: "lo.rhs.ext");
6542 }
6543
6544 Value *Mul = Builder.CreateMul(LHS: ExtLoLHS, RHS: ExtLoRHS, Name: "mul.overflow.no");
6545
6546 // Create the 'overflow.res' BB to merge the results of
6547 // the two paths:
6548 BasicBlock *OverflowResBB = I->getParent();
6549 OverflowResBB->setName("overflow.res");
6550
6551 // BB overflow.no: jump to overflow.res BB
6552 Builder.CreateBr(Dest: OverflowResBB);
6553 // No we don't need the old terminator in overflow.entry BB, erase it:
6554 OldTerminator->eraseFromParent();
6555
6556 // BB overflow.res:
6557 Builder.SetInsertPoint(TheBB: OverflowResBB, IP: OverflowResBB->getFirstInsertionPt());
6558 // Create PHI nodes to merge results from no.overflow BB and overflow BB to
6559 // replace the extract instructions.
6560 PHINode *OverflowResPHI = Builder.CreatePHI(Ty, NumReservedValues: 2),
6561 *OverflowFlagPHI =
6562 Builder.CreatePHI(Ty: IntegerType::getInt1Ty(C&: I->getContext()), NumReservedValues: 2);
6563
6564 // Add the incoming values from no.overflow BB and later from overflow BB.
6565 OverflowResPHI->addIncoming(V: Mul, BB: NoOverflowBB);
6566 OverflowFlagPHI->addIncoming(V: ConstantInt::getFalse(Context&: I->getContext()),
6567 BB: NoOverflowBB);
6568
6569 // Replace all users of MulExtract and OverflowExtract to use the PHI nodes.
6570 if (MulExtract) {
6571 MulExtract->replaceAllUsesWith(V: OverflowResPHI);
6572 MulExtract->eraseFromParent();
6573 }
6574 if (OverflowExtract) {
6575 OverflowExtract->replaceAllUsesWith(V: OverflowFlagPHI);
6576 OverflowExtract->eraseFromParent();
6577 }
6578
6579 // Remove the intrinsic from parent (overflow.res BB) as it will be part of
6580 // overflow BB
6581 I->removeFromParent();
6582 // BB overflow:
6583 I->insertInto(ParentBB: OverflowBB, It: OverflowBB->end());
6584 Builder.SetInsertPoint(TheBB: OverflowBB, IP: OverflowBB->end());
6585 Value *MulOverflow = Builder.CreateExtractValue(Agg: I, Idxs: {0}, Name: "mul.overflow");
6586 Value *OverflowFlag = Builder.CreateExtractValue(Agg: I, Idxs: {1}, Name: "overflow.flag");
6587 Builder.CreateBr(Dest: OverflowResBB);
6588
6589 // Add The Extracted values to the PHINodes in the overflow.res BB.
6590 OverflowResPHI->addIncoming(V: MulOverflow, BB: OverflowBB);
6591 OverflowFlagPHI->addIncoming(V: OverflowFlag, BB: OverflowBB);
6592
6593 DTU->applyUpdates(Updates: {{DominatorTree::Insert, OverflowEntryBB, OverflowBB},
6594 {DominatorTree::Insert, OverflowEntryBB, NoOverflowBB},
6595 {DominatorTree::Insert, NoOverflowBB, OverflowResBB},
6596 {DominatorTree::Delete, OverflowEntryBB, OverflowResBB},
6597 {DominatorTree::Insert, OverflowBB, OverflowResBB}});
6598
6599 ModifiedDT = ModifyDT::ModifyBBDT;
6600 return true;
6601}
6602
6603/// If there are any memory operands, use OptimizeMemoryInst to sink their
6604/// address computing into the block when possible / profitable.
6605bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
6606 bool MadeChange = false;
6607
6608 const TargetRegisterInfo *TRI =
6609 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
6610 TargetLowering::AsmOperandInfoVector TargetConstraints =
6611 TLI->ParseConstraints(DL: *DL, TRI, Call: *CS);
6612 unsigned ArgNo = 0;
6613 for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
6614 // Compute the constraint code and ConstraintType to use.
6615 TLI->ComputeConstraintToUse(OpInfo, Op: SDValue());
6616
6617 // TODO: Also handle C_Address?
6618 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6619 OpInfo.isIndirect) {
6620 Value *OpVal = CS->getArgOperand(i: ArgNo++);
6621 MadeChange |= optimizeMemoryInst(MemoryInst: CS, Addr: OpVal, AccessTy: OpVal->getType(), AddrSpace: ~0u);
6622 } else if (OpInfo.Type == InlineAsm::isInput)
6623 ArgNo++;
6624 }
6625
6626 return MadeChange;
6627}
6628
6629/// Check if all the uses of \p Val are equivalent (or free) zero or
6630/// sign extensions.
6631static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
6632 assert(!Val->use_empty() && "Input must have at least one use");
6633 const Instruction *FirstUser = cast<Instruction>(Val: *Val->user_begin());
6634 bool IsSExt = isa<SExtInst>(Val: FirstUser);
6635 Type *ExtTy = FirstUser->getType();
6636 for (const User *U : Val->users()) {
6637 const Instruction *UI = cast<Instruction>(Val: U);
6638 if ((IsSExt && !isa<SExtInst>(Val: UI)) || (!IsSExt && !isa<ZExtInst>(Val: UI)))
6639 return false;
6640 Type *CurTy = UI->getType();
6641 // Same input and output types: Same instruction after CSE.
6642 if (CurTy == ExtTy)
6643 continue;
6644
6645 // If IsSExt is true, we are in this situation:
6646 // a = Val
6647 // b = sext ty1 a to ty2
6648 // c = sext ty1 a to ty3
6649 // Assuming ty2 is shorter than ty3, this could be turned into:
6650 // a = Val
6651 // b = sext ty1 a to ty2
6652 // c = sext ty2 b to ty3
6653 // However, the last sext is not free.
6654 if (IsSExt)
6655 return false;
6656
6657 // This is a ZExt, maybe this is free to extend from one type to another.
6658 // In that case, we would not account for a different use.
6659 Type *NarrowTy;
6660 Type *LargeTy;
6661 if (ExtTy->getScalarType()->getIntegerBitWidth() >
6662 CurTy->getScalarType()->getIntegerBitWidth()) {
6663 NarrowTy = CurTy;
6664 LargeTy = ExtTy;
6665 } else {
6666 NarrowTy = ExtTy;
6667 LargeTy = CurTy;
6668 }
6669
6670 if (!TLI.isZExtFree(FromTy: NarrowTy, ToTy: LargeTy))
6671 return false;
6672 }
6673 // All uses are the same or can be derived from one another for free.
6674 return true;
6675}
6676
6677/// Try to speculatively promote extensions in \p Exts and continue
6678/// promoting through newly promoted operands recursively as far as doing so is
6679/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
6680/// When some promotion happened, \p TPT contains the proper state to revert
6681/// them.
6682///
6683/// \return true if some promotion happened, false otherwise.
6684bool CodeGenPrepare::tryToPromoteExts(
6685 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
6686 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
6687 unsigned CreatedInstsCost) {
6688 bool Promoted = false;
6689
6690 // Iterate over all the extensions to try to promote them.
6691 for (auto *I : Exts) {
6692 // Early check if we directly have ext(load).
6693 if (isa<LoadInst>(Val: I->getOperand(i: 0))) {
6694 ProfitablyMovedExts.push_back(Elt: I);
6695 continue;
6696 }
6697
6698 // Check whether or not we want to do any promotion. The reason we have
6699 // this check inside the for loop is to catch the case where an extension
6700 // is directly fed by a load because in such case the extension can be moved
6701 // up without any promotion on its operands.
6702 if (!TLI->enableExtLdPromotion() || DisableExtLdPromotion)
6703 return false;
6704
6705 // Get the action to perform the promotion.
6706 TypePromotionHelper::Action TPH =
6707 TypePromotionHelper::getAction(Ext: I, InsertedInsts, TLI: *TLI, PromotedInsts);
6708 // Check if we can promote.
6709 if (!TPH) {
6710 // Save the current extension as we cannot move up through its operand.
6711 ProfitablyMovedExts.push_back(Elt: I);
6712 continue;
6713 }
6714
6715 // Save the current state.
6716 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
6717 TPT.getRestorationPoint();
6718 SmallVector<Instruction *, 4> NewExts;
6719 unsigned NewCreatedInstsCost = 0;
6720 unsigned ExtCost = !TLI->isExtFree(I);
6721 // Promote.
6722 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
6723 &NewExts, nullptr, *TLI);
6724 assert(PromotedVal &&
6725 "TypePromotionHelper should have filtered out those cases");
6726
6727 // We would be able to merge only one extension in a load.
6728 // Therefore, if we have more than 1 new extension we heuristically
6729 // cut this search path, because it means we degrade the code quality.
6730 // With exactly 2, the transformation is neutral, because we will merge
6731 // one extension but leave one. However, we optimistically keep going,
6732 // because the new extension may be removed too. Also avoid replacing a
6733 // single free extension with multiple extensions, as this increases the
6734 // number of IR instructions while not providing any savings.
6735 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
6736 // FIXME: It would be possible to propagate a negative value instead of
6737 // conservatively ceiling it to 0.
6738 TotalCreatedInstsCost =
6739 std::max(a: (long long)0, b: (TotalCreatedInstsCost - ExtCost));
6740 if (!StressExtLdPromotion &&
6741 (TotalCreatedInstsCost > 1 ||
6742 !isPromotedInstructionLegal(TLI: *TLI, DL: *DL, Val: PromotedVal) ||
6743 (ExtCost == 0 && NewExts.size() > 1))) {
6744 // This promotion is not profitable, rollback to the previous state, and
6745 // save the current extension in ProfitablyMovedExts as the latest
6746 // speculative promotion turned out to be unprofitable.
6747 TPT.rollback(Point: LastKnownGood);
6748 ProfitablyMovedExts.push_back(Elt: I);
6749 continue;
6750 }
6751 // Continue promoting NewExts as far as doing so is profitable.
6752 SmallVector<Instruction *, 2> NewlyMovedExts;
6753 (void)tryToPromoteExts(TPT, Exts: NewExts, ProfitablyMovedExts&: NewlyMovedExts, CreatedInstsCost: TotalCreatedInstsCost);
6754 bool NewPromoted = false;
6755 for (auto *ExtInst : NewlyMovedExts) {
6756 Instruction *MovedExt = cast<Instruction>(Val: ExtInst);
6757 Value *ExtOperand = MovedExt->getOperand(i: 0);
6758 // If we have reached to a load, we need this extra profitability check
6759 // as it could potentially be merged into an ext(load).
6760 if (isa<LoadInst>(Val: ExtOperand) &&
6761 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
6762 (ExtOperand->hasOneUse() || hasSameExtUse(Val: ExtOperand, TLI: *TLI))))
6763 continue;
6764
6765 ProfitablyMovedExts.push_back(Elt: MovedExt);
6766 NewPromoted = true;
6767 }
6768
6769 // If none of speculative promotions for NewExts is profitable, rollback
6770 // and save the current extension (I) as the last profitable extension.
6771 if (!NewPromoted) {
6772 TPT.rollback(Point: LastKnownGood);
6773 ProfitablyMovedExts.push_back(Elt: I);
6774 continue;
6775 }
6776 // The promotion is profitable.
6777 Promoted = true;
6778 }
6779 return Promoted;
6780}
6781
6782/// Merging redundant sexts when one is dominating the other.
6783bool CodeGenPrepare::mergeSExts(Function &F) {
6784 bool Changed = false;
6785 for (auto &Entry : ValToSExtendedUses) {
6786 SExts &Insts = Entry.second;
6787 SExts CurPts;
6788 for (Instruction *Inst : Insts) {
6789 if (RemovedInsts.count(Ptr: Inst) || !isa<SExtInst>(Val: Inst) ||
6790 Inst->getOperand(i: 0) != Entry.first)
6791 continue;
6792 bool inserted = false;
6793 for (auto &Pt : CurPts) {
6794 if (getDT().dominates(Def: Inst, User: Pt)) {
6795 replaceAllUsesWith(Old: Pt, New: Inst, FreshBBs, IsHuge: IsHugeFunc);
6796 RemovedInsts.insert(Ptr: Pt);
6797 Pt->removeFromParent();
6798 Pt = Inst;
6799 inserted = true;
6800 Changed = true;
6801 break;
6802 }
6803 if (!getDT().dominates(Def: Pt, User: Inst))
6804 // Give up if we need to merge in a common dominator as the
6805 // experiments show it is not profitable.
6806 continue;
6807 replaceAllUsesWith(Old: Inst, New: Pt, FreshBBs, IsHuge: IsHugeFunc);
6808 RemovedInsts.insert(Ptr: Inst);
6809 Inst->removeFromParent();
6810 inserted = true;
6811 Changed = true;
6812 break;
6813 }
6814 if (!inserted)
6815 CurPts.push_back(Elt: Inst);
6816 }
6817 }
6818 return Changed;
6819}
6820
6821// Splitting large data structures so that the GEPs accessing them can have
6822// smaller offsets so that they can be sunk to the same blocks as their users.
6823// For example, a large struct starting from %base is split into two parts
6824// where the second part starts from %new_base.
6825//
6826// Before:
6827// BB0:
6828// %base =
6829//
6830// BB1:
6831// %gep0 = gep %base, off0
6832// %gep1 = gep %base, off1
6833// %gep2 = gep %base, off2
6834//
6835// BB2:
6836// %load1 = load %gep0
6837// %load2 = load %gep1
6838// %load3 = load %gep2
6839//
6840// After:
6841// BB0:
6842// %base =
6843// %new_base = gep %base, off0
6844//
6845// BB1:
6846// %new_gep0 = %new_base
6847// %new_gep1 = gep %new_base, off1 - off0
6848// %new_gep2 = gep %new_base, off2 - off0
6849//
6850// BB2:
6851// %load1 = load i32, i32* %new_gep0
6852// %load2 = load i32, i32* %new_gep1
6853// %load3 = load i32, i32* %new_gep2
6854//
6855// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
6856// their offsets are smaller enough to fit into the addressing mode.
6857bool CodeGenPrepare::splitLargeGEPOffsets() {
6858 bool Changed = false;
6859 for (auto &Entry : LargeOffsetGEPMap) {
6860 Value *OldBase = Entry.first;
6861 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
6862 &LargeOffsetGEPs = Entry.second;
6863 auto compareGEPOffset =
6864 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
6865 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
6866 if (LHS.first == RHS.first)
6867 return false;
6868 if (LHS.second != RHS.second)
6869 return LHS.second < RHS.second;
6870 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
6871 };
6872 // Sorting all the GEPs of the same data structures based on the offsets.
6873 llvm::sort(C&: LargeOffsetGEPs, Comp: compareGEPOffset);
6874 LargeOffsetGEPs.erase(CS: llvm::unique(R&: LargeOffsetGEPs), CE: LargeOffsetGEPs.end());
6875 // Skip if all the GEPs have the same offsets.
6876 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
6877 continue;
6878 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
6879 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
6880 Value *NewBaseGEP = nullptr;
6881
6882 auto createNewBase = [&](int64_t BaseOffset, Value *OldBase,
6883 GetElementPtrInst *GEP) {
6884 LLVMContext &Ctx = GEP->getContext();
6885 Type *PtrIdxTy = DL->getIndexType(PtrTy: GEP->getType());
6886 Type *I8PtrTy =
6887 PointerType::get(C&: Ctx, AddressSpace: GEP->getType()->getPointerAddressSpace());
6888
6889 BasicBlock::iterator NewBaseInsertPt;
6890 BasicBlock *NewBaseInsertBB;
6891 if (auto *BaseI = dyn_cast<Instruction>(Val: OldBase)) {
6892 // If the base of the struct is an instruction, the new base will be
6893 // inserted close to it.
6894 NewBaseInsertBB = BaseI->getParent();
6895 if (isa<PHINode>(Val: BaseI))
6896 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6897 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(Val: BaseI)) {
6898 NewBaseInsertBB =
6899 SplitEdge(From: NewBaseInsertBB, To: Invoke->getNormalDest(), DT: &getDT(), LI);
6900 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6901 } else
6902 NewBaseInsertPt = std::next(x: BaseI->getIterator());
6903 } else {
6904 // If the current base is an argument or global value, the new base
6905 // will be inserted to the entry block.
6906 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
6907 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
6908 }
6909 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
6910 // Create a new base.
6911 // TODO: Avoid implicit trunc?
6912 // See https://github.com/llvm/llvm-project/issues/112510.
6913 Value *BaseIndex =
6914 ConstantInt::getSigned(Ty: PtrIdxTy, V: BaseOffset, /*ImplicitTrunc=*/true);
6915 NewBaseGEP = OldBase;
6916 if (NewBaseGEP->getType() != I8PtrTy)
6917 NewBaseGEP = NewBaseBuilder.CreatePointerCast(V: NewBaseGEP, DestTy: I8PtrTy);
6918 NewBaseGEP =
6919 NewBaseBuilder.CreatePtrAdd(Ptr: NewBaseGEP, Offset: BaseIndex, Name: "splitgep");
6920 NewGEPBases.insert(V: NewBaseGEP);
6921 return;
6922 };
6923
6924 // Check whether all the offsets can be encoded with prefered common base.
6925 if (int64_t PreferBase = TLI->getPreferredLargeGEPBaseOffset(
6926 MinOffset: LargeOffsetGEPs.front().second, MaxOffset: LargeOffsetGEPs.back().second)) {
6927 BaseOffset = PreferBase;
6928 // Create a new base if the offset of the BaseGEP can be decoded with one
6929 // instruction.
6930 createNewBase(BaseOffset, OldBase, BaseGEP);
6931 }
6932
6933 auto *LargeOffsetGEP = LargeOffsetGEPs.begin();
6934 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
6935 GetElementPtrInst *GEP = LargeOffsetGEP->first;
6936 int64_t Offset = LargeOffsetGEP->second;
6937 if (Offset != BaseOffset) {
6938 TargetLowering::AddrMode AddrMode;
6939 AddrMode.HasBaseReg = true;
6940 AddrMode.BaseOffs = Offset - BaseOffset;
6941 // The result type of the GEP might not be the type of the memory
6942 // access.
6943 if (!TLI->isLegalAddressingMode(DL: *DL, AM: AddrMode,
6944 Ty: GEP->getResultElementType(),
6945 AddrSpace: GEP->getAddressSpace())) {
6946 // We need to create a new base if the offset to the current base is
6947 // too large to fit into the addressing mode. So, a very large struct
6948 // may be split into several parts.
6949 BaseGEP = GEP;
6950 BaseOffset = Offset;
6951 NewBaseGEP = nullptr;
6952 }
6953 }
6954
6955 // Generate a new GEP to replace the current one.
6956 Type *PtrIdxTy = DL->getIndexType(PtrTy: GEP->getType());
6957
6958 if (!NewBaseGEP) {
6959 // Create a new base if we don't have one yet. Find the insertion
6960 // pointer for the new base first.
6961 createNewBase(BaseOffset, OldBase, GEP);
6962 }
6963
6964 IRBuilder<> Builder(GEP);
6965 Value *NewGEP = NewBaseGEP;
6966 if (Offset != BaseOffset) {
6967 // Calculate the new offset for the new GEP.
6968 Value *Index = ConstantInt::get(Ty: PtrIdxTy, V: Offset - BaseOffset);
6969 NewGEP = Builder.CreatePtrAdd(Ptr: NewBaseGEP, Offset: Index);
6970 }
6971 replaceAllUsesWith(Old: GEP, New: NewGEP, FreshBBs, IsHuge: IsHugeFunc);
6972 LargeOffsetGEPID.erase(Val: GEP);
6973 LargeOffsetGEP = LargeOffsetGEPs.erase(CI: LargeOffsetGEP);
6974 GEP->eraseFromParent();
6975 Changed = true;
6976 }
6977 }
6978 return Changed;
6979}
6980
6981bool CodeGenPrepare::optimizePhiType(
6982 PHINode *I, SmallPtrSetImpl<PHINode *> &Visited,
6983 SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
6984 // We are looking for a collection on interconnected phi nodes that together
6985 // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts
6986 // are of the same type. Convert the whole set of nodes to the type of the
6987 // bitcast.
6988 Type *PhiTy = I->getType();
6989 Type *ConvertTy = nullptr;
6990 if (Visited.count(Ptr: I) ||
6991 (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy()))
6992 return false;
6993
6994 SmallVector<Instruction *, 4> Worklist;
6995 Worklist.push_back(Elt: cast<Instruction>(Val: I));
6996 SmallPtrSet<PHINode *, 4> PhiNodes;
6997 SmallPtrSet<ConstantData *, 4> Constants;
6998 PhiNodes.insert(Ptr: I);
6999 Visited.insert(Ptr: I);
7000 SmallPtrSet<Instruction *, 4> Defs;
7001 SmallPtrSet<Instruction *, 4> Uses;
7002 // This works by adding extra bitcasts between load/stores and removing
7003 // existing bitcasts. If we have a phi(bitcast(load)) or a store(bitcast(phi))
7004 // we can get in the situation where we remove a bitcast in one iteration
7005 // just to add it again in the next. We need to ensure that at least one
7006 // bitcast we remove are anchored to something that will not change back.
7007 bool AnyAnchored = false;
7008
7009 while (!Worklist.empty()) {
7010 Instruction *II = Worklist.pop_back_val();
7011
7012 if (auto *Phi = dyn_cast<PHINode>(Val: II)) {
7013 // Handle Defs, which might also be PHI's
7014 for (Value *V : Phi->incoming_values()) {
7015 if (auto *OpPhi = dyn_cast<PHINode>(Val: V)) {
7016 if (!PhiNodes.count(Ptr: OpPhi)) {
7017 if (!Visited.insert(Ptr: OpPhi).second)
7018 return false;
7019 PhiNodes.insert(Ptr: OpPhi);
7020 Worklist.push_back(Elt: OpPhi);
7021 }
7022 } else if (auto *OpLoad = dyn_cast<LoadInst>(Val: V)) {
7023 if (!OpLoad->isSimple())
7024 return false;
7025 if (Defs.insert(Ptr: OpLoad).second)
7026 Worklist.push_back(Elt: OpLoad);
7027 } else if (auto *OpEx = dyn_cast<ExtractElementInst>(Val: V)) {
7028 if (Defs.insert(Ptr: OpEx).second)
7029 Worklist.push_back(Elt: OpEx);
7030 } else if (auto *OpBC = dyn_cast<BitCastInst>(Val: V)) {
7031 if (!ConvertTy)
7032 ConvertTy = OpBC->getOperand(i_nocapture: 0)->getType();
7033 if (OpBC->getOperand(i_nocapture: 0)->getType() != ConvertTy)
7034 return false;
7035 if (Defs.insert(Ptr: OpBC).second) {
7036 Worklist.push_back(Elt: OpBC);
7037 AnyAnchored |= !isa<LoadInst>(Val: OpBC->getOperand(i_nocapture: 0)) &&
7038 !isa<ExtractElementInst>(Val: OpBC->getOperand(i_nocapture: 0));
7039 }
7040 } else if (auto *OpC = dyn_cast<ConstantData>(Val: V))
7041 Constants.insert(Ptr: OpC);
7042 else
7043 return false;
7044 }
7045 }
7046
7047 // Handle uses which might also be phi's
7048 for (User *V : II->users()) {
7049 if (auto *OpPhi = dyn_cast<PHINode>(Val: V)) {
7050 if (!PhiNodes.count(Ptr: OpPhi)) {
7051 if (Visited.count(Ptr: OpPhi))
7052 return false;
7053 PhiNodes.insert(Ptr: OpPhi);
7054 Visited.insert(Ptr: OpPhi);
7055 Worklist.push_back(Elt: OpPhi);
7056 }
7057 } else if (auto *OpStore = dyn_cast<StoreInst>(Val: V)) {
7058 if (!OpStore->isSimple() || OpStore->getOperand(i_nocapture: 0) != II)
7059 return false;
7060 Uses.insert(Ptr: OpStore);
7061 } else if (auto *OpBC = dyn_cast<BitCastInst>(Val: V)) {
7062 if (!ConvertTy)
7063 ConvertTy = OpBC->getType();
7064 if (OpBC->getType() != ConvertTy)
7065 return false;
7066 Uses.insert(Ptr: OpBC);
7067 AnyAnchored |=
7068 any_of(Range: OpBC->users(), P: [](User *U) { return !isa<StoreInst>(Val: U); });
7069 } else {
7070 return false;
7071 }
7072 }
7073 }
7074
7075 if (!ConvertTy || !AnyAnchored || PhiTy == ConvertTy ||
7076 !TLI->shouldConvertPhiType(From: PhiTy, To: ConvertTy))
7077 return false;
7078
7079 LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "
7080 << *ConvertTy << "\n");
7081
7082 // Create all the new phi nodes of the new type, and bitcast any loads to the
7083 // correct type.
7084 ValueToValueMap ValMap;
7085 for (ConstantData *C : Constants)
7086 ValMap[C] = ConstantExpr::getBitCast(C, Ty: ConvertTy);
7087 for (Instruction *D : Defs) {
7088 if (isa<BitCastInst>(Val: D)) {
7089 ValMap[D] = D->getOperand(i: 0);
7090 DeletedInstrs.insert(Ptr: D);
7091 } else {
7092 BasicBlock::iterator insertPt = std::next(x: D->getIterator());
7093 ValMap[D] = new BitCastInst(D, ConvertTy, D->getName() + ".bc", insertPt);
7094 }
7095 }
7096 for (PHINode *Phi : PhiNodes)
7097 ValMap[Phi] = PHINode::Create(Ty: ConvertTy, NumReservedValues: Phi->getNumIncomingValues(),
7098 NameStr: Phi->getName() + ".tc", InsertBefore: Phi->getIterator());
7099 // Pipe together all the PhiNodes.
7100 for (PHINode *Phi : PhiNodes) {
7101 PHINode *NewPhi = cast<PHINode>(Val: ValMap[Phi]);
7102 for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++)
7103 NewPhi->addIncoming(V: ValMap[Phi->getIncomingValue(i)],
7104 BB: Phi->getIncomingBlock(i));
7105 Visited.insert(Ptr: NewPhi);
7106 }
7107 // And finally pipe up the stores and bitcasts
7108 for (Instruction *U : Uses) {
7109 if (isa<BitCastInst>(Val: U)) {
7110 DeletedInstrs.insert(Ptr: U);
7111 replaceAllUsesWith(Old: U, New: ValMap[U->getOperand(i: 0)], FreshBBs, IsHuge: IsHugeFunc);
7112 } else {
7113 U->setOperand(i: 0, Val: new BitCastInst(ValMap[U->getOperand(i: 0)], PhiTy, "bc",
7114 U->getIterator()));
7115 }
7116 }
7117
7118 // Save the removed phis to be deleted later.
7119 DeletedInstrs.insert_range(R&: PhiNodes);
7120 return true;
7121}
7122
7123bool CodeGenPrepare::optimizePhiTypes(Function &F) {
7124 if (!OptimizePhiTypes)
7125 return false;
7126
7127 bool Changed = false;
7128 SmallPtrSet<PHINode *, 4> Visited;
7129 SmallPtrSet<Instruction *, 4> DeletedInstrs;
7130
7131 // Attempt to optimize all the phis in the functions to the correct type.
7132 for (auto &BB : F)
7133 for (auto &Phi : BB.phis())
7134 Changed |= optimizePhiType(I: &Phi, Visited, DeletedInstrs);
7135
7136 // Remove any old phi's that have been converted.
7137 for (auto *I : DeletedInstrs) {
7138 replaceAllUsesWith(Old: I, New: PoisonValue::get(T: I->getType()), FreshBBs, IsHuge: IsHugeFunc);
7139 I->eraseFromParent();
7140 }
7141
7142 return Changed;
7143}
7144
7145/// Return true, if an ext(load) can be formed from an extension in
7146/// \p MovedExts.
7147bool CodeGenPrepare::canFormExtLd(
7148 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
7149 Instruction *&Inst, bool HasPromoted) {
7150 for (auto *MovedExtInst : MovedExts) {
7151 if (isa<LoadInst>(Val: MovedExtInst->getOperand(i: 0))) {
7152 LI = cast<LoadInst>(Val: MovedExtInst->getOperand(i: 0));
7153 Inst = MovedExtInst;
7154 break;
7155 }
7156 }
7157 if (!LI)
7158 return false;
7159
7160 // If they're already in the same block, there's nothing to do.
7161 // Make the cheap checks first if we did not promote.
7162 // If we promoted, we need to check if it is indeed profitable.
7163 if (!HasPromoted && LI->getParent() == Inst->getParent())
7164 return false;
7165
7166 return TLI->isExtLoad(Load: LI, Ext: Inst, DL: *DL);
7167}
7168
7169/// Move a zext or sext fed by a load into the same basic block as the load,
7170/// unless conditions are unfavorable. This allows SelectionDAG to fold the
7171/// extend into the load.
7172///
7173/// E.g.,
7174/// \code
7175/// %ld = load i32* %addr
7176/// %add = add nuw i32 %ld, 4
7177/// %zext = zext i32 %add to i64
7178// \endcode
7179/// =>
7180/// \code
7181/// %ld = load i32* %addr
7182/// %zext = zext i32 %ld to i64
7183/// %add = add nuw i64 %zext, 4
7184/// \encode
7185/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
7186/// allow us to match zext(load i32*) to i64.
7187///
7188/// Also, try to promote the computations used to obtain a sign extended
7189/// value used into memory accesses.
7190/// E.g.,
7191/// \code
7192/// a = add nsw i32 b, 3
7193/// d = sext i32 a to i64
7194/// e = getelementptr ..., i64 d
7195/// \endcode
7196/// =>
7197/// \code
7198/// f = sext i32 b to i64
7199/// a = add nsw i64 f, 3
7200/// e = getelementptr ..., i64 a
7201/// \endcode
7202///
7203/// \p Inst[in/out] the extension may be modified during the process if some
7204/// promotions apply.
7205bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
7206 bool AllowPromotionWithoutCommonHeader = false;
7207 /// See if it is an interesting sext operations for the address type
7208 /// promotion before trying to promote it, e.g., the ones with the right
7209 /// type and used in memory accesses.
7210 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
7211 I: *Inst, AllowPromotionWithoutCommonHeader);
7212 TypePromotionTransaction TPT(RemovedInsts);
7213 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
7214 TPT.getRestorationPoint();
7215 SmallVector<Instruction *, 1> Exts;
7216 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
7217 Exts.push_back(Elt: Inst);
7218
7219 bool HasPromoted = tryToPromoteExts(TPT, Exts, ProfitablyMovedExts&: SpeculativelyMovedExts);
7220
7221 // Look for a load being extended.
7222 LoadInst *LI = nullptr;
7223 Instruction *ExtFedByLoad;
7224
7225 // Try to promote a chain of computation if it allows to form an extended
7226 // load.
7227 if (canFormExtLd(MovedExts: SpeculativelyMovedExts, LI, Inst&: ExtFedByLoad, HasPromoted)) {
7228 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
7229 TPT.commit();
7230 // Move the extend into the same block as the load.
7231 ExtFedByLoad->moveAfter(MovePos: LI);
7232 ++NumExtsMoved;
7233 Inst = ExtFedByLoad;
7234 return true;
7235 }
7236
7237 // Continue promoting SExts if known as considerable depending on targets.
7238 if (ATPConsiderable &&
7239 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
7240 HasPromoted, TPT, SpeculativelyMovedExts))
7241 return true;
7242
7243 TPT.rollback(Point: LastKnownGood);
7244 return false;
7245}
7246
7247// Perform address type promotion if doing so is profitable.
7248// If AllowPromotionWithoutCommonHeader == false, we should find other sext
7249// instructions that sign extended the same initial value. However, if
7250// AllowPromotionWithoutCommonHeader == true, we expect promoting the
7251// extension is just profitable.
7252bool CodeGenPrepare::performAddressTypePromotion(
7253 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
7254 bool HasPromoted, TypePromotionTransaction &TPT,
7255 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
7256 bool Promoted = false;
7257 SmallPtrSet<Instruction *, 1> UnhandledExts;
7258 bool AllSeenFirst = true;
7259 for (auto *I : SpeculativelyMovedExts) {
7260 Value *HeadOfChain = I->getOperand(i: 0);
7261 auto AlreadySeen = SeenChainsForSExt.find(Val: HeadOfChain);
7262 // If there is an unhandled SExt which has the same header, try to promote
7263 // it as well.
7264 if (AlreadySeen != SeenChainsForSExt.end()) {
7265 if (AlreadySeen->second != nullptr)
7266 UnhandledExts.insert(Ptr: AlreadySeen->second);
7267 AllSeenFirst = false;
7268 }
7269 }
7270
7271 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
7272 SpeculativelyMovedExts.size() == 1)) {
7273 TPT.commit();
7274 if (HasPromoted)
7275 Promoted = true;
7276 for (auto *I : SpeculativelyMovedExts) {
7277 Value *HeadOfChain = I->getOperand(i: 0);
7278 SeenChainsForSExt[HeadOfChain] = nullptr;
7279 ValToSExtendedUses[HeadOfChain].push_back(Elt: I);
7280 }
7281 // Update Inst as promotion happen.
7282 Inst = SpeculativelyMovedExts.pop_back_val();
7283 } else {
7284 // This is the first chain visited from the header, keep the current chain
7285 // as unhandled. Defer to promote this until we encounter another SExt
7286 // chain derived from the same header.
7287 for (auto *I : SpeculativelyMovedExts) {
7288 Value *HeadOfChain = I->getOperand(i: 0);
7289 SeenChainsForSExt[HeadOfChain] = Inst;
7290 }
7291 return false;
7292 }
7293
7294 if (!AllSeenFirst && !UnhandledExts.empty())
7295 for (auto *VisitedSExt : UnhandledExts) {
7296 if (RemovedInsts.count(Ptr: VisitedSExt))
7297 continue;
7298 TypePromotionTransaction TPT(RemovedInsts);
7299 SmallVector<Instruction *, 1> Exts;
7300 SmallVector<Instruction *, 2> Chains;
7301 Exts.push_back(Elt: VisitedSExt);
7302 bool HasPromoted = tryToPromoteExts(TPT, Exts, ProfitablyMovedExts&: Chains);
7303 TPT.commit();
7304 if (HasPromoted)
7305 Promoted = true;
7306 for (auto *I : Chains) {
7307 Value *HeadOfChain = I->getOperand(i: 0);
7308 // Mark this as handled.
7309 SeenChainsForSExt[HeadOfChain] = nullptr;
7310 ValToSExtendedUses[HeadOfChain].push_back(Elt: I);
7311 }
7312 }
7313 return Promoted;
7314}
7315
7316bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
7317 BasicBlock *DefBB = I->getParent();
7318
7319 // If the result of a {s|z}ext and its source are both live out, rewrite all
7320 // other uses of the source with result of extension.
7321 Value *Src = I->getOperand(i: 0);
7322 if (Src->hasOneUse())
7323 return false;
7324
7325 // Only do this xform if truncating is free.
7326 if (!TLI->isTruncateFree(FromTy: I->getType(), ToTy: Src->getType()))
7327 return false;
7328
7329 // Only safe to perform the optimization if the source is also defined in
7330 // this block.
7331 if (!isa<Instruction>(Val: Src) || DefBB != cast<Instruction>(Val: Src)->getParent())
7332 return false;
7333
7334 bool DefIsLiveOut = false;
7335 for (User *U : I->users()) {
7336 Instruction *UI = cast<Instruction>(Val: U);
7337
7338 // Figure out which BB this ext is used in.
7339 BasicBlock *UserBB = UI->getParent();
7340 if (UserBB == DefBB)
7341 continue;
7342 DefIsLiveOut = true;
7343 break;
7344 }
7345 if (!DefIsLiveOut)
7346 return false;
7347
7348 // Make sure none of the uses are PHI nodes.
7349 for (User *U : Src->users()) {
7350 Instruction *UI = cast<Instruction>(Val: U);
7351 BasicBlock *UserBB = UI->getParent();
7352 if (UserBB == DefBB)
7353 continue;
7354 // Be conservative. We don't want this xform to end up introducing
7355 // reloads just before load / store instructions.
7356 if (isa<PHINode>(Val: UI) || isa<LoadInst>(Val: UI) || isa<StoreInst>(Val: UI))
7357 return false;
7358 }
7359
7360 // InsertedTruncs - Only insert one trunc in each block once.
7361 DenseMap<BasicBlock *, Instruction *> InsertedTruncs;
7362
7363 bool MadeChange = false;
7364 for (Use &U : Src->uses()) {
7365 Instruction *User = cast<Instruction>(Val: U.getUser());
7366
7367 // Figure out which BB this ext is used in.
7368 BasicBlock *UserBB = User->getParent();
7369 if (UserBB == DefBB)
7370 continue;
7371
7372 // Both src and def are live in this block. Rewrite the use.
7373 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
7374
7375 if (!InsertedTrunc) {
7376 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
7377 assert(InsertPt != UserBB->end());
7378 InsertedTrunc = new TruncInst(I, Src->getType(), "");
7379 InsertedTrunc->insertBefore(BB&: *UserBB, InsertPos: InsertPt);
7380 InsertedInsts.insert(Ptr: InsertedTrunc);
7381 }
7382
7383 // Replace a use of the {s|z}ext source with a use of the result.
7384 U = InsertedTrunc;
7385 ++NumExtUses;
7386 MadeChange = true;
7387 }
7388
7389 return MadeChange;
7390}
7391
7392// Find loads whose uses only use some of the loaded value's bits. Add an "and"
7393// just after the load if the target can fold this into one extload instruction,
7394// with the hope of eliminating some of the other later "and" instructions using
7395// the loaded value. "and"s that are made trivially redundant by the insertion
7396// of the new "and" are removed by this function, while others (e.g. those whose
7397// path from the load goes through a phi) are left for isel to potentially
7398// remove.
7399//
7400// For example:
7401//
7402// b0:
7403// x = load i32
7404// ...
7405// b1:
7406// y = and x, 0xff
7407// z = use y
7408//
7409// becomes:
7410//
7411// b0:
7412// x = load i32
7413// x' = and x, 0xff
7414// ...
7415// b1:
7416// z = use x'
7417//
7418// whereas:
7419//
7420// b0:
7421// x1 = load i32
7422// ...
7423// b1:
7424// x2 = load i32
7425// ...
7426// b2:
7427// x = phi x1, x2
7428// y = and x, 0xff
7429//
7430// becomes (after a call to optimizeLoadExt for each load):
7431//
7432// b0:
7433// x1 = load i32
7434// x1' = and x1, 0xff
7435// ...
7436// b1:
7437// x2 = load i32
7438// x2' = and x2, 0xff
7439// ...
7440// b2:
7441// x = phi x1', x2'
7442// y = and x, 0xff
7443bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
7444 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
7445 return false;
7446
7447 // Skip loads we've already transformed.
7448 if (Load->hasOneUse() &&
7449 InsertedInsts.count(Ptr: cast<Instruction>(Val: *Load->user_begin())))
7450 return false;
7451
7452 // Look at all uses of Load, looking through phis, to determine how many bits
7453 // of the loaded value are needed.
7454 SmallVector<Instruction *, 8> WorkList;
7455 SmallPtrSet<Instruction *, 16> Visited;
7456 SmallVector<Instruction *, 8> AndsToMaybeRemove;
7457 SmallVector<Instruction *, 8> DropFlags;
7458 for (auto *U : Load->users())
7459 WorkList.push_back(Elt: cast<Instruction>(Val: U));
7460
7461 EVT LoadResultVT = TLI->getValueType(DL: *DL, Ty: Load->getType());
7462 unsigned BitWidth = LoadResultVT.getSizeInBits();
7463 // If the BitWidth is 0, do not try to optimize the type
7464 if (BitWidth == 0)
7465 return false;
7466
7467 APInt DemandBits(BitWidth, 0);
7468 APInt WidestAndBits(BitWidth, 0);
7469
7470 while (!WorkList.empty()) {
7471 Instruction *I = WorkList.pop_back_val();
7472
7473 // Break use-def graph loops.
7474 if (!Visited.insert(Ptr: I).second)
7475 continue;
7476
7477 // For a PHI node, push all of its users.
7478 if (auto *Phi = dyn_cast<PHINode>(Val: I)) {
7479 for (auto *U : Phi->users())
7480 WorkList.push_back(Elt: cast<Instruction>(Val: U));
7481 continue;
7482 }
7483
7484 switch (I->getOpcode()) {
7485 case Instruction::And: {
7486 auto *AndC = dyn_cast<ConstantInt>(Val: I->getOperand(i: 1));
7487 if (!AndC)
7488 return false;
7489 APInt AndBits = AndC->getValue();
7490 DemandBits |= AndBits;
7491 // Keep track of the widest and mask we see.
7492 if (AndBits.ugt(RHS: WidestAndBits))
7493 WidestAndBits = AndBits;
7494 if (AndBits == WidestAndBits && I->getOperand(i: 0) == Load)
7495 AndsToMaybeRemove.push_back(Elt: I);
7496 break;
7497 }
7498
7499 case Instruction::Shl: {
7500 auto *ShlC = dyn_cast<ConstantInt>(Val: I->getOperand(i: 1));
7501 if (!ShlC)
7502 return false;
7503 uint64_t ShiftAmt = ShlC->getLimitedValue(Limit: BitWidth - 1);
7504 DemandBits.setLowBits(BitWidth - ShiftAmt);
7505 DropFlags.push_back(Elt: I);
7506 break;
7507 }
7508
7509 case Instruction::Trunc: {
7510 EVT TruncVT = TLI->getValueType(DL: *DL, Ty: I->getType());
7511 unsigned TruncBitWidth = TruncVT.getSizeInBits();
7512 DemandBits.setLowBits(TruncBitWidth);
7513 DropFlags.push_back(Elt: I);
7514 break;
7515 }
7516
7517 default:
7518 return false;
7519 }
7520 }
7521
7522 uint32_t ActiveBits = DemandBits.getActiveBits();
7523 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
7524 // target even if isLoadLegal says an i1 EXTLOAD is valid. For example,
7525 // for the AArch64 target isLoadLegal(i32, i1, ..., ZEXTLOAD, false) returns
7526 // true, but (and (load x) 1) is not matched as a single instruction, rather
7527 // as a LDR followed by an AND.
7528 // TODO: Look into removing this restriction by fixing backends to either
7529 // return false for isLoadLegal for i1 or have them select this pattern to
7530 // a single instruction.
7531 //
7532 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
7533 // mask, since these are the only ands that will be removed by isel.
7534 if (ActiveBits <= 1 || !DemandBits.isMask(numBits: ActiveBits) ||
7535 WidestAndBits != DemandBits)
7536 return false;
7537
7538 LLVMContext &Ctx = Load->getType()->getContext();
7539 Type *TruncTy = Type::getIntNTy(C&: Ctx, N: ActiveBits);
7540 EVT TruncVT = TLI->getValueType(DL: *DL, Ty: TruncTy);
7541
7542 // Reject cases that won't be matched as extloads.
7543 if (!LoadResultVT.bitsGT(VT: TruncVT) || !TruncVT.isRound() ||
7544 !TLI->isLoadLegal(ValVT: LoadResultVT, MemVT: TruncVT, Alignment: Load->getAlign(),
7545 AddrSpace: Load->getPointerAddressSpace(), ExtType: ISD::ZEXTLOAD, Atomic: false))
7546 return false;
7547
7548 IRBuilder<> Builder(Load->getNextNode());
7549 auto *NewAnd = cast<Instruction>(
7550 Val: Builder.CreateAnd(LHS: Load, RHS: ConstantInt::get(Context&: Ctx, V: DemandBits)));
7551 // Mark this instruction as "inserted by CGP", so that other
7552 // optimizations don't touch it.
7553 InsertedInsts.insert(Ptr: NewAnd);
7554
7555 // Replace all uses of load with new and (except for the use of load in the
7556 // new and itself).
7557 replaceAllUsesWith(Old: Load, New: NewAnd, FreshBBs, IsHuge: IsHugeFunc);
7558 NewAnd->setOperand(i: 0, Val: Load);
7559
7560 // Remove any and instructions that are now redundant.
7561 for (auto *And : AndsToMaybeRemove)
7562 // Check that the and mask is the same as the one we decided to put on the
7563 // new and.
7564 if (cast<ConstantInt>(Val: And->getOperand(i: 1))->getValue() == DemandBits) {
7565 replaceAllUsesWith(Old: And, New: NewAnd, FreshBBs, IsHuge: IsHugeFunc);
7566 if (&*CurInstIterator == And)
7567 CurInstIterator = std::next(x: And->getIterator());
7568 And->eraseFromParent();
7569 ++NumAndUses;
7570 }
7571
7572 // NSW flags may not longer hold.
7573 for (auto *Inst : DropFlags)
7574 Inst->setHasNoSignedWrap(false);
7575
7576 ++NumAndsAdded;
7577 return true;
7578}
7579
7580/// Check if V (an operand of a select instruction) is an expensive instruction
7581/// that is only used once.
7582static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
7583 auto *I = dyn_cast<Instruction>(Val: V);
7584 // If it's safe to speculatively execute, then it should not have side
7585 // effects; therefore, it's safe to sink and possibly *not* execute.
7586 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
7587 TTI->isExpensiveToSpeculativelyExecute(I);
7588}
7589
7590/// Returns true if a SelectInst should be turned into an explicit branch.
7591static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
7592 const TargetLowering *TLI,
7593 SelectInst *SI) {
7594 // If even a predictable select is cheap, then a branch can't be cheaper.
7595 if (!TLI->isPredictableSelectExpensive())
7596 return false;
7597
7598 // FIXME: This should use the same heuristics as IfConversion to determine
7599 // whether a select is better represented as a branch.
7600
7601 // If metadata tells us that the select condition is obviously predictable,
7602 // then we want to replace the select with a branch.
7603 uint64_t TrueWeight, FalseWeight;
7604 if (extractBranchWeights(I: *SI, TrueVal&: TrueWeight, FalseVal&: FalseWeight)) {
7605 uint64_t Max = std::max(a: TrueWeight, b: FalseWeight);
7606 uint64_t Sum = TrueWeight + FalseWeight;
7607 if (Sum != 0) {
7608 auto Probability = BranchProbability::getBranchProbability(Numerator: Max, Denominator: Sum);
7609 if (Probability > TTI->getPredictableBranchThreshold())
7610 return true;
7611 }
7612 }
7613
7614 CmpInst *Cmp = dyn_cast<CmpInst>(Val: SI->getCondition());
7615
7616 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
7617 // comparison condition. If the compare has more than one use, there's
7618 // probably another cmov or setcc around, so it's not worth emitting a branch.
7619 if (!Cmp || !Cmp->hasOneUse())
7620 return false;
7621
7622 // If either operand of the select is expensive and only needed on one side
7623 // of the select, we should form a branch.
7624 if (sinkSelectOperand(TTI, V: SI->getTrueValue()) ||
7625 sinkSelectOperand(TTI, V: SI->getFalseValue()))
7626 return true;
7627
7628 return false;
7629}
7630
7631/// If \p isTrue is true, return the true value of \p SI, otherwise return
7632/// false value of \p SI. If the true/false value of \p SI is defined by any
7633/// select instructions in \p Selects, look through the defining select
7634/// instruction until the true/false value is not defined in \p Selects.
7635static Value *
7636getTrueOrFalseValue(SelectInst *SI, bool isTrue,
7637 const SmallPtrSet<const Instruction *, 2> &Selects) {
7638 Value *V = nullptr;
7639
7640 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(Ptr: DefSI);
7641 DefSI = dyn_cast<SelectInst>(Val: V)) {
7642 assert(DefSI->getCondition() == SI->getCondition() &&
7643 "The condition of DefSI does not match with SI");
7644 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
7645 }
7646
7647 assert(V && "Failed to get select true/false value");
7648 return V;
7649}
7650
7651bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
7652 assert(Shift->isShift() && "Expected a shift");
7653
7654 // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
7655 // general vector shifts, and (3) the shift amount is a select-of-splatted
7656 // values, hoist the shifts before the select:
7657 // shift Op0, (select Cond, TVal, FVal) -->
7658 // select Cond, (shift Op0, TVal), (shift Op0, FVal)
7659 //
7660 // This is inverting a generic IR transform when we know that the cost of a
7661 // general vector shift is more than the cost of 2 shift-by-scalars.
7662 // We can't do this effectively in SDAG because we may not be able to
7663 // determine if the select operands are splats from within a basic block.
7664 Type *Ty = Shift->getType();
7665 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7666 return false;
7667 Value *Cond, *TVal, *FVal;
7668 if (!match(V: Shift->getOperand(i_nocapture: 1),
7669 P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TVal), R: m_Value(V&: FVal)))))
7670 return false;
7671 if (!isSplatValue(V: TVal) || !isSplatValue(V: FVal))
7672 return false;
7673
7674 IRBuilder<> Builder(Shift);
7675 BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
7676 Value *NewTVal = Builder.CreateBinOp(Opc: Opcode, LHS: Shift->getOperand(i_nocapture: 0), RHS: TVal);
7677 Value *NewFVal = Builder.CreateBinOp(Opc: Opcode, LHS: Shift->getOperand(i_nocapture: 0), RHS: FVal);
7678 Value *NewSel = Builder.CreateSelect(C: Cond, True: NewTVal, False: NewFVal);
7679 replaceAllUsesWith(Old: Shift, New: NewSel, FreshBBs, IsHuge: IsHugeFunc);
7680 Shift->eraseFromParent();
7681 return true;
7682}
7683
7684bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
7685 Intrinsic::ID Opcode = Fsh->getIntrinsicID();
7686 assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&
7687 "Expected a funnel shift");
7688
7689 // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper
7690 // than general vector shifts, and (3) the shift amount is select-of-splatted
7691 // values, hoist the funnel shifts before the select:
7692 // fsh Op0, Op1, (select Cond, TVal, FVal) -->
7693 // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal)
7694 //
7695 // This is inverting a generic IR transform when we know that the cost of a
7696 // general vector shift is more than the cost of 2 shift-by-scalars.
7697 // We can't do this effectively in SDAG because we may not be able to
7698 // determine if the select operands are splats from within a basic block.
7699 Type *Ty = Fsh->getType();
7700 if (!Ty->isVectorTy() || !TTI->isVectorShiftByScalarCheap(Ty))
7701 return false;
7702 Value *Cond, *TVal, *FVal;
7703 if (!match(V: Fsh->getOperand(i_nocapture: 2),
7704 P: m_OneUse(SubPattern: m_Select(C: m_Value(V&: Cond), L: m_Value(V&: TVal), R: m_Value(V&: FVal)))))
7705 return false;
7706 if (!isSplatValue(V: TVal) || !isSplatValue(V: FVal))
7707 return false;
7708
7709 IRBuilder<> Builder(Fsh);
7710 Value *X = Fsh->getOperand(i_nocapture: 0), *Y = Fsh->getOperand(i_nocapture: 1);
7711 Value *NewTVal = Builder.CreateIntrinsic(ID: Opcode, OverloadTypes: Ty, Args: {X, Y, TVal});
7712 Value *NewFVal = Builder.CreateIntrinsic(ID: Opcode, OverloadTypes: Ty, Args: {X, Y, FVal});
7713 Value *NewSel = Builder.CreateSelect(C: Cond, True: NewTVal, False: NewFVal);
7714 replaceAllUsesWith(Old: Fsh, New: NewSel, FreshBBs, IsHuge: IsHugeFunc);
7715 Fsh->eraseFromParent();
7716 return true;
7717}
7718
7719/// If we have a SelectInst that will likely profit from branch prediction,
7720/// turn it into a branch.
7721bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
7722 if (DisableSelectToBranch)
7723 return false;
7724
7725 // If the SelectOptimize pass is enabled, selects have already been optimized.
7726 if (!getCGPassBuilderOption().DisableSelectOptimize)
7727 return false;
7728
7729 // Find all consecutive select instructions that share the same condition.
7730 SmallVector<SelectInst *, 2> ASI;
7731 ASI.push_back(Elt: SI);
7732 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
7733 It != SI->getParent()->end(); ++It) {
7734 SelectInst *I = dyn_cast<SelectInst>(Val: &*It);
7735 if (I && SI->getCondition() == I->getCondition()) {
7736 ASI.push_back(Elt: I);
7737 } else {
7738 break;
7739 }
7740 }
7741
7742 SelectInst *LastSI = ASI.back();
7743 // Increment the current iterator to skip all the rest of select instructions
7744 // because they will be either "not lowered" or "all lowered" to branch.
7745 CurInstIterator = std::next(x: LastSI->getIterator());
7746 // Examine debug-info attached to the consecutive select instructions. They
7747 // won't be individually optimised by optimizeInst, so we need to perform
7748 // DbgVariableRecord maintenence here instead.
7749 for (SelectInst *SI : ArrayRef(ASI).drop_front())
7750 fixupDbgVariableRecordsOnInst(I&: *SI);
7751
7752 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(BitWidth: 1);
7753
7754 // Can we convert the 'select' to CF ?
7755 if (VectorCond || SI->getMetadata(KindID: LLVMContext::MD_unpredictable))
7756 return false;
7757
7758 TargetLowering::SelectSupportKind SelectKind;
7759 if (SI->getType()->isVectorTy())
7760 SelectKind = TargetLowering::ScalarCondVectorVal;
7761 else
7762 SelectKind = TargetLowering::ScalarValSelect;
7763
7764 if (TLI->isSelectSupported(SelectKind) &&
7765 (!isFormingBranchFromSelectProfitable(TTI, TLI, SI) ||
7766 llvm::shouldOptimizeForSize(BB: SI->getParent(), PSI, BFI)))
7767 return false;
7768
7769 // Transform a sequence like this:
7770 // start:
7771 // %cmp = cmp uge i32 %a, %b
7772 // %sel = select i1 %cmp, i32 %c, i32 %d
7773 //
7774 // Into:
7775 // start:
7776 // %cmp = cmp uge i32 %a, %b
7777 // %cmp.frozen = freeze %cmp
7778 // br i1 %cmp.frozen, label %select.true, label %select.false
7779 // select.true:
7780 // br label %select.end
7781 // select.false:
7782 // br label %select.end
7783 // select.end:
7784 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
7785 //
7786 // %cmp should be frozen, otherwise it may introduce undefined behavior.
7787 // In addition, we may sink instructions that produce %c or %d from
7788 // the entry block into the destination(s) of the new branch.
7789 // If the true or false blocks do not contain a sunken instruction, that
7790 // block and its branch may be optimized away. In that case, one side of the
7791 // first branch will point directly to select.end, and the corresponding PHI
7792 // predecessor block will be the start block.
7793 // The CFG is altered here and we update the DominatorTree and the LoopInfo,
7794 // but we don't set a ModifiedDT flag to avoid restarting the function walk in
7795 // runOnFunction for each select optimized.
7796
7797 // Collect values that go on the true side and the values that go on the false
7798 // side.
7799 SmallVector<Instruction *> TrueInstrs, FalseInstrs;
7800 for (SelectInst *SI : ASI) {
7801 if (Value *V = SI->getTrueValue(); sinkSelectOperand(TTI, V))
7802 TrueInstrs.push_back(Elt: cast<Instruction>(Val: V));
7803 if (Value *V = SI->getFalseValue(); sinkSelectOperand(TTI, V))
7804 FalseInstrs.push_back(Elt: cast<Instruction>(Val: V));
7805 }
7806
7807 // Split the select block, according to how many (if any) values go on each
7808 // side.
7809 BasicBlock *StartBlock = SI->getParent();
7810 BasicBlock::iterator SplitPt = std::next(x: BasicBlock::iterator(LastSI));
7811 // We should split before any debug-info.
7812 SplitPt.setHeadBit(true);
7813
7814 IRBuilder<> IB(SI);
7815 auto *CondFr = IB.CreateFreeze(V: SI->getCondition(), Name: SI->getName() + ".frozen");
7816
7817 BasicBlock *TrueBlock = nullptr;
7818 BasicBlock *FalseBlock = nullptr;
7819 BasicBlock *EndBlock = nullptr;
7820 UncondBrInst *TrueBranch = nullptr;
7821 UncondBrInst *FalseBranch = nullptr;
7822 if (TrueInstrs.size() == 0) {
7823 FalseBranch = cast<UncondBrInst>(
7824 Val: SplitBlockAndInsertIfElse(Cond: CondFr, SplitBefore: SplitPt, Unreachable: false, BranchWeights: nullptr, DTU, LI));
7825 FalseBlock = FalseBranch->getParent();
7826 EndBlock = cast<BasicBlock>(Val: FalseBranch->getOperand(i_nocapture: 0));
7827 } else if (FalseInstrs.size() == 0) {
7828 TrueBranch = cast<UncondBrInst>(
7829 Val: SplitBlockAndInsertIfThen(Cond: CondFr, SplitBefore: SplitPt, Unreachable: false, BranchWeights: nullptr, DTU, LI));
7830 TrueBlock = TrueBranch->getParent();
7831 EndBlock = TrueBranch->getSuccessor();
7832 } else {
7833 Instruction *ThenTerm = nullptr;
7834 Instruction *ElseTerm = nullptr;
7835 SplitBlockAndInsertIfThenElse(Cond: CondFr, SplitBefore: SplitPt, ThenTerm: &ThenTerm, ElseTerm: &ElseTerm,
7836 BranchWeights: nullptr, DTU, LI);
7837 TrueBranch = cast<UncondBrInst>(Val: ThenTerm);
7838 FalseBranch = cast<UncondBrInst>(Val: ElseTerm);
7839 TrueBlock = TrueBranch->getParent();
7840 FalseBlock = FalseBranch->getParent();
7841 EndBlock = TrueBranch->getSuccessor();
7842 }
7843
7844 EndBlock->setName("select.end");
7845 if (TrueBlock)
7846 TrueBlock->setName("select.true.sink");
7847 if (FalseBlock)
7848 FalseBlock->setName(FalseInstrs.size() == 0 ? "select.false"
7849 : "select.false.sink");
7850
7851 if (IsHugeFunc) {
7852 if (TrueBlock)
7853 FreshBBs.insert(Ptr: TrueBlock);
7854 if (FalseBlock)
7855 FreshBBs.insert(Ptr: FalseBlock);
7856 FreshBBs.insert(Ptr: EndBlock);
7857 }
7858
7859 BFI->setBlockFreq(BB: EndBlock, Freq: BFI->getBlockFreq(BB: StartBlock));
7860
7861 static const unsigned MD[] = {
7862 LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
7863 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
7864 StartBlock->getTerminator()->copyMetadata(SrcInst: *SI, WL: MD);
7865
7866 // Sink expensive instructions into the conditional blocks to avoid executing
7867 // them speculatively.
7868 for (Instruction *I : TrueInstrs)
7869 I->moveBefore(InsertPos: TrueBranch->getIterator());
7870 for (Instruction *I : FalseInstrs)
7871 I->moveBefore(InsertPos: FalseBranch->getIterator());
7872
7873 // If we did not create a new block for one of the 'true' or 'false' paths
7874 // of the condition, it means that side of the branch goes to the end block
7875 // directly and the path originates from the start block from the point of
7876 // view of the new PHI.
7877 if (TrueBlock == nullptr)
7878 TrueBlock = StartBlock;
7879 else if (FalseBlock == nullptr)
7880 FalseBlock = StartBlock;
7881
7882 SmallPtrSet<const Instruction *, 2> INS(llvm::from_range, ASI);
7883 // Use reverse iterator because later select may use the value of the
7884 // earlier select, and we need to propagate value through earlier select
7885 // to get the PHI operand.
7886 for (SelectInst *SI : llvm::reverse(C&: ASI)) {
7887 // The select itself is replaced with a PHI Node.
7888 PHINode *PN = PHINode::Create(Ty: SI->getType(), NumReservedValues: 2, NameStr: "");
7889 PN->insertBefore(InsertPos: EndBlock->begin());
7890 PN->takeName(V: SI);
7891 PN->addIncoming(V: getTrueOrFalseValue(SI, isTrue: true, Selects: INS), BB: TrueBlock);
7892 PN->addIncoming(V: getTrueOrFalseValue(SI, isTrue: false, Selects: INS), BB: FalseBlock);
7893 PN->setDebugLoc(SI->getDebugLoc());
7894
7895 replaceAllUsesWith(Old: SI, New: PN, FreshBBs, IsHuge: IsHugeFunc);
7896 SI->eraseFromParent();
7897 INS.erase(Ptr: SI);
7898 ++NumSelectsExpanded;
7899 }
7900
7901 // Instruct OptimizeBlock to skip to the next block.
7902 CurInstIterator = StartBlock->end();
7903 return true;
7904}
7905
7906/// Some targets only accept certain types for splat inputs. For example a VDUP
7907/// in MVE takes a GPR (integer) register, and the instruction that incorporate
7908/// a VDUP (such as a VADD qd, qm, rm) also require a gpr register.
7909bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
7910 // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only
7911 if (!match(V: SVI, P: m_Shuffle(v1: m_InsertElt(Val: m_Undef(), Elt: m_Value(), Idx: m_ZeroInt()),
7912 v2: m_Undef(), mask: m_ZeroMask())))
7913 return false;
7914 Type *NewType = TLI->shouldConvertSplatType(SVI);
7915 if (!NewType)
7916 return false;
7917
7918 auto *SVIVecType = cast<FixedVectorType>(Val: SVI->getType());
7919 assert(!NewType->isVectorTy() && "Expected a scalar type!");
7920 assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&
7921 "Expected a type of the same size!");
7922 auto *NewVecType =
7923 FixedVectorType::get(ElementType: NewType, NumElts: SVIVecType->getNumElements());
7924
7925 // Create a bitcast (shuffle (insert (bitcast(..))))
7926 IRBuilder<> Builder(SVI->getContext());
7927 Builder.SetInsertPoint(SVI);
7928 Value *BC1 = Builder.CreateBitCast(
7929 V: cast<Instruction>(Val: SVI->getOperand(i_nocapture: 0))->getOperand(i: 1), DestTy: NewType);
7930 Value *Shuffle = Builder.CreateVectorSplat(NumElts: NewVecType->getNumElements(), V: BC1);
7931 Value *BC2 = Builder.CreateBitCast(V: Shuffle, DestTy: SVIVecType);
7932
7933 replaceAllUsesWith(Old: SVI, New: BC2, FreshBBs, IsHuge: IsHugeFunc);
7934 RecursivelyDeleteTriviallyDeadInstructions(
7935 V: SVI, TLI: TLInfo, MSSAU: nullptr,
7936 AboutToDeleteCallback: [&](Value *V) { removeAllAssertingVHReferences(V); });
7937
7938 // Also hoist the bitcast up to its operand if it they are not in the same
7939 // block.
7940 if (auto *BCI = dyn_cast<Instruction>(Val: BC1))
7941 if (auto *Op = dyn_cast<Instruction>(Val: BCI->getOperand(i: 0)))
7942 if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Val: Op) &&
7943 !Op->isTerminator() && !Op->isEHPad())
7944 BCI->moveAfter(MovePos: Op);
7945
7946 return true;
7947}
7948
7949bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
7950 // If the operands of I can be folded into a target instruction together with
7951 // I, duplicate and sink them.
7952 SmallVector<Use *, 4> OpsToSink;
7953 if (!TTI->isProfitableToSinkOperands(I, Ops&: OpsToSink))
7954 return false;
7955
7956 // OpsToSink can contain multiple uses in a use chain (e.g.
7957 // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
7958 // uses must come first, so we process the ops in reverse order so as to not
7959 // create invalid IR.
7960 BasicBlock *TargetBB = I->getParent();
7961 bool Changed = false;
7962 SmallVector<Use *, 4> ToReplace;
7963 Instruction *InsertPoint = I;
7964 for (Use *U : reverse(C&: OpsToSink)) {
7965 auto *UI = cast<Instruction>(Val: U->get());
7966 if (isa<PHINode>(Val: UI) || UI->mayHaveSideEffects() || UI->mayReadFromMemory())
7967 continue;
7968 if (UI->getParent() == TargetBB) {
7969 if (UI->comesBefore(Other: InsertPoint))
7970 InsertPoint = UI;
7971 continue;
7972 }
7973 ToReplace.push_back(Elt: U);
7974 }
7975
7976 SetVector<Instruction *> MaybeDead;
7977 DenseMap<Instruction *, Instruction *> NewInstructions;
7978 for (Use *U : ToReplace) {
7979 auto *UI = cast<Instruction>(Val: U->get());
7980 Instruction *NI = UI->clone();
7981
7982 if (IsHugeFunc) {
7983 // Now we clone an instruction, its operands' defs may sink to this BB
7984 // now. So we put the operands defs' BBs into FreshBBs to do optimization.
7985 for (Value *Op : NI->operands())
7986 if (auto *OpDef = dyn_cast<Instruction>(Val: Op))
7987 FreshBBs.insert(Ptr: OpDef->getParent());
7988 }
7989
7990 NewInstructions[UI] = NI;
7991 MaybeDead.insert(X: UI);
7992 LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
7993 NI->insertBefore(InsertPos: InsertPoint->getIterator());
7994 InsertPoint = NI;
7995 InsertedInsts.insert(Ptr: NI);
7996
7997 // Update the use for the new instruction, making sure that we update the
7998 // sunk instruction uses, if it is part of a chain that has already been
7999 // sunk.
8000 Instruction *OldI = cast<Instruction>(Val: U->getUser());
8001 if (auto It = NewInstructions.find(Val: OldI); It != NewInstructions.end())
8002 It->second->setOperand(i: U->getOperandNo(), Val: NI);
8003 else
8004 U->set(NI);
8005 Changed = true;
8006 }
8007
8008 // Remove instructions that are dead after sinking.
8009 for (auto *I : MaybeDead) {
8010 if (!I->hasNUsesOrMore(N: 1)) {
8011 LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
8012 I->eraseFromParent();
8013 }
8014 }
8015
8016 return Changed;
8017}
8018
8019bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
8020 Value *Cond = SI->getCondition();
8021 Type *OldType = Cond->getType();
8022 LLVMContext &Context = Cond->getContext();
8023 EVT OldVT = TLI->getValueType(DL: *DL, Ty: OldType);
8024 MVT RegType = TLI->getPreferredSwitchConditionType(Context, ConditionVT: OldVT);
8025 unsigned RegWidth = RegType.getSizeInBits();
8026
8027 if (RegWidth <= cast<IntegerType>(Val: OldType)->getBitWidth())
8028 return false;
8029
8030 // If the register width is greater than the type width, expand the condition
8031 // of the switch instruction and each case constant to the width of the
8032 // register. By widening the type of the switch condition, subsequent
8033 // comparisons (for case comparisons) will not need to be extended to the
8034 // preferred register width, so we will potentially eliminate N-1 extends,
8035 // where N is the number of cases in the switch.
8036 auto *NewType = Type::getIntNTy(C&: Context, N: RegWidth);
8037
8038 // Extend the switch condition and case constants using the target preferred
8039 // extend unless the switch condition is a function argument with an extend
8040 // attribute. In that case, we can avoid an unnecessary mask/extension by
8041 // matching the argument extension instead.
8042 Instruction::CastOps ExtType = Instruction::ZExt;
8043 // Some targets prefer SExt over ZExt.
8044 if (TLI->isSExtCheaperThanZExt(FromTy: OldVT, ToTy: RegType))
8045 ExtType = Instruction::SExt;
8046
8047 if (auto *Arg = dyn_cast<Argument>(Val: Cond)) {
8048 if (Arg->hasSExtAttr())
8049 ExtType = Instruction::SExt;
8050 if (Arg->hasZExtAttr())
8051 ExtType = Instruction::ZExt;
8052 }
8053
8054 auto *ExtInst = CastInst::Create(ExtType, S: Cond, Ty: NewType);
8055 ExtInst->insertBefore(InsertPos: SI->getIterator());
8056 ExtInst->setDebugLoc(SI->getDebugLoc());
8057 SI->setCondition(ExtInst);
8058 for (auto Case : SI->cases()) {
8059 const APInt &NarrowConst = Case.getCaseValue()->getValue();
8060 APInt WideConst = (ExtType == Instruction::ZExt)
8061 ? NarrowConst.zext(width: RegWidth)
8062 : NarrowConst.sext(width: RegWidth);
8063 Case.setValue(ConstantInt::get(Context, V: WideConst));
8064 }
8065
8066 return true;
8067}
8068
8069bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
8070 // The SCCP optimization tends to produce code like this:
8071 // switch(x) { case 42: phi(42, ...) }
8072 // Materializing the constant for the phi-argument needs instructions; So we
8073 // change the code to:
8074 // switch(x) { case 42: phi(x, ...) }
8075
8076 Value *Condition = SI->getCondition();
8077 // Avoid endless loop in degenerate case.
8078 if (isa<ConstantInt>(Val: *Condition))
8079 return false;
8080
8081 bool Changed = false;
8082 BasicBlock *SwitchBB = SI->getParent();
8083 Type *ConditionType = Condition->getType();
8084
8085 for (const SwitchInst::CaseHandle &Case : SI->cases()) {
8086 ConstantInt *CaseValue = Case.getCaseValue();
8087 BasicBlock *CaseBB = Case.getCaseSuccessor();
8088 // Set to true if we previously checked that `CaseBB` is only reached by
8089 // a single case from this switch.
8090 bool CheckedForSinglePred = false;
8091 for (PHINode &PHI : CaseBB->phis()) {
8092 Type *PHIType = PHI.getType();
8093 // If ZExt is free then we can also catch patterns like this:
8094 // switch((i32)x) { case 42: phi((i64)42, ...); }
8095 // and replace `(i64)42` with `zext i32 %x to i64`.
8096 bool TryZExt =
8097 PHIType->isIntegerTy() &&
8098 PHIType->getIntegerBitWidth() > ConditionType->getIntegerBitWidth() &&
8099 TLI->isZExtFree(FromTy: ConditionType, ToTy: PHIType);
8100 if (PHIType == ConditionType || TryZExt) {
8101 // Set to true to skip this case because of multiple preds.
8102 bool SkipCase = false;
8103 Value *Replacement = nullptr;
8104 for (unsigned I = 0, E = PHI.getNumIncomingValues(); I != E; I++) {
8105 Value *PHIValue = PHI.getIncomingValue(i: I);
8106 if (PHIValue != CaseValue) {
8107 if (!TryZExt)
8108 continue;
8109 ConstantInt *PHIValueInt = dyn_cast<ConstantInt>(Val: PHIValue);
8110 if (!PHIValueInt ||
8111 PHIValueInt->getValue() !=
8112 CaseValue->getValue().zext(width: PHIType->getIntegerBitWidth()))
8113 continue;
8114 }
8115 if (PHI.getIncomingBlock(i: I) != SwitchBB)
8116 continue;
8117 // We cannot optimize if there are multiple case labels jumping to
8118 // this block. This check may get expensive when there are many
8119 // case labels so we test for it last.
8120 if (!CheckedForSinglePred) {
8121 CheckedForSinglePred = true;
8122 if (SI->findCaseDest(BB: CaseBB) == nullptr) {
8123 SkipCase = true;
8124 break;
8125 }
8126 }
8127
8128 if (Replacement == nullptr) {
8129 if (PHIValue == CaseValue) {
8130 Replacement = Condition;
8131 } else {
8132 IRBuilder<> Builder(SI);
8133 Replacement = Builder.CreateZExt(V: Condition, DestTy: PHIType);
8134 }
8135 }
8136 PHI.setIncomingValue(i: I, V: Replacement);
8137 Changed = true;
8138 }
8139 if (SkipCase)
8140 break;
8141 }
8142 }
8143 }
8144 return Changed;
8145}
8146
8147bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
8148 bool Changed = optimizeSwitchType(SI);
8149 Changed |= optimizeSwitchPhiConstants(SI);
8150 return Changed;
8151}
8152
8153namespace {
8154
8155/// Helper class to promote a scalar operation to a vector one.
8156/// This class is used to move downward extractelement transition.
8157/// E.g.,
8158/// a = vector_op <2 x i32>
8159/// b = extractelement <2 x i32> a, i32 0
8160/// c = scalar_op b
8161/// store c
8162///
8163/// =>
8164/// a = vector_op <2 x i32>
8165/// c = vector_op a (equivalent to scalar_op on the related lane)
8166/// * d = extractelement <2 x i32> c, i32 0
8167/// * store d
8168/// Assuming both extractelement and store can be combine, we get rid of the
8169/// transition.
8170class VectorPromoteHelper {
8171 /// DataLayout associated with the current module.
8172 const DataLayout &DL;
8173
8174 /// Used to perform some checks on the legality of vector operations.
8175 const TargetLowering &TLI;
8176
8177 /// Used to estimated the cost of the promoted chain.
8178 const TargetTransformInfo &TTI;
8179
8180 /// The transition being moved downwards.
8181 Instruction *Transition;
8182
8183 /// The sequence of instructions to be promoted.
8184 SmallVector<Instruction *, 4> InstsToBePromoted;
8185
8186 /// Cost of combining a store and an extract.
8187 unsigned StoreExtractCombineCost;
8188
8189 /// Instruction that will be combined with the transition.
8190 Instruction *CombineInst = nullptr;
8191
8192 /// The instruction that represents the current end of the transition.
8193 /// Since we are faking the promotion until we reach the end of the chain
8194 /// of computation, we need a way to get the current end of the transition.
8195 Instruction *getEndOfTransition() const {
8196 if (InstsToBePromoted.empty())
8197 return Transition;
8198 return InstsToBePromoted.back();
8199 }
8200
8201 /// Return the index of the original value in the transition.
8202 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
8203 /// c, is at index 0.
8204 unsigned getTransitionOriginalValueIdx() const {
8205 assert(isa<ExtractElementInst>(Transition) &&
8206 "Other kind of transitions are not supported yet");
8207 return 0;
8208 }
8209
8210 /// Return the index of the index in the transition.
8211 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
8212 /// is at index 1.
8213 unsigned getTransitionIdx() const {
8214 assert(isa<ExtractElementInst>(Transition) &&
8215 "Other kind of transitions are not supported yet");
8216 return 1;
8217 }
8218
8219 /// Get the type of the transition.
8220 /// This is the type of the original value.
8221 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
8222 /// transition is <2 x i32>.
8223 Type *getTransitionType() const {
8224 return Transition->getOperand(i: getTransitionOriginalValueIdx())->getType();
8225 }
8226
8227 /// Promote \p ToBePromoted by moving \p Def downward through.
8228 /// I.e., we have the following sequence:
8229 /// Def = Transition <ty1> a to <ty2>
8230 /// b = ToBePromoted <ty2> Def, ...
8231 /// =>
8232 /// b = ToBePromoted <ty1> a, ...
8233 /// Def = Transition <ty1> ToBePromoted to <ty2>
8234 void promoteImpl(Instruction *ToBePromoted);
8235
8236 /// Check whether or not it is profitable to promote all the
8237 /// instructions enqueued to be promoted.
8238 bool isProfitableToPromote() {
8239 Value *ValIdx = Transition->getOperand(i: getTransitionOriginalValueIdx());
8240 unsigned Index = isa<ConstantInt>(Val: ValIdx)
8241 ? cast<ConstantInt>(Val: ValIdx)->getZExtValue()
8242 : -1;
8243 Type *PromotedType = getTransitionType();
8244
8245 StoreInst *ST = cast<StoreInst>(Val: CombineInst);
8246 unsigned AS = ST->getPointerAddressSpace();
8247 // Check if this store is supported.
8248 if (!TLI.allowsMisalignedMemoryAccesses(
8249 TLI.getValueType(DL, Ty: ST->getValueOperand()->getType()), AddrSpace: AS,
8250 Alignment: ST->getAlign())) {
8251 // If this is not supported, there is no way we can combine
8252 // the extract with the store.
8253 return false;
8254 }
8255
8256 // The scalar chain of computation has to pay for the transition
8257 // scalar to vector.
8258 // The vector chain has to account for the combining cost.
8259 enum TargetTransformInfo::TargetCostKind CostKind =
8260 TargetTransformInfo::TCK_RecipThroughput;
8261 InstructionCost ScalarCost =
8262 TTI.getVectorInstrCost(I: *Transition, Val: PromotedType, CostKind, Index);
8263 InstructionCost VectorCost = StoreExtractCombineCost;
8264 for (const auto &Inst : InstsToBePromoted) {
8265 // Compute the cost.
8266 // By construction, all instructions being promoted are arithmetic ones.
8267 // Moreover, one argument is a constant that can be viewed as a splat
8268 // constant.
8269 Value *Arg0 = Inst->getOperand(i: 0);
8270 bool IsArg0Constant = isa<UndefValue>(Val: Arg0) || isa<ConstantInt>(Val: Arg0) ||
8271 isa<ConstantFP>(Val: Arg0);
8272 TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
8273 if (IsArg0Constant)
8274 Arg0Info.Kind = TargetTransformInfo::OK_UniformConstantValue;
8275 else
8276 Arg1Info.Kind = TargetTransformInfo::OK_UniformConstantValue;
8277
8278 ScalarCost += TTI.getArithmeticInstrCost(
8279 Opcode: Inst->getOpcode(), Ty: Inst->getType(), CostKind, Opd1Info: Arg0Info, Opd2Info: Arg1Info);
8280 VectorCost += TTI.getArithmeticInstrCost(Opcode: Inst->getOpcode(), Ty: PromotedType,
8281 CostKind, Opd1Info: Arg0Info, Opd2Info: Arg1Info);
8282 }
8283 LLVM_DEBUG(
8284 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
8285 << ScalarCost << "\nVector: " << VectorCost << '\n');
8286 return ScalarCost > VectorCost;
8287 }
8288
8289 /// Generate a constant vector with \p Val with the same
8290 /// number of elements as the transition.
8291 /// \p UseSplat defines whether or not \p Val should be replicated
8292 /// across the whole vector.
8293 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
8294 /// otherwise we generate a vector with as many poison as possible:
8295 /// <poison, ..., poison, Val, poison, ..., poison> where \p Val is only
8296 /// used at the index of the extract.
8297 Value *getConstantVector(Constant *Val, bool UseSplat) const {
8298 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
8299 if (!UseSplat) {
8300 // If we cannot determine where the constant must be, we have to
8301 // use a splat constant.
8302 Value *ValExtractIdx = Transition->getOperand(i: getTransitionIdx());
8303 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(Val: ValExtractIdx))
8304 ExtractIdx = CstVal->getSExtValue();
8305 else
8306 UseSplat = true;
8307 }
8308
8309 ElementCount EC = cast<VectorType>(Val: getTransitionType())->getElementCount();
8310 if (UseSplat)
8311 return ConstantVector::getSplat(EC, Elt: Val);
8312
8313 if (!EC.isScalable()) {
8314 SmallVector<Constant *, 4> ConstVec;
8315 PoisonValue *PoisonVal = PoisonValue::get(T: Val->getType());
8316 for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) {
8317 if (Idx == ExtractIdx)
8318 ConstVec.push_back(Elt: Val);
8319 else
8320 ConstVec.push_back(Elt: PoisonVal);
8321 }
8322 return ConstantVector::get(V: ConstVec);
8323 } else
8324 llvm_unreachable(
8325 "Generate scalable vector for non-splat is unimplemented");
8326 }
8327
8328 /// Check if promoting to a vector type an operand at \p OperandIdx
8329 /// in \p Use can trigger undefined behavior.
8330 static bool canCauseUndefinedBehavior(const Instruction *Use,
8331 unsigned OperandIdx) {
8332 // This is not safe to introduce undef when the operand is on
8333 // the right hand side of a division-like instruction.
8334 if (OperandIdx != 1)
8335 return false;
8336 switch (Use->getOpcode()) {
8337 default:
8338 return false;
8339 case Instruction::SDiv:
8340 case Instruction::UDiv:
8341 case Instruction::SRem:
8342 case Instruction::URem:
8343 return true;
8344 case Instruction::FDiv:
8345 case Instruction::FRem:
8346 return !Use->hasNoNaNs();
8347 }
8348 llvm_unreachable(nullptr);
8349 }
8350
8351public:
8352 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
8353 const TargetTransformInfo &TTI, Instruction *Transition,
8354 unsigned CombineCost)
8355 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
8356 StoreExtractCombineCost(CombineCost) {
8357 assert(Transition && "Do not know how to promote null");
8358 }
8359
8360 /// Check if we can promote \p ToBePromoted to \p Type.
8361 bool canPromote(const Instruction *ToBePromoted) const {
8362 // We could support CastInst too.
8363 return isa<BinaryOperator>(Val: ToBePromoted);
8364 }
8365
8366 /// Check if it is profitable to promote \p ToBePromoted
8367 /// by moving downward the transition through.
8368 bool shouldPromote(const Instruction *ToBePromoted) const {
8369 // Promote only if all the operands can be statically expanded.
8370 // Indeed, we do not want to introduce any new kind of transitions.
8371 for (const Use &U : ToBePromoted->operands()) {
8372 const Value *Val = U.get();
8373 if (Val == getEndOfTransition()) {
8374 // If the use is a division and the transition is on the rhs,
8375 // we cannot promote the operation, otherwise we may create a
8376 // division by zero.
8377 if (canCauseUndefinedBehavior(Use: ToBePromoted, OperandIdx: U.getOperandNo()))
8378 return false;
8379 continue;
8380 }
8381 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
8382 !isa<ConstantFP>(Val))
8383 return false;
8384 }
8385 // Check that the resulting operation is legal.
8386 int ISDOpcode = TLI.InstructionOpcodeToISD(Opcode: ToBePromoted->getOpcode());
8387 if (!ISDOpcode)
8388 return false;
8389 return StressStoreExtract ||
8390 TLI.isOperationLegalOrCustom(
8391 Op: ISDOpcode, VT: TLI.getValueType(DL, Ty: getTransitionType(), AllowUnknown: true));
8392 }
8393
8394 /// Check whether or not \p Use can be combined
8395 /// with the transition.
8396 /// I.e., is it possible to do Use(Transition) => AnotherUse?
8397 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Val: Use); }
8398
8399 /// Record \p ToBePromoted as part of the chain to be promoted.
8400 void enqueueForPromotion(Instruction *ToBePromoted) {
8401 InstsToBePromoted.push_back(Elt: ToBePromoted);
8402 }
8403
8404 /// Set the instruction that will be combined with the transition.
8405 void recordCombineInstruction(Instruction *ToBeCombined) {
8406 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
8407 CombineInst = ToBeCombined;
8408 }
8409
8410 /// Promote all the instructions enqueued for promotion if it is
8411 /// is profitable.
8412 /// \return True if the promotion happened, false otherwise.
8413 bool promote() {
8414 // Check if there is something to promote.
8415 // Right now, if we do not have anything to combine with,
8416 // we assume the promotion is not profitable.
8417 if (InstsToBePromoted.empty() || !CombineInst)
8418 return false;
8419
8420 // Check cost.
8421 if (!StressStoreExtract && !isProfitableToPromote())
8422 return false;
8423
8424 // Promote.
8425 for (auto &ToBePromoted : InstsToBePromoted)
8426 promoteImpl(ToBePromoted);
8427 InstsToBePromoted.clear();
8428 return true;
8429 }
8430};
8431
8432} // end anonymous namespace
8433
8434void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
8435 // At this point, we know that all the operands of ToBePromoted but Def
8436 // can be statically promoted.
8437 // For Def, we need to use its parameter in ToBePromoted:
8438 // b = ToBePromoted ty1 a
8439 // Def = Transition ty1 b to ty2
8440 // Move the transition down.
8441 // 1. Replace all uses of the promoted operation by the transition.
8442 // = ... b => = ... Def.
8443 assert(ToBePromoted->getType() == Transition->getType() &&
8444 "The type of the result of the transition does not match "
8445 "the final type");
8446 ToBePromoted->replaceAllUsesWith(V: Transition);
8447 // 2. Update the type of the uses.
8448 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
8449 Type *TransitionTy = getTransitionType();
8450 ToBePromoted->mutateType(Ty: TransitionTy);
8451 // 3. Update all the operands of the promoted operation with promoted
8452 // operands.
8453 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
8454 for (Use &U : ToBePromoted->operands()) {
8455 Value *Val = U.get();
8456 Value *NewVal = nullptr;
8457 if (Val == Transition)
8458 NewVal = Transition->getOperand(i: getTransitionOriginalValueIdx());
8459 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
8460 isa<ConstantFP>(Val)) {
8461 // Use a splat constant if it is not safe to use undef.
8462 NewVal = getConstantVector(
8463 Val: cast<Constant>(Val),
8464 UseSplat: isa<UndefValue>(Val) ||
8465 canCauseUndefinedBehavior(Use: ToBePromoted, OperandIdx: U.getOperandNo()));
8466 } else
8467 llvm_unreachable("Did you modified shouldPromote and forgot to update "
8468 "this?");
8469 ToBePromoted->setOperand(i: U.getOperandNo(), Val: NewVal);
8470 }
8471 Transition->moveAfter(MovePos: ToBePromoted);
8472 Transition->setOperand(i: getTransitionOriginalValueIdx(), Val: ToBePromoted);
8473}
8474
8475/// Some targets can do store(extractelement) with one instruction.
8476/// Try to push the extractelement towards the stores when the target
8477/// has this feature and this is profitable.
8478bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
8479 unsigned CombineCost = std::numeric_limits<unsigned>::max();
8480 if (DisableStoreExtract ||
8481 (!StressStoreExtract &&
8482 !TLI->canCombineStoreAndExtract(VectorTy: Inst->getOperand(i: 0)->getType(),
8483 Idx: Inst->getOperand(i: 1), Cost&: CombineCost)))
8484 return false;
8485
8486 // At this point we know that Inst is a vector to scalar transition.
8487 // Try to move it down the def-use chain, until:
8488 // - We can combine the transition with its single use
8489 // => we got rid of the transition.
8490 // - We escape the current basic block
8491 // => we would need to check that we are moving it at a cheaper place and
8492 // we do not do that for now.
8493 BasicBlock *Parent = Inst->getParent();
8494 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
8495 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
8496 // If the transition has more than one use, assume this is not going to be
8497 // beneficial.
8498 while (Inst->hasOneUse()) {
8499 Instruction *ToBePromoted = cast<Instruction>(Val: *Inst->user_begin());
8500 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
8501
8502 if (ToBePromoted->getParent() != Parent) {
8503 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
8504 << ToBePromoted->getParent()->getName()
8505 << ") than the transition (" << Parent->getName()
8506 << ").\n");
8507 return false;
8508 }
8509
8510 if (VPH.canCombine(Use: ToBePromoted)) {
8511 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
8512 << "will be combined with: " << *ToBePromoted << '\n');
8513 VPH.recordCombineInstruction(ToBeCombined: ToBePromoted);
8514 bool Changed = VPH.promote();
8515 NumStoreExtractExposed += Changed;
8516 return Changed;
8517 }
8518
8519 LLVM_DEBUG(dbgs() << "Try promoting.\n");
8520 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
8521 return false;
8522
8523 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
8524
8525 VPH.enqueueForPromotion(ToBePromoted);
8526 Inst = ToBePromoted;
8527 }
8528 return false;
8529}
8530
8531/// For the instruction sequence of store below, F and I values
8532/// are bundled together as an i64 value before being stored into memory.
8533/// Sometimes it is more efficient to generate separate stores for F and I,
8534/// which can remove the bitwise instructions or sink them to colder places.
8535///
8536/// (store (or (zext (bitcast F to i32) to i64),
8537/// (shl (zext I to i64), 32)), addr) -->
8538/// (store F, addr) and (store I, addr+4)
8539///
8540/// Similarly, splitting for other merged store can also be beneficial, like:
8541/// For pair of {i32, i32}, i64 store --> two i32 stores.
8542/// For pair of {i32, i16}, i64 store --> two i32 stores.
8543/// For pair of {i16, i16}, i32 store --> two i16 stores.
8544/// For pair of {i16, i8}, i32 store --> two i16 stores.
8545/// For pair of {i8, i8}, i16 store --> two i8 stores.
8546///
8547/// We allow each target to determine specifically which kind of splitting is
8548/// supported.
8549///
8550/// The store patterns are commonly seen from the simple code snippet below
8551/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
8552/// void goo(const std::pair<int, float> &);
8553/// hoo() {
8554/// ...
8555/// goo(std::make_pair(tmp, ftmp));
8556/// ...
8557/// }
8558///
8559/// Although we already have similar splitting in DAG Combine, we duplicate
8560/// it in CodeGenPrepare to catch the case in which pattern is across
8561/// multiple BBs. The logic in DAG Combine is kept to catch case generated
8562/// during code expansion.
8563static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
8564 const TargetLowering &TLI) {
8565 // Handle simple but common cases only.
8566 Type *StoreType = SI.getValueOperand()->getType();
8567
8568 // The code below assumes shifting a value by <number of bits>,
8569 // whereas scalable vectors would have to be shifted by
8570 // <2log(vscale) + number of bits> in order to store the
8571 // low/high parts. Bailing out for now.
8572 if (StoreType->isScalableTy())
8573 return false;
8574
8575 if (!DL.typeSizeEqualsStoreSize(Ty: StoreType) ||
8576 DL.getTypeSizeInBits(Ty: StoreType) == 0)
8577 return false;
8578
8579 unsigned HalfValBitSize = DL.getTypeSizeInBits(Ty: StoreType) / 2;
8580 Type *SplitStoreType = Type::getIntNTy(C&: SI.getContext(), N: HalfValBitSize);
8581 if (!DL.typeSizeEqualsStoreSize(Ty: SplitStoreType))
8582 return false;
8583
8584 // Don't split the store if it is volatile or atomic.
8585 if (!SI.isSimple())
8586 return false;
8587
8588 // Match the following patterns:
8589 // (store (or (zext LValue to i64),
8590 // (shl (zext HValue to i64), 32)), HalfValBitSize)
8591 // or
8592 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
8593 // (zext LValue to i64),
8594 // Expect both operands of OR and the first operand of SHL have only
8595 // one use.
8596 Value *LValue, *HValue;
8597 if (!match(V: SI.getValueOperand(),
8598 P: m_c_Or(L: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: LValue))),
8599 R: m_OneUse(SubPattern: m_Shl(L: m_OneUse(SubPattern: m_ZExt(Op: m_Value(V&: HValue))),
8600 R: m_SpecificInt(V: HalfValBitSize))))))
8601 return false;
8602
8603 // Check LValue and HValue are int with size less or equal than 32.
8604 if (!LValue->getType()->isIntegerTy() ||
8605 DL.getTypeSizeInBits(Ty: LValue->getType()) > HalfValBitSize ||
8606 !HValue->getType()->isIntegerTy() ||
8607 DL.getTypeSizeInBits(Ty: HValue->getType()) > HalfValBitSize)
8608 return false;
8609
8610 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
8611 // as the input of target query.
8612 auto *LBC = dyn_cast<BitCastInst>(Val: LValue);
8613 auto *HBC = dyn_cast<BitCastInst>(Val: HValue);
8614 EVT LowTy = LBC ? EVT::getEVT(Ty: LBC->getOperand(i_nocapture: 0)->getType())
8615 : EVT::getEVT(Ty: LValue->getType());
8616 EVT HighTy = HBC ? EVT::getEVT(Ty: HBC->getOperand(i_nocapture: 0)->getType())
8617 : EVT::getEVT(Ty: HValue->getType());
8618 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LTy: LowTy, HTy: HighTy))
8619 return false;
8620
8621 // Start to split store.
8622 IRBuilder<> Builder(SI.getContext());
8623 Builder.SetInsertPoint(&SI);
8624
8625 // If LValue/HValue is a bitcast in another BB, create a new one in current
8626 // BB so it may be merged with the splitted stores by dag combiner.
8627 if (LBC && LBC->getParent() != SI.getParent())
8628 LValue = Builder.CreateBitCast(V: LBC->getOperand(i_nocapture: 0), DestTy: LBC->getType());
8629 if (HBC && HBC->getParent() != SI.getParent())
8630 HValue = Builder.CreateBitCast(V: HBC->getOperand(i_nocapture: 0), DestTy: HBC->getType());
8631
8632 bool IsLE = SI.getDataLayout().isLittleEndian();
8633 auto CreateSplitStore = [&](Value *V, bool Upper) {
8634 V = Builder.CreateZExtOrBitCast(V, DestTy: SplitStoreType);
8635 Value *Addr = SI.getPointerOperand();
8636 Align Alignment = SI.getAlign();
8637 const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper);
8638 if (IsOffsetStore) {
8639 Addr = Builder.CreateGEP(
8640 Ty: SplitStoreType, Ptr: Addr,
8641 IdxList: ConstantInt::get(Ty: Type::getInt32Ty(C&: SI.getContext()), V: 1));
8642
8643 // When splitting the store in half, naturally one half will retain the
8644 // alignment of the original wider store, regardless of whether it was
8645 // over-aligned or not, while the other will require adjustment.
8646 Alignment = commonAlignment(A: Alignment, Offset: HalfValBitSize / 8);
8647 }
8648 Builder.CreateAlignedStore(Val: V, Ptr: Addr, Align: Alignment);
8649 };
8650
8651 CreateSplitStore(LValue, false);
8652 CreateSplitStore(HValue, true);
8653
8654 // Delete the old store.
8655 SI.eraseFromParent();
8656 return true;
8657}
8658
8659// Return true if the GEP has two operands, the first operand is of a sequential
8660// type, and the second operand is a constant.
8661static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
8662 gep_type_iterator I = gep_type_begin(GEP: *GEP);
8663 return GEP->getNumOperands() == 2 && I.isSequential() &&
8664 isa<ConstantInt>(Val: GEP->getOperand(i_nocapture: 1));
8665}
8666
8667// Try unmerging GEPs to reduce liveness interference (register pressure) across
8668// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
8669// reducing liveness interference across those edges benefits global register
8670// allocation. Currently handles only certain cases.
8671//
8672// For example, unmerge %GEPI and %UGEPI as below.
8673//
8674// ---------- BEFORE ----------
8675// SrcBlock:
8676// ...
8677// %GEPIOp = ...
8678// ...
8679// %GEPI = gep %GEPIOp, Idx
8680// ...
8681// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
8682// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
8683// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
8684// %UGEPI)
8685//
8686// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
8687// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
8688// ...
8689//
8690// DstBi:
8691// ...
8692// %UGEPI = gep %GEPIOp, UIdx
8693// ...
8694// ---------------------------
8695//
8696// ---------- AFTER ----------
8697// SrcBlock:
8698// ... (same as above)
8699// (* %GEPI is still alive on the indirectbr edges)
8700// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
8701// unmerging)
8702// ...
8703//
8704// DstBi:
8705// ...
8706// %UGEPI = gep %GEPI, (UIdx-Idx)
8707// ...
8708// ---------------------------
8709//
8710// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
8711// no longer alive on them.
8712//
8713// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
8714// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
8715// not to disable further simplications and optimizations as a result of GEP
8716// merging.
8717//
8718// Note this unmerging may increase the length of the data flow critical path
8719// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
8720// between the register pressure and the length of data-flow critical
8721// path. Restricting this to the uncommon IndirectBr case would minimize the
8722// impact of potentially longer critical path, if any, and the impact on compile
8723// time.
8724static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
8725 const TargetTransformInfo *TTI) {
8726 BasicBlock *SrcBlock = GEPI->getParent();
8727 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
8728 // (non-IndirectBr) cases exit early here.
8729 if (!isa<IndirectBrInst>(Val: SrcBlock->getTerminator()))
8730 return false;
8731 // Check that GEPI is a simple gep with a single constant index.
8732 if (!GEPSequentialConstIndexed(GEP: GEPI))
8733 return false;
8734 ConstantInt *GEPIIdx = cast<ConstantInt>(Val: GEPI->getOperand(i_nocapture: 1));
8735 // Check that GEPI is a cheap one.
8736 if (TTI->getIntImmCost(Imm: GEPIIdx->getValue(), Ty: GEPIIdx->getType(),
8737 CostKind: TargetTransformInfo::TCK_SizeAndLatency) >
8738 TargetTransformInfo::TCC_Basic)
8739 return false;
8740 Value *GEPIOp = GEPI->getOperand(i_nocapture: 0);
8741 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
8742 if (!isa<Instruction>(Val: GEPIOp))
8743 return false;
8744 auto *GEPIOpI = cast<Instruction>(Val: GEPIOp);
8745 if (GEPIOpI->getParent() != SrcBlock)
8746 return false;
8747 // Check that GEP is used outside the block, meaning it's alive on the
8748 // IndirectBr edge(s).
8749 if (llvm::none_of(Range: GEPI->users(), P: [&](User *Usr) {
8750 if (auto *I = dyn_cast<Instruction>(Val: Usr)) {
8751 if (I->getParent() != SrcBlock) {
8752 return true;
8753 }
8754 }
8755 return false;
8756 }))
8757 return false;
8758 // The second elements of the GEP chains to be unmerged.
8759 std::vector<GetElementPtrInst *> UGEPIs;
8760 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
8761 // on IndirectBr edges.
8762 for (User *Usr : GEPIOp->users()) {
8763 if (Usr == GEPI)
8764 continue;
8765 // Check if Usr is an Instruction. If not, give up.
8766 if (!isa<Instruction>(Val: Usr))
8767 return false;
8768 auto *UI = cast<Instruction>(Val: Usr);
8769 // Check if Usr in the same block as GEPIOp, which is fine, skip.
8770 if (UI->getParent() == SrcBlock)
8771 continue;
8772 // Check if Usr is a GEP. If not, give up.
8773 if (!isa<GetElementPtrInst>(Val: Usr))
8774 return false;
8775 auto *UGEPI = cast<GetElementPtrInst>(Val: Usr);
8776 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
8777 // the pointer operand to it. If so, record it in the vector. If not, give
8778 // up.
8779 if (!GEPSequentialConstIndexed(GEP: UGEPI))
8780 return false;
8781 if (UGEPI->getOperand(i_nocapture: 0) != GEPIOp)
8782 return false;
8783 if (UGEPI->getSourceElementType() != GEPI->getSourceElementType())
8784 return false;
8785 if (GEPIIdx->getType() !=
8786 cast<ConstantInt>(Val: UGEPI->getOperand(i_nocapture: 1))->getType())
8787 return false;
8788 ConstantInt *UGEPIIdx = cast<ConstantInt>(Val: UGEPI->getOperand(i_nocapture: 1));
8789 if (TTI->getIntImmCost(Imm: UGEPIIdx->getValue(), Ty: UGEPIIdx->getType(),
8790 CostKind: TargetTransformInfo::TCK_SizeAndLatency) >
8791 TargetTransformInfo::TCC_Basic)
8792 return false;
8793 UGEPIs.push_back(x: UGEPI);
8794 }
8795 if (UGEPIs.size() == 0)
8796 return false;
8797 // Check the materializing cost of (Uidx-Idx).
8798 for (GetElementPtrInst *UGEPI : UGEPIs) {
8799 ConstantInt *UGEPIIdx = cast<ConstantInt>(Val: UGEPI->getOperand(i_nocapture: 1));
8800 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8801 InstructionCost ImmCost = TTI->getIntImmCost(
8802 Imm: NewIdx, Ty: GEPIIdx->getType(), CostKind: TargetTransformInfo::TCK_SizeAndLatency);
8803 if (ImmCost > TargetTransformInfo::TCC_Basic)
8804 return false;
8805 }
8806 // Now unmerge between GEPI and UGEPIs.
8807 for (GetElementPtrInst *UGEPI : UGEPIs) {
8808 UGEPI->setOperand(i_nocapture: 0, Val_nocapture: GEPI);
8809 ConstantInt *UGEPIIdx = cast<ConstantInt>(Val: UGEPI->getOperand(i_nocapture: 1));
8810 auto NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
8811 Constant *NewUGEPIIdx = ConstantInt::get(Ty: GEPIIdx->getType(), V: NewIdx);
8812 UGEPI->setOperand(i_nocapture: 1, Val_nocapture: NewUGEPIIdx);
8813
8814 auto SourceFlags = GEPI->getNoWrapFlags();
8815 // Intersect flags to avoid UB in updated GEP.
8816 auto TargetFlags =
8817 UGEPI->getNoWrapFlags().intersectForOffsetAdd(Other: SourceFlags);
8818 // If UGEPI now has a negative index, drop the nuw flag.
8819 if (NewIdx.isNegative() && TargetFlags.hasNoUnsignedWrap())
8820 TargetFlags = TargetFlags.withoutNoUnsignedWrap();
8821 UGEPI->setNoWrapFlags(TargetFlags);
8822 }
8823 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
8824 // alive on IndirectBr edges).
8825 assert(llvm::none_of(GEPIOp->users(),
8826 [&](User *Usr) {
8827 return cast<Instruction>(Usr)->getParent() != SrcBlock;
8828 }) &&
8829 "GEPIOp is used outside SrcBlock");
8830 return true;
8831}
8832
8833static bool optimizeBranch(CondBrInst *Branch, const TargetLowering &TLI,
8834 SmallPtrSet<BasicBlock *, 32> &FreshBBs,
8835 bool IsHugeFunc) {
8836 // Try and convert
8837 // %c = icmp ult %x, 8
8838 // br %c, bla, blb
8839 // %tc = lshr %x, 3
8840 // to
8841 // %tc = lshr %x, 3
8842 // %c = icmp eq %tc, 0
8843 // br %c, bla, blb
8844 // Creating the cmp to zero can be better for the backend, especially if the
8845 // lshr produces flags that can be used automatically.
8846 if (!TLI.preferZeroCompareBranch())
8847 return false;
8848
8849 ICmpInst *Cmp = dyn_cast<ICmpInst>(Val: Branch->getCondition());
8850 if (!Cmp || !isa<ConstantInt>(Val: Cmp->getOperand(i_nocapture: 1)) || !Cmp->hasOneUse())
8851 return false;
8852
8853 Value *X = Cmp->getOperand(i_nocapture: 0);
8854 if (!X->hasUseList())
8855 return false;
8856
8857 APInt CmpC = cast<ConstantInt>(Val: Cmp->getOperand(i_nocapture: 1))->getValue();
8858
8859 for (auto *U : X->users()) {
8860 Instruction *UI = dyn_cast<Instruction>(Val: U);
8861 // A quick dominance check
8862 if (!UI ||
8863 (UI->getParent() != Branch->getParent() &&
8864 UI->getParent() != Branch->getSuccessor(i: 0) &&
8865 UI->getParent() != Branch->getSuccessor(i: 1)) ||
8866 (UI->getParent() != Branch->getParent() &&
8867 !UI->getParent()->getSinglePredecessor()))
8868 continue;
8869
8870 if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT &&
8871 match(V: UI, P: m_Shr(L: m_Specific(V: X), R: m_SpecificInt(V: CmpC.logBase2())))) {
8872 IRBuilder<> Builder(Branch);
8873 if (UI->getParent() != Branch->getParent())
8874 UI->moveBefore(InsertPos: Branch->getIterator());
8875 UI->dropPoisonGeneratingFlags();
8876 Value *NewCmp = Builder.CreateCmp(Pred: ICmpInst::ICMP_EQ, LHS: UI,
8877 RHS: ConstantInt::get(Ty: UI->getType(), V: 0));
8878 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8879 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8880 replaceAllUsesWith(Old: Cmp, New: NewCmp, FreshBBs, IsHuge: IsHugeFunc);
8881 return true;
8882 }
8883 if (Cmp->isEquality() &&
8884 (match(V: UI, P: m_Add(L: m_Specific(V: X), R: m_SpecificInt(V: -CmpC))) ||
8885 match(V: UI, P: m_Sub(L: m_Specific(V: X), R: m_SpecificInt(V: CmpC))) ||
8886 match(V: UI, P: m_Xor(L: m_Specific(V: X), R: m_SpecificInt(V: CmpC))))) {
8887 IRBuilder<> Builder(Branch);
8888 if (UI->getParent() != Branch->getParent())
8889 UI->moveBefore(InsertPos: Branch->getIterator());
8890 UI->dropPoisonGeneratingFlags();
8891 Value *NewCmp = Builder.CreateCmp(Pred: Cmp->getPredicate(), LHS: UI,
8892 RHS: ConstantInt::get(Ty: UI->getType(), V: 0));
8893 LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
8894 LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
8895 replaceAllUsesWith(Old: Cmp, New: NewCmp, FreshBBs, IsHuge: IsHugeFunc);
8896 return true;
8897 }
8898 }
8899 return false;
8900}
8901
8902bool CodeGenPrepare::optimizeInst(Instruction *I, ModifyDT &ModifiedDT) {
8903 bool AnyChange = false;
8904 AnyChange = fixupDbgVariableRecordsOnInst(I&: *I);
8905
8906 // Bail out if we inserted the instruction to prevent optimizations from
8907 // stepping on each other's toes.
8908 if (InsertedInsts.count(Ptr: I))
8909 return AnyChange;
8910
8911 // TODO: Move into the switch on opcode below here.
8912 if (PHINode *P = dyn_cast<PHINode>(Val: I)) {
8913 // It is possible for very late stage optimizations (such as SimplifyCFG)
8914 // to introduce PHI nodes too late to be cleaned up. If we detect such a
8915 // trivial PHI, go ahead and zap it here.
8916 if (Value *V = simplifyInstruction(I: P, Q: {*DL, TLInfo})) {
8917 LargeOffsetGEPMap.erase(Key: P);
8918 replaceAllUsesWith(Old: P, New: V, FreshBBs, IsHuge: IsHugeFunc);
8919 P->eraseFromParent();
8920 ++NumPHIsElim;
8921 return true;
8922 }
8923 return AnyChange;
8924 }
8925
8926 if (CastInst *CI = dyn_cast<CastInst>(Val: I)) {
8927 // If the source of the cast is a constant, then this should have
8928 // already been constant folded. The only reason NOT to constant fold
8929 // it is if something (e.g. LSR) was careful to place the constant
8930 // evaluation in a block other than then one that uses it (e.g. to hoist
8931 // the address of globals out of a loop). If this is the case, we don't
8932 // want to forward-subst the cast.
8933 if (isa<Constant>(Val: CI->getOperand(i_nocapture: 0)))
8934 return AnyChange;
8935
8936 if (OptimizeNoopCopyExpression(CI, TLI: *TLI, DL: *DL))
8937 return true;
8938
8939 if ((isa<UIToFPInst>(Val: I) || isa<SIToFPInst>(Val: I) || isa<FPToUIInst>(Val: I) ||
8940 isa<TruncInst>(Val: I)) &&
8941 TLI->optimizeExtendOrTruncateConversion(
8942 I, L: LI->getLoopFor(BB: I->getParent()), TTI: *TTI))
8943 return true;
8944
8945 if (isa<ZExtInst>(Val: I) || isa<SExtInst>(Val: I)) {
8946 /// Sink a zext or sext into its user blocks if the target type doesn't
8947 /// fit in one register
8948 if (TLI->getTypeAction(Context&: CI->getContext(),
8949 VT: TLI->getValueType(DL: *DL, Ty: CI->getType())) ==
8950 TargetLowering::TypeExpandInteger) {
8951 return SinkCast(CI);
8952 } else {
8953 if (TLI->optimizeExtendOrTruncateConversion(
8954 I, L: LI->getLoopFor(BB: I->getParent()), TTI: *TTI))
8955 return true;
8956
8957 bool MadeChange = optimizeExt(Inst&: I);
8958 return MadeChange | optimizeExtUses(I);
8959 }
8960 }
8961 return AnyChange;
8962 }
8963
8964 if (auto *Cmp = dyn_cast<CmpInst>(Val: I))
8965 if (optimizeCmp(Cmp, ModifiedDT))
8966 return true;
8967
8968 if (match(V: I, P: m_URem(L: m_Value(), R: m_Value())))
8969 if (optimizeURem(Rem: I))
8970 return true;
8971
8972 if (LoadInst *LI = dyn_cast<LoadInst>(Val: I)) {
8973 LI->setMetadata(KindID: LLVMContext::MD_invariant_group, Node: nullptr);
8974 bool Modified = optimizeLoadExt(Load: LI);
8975 unsigned AS = LI->getPointerAddressSpace();
8976 Modified |= optimizeMemoryInst(MemoryInst: I, Addr: I->getOperand(i: 0), AccessTy: LI->getType(), AddrSpace: AS);
8977 return Modified;
8978 }
8979
8980 if (StoreInst *SI = dyn_cast<StoreInst>(Val: I)) {
8981 if (splitMergedValStore(SI&: *SI, DL: *DL, TLI: *TLI))
8982 return true;
8983 SI->setMetadata(KindID: LLVMContext::MD_invariant_group, Node: nullptr);
8984 unsigned AS = SI->getPointerAddressSpace();
8985 return optimizeMemoryInst(MemoryInst: I, Addr: SI->getOperand(i_nocapture: 1),
8986 AccessTy: SI->getOperand(i_nocapture: 0)->getType(), AddrSpace: AS);
8987 }
8988
8989 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Val: I)) {
8990 unsigned AS = RMW->getPointerAddressSpace();
8991 return optimizeMemoryInst(MemoryInst: I, Addr: RMW->getPointerOperand(), AccessTy: RMW->getType(), AddrSpace: AS);
8992 }
8993
8994 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Val: I)) {
8995 unsigned AS = CmpX->getPointerAddressSpace();
8996 return optimizeMemoryInst(MemoryInst: I, Addr: CmpX->getPointerOperand(),
8997 AccessTy: CmpX->getCompareOperand()->getType(), AddrSpace: AS);
8998 }
8999
9000 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val: I);
9001
9002 if (BinOp && BinOp->getOpcode() == Instruction::And && EnableAndCmpSinking &&
9003 sinkAndCmp0Expression(AndI: BinOp, TLI: *TLI, InsertedInsts))
9004 return true;
9005
9006 // TODO: Move this into the switch on opcode - it handles shifts already.
9007 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
9008 BinOp->getOpcode() == Instruction::LShr)) {
9009 ConstantInt *CI = dyn_cast<ConstantInt>(Val: BinOp->getOperand(i_nocapture: 1));
9010 if (CI && TLI->hasExtractBitsInsn())
9011 if (OptimizeExtractBits(ShiftI: BinOp, CI, TLI: *TLI, DL: *DL))
9012 return true;
9013 }
9014
9015 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Val: I)) {
9016 if (GEPI->hasAllZeroIndices()) {
9017 /// The GEP operand must be a pointer, so must its result -> BitCast
9018 Instruction *NC = new BitCastInst(GEPI->getOperand(i_nocapture: 0), GEPI->getType(),
9019 GEPI->getName(), GEPI->getIterator());
9020 NC->setDebugLoc(GEPI->getDebugLoc());
9021 replaceAllUsesWith(Old: GEPI, New: NC, FreshBBs, IsHuge: IsHugeFunc);
9022 RecursivelyDeleteTriviallyDeadInstructions(
9023 V: GEPI, TLI: TLInfo, MSSAU: nullptr,
9024 AboutToDeleteCallback: [&](Value *V) { removeAllAssertingVHReferences(V); });
9025 ++NumGEPsElim;
9026 optimizeInst(I: NC, ModifiedDT);
9027 return true;
9028 }
9029 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
9030 return true;
9031 }
9032 }
9033
9034 if (FreezeInst *FI = dyn_cast<FreezeInst>(Val: I)) {
9035 // freeze(icmp a, const)) -> icmp (freeze a), const
9036 // This helps generate efficient conditional jumps.
9037 Instruction *CmpI = nullptr;
9038 if (ICmpInst *II = dyn_cast<ICmpInst>(Val: FI->getOperand(i_nocapture: 0)))
9039 CmpI = II;
9040 else if (FCmpInst *F = dyn_cast<FCmpInst>(Val: FI->getOperand(i_nocapture: 0)))
9041 CmpI = F->getFastMathFlags().none() ? F : nullptr;
9042
9043 if (CmpI && CmpI->hasOneUse()) {
9044 auto Op0 = CmpI->getOperand(i: 0), Op1 = CmpI->getOperand(i: 1);
9045 bool Const0 = isa<ConstantInt>(Val: Op0) || isa<ConstantFP>(Val: Op0) ||
9046 isa<ConstantPointerNull>(Val: Op0);
9047 bool Const1 = isa<ConstantInt>(Val: Op1) || isa<ConstantFP>(Val: Op1) ||
9048 isa<ConstantPointerNull>(Val: Op1);
9049 if (Const0 || Const1) {
9050 if (!Const0 || !Const1) {
9051 auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI->getIterator());
9052 F->takeName(V: FI);
9053 CmpI->setOperand(i: Const0 ? 1 : 0, Val: F);
9054 }
9055 replaceAllUsesWith(Old: FI, New: CmpI, FreshBBs, IsHuge: IsHugeFunc);
9056 FI->eraseFromParent();
9057 return true;
9058 }
9059 }
9060 return AnyChange;
9061 }
9062
9063 if (tryToSinkFreeOperands(I))
9064 return true;
9065
9066 switch (I->getOpcode()) {
9067 case Instruction::Shl:
9068 case Instruction::LShr:
9069 case Instruction::AShr:
9070 return optimizeShiftInst(Shift: cast<BinaryOperator>(Val: I));
9071 case Instruction::Call:
9072 return optimizeCallInst(CI: cast<CallInst>(Val: I), ModifiedDT);
9073 case Instruction::Select:
9074 return optimizeSelectInst(SI: cast<SelectInst>(Val: I));
9075 case Instruction::ShuffleVector:
9076 return optimizeShuffleVectorInst(SVI: cast<ShuffleVectorInst>(Val: I));
9077 case Instruction::Switch:
9078 return optimizeSwitchInst(SI: cast<SwitchInst>(Val: I));
9079 case Instruction::ExtractElement:
9080 return optimizeExtractElementInst(Inst: cast<ExtractElementInst>(Val: I));
9081 case Instruction::CondBr:
9082 return optimizeBranch(Branch: cast<CondBrInst>(Val: I), TLI: *TLI, FreshBBs, IsHugeFunc);
9083 }
9084
9085 return AnyChange;
9086}
9087
9088/// Given an OR instruction, check to see if this is a bitreverse
9089/// idiom. If so, insert the new intrinsic and return true.
9090bool CodeGenPrepare::makeBitReverse(Instruction &I) {
9091 if (!I.getType()->isIntegerTy() ||
9092 !TLI->isOperationLegalOrCustom(Op: ISD::BITREVERSE,
9093 VT: TLI->getValueType(DL: *DL, Ty: I.getType(), AllowUnknown: true)))
9094 return false;
9095
9096 SmallVector<Instruction *, 4> Insts;
9097 if (!recognizeBSwapOrBitReverseIdiom(I: &I, MatchBSwaps: false, MatchBitReversals: true, InsertedInsts&: Insts))
9098 return false;
9099 Instruction *LastInst = Insts.back();
9100 replaceAllUsesWith(Old: &I, New: LastInst, FreshBBs, IsHuge: IsHugeFunc);
9101 RecursivelyDeleteTriviallyDeadInstructions(
9102 V: &I, TLI: TLInfo, MSSAU: nullptr,
9103 AboutToDeleteCallback: [&](Value *V) { removeAllAssertingVHReferences(V); });
9104 return true;
9105}
9106
9107// In this pass we look for GEP and cast instructions that are used
9108// across basic blocks and rewrite them to improve basic-block-at-a-time
9109// selection.
9110bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
9111 SunkAddrs.clear();
9112 bool MadeChange = false;
9113
9114 do {
9115 CurInstIterator = BB.begin();
9116 ModifiedDT = ModifyDT::NotModifyDT;
9117 while (CurInstIterator != BB.end()) {
9118 MadeChange |= optimizeInst(I: &*CurInstIterator++, ModifiedDT);
9119 if (ModifiedDT != ModifyDT::NotModifyDT) {
9120 // For huge function we tend to quickly go though the inner optmization
9121 // opportunities in the BB. So we go back to the BB head to re-optimize
9122 // each instruction instead of go back to the function head.
9123 if (IsHugeFunc)
9124 break;
9125 return true;
9126 }
9127 }
9128 } while (ModifiedDT == ModifyDT::ModifyInstDT);
9129
9130 bool MadeBitReverse = true;
9131 while (MadeBitReverse) {
9132 MadeBitReverse = false;
9133 for (auto &I : reverse(C&: BB)) {
9134 if (makeBitReverse(I)) {
9135 MadeBitReverse = MadeChange = true;
9136 break;
9137 }
9138 }
9139 }
9140 MadeChange |= dupRetToEnableTailCallOpts(BB: &BB, ModifiedDT);
9141
9142 return MadeChange;
9143}
9144
9145bool CodeGenPrepare::fixupDbgVariableRecordsOnInst(Instruction &I) {
9146 bool AnyChange = false;
9147 for (DbgVariableRecord &DVR : filterDbgVars(R: I.getDbgRecordRange()))
9148 AnyChange |= fixupDbgVariableRecord(I&: DVR);
9149 return AnyChange;
9150}
9151
9152// FIXME: should updating debug-info really cause the "changed" flag to fire,
9153// which can cause a function to be reprocessed?
9154bool CodeGenPrepare::fixupDbgVariableRecord(DbgVariableRecord &DVR) {
9155 if (DVR.Type != DbgVariableRecord::LocationType::Value &&
9156 DVR.Type != DbgVariableRecord::LocationType::Assign)
9157 return false;
9158
9159 // Does this DbgVariableRecord refer to a sunk address calculation?
9160 bool AnyChange = false;
9161 SmallDenseSet<Value *> LocationOps(DVR.location_ops().begin(),
9162 DVR.location_ops().end());
9163 for (Value *Location : LocationOps) {
9164 WeakTrackingVH SunkAddrVH = SunkAddrs[Location];
9165 Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
9166 if (SunkAddr) {
9167 // Point dbg.value at locally computed address, which should give the best
9168 // opportunity to be accurately lowered. This update may change the type
9169 // of pointer being referred to; however this makes no difference to
9170 // debugging information, and we can't generate bitcasts that may affect
9171 // codegen.
9172 DVR.replaceVariableLocationOp(OldValue: Location, NewValue: SunkAddr);
9173 AnyChange = true;
9174 }
9175 }
9176 return AnyChange;
9177}
9178
9179static void DbgInserterHelper(DbgVariableRecord *DVR, BasicBlock::iterator VI) {
9180 DVR->removeFromParent();
9181 BasicBlock *VIBB = VI->getParent();
9182 if (isa<PHINode>(Val: VI))
9183 VIBB->insertDbgRecordBefore(DR: DVR, Here: VIBB->getFirstInsertionPt());
9184 else
9185 VIBB->insertDbgRecordAfter(DR: DVR, I: &*VI);
9186}
9187
9188// A llvm.dbg.value may be using a value before its definition, due to
9189// optimizations in this pass and others. Scan for such dbg.values, and rescue
9190// them by moving the dbg.value to immediately after the value definition.
9191// FIXME: Ideally this should never be necessary, and this has the potential
9192// to re-order dbg.value intrinsics.
9193bool CodeGenPrepare::placeDbgValues(Function &F) {
9194 bool MadeChange = false;
9195 DominatorTree &DT = getDT();
9196
9197 auto DbgProcessor = [&](auto *DbgItem, Instruction *Position) {
9198 SmallVector<Instruction *, 4> VIs;
9199 for (Value *V : DbgItem->location_ops())
9200 if (Instruction *VI = dyn_cast_or_null<Instruction>(Val: V))
9201 VIs.push_back(Elt: VI);
9202
9203 // This item may depend on multiple instructions, complicating any
9204 // potential sink. This block takes the defensive approach, opting to
9205 // "undef" the item if it has more than one instruction and any of them do
9206 // not dominate iem.
9207 for (Instruction *VI : VIs) {
9208 if (VI->isTerminator())
9209 continue;
9210
9211 // If VI is a phi in a block with an EHPad terminator, we can't insert
9212 // after it.
9213 if (isa<PHINode>(Val: VI) && VI->getParent()->getTerminator()->isEHPad())
9214 continue;
9215
9216 // If the defining instruction dominates the dbg.value, we do not need
9217 // to move the dbg.value.
9218 if (DT.dominates(Def: VI, User: Position))
9219 continue;
9220
9221 // If we depend on multiple instructions and any of them doesn't
9222 // dominate this DVI, we probably can't salvage it: moving it to
9223 // after any of the instructions could cause us to lose the others.
9224 if (VIs.size() > 1) {
9225 LLVM_DEBUG(
9226 dbgs()
9227 << "Unable to find valid location for Debug Value, undefing:\n"
9228 << *DbgItem);
9229 DbgItem->setKillLocation();
9230 break;
9231 }
9232
9233 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
9234 << *DbgItem << ' ' << *VI);
9235 DbgInserterHelper(DbgItem, VI->getIterator());
9236 MadeChange = true;
9237 ++NumDbgValueMoved;
9238 }
9239 };
9240
9241 for (BasicBlock &BB : F) {
9242 for (Instruction &Insn : llvm::make_early_inc_range(Range&: BB)) {
9243 // Process any DbgVariableRecord records attached to this
9244 // instruction.
9245 for (DbgVariableRecord &DVR : llvm::make_early_inc_range(
9246 Range: filterDbgVars(R: Insn.getDbgRecordRange()))) {
9247 if (DVR.Type != DbgVariableRecord::LocationType::Value)
9248 continue;
9249 DbgProcessor(&DVR, &Insn);
9250 }
9251 }
9252 }
9253
9254 return MadeChange;
9255}
9256
9257// Group scattered pseudo probes in a block to favor SelectionDAG. Scattered
9258// probes can be chained dependencies of other regular DAG nodes and block DAG
9259// combine optimizations.
9260bool CodeGenPrepare::placePseudoProbes(Function &F) {
9261 bool MadeChange = false;
9262 for (auto &Block : F) {
9263 // Move the rest probes to the beginning of the block.
9264 auto FirstInst = Block.getFirstInsertionPt();
9265 while (FirstInst != Block.end() && FirstInst->isDebugOrPseudoInst())
9266 ++FirstInst;
9267 BasicBlock::iterator I(FirstInst);
9268 I++;
9269 while (I != Block.end()) {
9270 if (auto *II = dyn_cast<PseudoProbeInst>(Val: I++)) {
9271 II->moveBefore(InsertPos: FirstInst);
9272 MadeChange = true;
9273 }
9274 }
9275 }
9276 return MadeChange;
9277}
9278
9279/// Some targets prefer to split a conditional branch like:
9280/// \code
9281/// %0 = icmp ne i32 %a, 0
9282/// %1 = icmp ne i32 %b, 0
9283/// %or.cond = or i1 %0, %1
9284/// br i1 %or.cond, label %TrueBB, label %FalseBB
9285/// \endcode
9286/// into multiple branch instructions like:
9287/// \code
9288/// bb1:
9289/// %0 = icmp ne i32 %a, 0
9290/// br i1 %0, label %TrueBB, label %bb2
9291/// bb2:
9292/// %1 = icmp ne i32 %b, 0
9293/// br i1 %1, label %TrueBB, label %FalseBB
9294/// \endcode
9295/// This usually allows instruction selection to do even further optimizations
9296/// and combine the compare with the branch instruction. Currently this is
9297/// applied for targets which have "cheap" jump instructions.
9298///
9299/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
9300///
9301bool CodeGenPrepare::splitBranchCondition(Function &F) {
9302 if (!TM->Options.EnableFastISel || TLI->isJumpExpensive())
9303 return false;
9304
9305 bool MadeChange = false;
9306 for (auto &BB : F) {
9307 // Does this BB end with the following?
9308 // %cond1 = icmp|fcmp|binary instruction ...
9309 // %cond2 = icmp|fcmp|binary instruction ...
9310 // %cond.or = or|and i1 %cond1, cond2
9311 // br i1 %cond.or label %dest1, label %dest2"
9312 Instruction *LogicOp;
9313 BasicBlock *TBB, *FBB;
9314 if (!match(V: BB.getTerminator(),
9315 P: m_Br(C: m_OneUse(SubPattern: m_Instruction(I&: LogicOp)), T&: TBB, F&: FBB)))
9316 continue;
9317
9318 auto *Br1 = cast<CondBrInst>(Val: BB.getTerminator());
9319 if (Br1->getMetadata(KindID: LLVMContext::MD_unpredictable))
9320 continue;
9321
9322 // The merging of mostly empty BB can cause a degenerate branch.
9323 if (TBB == FBB)
9324 continue;
9325
9326 unsigned Opc;
9327 Value *Cond1, *Cond2;
9328 if (match(V: LogicOp,
9329 P: m_LogicalAnd(L: m_OneUse(SubPattern: m_Value(V&: Cond1)), R: m_OneUse(SubPattern: m_Value(V&: Cond2)))))
9330 Opc = Instruction::And;
9331 else if (match(V: LogicOp, P: m_LogicalOr(L: m_OneUse(SubPattern: m_Value(V&: Cond1)),
9332 R: m_OneUse(SubPattern: m_Value(V&: Cond2)))))
9333 Opc = Instruction::Or;
9334 else
9335 continue;
9336
9337 auto IsGoodCond = [](Value *Cond) {
9338 return match(
9339 V: Cond,
9340 P: m_CombineOr(Ps: m_Cmp(), Ps: m_CombineOr(Ps: m_LogicalAnd(L: m_Value(), R: m_Value()),
9341 Ps: m_LogicalOr(L: m_Value(), R: m_Value()))));
9342 };
9343 if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
9344 continue;
9345
9346 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
9347
9348 // Create a new BB.
9349 auto *TmpBB =
9350 BasicBlock::Create(Context&: BB.getContext(), Name: BB.getName() + ".cond.split",
9351 Parent: BB.getParent(), InsertBefore: BB.getNextNode());
9352 if (IsHugeFunc)
9353 FreshBBs.insert(Ptr: TmpBB);
9354
9355 // Update original basic block by using the first condition directly by the
9356 // branch instruction and removing the no longer needed and/or instruction.
9357 Br1->setCondition(Cond1);
9358 LogicOp->eraseFromParent();
9359
9360 // Depending on the condition we have to either replace the true or the
9361 // false successor of the original branch instruction.
9362 if (Opc == Instruction::And)
9363 Br1->setSuccessor(idx: 0, NewSucc: TmpBB);
9364 else
9365 Br1->setSuccessor(idx: 1, NewSucc: TmpBB);
9366
9367 // Fill in the new basic block.
9368 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond: Cond2, True: TBB, False: FBB);
9369 if (auto *I = dyn_cast<Instruction>(Val: Cond2)) {
9370 I->removeFromParent();
9371 I->insertBefore(InsertPos: Br2->getIterator());
9372 }
9373
9374 // Update PHI nodes in both successors. The original BB needs to be
9375 // replaced in one successor's PHI nodes, because the branch comes now from
9376 // the newly generated BB (NewBB). In the other successor we need to add one
9377 // incoming edge to the PHI nodes, because both branch instructions target
9378 // now the same successor. Depending on the original branch condition
9379 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
9380 // we perform the correct update for the PHI nodes.
9381 // This doesn't change the successor order of the just created branch
9382 // instruction (or any other instruction).
9383 if (Opc == Instruction::Or)
9384 std::swap(a&: TBB, b&: FBB);
9385
9386 // Replace the old BB with the new BB.
9387 TBB->replacePhiUsesWith(Old: &BB, New: TmpBB);
9388
9389 // Add another incoming edge from the new BB.
9390 for (PHINode &PN : FBB->phis()) {
9391 auto *Val = PN.getIncomingValueForBlock(BB: &BB);
9392 PN.addIncoming(V: Val, BB: TmpBB);
9393 }
9394
9395 if (Loop *L = LI->getLoopFor(BB: &BB))
9396 L->addBasicBlockToLoop(NewBB: TmpBB, LI&: *LI);
9397
9398 // The edge we need to delete starts at BB and ends at whatever TBB ends
9399 // up pointing to.
9400 DTU->applyUpdates(Updates: {{DominatorTree::Insert, &BB, TmpBB},
9401 {DominatorTree::Insert, TmpBB, TBB},
9402 {DominatorTree::Insert, TmpBB, FBB},
9403 {DominatorTree::Delete, &BB, TBB}});
9404
9405 // Update the branch weights (from SelectionDAGBuilder::
9406 // FindMergedConditions).
9407 if (Opc == Instruction::Or) {
9408 // Codegen X | Y as:
9409 // BB1:
9410 // jmp_if_X TBB
9411 // jmp TmpBB
9412 // TmpBB:
9413 // jmp_if_Y TBB
9414 // jmp FBB
9415 //
9416
9417 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
9418 // The requirement is that
9419 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
9420 // = TrueProb for original BB.
9421 // Assuming the original weights are A and B, one choice is to set BB1's
9422 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
9423 // assumes that
9424 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
9425 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
9426 // TmpBB, but the math is more complicated.
9427 uint64_t TrueWeight, FalseWeight;
9428 if (extractBranchWeights(I: *Br1, TrueVal&: TrueWeight, FalseVal&: FalseWeight)) {
9429 uint64_t NewTrueWeight = TrueWeight;
9430 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
9431 setFittedBranchWeights(I&: *Br1, Weights: {NewTrueWeight, NewFalseWeight},
9432 IsExpected: hasBranchWeightOrigin(I: *Br1));
9433
9434 NewTrueWeight = TrueWeight;
9435 NewFalseWeight = 2 * FalseWeight;
9436 setFittedBranchWeights(I&: *Br2, Weights: {NewTrueWeight, NewFalseWeight},
9437 /*IsExpected=*/false);
9438 }
9439 } else {
9440 // Codegen X & Y as:
9441 // BB1:
9442 // jmp_if_X TmpBB
9443 // jmp FBB
9444 // TmpBB:
9445 // jmp_if_Y TBB
9446 // jmp FBB
9447 //
9448 // This requires creation of TmpBB after CurBB.
9449
9450 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
9451 // The requirement is that
9452 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
9453 // = FalseProb for original BB.
9454 // Assuming the original weights are A and B, one choice is to set BB1's
9455 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
9456 // assumes that
9457 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
9458 uint64_t TrueWeight, FalseWeight;
9459 if (extractBranchWeights(I: *Br1, TrueVal&: TrueWeight, FalseVal&: FalseWeight)) {
9460 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
9461 uint64_t NewFalseWeight = FalseWeight;
9462 setFittedBranchWeights(I&: *Br1, Weights: {NewTrueWeight, NewFalseWeight},
9463 /*IsExpected=*/false);
9464
9465 NewTrueWeight = 2 * TrueWeight;
9466 NewFalseWeight = FalseWeight;
9467 setFittedBranchWeights(I&: *Br2, Weights: {NewTrueWeight, NewFalseWeight},
9468 /*IsExpected=*/false);
9469 }
9470 }
9471
9472 MadeChange = true;
9473
9474 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
9475 TmpBB->dump());
9476 }
9477 return MadeChange;
9478}
9479