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