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