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