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