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