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