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