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