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