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