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