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