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