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