52118f97611fd62b475b06d20de9a31218e1d019
[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* method,
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* method,
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* method,
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* method,
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   // method 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 method 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   // To find whether a particular call is to a var arg method
288   //
289   bool isVarArgCall(const MachineInstr *CallMI) const;
290
291
292 public:
293   UltraSparcRegInfo(const UltraSparc &tgt);
294
295   // To get complete machine information structure using the machine register
296   // information
297   //
298   inline const UltraSparc &getUltraSparcInfo() const { 
299     return *UltraSparcInfo;
300   }
301
302   // To find the register class used for a specified Type
303   //
304   inline unsigned getRegClassIDOfType(const Type *type,
305                                       bool isCCReg = false) const {
306     Type::PrimitiveID ty = type->getPrimitiveID();
307     unsigned res;
308     
309     // FIXME: Comparing types like this isn't very safe...
310     if ((ty && ty <= Type::LongTyID) || (ty == Type::LabelTyID) ||
311         (ty == Type::FunctionTyID) ||  (ty == Type::PointerTyID) )
312       res = IntRegClassID;             // sparc int reg (ty=0: void)
313     else if (ty <= Type::DoubleTyID)
314       res = FloatRegClassID;           // sparc float reg class
315     else { 
316       //std::cerr << "TypeID: " << ty << "\n";
317       assert(0 && "Cannot resolve register class for type");
318       return 0;
319     }
320
321     if(isCCReg)
322       return res + 2;      // corresponidng condition code regiser 
323     else 
324       return res;
325   }
326
327   // To find the register class of a Value
328   //
329   inline unsigned getRegClassIDOfValue(const Value *Val,
330                                        bool isCCReg = false) const {
331     return getRegClassIDOfType(Val->getType(), isCCReg);
332   }
333
334   
335
336   // getZeroRegNum - returns the register that contains always zero this is the
337   // unified register number
338   //
339   virtual int getZeroRegNum() const;
340
341   // getCallAddressReg - returns the reg used for pushing the address when a
342   // method is called. This can be used for other purposes between calls
343   //
344   unsigned getCallAddressReg() const;
345
346   // Returns the register containing the return address.
347   // It should be made sure that this  register contains the return 
348   // value when a return instruction is reached.
349   //
350   unsigned getReturnAddressReg() const;
351
352
353
354   // The following methods are used to color special live ranges (e.g.
355   // method args and return values etc.) with specific hardware registers
356   // as required. See SparcRegInfo.cpp for the implementation for Sparc.
357   //
358   void suggestRegs4MethodArgs(const Function *Meth, 
359                               LiveRangeInfo& LRI) const;
360
361   void suggestRegs4CallArgs(const MachineInstr *CallMI, 
362                             LiveRangeInfo& LRI,
363                             std::vector<RegClass *> RCL) const; 
364
365   void suggestReg4RetValue(const MachineInstr *RetMI, 
366                            LiveRangeInfo& LRI) const;
367
368
369   void colorMethodArgs(const Function *Meth,  LiveRangeInfo &LRI,
370                        AddedInstrns *FirstAI) const;
371
372   void colorCallArgs(const MachineInstr *CallMI, LiveRangeInfo &LRI,
373                      AddedInstrns *CallAI,  PhyRegAlloc &PRA,
374                      const BasicBlock *BB) const;
375
376   void colorRetValue(const MachineInstr *RetI,   LiveRangeInfo& LRI,
377                      AddedInstrns *RetAI) const;
378
379
380
381   // method used for printing a register for debugging purposes
382   //
383   static void printReg(const LiveRange *LR);
384
385   // this method provides a unique number for each register 
386   //
387   inline int getUnifiedRegNum(int RegClassID, int reg) const {
388
389     if( RegClassID == IntRegClassID && reg < 32 ) 
390       return reg;
391     else if ( RegClassID == FloatRegClassID && reg < 64)
392       return reg + 32;                  // we have 32 int regs
393     else if( RegClassID == FloatCCRegClassID && reg < 4)
394       return reg + 32 + 64;             // 32 int, 64 float
395     else if( RegClassID == IntCCRegClassID ) 
396       return reg + 4+ 32 + 64;                // only int cc reg
397     else if (reg==InvalidRegNum)                
398       return InvalidRegNum;
399     else  
400       assert(0 && "Invalid register class or reg number");
401     return 0;
402   }
403
404   // given the unified register number, this gives the name
405   // for generating assembly code or debugging.
406   //
407   virtual const std::string getUnifiedRegName(int reg) const;
408
409
410   // returns the # of bytes of stack space allocated for each register
411   // type. For Sparc, currently we allocate 8 bytes on stack for all 
412   // register types. We can optimize this later if necessary to save stack
413   // space (However, should make sure that stack alignment is correct)
414   //
415   inline int getSpilledRegSize(int RegType) const {
416     return 8;
417   }
418
419
420   // To obtain the return value and the indirect call address (if any)
421   // contained in a CALL machine instruction
422   //
423   const Value * getCallInstRetVal(const MachineInstr *CallMI) const;
424   const Value * getCallInstIndirectAddrVal(const MachineInstr *CallMI) const;
425
426
427   // The following methods are used to generate "copy" machine instructions
428   // for an architecture.
429   //
430   MachineInstr * cpReg2RegMI(unsigned SrcReg, unsigned DestReg,
431                              int RegType) const;
432
433   MachineInstr * cpReg2MemMI(unsigned SrcReg, unsigned DestPtrReg,
434                              int Offset, int RegType) const;
435
436   MachineInstr * cpMem2RegMI(unsigned SrcPtrReg, int Offset,
437                              unsigned DestReg, int RegType) const;
438
439   MachineInstr* cpValue2Value(Value *Src, Value *Dest) const;
440
441
442   // To see whether a register is a volatile (i.e., whehter it must be
443   // preserved acorss calls)
444   //
445   inline bool isRegVolatile(int RegClassID, int Reg) const {
446     return MachineRegClassArr[RegClassID]->isRegVolatile(Reg);
447   }
448
449
450   virtual unsigned getFramePointer() const;
451   virtual unsigned getStackPointer() const;
452
453   virtual int getInvalidRegNum() const {
454     return InvalidRegNum;
455   }
456
457   // This method inserts the caller saving code for call instructions
458   //
459   void insertCallerSavingCode(const MachineInstr *MInst, 
460                               const BasicBlock *BB, PhyRegAlloc &PRA ) const;
461 };
462
463
464
465
466 //---------------------------------------------------------------------------
467 // class UltraSparcSchedInfo
468 // 
469 // Purpose:
470 //   Interface to instruction scheduling information for UltraSPARC.
471 //   The parameter values above are based on UltraSPARC IIi.
472 //---------------------------------------------------------------------------
473
474
475 class UltraSparcSchedInfo: public MachineSchedInfo {
476 public:
477   UltraSparcSchedInfo(const TargetMachine &tgt);
478 protected:
479   virtual void initializeResources();
480 };
481
482
483 //---------------------------------------------------------------------------
484 // class UltraSparcFrameInfo 
485 // 
486 // Purpose:
487 //   Interface to stack frame layout info for the UltraSPARC.
488 //   Starting offsets for each area of the stack frame are aligned at
489 //   a multiple of getStackFrameSizeAlignment().
490 //---------------------------------------------------------------------------
491
492 class UltraSparcFrameInfo: public MachineFrameInfo {
493 public:
494   UltraSparcFrameInfo(const TargetMachine &tgt) : MachineFrameInfo(tgt) {}
495   
496 public:
497   int  getStackFrameSizeAlignment   () const { return StackFrameSizeAlignment;}
498   int  getMinStackFrameSize         () const { return MinStackFrameSize; }
499   int  getNumFixedOutgoingArgs      () const { return NumFixedOutgoingArgs; }
500   int  getSizeOfEachArgOnStack      () const { return SizeOfEachArgOnStack; }
501   bool argsOnStackHaveFixedSize     () const { return true; }
502
503   //
504   // These methods compute offsets using the frame contents for a
505   // particular method.  The frame contents are obtained from the
506   // MachineCodeInfoForMethod object for the given method.
507   // 
508   int getFirstIncomingArgOffset  (MachineCodeForMethod& mcInfo,
509                                   bool& pos) const
510   {
511     pos = true;                         // arguments area grows upwards
512     return FirstIncomingArgOffsetFromFP;
513   }
514   int getFirstOutgoingArgOffset  (MachineCodeForMethod& mcInfo,
515                                   bool& pos) const
516   {
517     pos = true;                         // arguments area grows upwards
518     return FirstOutgoingArgOffsetFromSP;
519   }
520   int getFirstOptionalOutgoingArgOffset(MachineCodeForMethod& mcInfo,
521                                         bool& pos)const
522   {
523     pos = true;                         // arguments area grows upwards
524     return FirstOptionalOutgoingArgOffsetFromSP;
525   }
526   
527   int getFirstAutomaticVarOffset (MachineCodeForMethod& mcInfo,
528                                   bool& pos) const;
529   int getRegSpillAreaOffset      (MachineCodeForMethod& mcInfo,
530                                   bool& pos) const;
531   int getTmpAreaOffset           (MachineCodeForMethod& mcInfo,
532                                   bool& pos) const;
533   int getDynamicAreaOffset       (MachineCodeForMethod& mcInfo,
534                                   bool& pos) const;
535
536   //
537   // These methods specify the base register used for each stack area
538   // (generally FP or SP)
539   // 
540   virtual int getIncomingArgBaseRegNum()               const {
541     return (int) target.getRegInfo().getFramePointer();
542   }
543   virtual int getOutgoingArgBaseRegNum()               const {
544     return (int) target.getRegInfo().getStackPointer();
545   }
546   virtual int getOptionalOutgoingArgBaseRegNum()       const {
547     return (int) target.getRegInfo().getStackPointer();
548   }
549   virtual int getAutomaticVarBaseRegNum()              const {
550     return (int) target.getRegInfo().getFramePointer();
551   }
552   virtual int getRegSpillAreaBaseRegNum()              const {
553     return (int) target.getRegInfo().getFramePointer();
554   }
555   virtual int getDynamicAreaBaseRegNum()               const {
556     return (int) target.getRegInfo().getStackPointer();
557   }
558   
559 private:
560   // All stack addresses must be offset by 0x7ff (2047) on Sparc V9.
561   static const int OFFSET                                  = (int) 0x7ff;
562   static const int StackFrameSizeAlignment                 =  16;
563   static const int MinStackFrameSize                       = 176;
564   static const int NumFixedOutgoingArgs                    =   6;
565   static const int SizeOfEachArgOnStack                    =   8;
566   static const int StaticAreaOffsetFromFP                  =  0 + OFFSET;
567   static const int FirstIncomingArgOffsetFromFP            = 128 + OFFSET;
568   static const int FirstOptionalIncomingArgOffsetFromFP    = 176 + OFFSET;
569   static const int FirstOutgoingArgOffsetFromSP            = 128 + OFFSET;
570   static const int FirstOptionalOutgoingArgOffsetFromSP    = 176 + OFFSET;
571 };
572
573
574 //---------------------------------------------------------------------------
575 // class UltraSparcCacheInfo 
576 // 
577 // Purpose:
578 //   Interface to cache parameters for the UltraSPARC.
579 //   Just use defaults for now.
580 //---------------------------------------------------------------------------
581
582 class UltraSparcCacheInfo: public MachineCacheInfo {
583 public:
584   UltraSparcCacheInfo(const TargetMachine &T) : MachineCacheInfo(T) {} 
585 };
586
587
588 //---------------------------------------------------------------------------
589 // class UltraSparcMachine 
590 // 
591 // Purpose:
592 //   Primary interface to machine description for the UltraSPARC.
593 //   Primarily just initializes machine-dependent parameters in
594 //   class TargetMachine, and creates machine-dependent subclasses
595 //   for classes such as InstrInfo, SchedInfo and RegInfo. 
596 //---------------------------------------------------------------------------
597
598 class UltraSparc : public TargetMachine {
599 private:
600   UltraSparcInstrInfo instrInfo;
601   UltraSparcSchedInfo schedInfo;
602   UltraSparcRegInfo   regInfo;
603   UltraSparcFrameInfo frameInfo;
604   UltraSparcCacheInfo cacheInfo;
605 public:
606   UltraSparc();
607   
608   virtual const MachineInstrInfo &getInstrInfo() const { return instrInfo; }
609   virtual const MachineSchedInfo &getSchedInfo() const { return schedInfo; }
610   virtual const MachineRegInfo   &getRegInfo()   const { return regInfo; }
611   virtual const MachineFrameInfo &getFrameInfo() const { return frameInfo; }
612   virtual const MachineCacheInfo &getCacheInfo() const { return cacheInfo; }
613
614   //
615   // addPassesToEmitAssembly - Add passes to the specified pass manager to get
616   // assembly langage code emited.  For sparc, we have to do ...
617   //
618   virtual void addPassesToEmitAssembly(PassManager &PM, std::ostream &Out);
619
620 private:
621   Pass *getMethodAsmPrinterPass(PassManager &PM, std::ostream &Out);
622   Pass *getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out);
623   Pass *getEmitBytecodeToAsmPass(std::ostream &Out);
624 };
625
626 #endif