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