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