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