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