Move the FunctionLoweringInfo class and some related utility functions out
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuild.h
1 //===-- SelectionDAGBuild.h - Selection-DAG building ----------------------===//
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 SELECTIONDAGBUILD_H
15 #define SELECTIONDAGBUILD_H
16
17 #include "llvm/Constants.h"
18 #include "llvm/CodeGen/SelectionDAG.h"
19 #include "llvm/ADT/APInt.h"
20 #include "llvm/ADT/DenseMap.h"
21 #ifndef NDEBUG
22 #include "llvm/ADT/SmallSet.h"
23 #endif
24 #include "llvm/CodeGen/SelectionDAGNodes.h"
25 #include "llvm/CodeGen/ValueTypes.h"
26 #include "llvm/Support/CallSite.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include <vector>
30 #include <set>
31
32 namespace llvm {
33
34 class AliasAnalysis;
35 class AllocaInst;
36 class BasicBlock;
37 class BitCastInst;
38 class BranchInst;
39 class CallInst;
40 class ExtractElementInst;
41 class ExtractValueInst;
42 class FCmpInst;
43 class FPExtInst;
44 class FPToSIInst;
45 class FPToUIInst;
46 class FPTruncInst;
47 class Function;
48 class FunctionLoweringInfo;
49 class GetElementPtrInst;
50 class GCFunctionInfo;
51 class ICmpInst;
52 class IntToPtrInst;
53 class IndirectBrInst;
54 class InvokeInst;
55 class InsertElementInst;
56 class InsertValueInst;
57 class Instruction;
58 class LoadInst;
59 class MachineBasicBlock;
60 class MachineFunction;
61 class MachineInstr;
62 class MachineModuleInfo;
63 class MachineRegisterInfo;
64 class PHINode;
65 class PtrToIntInst;
66 class ReturnInst;
67 class SDISelAsmOperandInfo;
68 class SExtInst;
69 class SelectInst;
70 class ShuffleVectorInst;
71 class SIToFPInst;
72 class StoreInst;
73 class SwitchInst;
74 class TargetData;
75 class TargetLowering;
76 class TruncInst;
77 class UIToFPInst;
78 class UnreachableInst;
79 class UnwindInst;
80 class VAArgInst;
81 class ZExtInst;
82
83 //===----------------------------------------------------------------------===//
84 /// SelectionDAGLowering - This is the common target-independent lowering
85 /// implementation that is parameterized by a TargetLowering object.
86 /// Also, targets can overload any lowering method.
87 ///
88 class SelectionDAGLowering {
89   MachineBasicBlock *CurMBB;
90
91   /// CurDebugLoc - current file + line number.  Changes as we build the DAG.
92   DebugLoc CurDebugLoc;
93
94   DenseMap<const Value*, SDValue> NodeMap;
95
96   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
97   /// them up and then emit token factor nodes when possible.  This allows us to
98   /// get simple disambiguation between loads without worrying about alias
99   /// analysis.
100   SmallVector<SDValue, 8> PendingLoads;
101
102   /// PendingExports - CopyToReg nodes that copy values to virtual registers
103   /// for export to other blocks need to be emitted before any terminator
104   /// instruction, but they have no other ordering requirements. We bunch them
105   /// up and the emit a single tokenfactor for them just before terminator
106   /// instructions.
107   SmallVector<SDValue, 8> PendingExports;
108
109   /// Case - A struct to record the Value for a switch case, and the
110   /// case's target basic block.
111   struct Case {
112     Constant* Low;
113     Constant* High;
114     MachineBasicBlock* BB;
115
116     Case() : Low(0), High(0), BB(0) { }
117     Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
118       Low(low), High(high), BB(bb) { }
119     APInt size() const {
120       const APInt &rHigh = cast<ConstantInt>(High)->getValue();
121       const APInt &rLow  = cast<ConstantInt>(Low)->getValue();
122       return (rHigh - rLow + 1ULL);
123     }
124   };
125
126   struct CaseBits {
127     uint64_t Mask;
128     MachineBasicBlock* BB;
129     unsigned Bits;
130
131     CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
132       Mask(mask), BB(bb), Bits(bits) { }
133   };
134
135   typedef std::vector<Case>           CaseVector;
136   typedef std::vector<CaseBits>       CaseBitsVector;
137   typedef CaseVector::iterator        CaseItr;
138   typedef std::pair<CaseItr, CaseItr> CaseRange;
139
140   /// CaseRec - A struct with ctor used in lowering switches to a binary tree
141   /// of conditional branches.
142   struct CaseRec {
143     CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
144     CaseBB(bb), LT(lt), GE(ge), Range(r) {}
145
146     /// CaseBB - The MBB in which to emit the compare and branch
147     MachineBasicBlock *CaseBB;
148     /// LT, GE - If nonzero, we know the current case value must be less-than or
149     /// greater-than-or-equal-to these Constants.
150     Constant *LT;
151     Constant *GE;
152     /// Range - A pair of iterators representing the range of case values to be
153     /// processed at this point in the binary search tree.
154     CaseRange Range;
155   };
156
157   typedef std::vector<CaseRec> CaseRecVector;
158
159   /// The comparison function for sorting the switch case values in the vector.
160   /// WARNING: Case ranges should be disjoint!
161   struct CaseCmp {
162     bool operator () (const Case& C1, const Case& C2) {
163       assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
164       const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
165       const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
166       return CI1->getValue().slt(CI2->getValue());
167     }
168   };
169
170   struct CaseBitsCmp {
171     bool operator () (const CaseBits& C1, const CaseBits& C2) {
172       return C1.Bits > C2.Bits;
173     }
174   };
175
176   size_t Clusterify(CaseVector& Cases, const SwitchInst &SI);
177
178   /// CaseBlock - This structure is used to communicate between SDLowering and
179   /// SDISel for the code generation of additional basic blocks needed by multi-
180   /// case switch statements.
181   struct CaseBlock {
182     CaseBlock(ISD::CondCode cc, Value *cmplhs, Value *cmprhs, Value *cmpmiddle,
183               MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
184               MachineBasicBlock *me)
185       : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
186         TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
187     // CC - the condition code to use for the case block's setcc node
188     ISD::CondCode CC;
189     // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
190     // Emit by default LHS op RHS. MHS is used for range comparisons:
191     // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
192     Value *CmpLHS, *CmpMHS, *CmpRHS;
193     // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
194     MachineBasicBlock *TrueBB, *FalseBB;
195     // ThisBB - the block into which to emit the code for the setcc and branches
196     MachineBasicBlock *ThisBB;
197   };
198   struct JumpTable {
199     JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
200               MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
201   
202     /// Reg - the virtual register containing the index of the jump table entry
203     //. to jump to.
204     unsigned Reg;
205     /// JTI - the JumpTableIndex for this jump table in the function.
206     unsigned JTI;
207     /// MBB - the MBB into which to emit the code for the indirect jump.
208     MachineBasicBlock *MBB;
209     /// Default - the MBB of the default bb, which is a successor of the range
210     /// check MBB.  This is when updating PHI nodes in successors.
211     MachineBasicBlock *Default;
212   };
213   struct JumpTableHeader {
214     JumpTableHeader(APInt F, APInt L, Value* SV, MachineBasicBlock* H,
215                     bool E = false):
216       First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
217     APInt First;
218     APInt Last;
219     Value *SValue;
220     MachineBasicBlock *HeaderBB;
221     bool Emitted;
222   };
223   typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
224
225   struct BitTestCase {
226     BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
227       Mask(M), ThisBB(T), TargetBB(Tr) { }
228     uint64_t Mask;
229     MachineBasicBlock* ThisBB;
230     MachineBasicBlock* TargetBB;
231   };
232
233   typedef SmallVector<BitTestCase, 3> BitTestInfo;
234
235   struct BitTestBlock {
236     BitTestBlock(APInt F, APInt R, Value* SV,
237                  unsigned Rg, bool E,
238                  MachineBasicBlock* P, MachineBasicBlock* D,
239                  const BitTestInfo& C):
240       First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
241       Parent(P), Default(D), Cases(C) { }
242     APInt First;
243     APInt Range;
244     Value  *SValue;
245     unsigned Reg;
246     bool Emitted;
247     MachineBasicBlock *Parent;
248     MachineBasicBlock *Default;
249     BitTestInfo Cases;
250   };
251
252 public:
253   // TLI - This is information that describes the available target features we
254   // need for lowering.  This indicates when operations are unavailable,
255   // implemented with a libcall, etc.
256   TargetLowering &TLI;
257   SelectionDAG &DAG;
258   const TargetData *TD;
259   AliasAnalysis *AA;
260
261   /// SwitchCases - Vector of CaseBlock structures used to communicate
262   /// SwitchInst code generation information.
263   std::vector<CaseBlock> SwitchCases;
264   /// JTCases - Vector of JumpTable structures used to communicate
265   /// SwitchInst code generation information.
266   std::vector<JumpTableBlock> JTCases;
267   /// BitTestCases - Vector of BitTestBlock structures used to communicate
268   /// SwitchInst code generation information.
269   std::vector<BitTestBlock> BitTestCases;
270
271   /// PHINodesToUpdate - A list of phi instructions whose operand list will
272   /// be updated after processing the current basic block.
273   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
274
275   /// EdgeMapping - If an edge from CurMBB to any MBB is changed (e.g. due to
276   /// scheduler custom lowering), track the change here.
277   DenseMap<MachineBasicBlock*, MachineBasicBlock*> EdgeMapping;
278
279   // Emit PHI-node-operand constants only once even if used by multiple
280   // PHI nodes.
281   DenseMap<Constant*, unsigned> ConstantsOut;
282
283   /// FuncInfo - Information about the function as a whole.
284   ///
285   FunctionLoweringInfo &FuncInfo;
286
287   /// OptLevel - What optimization level we're generating code for.
288   /// 
289   CodeGenOpt::Level OptLevel;
290   
291   /// GFI - Garbage collection metadata for the function.
292   GCFunctionInfo *GFI;
293
294   /// HasTailCall - This is set to true if a call in the current
295   /// block has been translated as a tail call. In this case,
296   /// no subsequent DAG nodes should be created.
297   ///
298   bool HasTailCall;
299
300   LLVMContext *Context;
301
302   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
303                        FunctionLoweringInfo &funcinfo,
304                        CodeGenOpt::Level ol)
305     : CurDebugLoc(DebugLoc::getUnknownLoc()), 
306       TLI(tli), DAG(dag), FuncInfo(funcinfo), OptLevel(ol),
307       HasTailCall(false),
308       Context(dag.getContext()) {
309   }
310
311   void init(GCFunctionInfo *gfi, AliasAnalysis &aa);
312
313   /// clear - Clear out the curret SelectionDAG and the associated
314   /// state and prepare this SelectionDAGLowering object to be used
315   /// for a new block. This doesn't clear out information about
316   /// additional blocks that are needed to complete switch lowering
317   /// or PHI node updating; that information is cleared out as it is
318   /// consumed.
319   void clear();
320
321   /// getRoot - Return the current virtual root of the Selection DAG,
322   /// flushing any PendingLoad items. This must be done before emitting
323   /// a store or any other node that may need to be ordered after any
324   /// prior load instructions.
325   ///
326   SDValue getRoot();
327
328   /// getControlRoot - Similar to getRoot, but instead of flushing all the
329   /// PendingLoad items, flush all the PendingExports items. It is necessary
330   /// to do this before emitting a terminator instruction.
331   ///
332   SDValue getControlRoot();
333
334   DebugLoc getCurDebugLoc() const { return CurDebugLoc; }
335   void setCurDebugLoc(DebugLoc dl) { CurDebugLoc = dl; }
336
337   void CopyValueToVirtualRegister(Value *V, unsigned Reg);
338
339   void visit(Instruction &I);
340
341   void visit(unsigned Opcode, User &I);
342
343   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
344
345   SDValue getValue(const Value *V);
346
347   void setValue(const Value *V, SDValue NewN) {
348     SDValue &N = NodeMap[V];
349     assert(N.getNode() == 0 && "Already set a value for this node!");
350     N = NewN;
351   }
352   
353   void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
354                             std::set<unsigned> &OutputRegs, 
355                             std::set<unsigned> &InputRegs);
356
357   void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
358                             MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
359                             unsigned Opc);
360   void EmitBranchForMergedCondition(Value *Cond, MachineBasicBlock *TBB,
361                                     MachineBasicBlock *FBB,
362                                     MachineBasicBlock *CurBB);
363   bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
364   bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
365   void CopyToExportRegsIfNeeded(Value *V);
366   void ExportFromCurrentBlock(Value *V);
367   void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
368                    MachineBasicBlock *LandingPad = NULL);
369
370 private:
371   // Terminator instructions.
372   void visitRet(ReturnInst &I);
373   void visitBr(BranchInst &I);
374   void visitSwitch(SwitchInst &I);
375   void visitIndirectBr(IndirectBrInst &I);
376   void visitUnreachable(UnreachableInst &I) { /* noop */ }
377
378   // Helpers for visitSwitch
379   bool handleSmallSwitchRange(CaseRec& CR,
380                               CaseRecVector& WorkList,
381                               Value* SV,
382                               MachineBasicBlock* Default);
383   bool handleJTSwitchCase(CaseRec& CR,
384                           CaseRecVector& WorkList,
385                           Value* SV,
386                           MachineBasicBlock* Default);
387   bool handleBTSplitSwitchCase(CaseRec& CR,
388                                CaseRecVector& WorkList,
389                                Value* SV,
390                                MachineBasicBlock* Default);
391   bool handleBitTestsSwitchCase(CaseRec& CR,
392                                 CaseRecVector& WorkList,
393                                 Value* SV,
394                                 MachineBasicBlock* Default);  
395 public:
396   void visitSwitchCase(CaseBlock &CB);
397   void visitBitTestHeader(BitTestBlock &B);
398   void visitBitTestCase(MachineBasicBlock* NextMBB,
399                         unsigned Reg,
400                         BitTestCase &B);
401   void visitJumpTable(JumpTable &JT);
402   void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
403   
404 private:
405   // These all get lowered before this pass.
406   void visitInvoke(InvokeInst &I);
407   void visitUnwind(UnwindInst &I);
408
409   void visitBinary(User &I, unsigned OpCode);
410   void visitShift(User &I, unsigned Opcode);
411   void visitAdd(User &I)  { visitBinary(I, ISD::ADD); }
412   void visitFAdd(User &I) { visitBinary(I, ISD::FADD); }
413   void visitSub(User &I)  { visitBinary(I, ISD::SUB); }
414   void visitFSub(User &I);
415   void visitMul(User &I)  { visitBinary(I, ISD::MUL); }
416   void visitFMul(User &I) { visitBinary(I, ISD::FMUL); }
417   void visitURem(User &I) { visitBinary(I, ISD::UREM); }
418   void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
419   void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
420   void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
421   void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
422   void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
423   void visitAnd (User &I) { visitBinary(I, ISD::AND); }
424   void visitOr  (User &I) { visitBinary(I, ISD::OR); }
425   void visitXor (User &I) { visitBinary(I, ISD::XOR); }
426   void visitShl (User &I) { visitShift(I, ISD::SHL); }
427   void visitLShr(User &I) { visitShift(I, ISD::SRL); }
428   void visitAShr(User &I) { visitShift(I, ISD::SRA); }
429   void visitICmp(User &I);
430   void visitFCmp(User &I);
431   // Visit the conversion instructions
432   void visitTrunc(User &I);
433   void visitZExt(User &I);
434   void visitSExt(User &I);
435   void visitFPTrunc(User &I);
436   void visitFPExt(User &I);
437   void visitFPToUI(User &I);
438   void visitFPToSI(User &I);
439   void visitUIToFP(User &I);
440   void visitSIToFP(User &I);
441   void visitPtrToInt(User &I);
442   void visitIntToPtr(User &I);
443   void visitBitCast(User &I);
444
445   void visitExtractElement(User &I);
446   void visitInsertElement(User &I);
447   void visitShuffleVector(User &I);
448
449   void visitExtractValue(ExtractValueInst &I);
450   void visitInsertValue(InsertValueInst &I);
451
452   void visitGetElementPtr(User &I);
453   void visitSelect(User &I);
454
455   void visitAlloca(AllocaInst &I);
456   void visitLoad(LoadInst &I);
457   void visitStore(StoreInst &I);
458   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
459   void visitCall(CallInst &I);
460   void visitInlineAsm(CallSite CS);
461   const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
462   void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
463
464   void visitPow(CallInst &I);
465   void visitExp2(CallInst &I);
466   void visitExp(CallInst &I);
467   void visitLog(CallInst &I);
468   void visitLog2(CallInst &I);
469   void visitLog10(CallInst &I);
470
471   void visitVAStart(CallInst &I);
472   void visitVAArg(VAArgInst &I);
473   void visitVAEnd(CallInst &I);
474   void visitVACopy(CallInst &I);
475
476   void visitUserOp1(Instruction &I) {
477     llvm_unreachable("UserOp1 should not exist at instruction selection time!");
478   }
479   void visitUserOp2(Instruction &I) {
480     llvm_unreachable("UserOp2 should not exist at instruction selection time!");
481   }
482   
483   const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
484   const char *implVisitAluOverflow(CallInst &I, ISD::NodeType Op);
485 };
486
487 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
488 /// call, and add them to the specified machine basic block.
489 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
490                   MachineBasicBlock *MBB);
491
492 } // end namespace llvm
493
494 #endif