0e80179f4eb5a1575e012fa9f7da7caec75fc3cc
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9Internals.h
1 // $Id$ -*- C++ -*--
2 //***************************************************************************
3 // File:
4 //      SparcInternals.h
5 // 
6 // Purpose:
7 //       This file defines stuff that is to be private to the Sparc
8 //       backend, but is shared among different portions of the backend.
9 //**************************************************************************/
10
11
12 #ifndef SPARC_INTERNALS_H
13 #define SPARC_INTERNALS_H
14
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Target/MachineInstrInfo.h"
17 #include "llvm/Target/MachineSchedInfo.h"
18 #include "llvm/Target/MachineFrameInfo.h"
19 #include "llvm/Target/MachineCacheInfo.h"
20 #include "llvm/Target/MachineRegInfo.h"
21 #include "llvm/Type.h"
22 #include <sys/types.h>
23
24 class LiveRange;
25 class UltraSparc;
26 class PhyRegAlloc;
27 class Pass;
28
29 Pass *createPrologEpilogCodeInserter(TargetMachine &TM);
30
31 // OpCodeMask definitions for the Sparc V9
32 // 
33 const OpCodeMask        Immed           = 0x00002000; // immed or reg operand?
34 const OpCodeMask        Annul           = 0x20000000; // annul delay instr?
35 const OpCodeMask        PredictTaken    = 0x00080000; // predict branch taken?
36
37
38 enum SparcInstrSchedClass {
39   SPARC_NONE,           /* Instructions with no scheduling restrictions */
40   SPARC_IEUN,           /* Integer class that can use IEU0 or IEU1 */
41   SPARC_IEU0,           /* Integer class IEU0 */
42   SPARC_IEU1,           /* Integer class IEU1 */
43   SPARC_FPM,            /* FP Multiply or Divide instructions */
44   SPARC_FPA,            /* All other FP instructions */ 
45   SPARC_CTI,            /* Control-transfer instructions */
46   SPARC_LD,             /* Load instructions */
47   SPARC_ST,             /* Store instructions */
48   SPARC_SINGLE,         /* Instructions that must issue by themselves */
49   
50   SPARC_INV,            /* This should stay at the end for the next value */
51   SPARC_NUM_SCHED_CLASSES = SPARC_INV
52 };
53
54
55 //---------------------------------------------------------------------------
56 // enum SparcMachineOpCode. 
57 // const MachineInstrDescriptor SparcMachineInstrDesc[]
58 // 
59 // Purpose:
60 //   Description of UltraSparc machine instructions.
61 // 
62 //---------------------------------------------------------------------------
63
64 enum SparcMachineOpCode {
65 #define I(ENUM, OPCODESTRING, NUMOPERANDS, RESULTPOS, MAXIMM, IMMSE, \
66           NUMDELAYSLOTS, LATENCY, SCHEDCLASS, INSTFLAGS)             \
67    ENUM,
68 #include "SparcInstr.def"
69
70   // End-of-array marker
71   INVALID_OPCODE,
72   NUM_REAL_OPCODES = PHI,               // number of valid opcodes
73   NUM_TOTAL_OPCODES = INVALID_OPCODE
74 };
75
76
77 // Array of machine instruction descriptions...
78 extern const MachineInstrDescriptor SparcMachineInstrDesc[];
79
80
81 //---------------------------------------------------------------------------
82 // class UltraSparcInstrInfo 
83 // 
84 // Purpose:
85 //   Information about individual instructions.
86 //   Most information is stored in the SparcMachineInstrDesc array above.
87 //   Other information is computed on demand, and most such functions
88 //   default to member functions in base class MachineInstrInfo. 
89 //---------------------------------------------------------------------------
90
91 class UltraSparcInstrInfo : public MachineInstrInfo {
92 public:
93   /*ctor*/      UltraSparcInstrInfo(const TargetMachine& tgt);
94
95   //
96   // All immediate constants are in position 1 except the
97   // store instructions.
98   // 
99   virtual int getImmedConstantPos(MachineOpCode opCode) const {
100     bool ignore;
101     if (this->maxImmedConstant(opCode, ignore) != 0)
102       {
103         assert(! this->isStore((MachineOpCode) STB - 1)); // first store is STB
104         assert(! this->isStore((MachineOpCode) STD + 1)); // last  store is STD
105         return (opCode >= STB && opCode <= STD)? 2 : 1;
106       }
107     else
108       return -1;
109   }
110   
111   virtual bool          hasResultInterlock      (MachineOpCode opCode) const
112   {
113     // All UltraSPARC instructions have interlocks (note that delay slots
114     // are not considered here).
115     // However, instructions that use the result of an FCMP produce a
116     // 9-cycle stall if they are issued less than 3 cycles after the FCMP.
117     // Force the compiler to insert a software interlock (i.e., gap of
118     // 2 other groups, including NOPs if necessary).
119     return (opCode == FCMPS || opCode == FCMPD || opCode == FCMPQ);
120   }
121
122   //-------------------------------------------------------------------------
123   // Code generation support for creating individual machine instructions
124   //-------------------------------------------------------------------------
125   
126   // Create an instruction sequence to put the constant `val' into
127   // the virtual register `dest'.  The generated instructions are
128   // returned in `minstrVec'.  Any temporary registers (TmpInstruction)
129   // created are returned in `tempVec'.
130   // 
131   virtual void  CreateCodeToLoadConst(Function *F,
132                                       Value* val,
133                                       Instruction* dest,
134                                       std::vector<MachineInstr*>& minstrVec,
135                                       std::vector<TmpInstruction*>& tmp) const;
136
137   
138   // Create an instruction sequence to copy an integer value `val'
139   // to a floating point value `dest' by copying to memory and back.
140   // val must be an integral type.  dest must be a Float or Double.
141   // The generated instructions are returned in `minstrVec'.
142   // Any temp. registers (TmpInstruction) created are returned in `tempVec'.
143   // 
144   virtual void  CreateCodeToCopyIntToFloat(Function* F,
145                                            Value* val,
146                                            Instruction* dest,
147                                            std::vector<MachineInstr*>& minstr,
148                                            std::vector<TmpInstruction*>& temp,
149                                            TargetMachine& target) const;
150
151   // Similarly, create an instruction sequence to copy an FP value
152   // `val' to an integer value `dest' by copying to memory and back.
153   // See the previous function for information about return values.
154   // 
155   virtual void  CreateCodeToCopyFloatToInt(Function* F,
156                                            Value* val,
157                                            Instruction* dest,
158                                            std::vector<MachineInstr*>& minstr,
159                                            std::vector<TmpInstruction*>& temp,
160                                            TargetMachine& target) const;
161
162  // create copy instruction(s)
163   virtual void CreateCopyInstructionsByType(const TargetMachine& target,
164                                             Function* F,
165                                             Value* src,
166                                             Instruction* dest,
167                                             std::vector<MachineInstr*>& minstr) const;
168 };
169
170
171 //----------------------------------------------------------------------------
172 // class UltraSparcRegInfo
173 //
174 // This class implements the virtual class MachineRegInfo for Sparc.
175 //
176 //----------------------------------------------------------------------------
177
178 class UltraSparcRegInfo : public MachineRegInfo {
179   // The actual register classes in the Sparc
180   //
181   enum RegClassIDs { 
182     IntRegClassID,                      // Integer
183     FloatRegClassID,                    // Float (both single/double)
184     IntCCRegClassID,                    // Int Condition Code
185     FloatCCRegClassID                   // Float Condition code
186   };
187
188
189   // Type of registers available in Sparc. There can be several reg types
190   // in the same class. For instace, the float reg class has Single/Double
191   // types
192   //
193   enum RegTypes {
194     IntRegType,
195     FPSingleRegType,
196     FPDoubleRegType,
197     IntCCRegType,
198     FloatCCRegType
199   };
200
201   // **** WARNING: If the above enum order is changed, also modify 
202   // getRegisterClassOfValue method below since it assumes this particular 
203   // order for efficiency.
204
205
206   // reverse pointer to get info about the ultra sparc machine
207   //
208   const UltraSparc *const UltraSparcInfo;
209
210   // Number of registers used for passing int args (usually 6: %o0 - %o5)
211   //
212   unsigned const NumOfIntArgRegs;
213
214   // Number of registers used for passing float args (usually 32: %f0 - %f31)
215   //
216   unsigned const NumOfFloatArgRegs;
217
218   // An out of bound register number that can be used to initialize register
219   // numbers. Useful for error detection.
220   //
221   int const InvalidRegNum;
222
223
224   // ========================  Private Methods =============================
225
226   // The following methods are used to color special live ranges (e.g.
227   // function args and return values etc.) with specific hardware registers
228   // as required. See SparcRegInfo.cpp for the implementation.
229   //
230   void setCallOrRetArgCol(LiveRange *LR, unsigned RegNo,
231                           const MachineInstr *MI, 
232                           std::hash_map<const MachineInstr *,
233                                         AddedInstrns *> &AIMap) const;
234
235   MachineInstr *getCopy2RegMI(const Value *SrcVal, unsigned Reg,
236                               unsigned RegClassID) const;
237
238   void suggestReg4RetAddr(const MachineInstr *RetMI, 
239                           LiveRangeInfo &LRI) const;
240
241   void suggestReg4CallAddr(const MachineInstr *CallMI, LiveRangeInfo &LRI,
242                            std::vector<RegClass *> RCList) const;
243
244
245
246   // The following methods are used to find the addresses etc. contained
247   // in specail machine instructions like CALL/RET
248   //
249   Value *getValue4ReturnAddr(const MachineInstr *MInst) const;
250   const Value *getCallInstRetAddr(const MachineInstr *CallMI) const;
251   unsigned getCallInstNumArgs(const MachineInstr *CallMI) const;
252
253
254   // The following 3 methods are used to find the RegType (see enum above)
255   // of a LiveRange, Value and using the unified RegClassID
256   int getRegType(const LiveRange *LR) const;
257   int getRegType(const Value *Val) const;
258   int getRegType(int reg) const;
259
260
261   // The following methods are used to generate copy instructions to move
262   // data between condition code registers
263   //
264   MachineInstr *cpCCR2IntMI(unsigned IntReg) const;
265   MachineInstr *cpInt2CCRMI(unsigned IntReg) const;
266
267   // Used to generate a copy instruction based on the register class of
268   // value.
269   //
270   MachineInstr *cpValue2RegMI(Value *Val,  unsigned DestReg,
271                               int RegType) const;
272
273
274   // The following 2 methods are used to order the instructions addeed by
275   // the register allocator in association with function calling. See
276   // SparcRegInfo.cpp for more details
277   //
278   void moveInst2OrdVec(std::vector<MachineInstr *> &OrdVec,
279                        MachineInstr *UnordInst,
280                        PhyRegAlloc &PRA) const;
281
282   void OrderAddedInstrns(std::vector<MachineInstr *> &UnordVec, 
283                          std::vector<MachineInstr *> &OrdVec,
284                          PhyRegAlloc &PRA) const;
285
286
287   // Compute which register can be used for an argument, if any
288   // 
289   int regNumForIntArg(bool inCallee, bool isVarArgsCall,
290                       unsigned argNo, unsigned intArgNo, unsigned fpArgNo,
291                       unsigned& regClassId) const;
292
293   int regNumForFPArg(unsigned RegType, bool inCallee, bool isVarArgsCall,
294                      unsigned argNo, unsigned intArgNo, unsigned fpArgNo,
295                      unsigned& regClassId) const;
296   
297 public:
298   UltraSparcRegInfo(const UltraSparc &tgt);
299
300   // To get complete machine information structure using the machine register
301   // information
302   //
303   inline const UltraSparc &getUltraSparcInfo() const { 
304     return *UltraSparcInfo;
305   }
306
307   // To find the register class used for a specified Type
308   //
309   inline unsigned getRegClassIDOfType(const Type *type,
310                                       bool isCCReg = false) const {
311     Type::PrimitiveID ty = type->getPrimitiveID();
312     unsigned res;
313     
314     // FIXME: Comparing types like this isn't very safe...
315     if ((ty && ty <= Type::LongTyID) || (ty == Type::LabelTyID) ||
316         (ty == Type::FunctionTyID) ||  (ty == Type::PointerTyID) )
317       res = IntRegClassID;             // sparc int reg (ty=0: void)
318     else if (ty <= Type::DoubleTyID)
319       res = FloatRegClassID;           // sparc float reg class
320     else { 
321       //std::cerr << "TypeID: " << ty << "\n";
322       assert(0 && "Cannot resolve register class for type");
323       return 0;
324     }
325
326     if(isCCReg)
327       return res + 2;      // corresponidng condition code regiser 
328     else 
329       return res;
330   }
331
332   // To find the register class of a Value
333   //
334   inline unsigned getRegClassIDOfValue(const Value *Val,
335                                        bool isCCReg = false) const {
336     return getRegClassIDOfType(Val->getType(), isCCReg);
337   }
338
339   
340
341   // getZeroRegNum - returns the register that contains always zero this is the
342   // unified register number
343   //
344   virtual int getZeroRegNum() const;
345
346   // getCallAddressReg - returns the reg used for pushing the address when a
347   // function is called. This can be used for other purposes between calls
348   //
349   unsigned getCallAddressReg() const;
350
351   // Returns the register containing the return address.
352   // It should be made sure that this  register contains the return 
353   // value when a return instruction is reached.
354   //
355   unsigned getReturnAddressReg() const;
356
357
358
359   // The following methods are used to color special live ranges (e.g.
360   // function args and return values etc.) with specific hardware registers
361   // as required. See SparcRegInfo.cpp for the implementation for Sparc.
362   //
363   void suggestRegs4MethodArgs(const Function *Meth, 
364                               LiveRangeInfo& LRI) const;
365
366   void suggestRegs4CallArgs(const MachineInstr *CallMI, 
367                             LiveRangeInfo& LRI,
368                             std::vector<RegClass *> RCL) const; 
369
370   void suggestReg4RetValue(const MachineInstr *RetMI, 
371                            LiveRangeInfo& LRI) const;
372
373
374   void colorMethodArgs(const Function *Meth,  LiveRangeInfo &LRI,
375                        AddedInstrns *FirstAI) const;
376
377   void colorCallArgs(const MachineInstr *CallMI, LiveRangeInfo &LRI,
378                      AddedInstrns *CallAI,  PhyRegAlloc &PRA,
379                      const BasicBlock *BB) const;
380
381   void colorRetValue(const MachineInstr *RetI,   LiveRangeInfo& LRI,
382                      AddedInstrns *RetAI) const;
383
384
385
386   // method used for printing a register for debugging purposes
387   //
388   static void printReg(const LiveRange *LR);
389
390   // this method provides a unique number for each register 
391   //
392   inline int getUnifiedRegNum(int RegClassID, int reg) const {
393
394     if( RegClassID == IntRegClassID && reg < 32 ) 
395       return reg;
396     else if ( RegClassID == FloatRegClassID && reg < 64)
397       return reg + 32;                  // we have 32 int regs
398     else if( RegClassID == FloatCCRegClassID && reg < 4)
399       return reg + 32 + 64;             // 32 int, 64 float
400     else if( RegClassID == IntCCRegClassID ) 
401       return reg + 4+ 32 + 64;                // only int cc reg
402     else if (reg==InvalidRegNum)                
403       return InvalidRegNum;
404     else  
405       assert(0 && "Invalid register class or reg number");
406     return 0;
407   }
408
409   // given the unified register number, this gives the name
410   // for generating assembly code or debugging.
411   //
412   virtual const std::string getUnifiedRegName(int reg) const;
413
414
415   // returns the # of bytes of stack space allocated for each register
416   // type. For Sparc, currently we allocate 8 bytes on stack for all 
417   // register types. We can optimize this later if necessary to save stack
418   // space (However, should make sure that stack alignment is correct)
419   //
420   inline int getSpilledRegSize(int RegType) const {
421     return 8;
422   }
423
424
425   // To obtain the return value and the indirect call address (if any)
426   // contained in a CALL machine instruction
427   //
428   const Value * getCallInstRetVal(const MachineInstr *CallMI) const;
429   const Value * getCallInstIndirectAddrVal(const MachineInstr *CallMI) const;
430
431
432   // The following methods are used to generate "copy" machine instructions
433   // for an architecture.
434   //
435   MachineInstr * cpReg2RegMI(unsigned SrcReg, unsigned DestReg,
436                              int RegType) const;
437   
438   MachineInstr * cpReg2MemMI(unsigned SrcReg, unsigned DestPtrReg,
439                              int Offset, int RegType) const;
440
441   MachineInstr * cpMem2RegMI(unsigned SrcPtrReg, int Offset,
442                              unsigned DestReg, int RegType) const;
443
444   MachineInstr* cpValue2Value(Value *Src, Value *Dest) const;
445
446
447   // To see whether a register is a volatile (i.e., whehter it must be
448   // preserved acorss calls)
449   //
450   inline bool isRegVolatile(int RegClassID, int Reg) const {
451     return MachineRegClassArr[RegClassID]->isRegVolatile(Reg);
452   }
453
454
455   virtual unsigned getFramePointer() const;
456   virtual unsigned getStackPointer() const;
457
458   virtual int getInvalidRegNum() const {
459     return InvalidRegNum;
460   }
461
462   // This method inserts the caller saving code for call instructions
463   //
464   void insertCallerSavingCode(const MachineInstr *MInst, 
465                               const BasicBlock *BB, PhyRegAlloc &PRA ) const;
466 };
467
468
469
470
471 //---------------------------------------------------------------------------
472 // class UltraSparcSchedInfo
473 // 
474 // Purpose:
475 //   Interface to instruction scheduling information for UltraSPARC.
476 //   The parameter values above are based on UltraSPARC IIi.
477 //---------------------------------------------------------------------------
478
479
480 class UltraSparcSchedInfo: public MachineSchedInfo {
481 public:
482   UltraSparcSchedInfo(const TargetMachine &tgt);
483 protected:
484   virtual void initializeResources();
485 };
486
487
488 //---------------------------------------------------------------------------
489 // class UltraSparcFrameInfo 
490 // 
491 // Purpose:
492 //   Interface to stack frame layout info for the UltraSPARC.
493 //   Starting offsets for each area of the stack frame are aligned at
494 //   a multiple of getStackFrameSizeAlignment().
495 //---------------------------------------------------------------------------
496
497 class UltraSparcFrameInfo: public MachineFrameInfo {
498 public:
499   UltraSparcFrameInfo(const TargetMachine &tgt) : MachineFrameInfo(tgt) {}
500   
501 public:
502   int  getStackFrameSizeAlignment() const { return StackFrameSizeAlignment;}
503   int  getMinStackFrameSize()       const { return MinStackFrameSize; }
504   int  getNumFixedOutgoingArgs()    const { return NumFixedOutgoingArgs; }
505   int  getSizeOfEachArgOnStack()    const { return SizeOfEachArgOnStack; }
506   bool argsOnStackHaveFixedSize()   const { return true; }
507
508   //
509   // These methods compute offsets using the frame contents for a
510   // particular function.  The frame contents are obtained from the
511   // MachineCodeInfoForMethod object for the given function.
512   // 
513   int getFirstIncomingArgOffset  (MachineCodeForMethod& mcInfo,
514                                   bool& growUp) const
515   {
516     growUp = true;                         // arguments area grows upwards
517     return FirstIncomingArgOffsetFromFP;
518   }
519   int getFirstOutgoingArgOffset  (MachineCodeForMethod& mcInfo,
520                                   bool& growUp) const
521   {
522     growUp = true;                         // arguments area grows upwards
523     return FirstOutgoingArgOffsetFromSP;
524   }
525   int getFirstOptionalOutgoingArgOffset(MachineCodeForMethod& mcInfo,
526                                         bool& growUp)const
527   {
528     growUp = true;                         // arguments area grows upwards
529     return FirstOptionalOutgoingArgOffsetFromSP;
530   }
531   
532   int getFirstAutomaticVarOffset (MachineCodeForMethod& mcInfo,
533                                   bool& growUp) const;
534   int getRegSpillAreaOffset      (MachineCodeForMethod& mcInfo,
535                                   bool& growUp) const;
536   int getTmpAreaOffset           (MachineCodeForMethod& mcInfo,
537                                   bool& growUp) const;
538   int getDynamicAreaOffset       (MachineCodeForMethod& mcInfo,
539                                   bool& growUp) const;
540
541   //
542   // These methods specify the base register used for each stack area
543   // (generally FP or SP)
544   // 
545   virtual int getIncomingArgBaseRegNum()               const {
546     return (int) target.getRegInfo().getFramePointer();
547   }
548   virtual int getOutgoingArgBaseRegNum()               const {
549     return (int) target.getRegInfo().getStackPointer();
550   }
551   virtual int getOptionalOutgoingArgBaseRegNum()       const {
552     return (int) target.getRegInfo().getStackPointer();
553   }
554   virtual int getAutomaticVarBaseRegNum()              const {
555     return (int) target.getRegInfo().getFramePointer();
556   }
557   virtual int getRegSpillAreaBaseRegNum()              const {
558     return (int) target.getRegInfo().getFramePointer();
559   }
560   virtual int getDynamicAreaBaseRegNum()               const {
561     return (int) target.getRegInfo().getStackPointer();
562   }
563   
564 private:
565   // All stack addresses must be offset by 0x7ff (2047) on Sparc V9.
566   static const int OFFSET                                  = (int) 0x7ff;
567   static const int StackFrameSizeAlignment                 =  16;
568   static const int MinStackFrameSize                       = 176;
569   static const int NumFixedOutgoingArgs                    =   6;
570   static const int SizeOfEachArgOnStack                    =   8;
571   static const int StaticAreaOffsetFromFP                  =  0 + OFFSET;
572   static const int FirstIncomingArgOffsetFromFP            = 128 + OFFSET;
573   static const int FirstOptionalIncomingArgOffsetFromFP    = 176 + OFFSET;
574   static const int FirstOutgoingArgOffsetFromSP            = 128 + OFFSET;
575   static const int FirstOptionalOutgoingArgOffsetFromSP    = 176 + OFFSET;
576 };
577
578
579 //---------------------------------------------------------------------------
580 // class UltraSparcCacheInfo 
581 // 
582 // Purpose:
583 //   Interface to cache parameters for the UltraSPARC.
584 //   Just use defaults for now.
585 //---------------------------------------------------------------------------
586
587 class UltraSparcCacheInfo: public MachineCacheInfo {
588 public:
589   UltraSparcCacheInfo(const TargetMachine &T) : MachineCacheInfo(T) {} 
590 };
591
592
593 //---------------------------------------------------------------------------
594 // class UltraSparcMachine 
595 // 
596 // Purpose:
597 //   Primary interface to machine description for the UltraSPARC.
598 //   Primarily just initializes machine-dependent parameters in
599 //   class TargetMachine, and creates machine-dependent subclasses
600 //   for classes such as InstrInfo, SchedInfo and RegInfo. 
601 //---------------------------------------------------------------------------
602
603 class UltraSparc : public TargetMachine {
604 private:
605   UltraSparcInstrInfo instrInfo;
606   UltraSparcSchedInfo schedInfo;
607   UltraSparcRegInfo   regInfo;
608   UltraSparcFrameInfo frameInfo;
609   UltraSparcCacheInfo cacheInfo;
610 public:
611   UltraSparc();
612   
613   virtual const MachineInstrInfo &getInstrInfo() const { return instrInfo; }
614   virtual const MachineSchedInfo &getSchedInfo() const { return schedInfo; }
615   virtual const MachineRegInfo   &getRegInfo()   const { return regInfo; }
616   virtual const MachineFrameInfo &getFrameInfo() const { return frameInfo; }
617   virtual const MachineCacheInfo &getCacheInfo() const { return cacheInfo; }
618
619   //
620   // addPassesToEmitAssembly - Add passes to the specified pass manager to get
621   // assembly langage code emited.  For sparc, we have to do ...
622   //
623   virtual void addPassesToEmitAssembly(PassManager &PM, std::ostream &Out);
624
625 private:
626   Pass *getFunctionAsmPrinterPass(PassManager &PM, std::ostream &Out);
627   Pass *getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out);
628   Pass *getEmitBytecodeToAsmPass(std::ostream &Out);
629 };
630
631 #endif