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