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