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