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