4cdb69196d7fff7ca3b614b9de87e2b49a10cb84
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuilder.h
1 //===-- SelectionDAGBuilder.h - Selection-DAG building --------*- C++ -*---===//
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 implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H
15 #define LLVM_LIB_CODEGEN_SELECTIONDAG_SELECTIONDAGBUILDER_H
16
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/CodeGen/SelectionDAGNodes.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include <vector>
26
27 namespace llvm {
28
29 class AddrSpaceCastInst;
30 class AliasAnalysis;
31 class AllocaInst;
32 class BasicBlock;
33 class BitCastInst;
34 class BranchInst;
35 class CallInst;
36 class DbgValueInst;
37 class ExtractElementInst;
38 class ExtractValueInst;
39 class FCmpInst;
40 class FPExtInst;
41 class FPToSIInst;
42 class FPToUIInst;
43 class FPTruncInst;
44 class Function;
45 class FunctionLoweringInfo;
46 class GetElementPtrInst;
47 class GCFunctionInfo;
48 class ICmpInst;
49 class IntToPtrInst;
50 class IndirectBrInst;
51 class InvokeInst;
52 class InsertElementInst;
53 class InsertValueInst;
54 class Instruction;
55 class LoadInst;
56 class MachineBasicBlock;
57 class MachineInstr;
58 class MachineRegisterInfo;
59 class MDNode;
60 class MVT;
61 class PHINode;
62 class PtrToIntInst;
63 class ReturnInst;
64 class SDDbgValue;
65 class SExtInst;
66 class SelectInst;
67 class ShuffleVectorInst;
68 class SIToFPInst;
69 class StoreInst;
70 class SwitchInst;
71 class DataLayout;
72 class TargetLibraryInfo;
73 class TargetLowering;
74 class TruncInst;
75 class UIToFPInst;
76 class UnreachableInst;
77 class VAArgInst;
78 class ZExtInst;
79
80 //===----------------------------------------------------------------------===//
81 /// SelectionDAGBuilder - This is the common target-independent lowering
82 /// implementation that is parameterized by a TargetLowering object.
83 ///
84 class SelectionDAGBuilder {
85   /// CurInst - The current instruction being visited
86   const Instruction *CurInst;
87
88   DenseMap<const Value*, SDValue> NodeMap;
89
90   /// UnusedArgNodeMap - Maps argument value for unused arguments. This is used
91   /// to preserve debug information for incoming arguments.
92   DenseMap<const Value*, SDValue> UnusedArgNodeMap;
93
94   /// DanglingDebugInfo - Helper type for DanglingDebugInfoMap.
95   class DanglingDebugInfo {
96     const DbgValueInst* DI;
97     DebugLoc dl;
98     unsigned SDNodeOrder;
99   public:
100     DanglingDebugInfo() : DI(nullptr), dl(DebugLoc()), SDNodeOrder(0) { }
101     DanglingDebugInfo(const DbgValueInst *di, DebugLoc DL, unsigned SDNO) :
102       DI(di), dl(DL), SDNodeOrder(SDNO) { }
103     const DbgValueInst* getDI() { return DI; }
104     DebugLoc getdl() { return dl; }
105     unsigned getSDNodeOrder() { return SDNodeOrder; }
106   };
107
108   /// DanglingDebugInfoMap - Keeps track of dbg_values for which we have not
109   /// yet seen the referent.  We defer handling these until we do see it.
110   DenseMap<const Value*, DanglingDebugInfo> DanglingDebugInfoMap;
111
112 public:
113   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
114   /// them up and then emit token factor nodes when possible.  This allows us to
115   /// get simple disambiguation between loads without worrying about alias
116   /// analysis.
117   SmallVector<SDValue, 8> PendingLoads;
118 private:
119
120   /// PendingExports - CopyToReg nodes that copy values to virtual registers
121   /// for export to other blocks need to be emitted before any terminator
122   /// instruction, but they have no other ordering requirements. We bunch them
123   /// up and the emit a single tokenfactor for them just before terminator
124   /// instructions.
125   SmallVector<SDValue, 8> PendingExports;
126
127   /// SDNodeOrder - A unique monotonically increasing number used to order the
128   /// SDNodes we create.
129   unsigned SDNodeOrder;
130
131   /// Case - A struct to record the Value for a switch case, and the
132   /// case's target basic block.
133   struct Case {
134     const Constant *Low;
135     const Constant *High;
136     MachineBasicBlock* BB;
137     uint32_t ExtraWeight;
138
139     Case() : Low(nullptr), High(nullptr), BB(nullptr), ExtraWeight(0) { }
140     Case(const Constant *low, const Constant *high, MachineBasicBlock *bb,
141          uint32_t extraweight) : Low(low), High(high), BB(bb),
142          ExtraWeight(extraweight) { }
143
144     APInt size() const {
145       const APInt &rHigh = cast<ConstantInt>(High)->getValue();
146       const APInt &rLow  = cast<ConstantInt>(Low)->getValue();
147       return (rHigh - rLow + 1ULL);
148     }
149   };
150
151   struct CaseBits {
152     uint64_t Mask;
153     MachineBasicBlock* BB;
154     unsigned Bits;
155     uint32_t ExtraWeight;
156
157     CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits,
158              uint32_t Weight):
159       Mask(mask), BB(bb), Bits(bits), ExtraWeight(Weight) { }
160   };
161
162   typedef std::vector<Case>           CaseVector;
163   typedef std::vector<CaseBits>       CaseBitsVector;
164   typedef CaseVector::iterator        CaseItr;
165   typedef std::pair<CaseItr, CaseItr> CaseRange;
166
167   /// CaseRec - A struct with ctor used in lowering switches to a binary tree
168   /// of conditional branches.
169   struct CaseRec {
170     CaseRec(MachineBasicBlock *bb, const Constant *lt, const Constant *ge,
171             CaseRange r) :
172     CaseBB(bb), LT(lt), GE(ge), Range(r) {}
173
174     /// CaseBB - The MBB in which to emit the compare and branch
175     MachineBasicBlock *CaseBB;
176     /// LT, GE - If nonzero, we know the current case value must be less-than or
177     /// greater-than-or-equal-to these Constants.
178     const Constant *LT;
179     const Constant *GE;
180     /// Range - A pair of iterators representing the range of case values to be
181     /// processed at this point in the binary search tree.
182     CaseRange Range;
183   };
184
185   typedef std::vector<CaseRec> CaseRecVector;
186
187   /// The comparison function for sorting the switch case values in the vector.
188   /// WARNING: Case ranges should be disjoint!
189   struct CaseCmp {
190     bool operator()(const Case &C1, const Case &C2) {
191       assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
192       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
193       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
194       return CI1->getValue().slt(CI2->getValue());
195     }
196   };
197
198   struct CaseBitsCmp {
199     bool operator()(const CaseBits &C1, const CaseBits &C2) {
200       return C1.Bits > C2.Bits;
201     }
202   };
203
204   void Clusterify(CaseVector &Cases, const SwitchInst &SI);
205
206   /// CaseBlock - This structure is used to communicate between
207   /// SelectionDAGBuilder and SDISel for the code generation of additional basic
208   /// blocks needed by multi-case switch statements.
209   struct CaseBlock {
210     CaseBlock(ISD::CondCode cc, const Value *cmplhs, const Value *cmprhs,
211               const Value *cmpmiddle,
212               MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
213               MachineBasicBlock *me,
214               uint32_t trueweight = 0, uint32_t falseweight = 0)
215       : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
216         TrueBB(truebb), FalseBB(falsebb), ThisBB(me),
217         TrueWeight(trueweight), FalseWeight(falseweight) { }
218
219     // CC - the condition code to use for the case block's setcc node
220     ISD::CondCode CC;
221
222     // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
223     // Emit by default LHS op RHS. MHS is used for range comparisons:
224     // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
225     const Value *CmpLHS, *CmpMHS, *CmpRHS;
226
227     // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
228     MachineBasicBlock *TrueBB, *FalseBB;
229
230     // ThisBB - the block into which to emit the code for the setcc and branches
231     MachineBasicBlock *ThisBB;
232
233     // TrueWeight/FalseWeight - branch weights.
234     uint32_t TrueWeight, FalseWeight;
235   };
236
237   struct JumpTable {
238     JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
239               MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
240
241     /// Reg - the virtual register containing the index of the jump table entry
242     //. to jump to.
243     unsigned Reg;
244     /// JTI - the JumpTableIndex for this jump table in the function.
245     unsigned JTI;
246     /// MBB - the MBB into which to emit the code for the indirect jump.
247     MachineBasicBlock *MBB;
248     /// Default - the MBB of the default bb, which is a successor of the range
249     /// check MBB.  This is when updating PHI nodes in successors.
250     MachineBasicBlock *Default;
251   };
252   struct JumpTableHeader {
253     JumpTableHeader(APInt F, APInt L, const Value *SV, MachineBasicBlock *H,
254                     bool E = false):
255       First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
256     APInt First;
257     APInt Last;
258     const Value *SValue;
259     MachineBasicBlock *HeaderBB;
260     bool Emitted;
261   };
262   typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
263
264   struct BitTestCase {
265     BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr,
266                 uint32_t Weight):
267       Mask(M), ThisBB(T), TargetBB(Tr), ExtraWeight(Weight) { }
268     uint64_t Mask;
269     MachineBasicBlock *ThisBB;
270     MachineBasicBlock *TargetBB;
271     uint32_t ExtraWeight;
272   };
273
274   typedef SmallVector<BitTestCase, 3> BitTestInfo;
275
276   struct BitTestBlock {
277     BitTestBlock(APInt F, APInt R, const Value* SV,
278                  unsigned Rg, MVT RgVT, bool E,
279                  MachineBasicBlock* P, MachineBasicBlock* D,
280                  BitTestInfo C):
281       First(F), Range(R), SValue(SV), Reg(Rg), RegVT(RgVT), Emitted(E),
282       Parent(P), Default(D), Cases(std::move(C)) { }
283     APInt First;
284     APInt Range;
285     const Value *SValue;
286     unsigned Reg;
287     MVT RegVT;
288     bool Emitted;
289     MachineBasicBlock *Parent;
290     MachineBasicBlock *Default;
291     BitTestInfo Cases;
292   };
293
294   /// A class which encapsulates all of the information needed to generate a
295   /// stack protector check and signals to isel via its state being initialized
296   /// that a stack protector needs to be generated.
297   ///
298   /// *NOTE* The following is a high level documentation of SelectionDAG Stack
299   /// Protector Generation. The reason that it is placed here is for a lack of
300   /// other good places to stick it.
301   ///
302   /// High Level Overview of SelectionDAG Stack Protector Generation:
303   ///
304   /// Previously, generation of stack protectors was done exclusively in the
305   /// pre-SelectionDAG Codegen LLVM IR Pass "Stack Protector". This necessitated
306   /// splitting basic blocks at the IR level to create the success/failure basic
307   /// blocks in the tail of the basic block in question. As a result of this,
308   /// calls that would have qualified for the sibling call optimization were no
309   /// longer eligible for optimization since said calls were no longer right in
310   /// the "tail position" (i.e. the immediate predecessor of a ReturnInst
311   /// instruction).
312   ///
313   /// Then it was noticed that since the sibling call optimization causes the
314   /// callee to reuse the caller's stack, if we could delay the generation of
315   /// the stack protector check until later in CodeGen after the sibling call
316   /// decision was made, we get both the tail call optimization and the stack
317   /// protector check!
318   ///
319   /// A few goals in solving this problem were:
320   ///
321   ///   1. Preserve the architecture independence of stack protector generation.
322   ///
323   ///   2. Preserve the normal IR level stack protector check for platforms like
324   ///      OpenBSD for which we support platform-specific stack protector
325   ///      generation.
326   ///
327   /// The main problem that guided the present solution is that one can not
328   /// solve this problem in an architecture independent manner at the IR level
329   /// only. This is because:
330   ///
331   ///   1. The decision on whether or not to perform a sibling call on certain
332   ///      platforms (for instance i386) requires lower level information
333   ///      related to available registers that can not be known at the IR level.
334   ///
335   ///   2. Even if the previous point were not true, the decision on whether to
336   ///      perform a tail call is done in LowerCallTo in SelectionDAG which
337   ///      occurs after the Stack Protector Pass. As a result, one would need to
338   ///      put the relevant callinst into the stack protector check success
339   ///      basic block (where the return inst is placed) and then move it back
340   ///      later at SelectionDAG/MI time before the stack protector check if the
341   ///      tail call optimization failed. The MI level option was nixed
342   ///      immediately since it would require platform-specific pattern
343   ///      matching. The SelectionDAG level option was nixed because
344   ///      SelectionDAG only processes one IR level basic block at a time
345   ///      implying one could not create a DAG Combine to move the callinst.
346   ///
347   /// To get around this problem a few things were realized:
348   ///
349   ///   1. While one can not handle multiple IR level basic blocks at the
350   ///      SelectionDAG Level, one can generate multiple machine basic blocks
351   ///      for one IR level basic block. This is how we handle bit tests and
352   ///      switches.
353   ///
354   ///   2. At the MI level, tail calls are represented via a special return
355   ///      MIInst called "tcreturn". Thus if we know the basic block in which we
356   ///      wish to insert the stack protector check, we get the correct behavior
357   ///      by always inserting the stack protector check right before the return
358   ///      statement. This is a "magical transformation" since no matter where
359   ///      the stack protector check intrinsic is, we always insert the stack
360   ///      protector check code at the end of the BB.
361   ///
362   /// Given the aforementioned constraints, the following solution was devised:
363   ///
364   ///   1. On platforms that do not support SelectionDAG stack protector check
365   ///      generation, allow for the normal IR level stack protector check
366   ///      generation to continue.
367   ///
368   ///   2. On platforms that do support SelectionDAG stack protector check
369   ///      generation:
370   ///
371   ///     a. Use the IR level stack protector pass to decide if a stack
372   ///        protector is required/which BB we insert the stack protector check
373   ///        in by reusing the logic already therein. If we wish to generate a
374   ///        stack protector check in a basic block, we place a special IR
375   ///        intrinsic called llvm.stackprotectorcheck right before the BB's
376   ///        returninst or if there is a callinst that could potentially be
377   ///        sibling call optimized, before the call inst.
378   ///
379   ///     b. Then when a BB with said intrinsic is processed, we codegen the BB
380   ///        normally via SelectBasicBlock. In said process, when we visit the
381   ///        stack protector check, we do not actually emit anything into the
382   ///        BB. Instead, we just initialize the stack protector descriptor
383   ///        class (which involves stashing information/creating the success
384   ///        mbbb and the failure mbb if we have not created one for this
385   ///        function yet) and export the guard variable that we are going to
386   ///        compare.
387   ///
388   ///     c. After we finish selecting the basic block, in FinishBasicBlock if
389   ///        the StackProtectorDescriptor attached to the SelectionDAGBuilder is
390   ///        initialized, we first find a splice point in the parent basic block
391   ///        before the terminator and then splice the terminator of said basic
392   ///        block into the success basic block. Then we code-gen a new tail for
393   ///        the parent basic block consisting of the two loads, the comparison,
394   ///        and finally two branches to the success/failure basic blocks. We
395   ///        conclude by code-gening the failure basic block if we have not
396   ///        code-gened it already (all stack protector checks we generate in
397   ///        the same function, use the same failure basic block).
398   class StackProtectorDescriptor {
399   public:
400     StackProtectorDescriptor() : ParentMBB(nullptr), SuccessMBB(nullptr),
401                                  FailureMBB(nullptr), Guard(nullptr),
402                                  GuardReg(0) { }
403     ~StackProtectorDescriptor() { }
404
405     /// Returns true if all fields of the stack protector descriptor are
406     /// initialized implying that we should/are ready to emit a stack protector.
407     bool shouldEmitStackProtector() const {
408       return ParentMBB && SuccessMBB && FailureMBB && Guard;
409     }
410
411     /// Initialize the stack protector descriptor structure for a new basic
412     /// block.
413     void initialize(const BasicBlock *BB,
414                     MachineBasicBlock *MBB,
415                     const CallInst &StackProtCheckCall) {
416       // Make sure we are not initialized yet.
417       assert(!shouldEmitStackProtector() && "Stack Protector Descriptor is "
418              "already initialized!");
419       ParentMBB = MBB;
420       SuccessMBB = AddSuccessorMBB(BB, MBB);
421       FailureMBB = AddSuccessorMBB(BB, MBB, FailureMBB);
422       if (!Guard)
423         Guard = StackProtCheckCall.getArgOperand(0);
424     }
425
426     /// Reset state that changes when we handle different basic blocks.
427     ///
428     /// This currently includes:
429     ///
430     /// 1. The specific basic block we are generating a
431     /// stack protector for (ParentMBB).
432     ///
433     /// 2. The successor machine basic block that will contain the tail of
434     /// parent mbb after we create the stack protector check (SuccessMBB). This
435     /// BB is visited only on stack protector check success.
436     void resetPerBBState() {
437       ParentMBB = nullptr;
438       SuccessMBB = nullptr;
439     }
440
441     /// Reset state that only changes when we switch functions.
442     ///
443     /// This currently includes:
444     ///
445     /// 1. FailureMBB since we reuse the failure code path for all stack
446     /// protector checks created in an individual function.
447     ///
448     /// 2.The guard variable since the guard variable we are checking against is
449     /// always the same.
450     void resetPerFunctionState() {
451       FailureMBB = nullptr;
452       Guard = nullptr;
453     }
454
455     MachineBasicBlock *getParentMBB() { return ParentMBB; }
456     MachineBasicBlock *getSuccessMBB() { return SuccessMBB; }
457     MachineBasicBlock *getFailureMBB() { return FailureMBB; }
458     const Value *getGuard() { return Guard; }
459
460     unsigned getGuardReg() const { return GuardReg; }
461     void setGuardReg(unsigned R) { GuardReg = R; }
462
463   private:
464     /// The basic block for which we are generating the stack protector.
465     ///
466     /// As a result of stack protector generation, we will splice the
467     /// terminators of this basic block into the successor mbb SuccessMBB and
468     /// replace it with a compare/branch to the successor mbbs
469     /// SuccessMBB/FailureMBB depending on whether or not the stack protector
470     /// was violated.
471     MachineBasicBlock *ParentMBB;
472
473     /// A basic block visited on stack protector check success that contains the
474     /// terminators of ParentMBB.
475     MachineBasicBlock *SuccessMBB;
476
477     /// This basic block visited on stack protector check failure that will
478     /// contain a call to __stack_chk_fail().
479     MachineBasicBlock *FailureMBB;
480
481     /// The guard variable which we will compare against the stored value in the
482     /// stack protector stack slot.
483     const Value *Guard;
484
485     /// The virtual register holding the stack guard value.
486     unsigned GuardReg;
487
488     /// Add a successor machine basic block to ParentMBB. If the successor mbb
489     /// has not been created yet (i.e. if SuccMBB = 0), then the machine basic
490     /// block will be created.
491     MachineBasicBlock *AddSuccessorMBB(const BasicBlock *BB,
492                                        MachineBasicBlock *ParentMBB,
493                                        MachineBasicBlock *SuccMBB = nullptr);
494   };
495
496 private:
497   const TargetMachine &TM;
498 public:
499   /// Lowest valid SDNodeOrder. The special case 0 is reserved for scheduling
500   /// nodes without a corresponding SDNode.
501   static const unsigned LowestSDNodeOrder = 1;
502
503   SelectionDAG &DAG;
504   const DataLayout *DL;
505   AliasAnalysis *AA;
506   const TargetLibraryInfo *LibInfo;
507
508   /// SwitchCases - Vector of CaseBlock structures used to communicate
509   /// SwitchInst code generation information.
510   std::vector<CaseBlock> SwitchCases;
511   /// JTCases - Vector of JumpTable structures used to communicate
512   /// SwitchInst code generation information.
513   std::vector<JumpTableBlock> JTCases;
514   /// BitTestCases - Vector of BitTestBlock structures used to communicate
515   /// SwitchInst code generation information.
516   std::vector<BitTestBlock> BitTestCases;
517   /// A StackProtectorDescriptor structure used to communicate stack protector
518   /// information in between SelectBasicBlock and FinishBasicBlock.
519   StackProtectorDescriptor SPDescriptor;
520
521   // Emit PHI-node-operand constants only once even if used by multiple
522   // PHI nodes.
523   DenseMap<const Constant *, unsigned> ConstantsOut;
524
525   /// FuncInfo - Information about the function as a whole.
526   ///
527   FunctionLoweringInfo &FuncInfo;
528
529   /// OptLevel - What optimization level we're generating code for.
530   ///
531   CodeGenOpt::Level OptLevel;
532
533   /// GFI - Garbage collection metadata for the function.
534   GCFunctionInfo *GFI;
535
536   /// LPadToCallSiteMap - Map a landing pad to the call site indexes.
537   DenseMap<MachineBasicBlock*, SmallVector<unsigned, 4> > LPadToCallSiteMap;
538
539   /// HasTailCall - This is set to true if a call in the current
540   /// block has been translated as a tail call. In this case,
541   /// no subsequent DAG nodes should be created.
542   ///
543   bool HasTailCall;
544
545   LLVMContext *Context;
546
547   SelectionDAGBuilder(SelectionDAG &dag, FunctionLoweringInfo &funcinfo,
548                       CodeGenOpt::Level ol)
549     : CurInst(nullptr), SDNodeOrder(LowestSDNodeOrder), TM(dag.getTarget()),
550       DAG(dag), FuncInfo(funcinfo), OptLevel(ol),
551       HasTailCall(false) {
552   }
553
554   void init(GCFunctionInfo *gfi, AliasAnalysis &aa,
555             const TargetLibraryInfo *li);
556
557   /// clear - Clear out the current SelectionDAG and the associated
558   /// state and prepare this SelectionDAGBuilder object to be used
559   /// for a new block. This doesn't clear out information about
560   /// additional blocks that are needed to complete switch lowering
561   /// or PHI node updating; that information is cleared out as it is
562   /// consumed.
563   void clear();
564
565   /// clearDanglingDebugInfo - Clear the dangling debug information
566   /// map. This function is separated from the clear so that debug
567   /// information that is dangling in a basic block can be properly
568   /// resolved in a different basic block. This allows the
569   /// SelectionDAG to resolve dangling debug information attached
570   /// to PHI nodes.
571   void clearDanglingDebugInfo();
572
573   /// getRoot - Return the current virtual root of the Selection DAG,
574   /// flushing any PendingLoad items. This must be done before emitting
575   /// a store or any other node that may need to be ordered after any
576   /// prior load instructions.
577   ///
578   SDValue getRoot();
579
580   /// getControlRoot - Similar to getRoot, but instead of flushing all the
581   /// PendingLoad items, flush all the PendingExports items. It is necessary
582   /// to do this before emitting a terminator instruction.
583   ///
584   SDValue getControlRoot();
585
586   SDLoc getCurSDLoc() const {
587     return SDLoc(CurInst, SDNodeOrder);
588   }
589
590   DebugLoc getCurDebugLoc() const {
591     return CurInst ? CurInst->getDebugLoc() : DebugLoc();
592   }
593
594   unsigned getSDNodeOrder() const { return SDNodeOrder; }
595
596   void CopyValueToVirtualRegister(const Value *V, unsigned Reg);
597
598   void visit(const Instruction &I);
599
600   void visit(unsigned Opcode, const User &I);
601
602   // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
603   // generate the debug data structures now that we've seen its definition.
604   void resolveDanglingDebugInfo(const Value *V, SDValue Val);
605   SDValue getValue(const Value *V);
606   SDValue getNonRegisterValue(const Value *V);
607   SDValue getValueImpl(const Value *V);
608
609   void setValue(const Value *V, SDValue NewN) {
610     SDValue &N = NodeMap[V];
611     assert(!N.getNode() && "Already set a value for this node!");
612     N = NewN;
613   }
614
615   void setUnusedArgValue(const Value *V, SDValue NewN) {
616     SDValue &N = UnusedArgNodeMap[V];
617     assert(!N.getNode() && "Already set a value for this node!");
618     N = NewN;
619   }
620
621   void FindMergedConditions(const Value *Cond, MachineBasicBlock *TBB,
622                             MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
623                             MachineBasicBlock *SwitchBB, unsigned Opc,
624                             uint32_t TW, uint32_t FW);
625   void EmitBranchForMergedCondition(const Value *Cond, MachineBasicBlock *TBB,
626                                     MachineBasicBlock *FBB,
627                                     MachineBasicBlock *CurBB,
628                                     MachineBasicBlock *SwitchBB,
629                                     uint32_t TW, uint32_t FW);
630   bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
631   bool isExportableFromCurrentBlock(const Value *V, const BasicBlock *FromBB);
632   void CopyToExportRegsIfNeeded(const Value *V);
633   void ExportFromCurrentBlock(const Value *V);
634   void LowerCallTo(ImmutableCallSite CS, SDValue Callee, bool IsTailCall,
635                    MachineBasicBlock *LandingPad = nullptr);
636
637   std::pair<SDValue, SDValue> lowerCallOperands(
638           ImmutableCallSite CS,
639           unsigned ArgIdx,
640           unsigned NumArgs,
641           SDValue Callee,
642           bool UseVoidTy = false,
643           MachineBasicBlock *LandingPad = nullptr);
644
645   /// UpdateSplitBlock - When an MBB was split during scheduling, update the
646   /// references that need to refer to the last resulting block.
647   void UpdateSplitBlock(MachineBasicBlock *First, MachineBasicBlock *Last);
648
649 private:
650   std::pair<SDValue, SDValue> lowerInvokable(
651           TargetLowering::CallLoweringInfo &CLI,
652           MachineBasicBlock *LandingPad);
653
654   // Terminator instructions.
655   void visitRet(const ReturnInst &I);
656   void visitBr(const BranchInst &I);
657   void visitSwitch(const SwitchInst &I);
658   void visitIndirectBr(const IndirectBrInst &I);
659   void visitUnreachable(const UnreachableInst &I);
660
661   // Helpers for visitSwitch
662   bool handleSmallSwitchRange(CaseRec& CR,
663                               CaseRecVector& WorkList,
664                               const Value* SV,
665                               MachineBasicBlock* Default,
666                               MachineBasicBlock *SwitchBB);
667   bool handleJTSwitchCase(CaseRec& CR,
668                           CaseRecVector& WorkList,
669                           const Value* SV,
670                           MachineBasicBlock* Default,
671                           MachineBasicBlock *SwitchBB);
672   bool handleBTSplitSwitchCase(CaseRec& CR,
673                                CaseRecVector& WorkList,
674                                const Value* SV,
675                                MachineBasicBlock *SwitchBB);
676   bool handleBitTestsSwitchCase(CaseRec& CR,
677                                 CaseRecVector& WorkList,
678                                 const Value* SV,
679                                 MachineBasicBlock* Default,
680                                 MachineBasicBlock *SwitchBB);
681
682   uint32_t getEdgeWeight(const MachineBasicBlock *Src,
683                          const MachineBasicBlock *Dst) const;
684   void addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
685                               uint32_t Weight = 0);
686 public:
687   void visitSwitchCase(CaseBlock &CB,
688                        MachineBasicBlock *SwitchBB);
689   void visitSPDescriptorParent(StackProtectorDescriptor &SPD,
690                                MachineBasicBlock *ParentBB);
691   void visitSPDescriptorFailure(StackProtectorDescriptor &SPD);
692   void visitBitTestHeader(BitTestBlock &B, MachineBasicBlock *SwitchBB);
693   void visitBitTestCase(BitTestBlock &BB,
694                         MachineBasicBlock* NextMBB,
695                         uint32_t BranchWeightToNext,
696                         unsigned Reg,
697                         BitTestCase &B,
698                         MachineBasicBlock *SwitchBB);
699   void visitJumpTable(JumpTable &JT);
700   void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH,
701                             MachineBasicBlock *SwitchBB);
702
703 private:
704   // These all get lowered before this pass.
705   void visitInvoke(const InvokeInst &I);
706   void visitResume(const ResumeInst &I);
707
708   void visitBinary(const User &I, unsigned OpCode);
709   void visitShift(const User &I, unsigned Opcode);
710   void visitAdd(const User &I)  { visitBinary(I, ISD::ADD); }
711   void visitFAdd(const User &I) { visitBinary(I, ISD::FADD); }
712   void visitSub(const User &I)  { visitBinary(I, ISD::SUB); }
713   void visitFSub(const User &I);
714   void visitMul(const User &I)  { visitBinary(I, ISD::MUL); }
715   void visitFMul(const User &I) { visitBinary(I, ISD::FMUL); }
716   void visitURem(const User &I) { visitBinary(I, ISD::UREM); }
717   void visitSRem(const User &I) { visitBinary(I, ISD::SREM); }
718   void visitFRem(const User &I) { visitBinary(I, ISD::FREM); }
719   void visitUDiv(const User &I) { visitBinary(I, ISD::UDIV); }
720   void visitSDiv(const User &I);
721   void visitFDiv(const User &I) { visitBinary(I, ISD::FDIV); }
722   void visitAnd (const User &I) { visitBinary(I, ISD::AND); }
723   void visitOr  (const User &I) { visitBinary(I, ISD::OR); }
724   void visitXor (const User &I) { visitBinary(I, ISD::XOR); }
725   void visitShl (const User &I) { visitShift(I, ISD::SHL); }
726   void visitLShr(const User &I) { visitShift(I, ISD::SRL); }
727   void visitAShr(const User &I) { visitShift(I, ISD::SRA); }
728   void visitICmp(const User &I);
729   void visitFCmp(const User &I);
730   // Visit the conversion instructions
731   void visitTrunc(const User &I);
732   void visitZExt(const User &I);
733   void visitSExt(const User &I);
734   void visitFPTrunc(const User &I);
735   void visitFPExt(const User &I);
736   void visitFPToUI(const User &I);
737   void visitFPToSI(const User &I);
738   void visitUIToFP(const User &I);
739   void visitSIToFP(const User &I);
740   void visitPtrToInt(const User &I);
741   void visitIntToPtr(const User &I);
742   void visitBitCast(const User &I);
743   void visitAddrSpaceCast(const User &I);
744
745   void visitExtractElement(const User &I);
746   void visitInsertElement(const User &I);
747   void visitShuffleVector(const User &I);
748
749   void visitExtractValue(const ExtractValueInst &I);
750   void visitInsertValue(const InsertValueInst &I);
751   void visitLandingPad(const LandingPadInst &I);
752
753   void visitGetElementPtr(const User &I);
754   void visitSelect(const User &I);
755
756   void visitAlloca(const AllocaInst &I);
757   void visitLoad(const LoadInst &I);
758   void visitStore(const StoreInst &I);
759   void visitAtomicCmpXchg(const AtomicCmpXchgInst &I);
760   void visitAtomicRMW(const AtomicRMWInst &I);
761   void visitFence(const FenceInst &I);
762   void visitPHI(const PHINode &I);
763   void visitCall(const CallInst &I);
764   bool visitMemCmpCall(const CallInst &I);
765   bool visitMemChrCall(const CallInst &I);
766   bool visitStrCpyCall(const CallInst &I, bool isStpcpy);
767   bool visitStrCmpCall(const CallInst &I);
768   bool visitStrLenCall(const CallInst &I);
769   bool visitStrNLenCall(const CallInst &I);
770   bool visitUnaryFloatCall(const CallInst &I, unsigned Opcode);
771   void visitAtomicLoad(const LoadInst &I);
772   void visitAtomicStore(const StoreInst &I);
773
774   void visitInlineAsm(ImmutableCallSite CS);
775   const char *visitIntrinsicCall(const CallInst &I, unsigned Intrinsic);
776   void visitTargetIntrinsic(const CallInst &I, unsigned Intrinsic);
777
778   void visitVAStart(const CallInst &I);
779   void visitVAArg(const VAArgInst &I);
780   void visitVAEnd(const CallInst &I);
781   void visitVACopy(const CallInst &I);
782   void visitStackmap(const CallInst &I);
783   void visitPatchpoint(ImmutableCallSite CS,
784                        MachineBasicBlock *LandingPad = nullptr);
785
786   void visitUserOp1(const Instruction &I) {
787     llvm_unreachable("UserOp1 should not exist at instruction selection time!");
788   }
789   void visitUserOp2(const Instruction &I) {
790     llvm_unreachable("UserOp2 should not exist at instruction selection time!");
791   }
792
793   void processIntegerCallValue(const Instruction &I,
794                                SDValue Value, bool IsSigned);
795
796   void HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB);
797
798   /// EmitFuncArgumentDbgValue - If V is an function argument then create
799   /// corresponding DBG_VALUE machine instruction for it now. At the end of
800   /// instruction selection, they will be inserted to the entry BB.
801   bool EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable, MDNode *Expr,
802                                 int64_t Offset, bool IsIndirect,
803                                 const SDValue &N);
804 };
805
806 } // end namespace llvm
807
808 #endif