Add support to print constant arrays and structures.
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9AsmPrinter.cpp
1 //===-- EmitAssembly.cpp - Emit Sparc Specific .s File ---------------------==//
2 //
3 // This file implements all of the stuff neccesary to output a .s file from
4 // LLVM.  The code in this file assumes that the specified module has already
5 // been compiled into the internal data structures of the Module.
6 //
7 // The entry point of this file is the UltraSparc::emitAssembly method.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "SparcInternals.h"
12 #include "llvm/Analysis/SlotCalculator.h"
13 #include "llvm/Transforms/Linker.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/GlobalVariable.h"
16 #include "llvm/GlobalValue.h"
17 #include "llvm/ConstPoolVals.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/BasicBlock.h"
20 #include "llvm/Method.h"
21 #include "llvm/Module.h"
22 #include "llvm/Support/HashExtras.h"
23 #include "llvm/Support/StringExtras.h"
24 #include <locale.h>
25
26 namespace {
27
28
29 class SparcAsmPrinter {
30   typedef hash_map<const Value*, int> ValIdMap;
31   typedef ValIdMap::      iterator ValIdMapIterator;
32   typedef ValIdMap::const_iterator ValIdMapConstIterator;
33   
34   ostream &toAsm;
35   SlotCalculator Table;   // map anonymous values to unique integer IDs
36   ValIdMap valToIdMap;    // used for values not handled by SlotCalculator 
37   const UltraSparc &Target;
38   
39   enum Sections {
40     Unknown,
41     Text,
42     ReadOnlyData,
43     InitRWData,
44     UninitRWData,
45   } CurSection;
46   
47 public:
48   inline SparcAsmPrinter(ostream &o, const Module *M, const UltraSparc &t)
49     : toAsm(o), Table(SlotCalculator(M, true)), Target(t), CurSection(Unknown) {
50     emitModule(M);
51   }
52
53 private :
54   void emitModule(const Module *M);
55   void emitMethod(const Method *M);
56   void emitGlobalsAndConstants(const Module* module);
57   //void processMethodArgument(const MethodArgument *MA);
58   void emitBasicBlock(const BasicBlock *BB);
59   void emitMachineInst(const MachineInstr *MI);
60   
61   void printGlobalVariable(const GlobalVariable* GV);
62   void printSingleConstant(const ConstPoolVal* CV, string valID = string(""));
63   void printConstant(      const ConstPoolVal* CV, string valID = string(""));
64   
65   unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
66   void printOneOperand(const MachineOperand &Op);
67
68   bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
69   bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
70   
71   // enterSection - Use this method to enter a different section of the output
72   // executable.  This is used to only output neccesary section transitions.
73   //
74   void enterSection(enum Sections S) {
75     if (S == CurSection) return;        // Only switch section if neccesary
76     CurSection = S;
77
78     toAsm << "\n\t.section ";
79     switch (S)
80       {
81       default: assert(0 && "Bad section name!");
82       case Text:         toAsm << "\".text\""; break;
83       case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
84       case InitRWData:   toAsm << "\".data\",#alloc,#write"; break;
85       case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
86       }
87     toAsm << "\n";
88   }
89
90   string getValidSymbolName(const string &S) {
91     string Result;
92     
93     // Symbol names in Sparc assembly language have these rules:
94     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
95     // (b) A name beginning in "." is treated as a local name.
96     // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
97     // 
98     if (S[0] == '_' || isdigit(S[0]))
99       Result += "ll";
100     
101     for (unsigned i = 0; i < S.size(); ++i)
102       {
103         char C = S[i];
104         if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
105           Result += C;
106         else
107           {
108             Result += '_';
109             Result += char('0' + ((unsigned char)C >> 4));
110             Result += char('0' + (C & 0xF));
111           }
112       }
113     return Result;
114   }
115
116   // getID - Return a valid identifier for the specified value.  Base it on
117   // the name of the identifier if possible, use a numbered value based on
118   // prefix otherwise.  FPrefix is always prepended to the output identifier.
119   //
120   string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
121     string Result;
122     string FP(FPrefix ? FPrefix : "");  // "Forced prefix"
123     if (V->hasName()) {
124       Result = FP + V->getName();
125     } else {
126       int valId = Table.getValSlot(V);
127       if (valId == -1) {
128         ValIdMapConstIterator I = valToIdMap.find(V);
129         valId = (I == valToIdMap.end())? (valToIdMap[V] = valToIdMap.size())
130                                        : (*I).second;
131       }
132       Result = FP + string(Prefix) + itostr(valId);
133     }
134     return getValidSymbolName(Result);
135   }
136   
137   // getID Wrappers - Ensure consistent usage...
138   string getID(const Module *M) {
139     return getID(M, "LLVMModule_");
140   }
141   string getID(const Method *M) {
142     return getID(M, "LLVMMethod_");
143   }
144   string getID(const BasicBlock *BB) {
145     return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
146   }
147   string getID(const GlobalVariable *GV) {
148     return getID(GV, "LLVMGlobal_", ".G_");
149   }
150   string getID(const ConstPoolVal *CV) {
151     return getID(CV, "LLVMConst_", ".C_");
152   }
153   
154   unsigned getOperandMask(unsigned Opcode) {
155     switch (Opcode) {
156     case SUBcc:   return 1 << 3;  // Remove CC argument
157     case BA:    case BRZ:         // Remove Arg #0, which is always null or xcc
158     case BRLEZ: case BRLZ:
159     case BRNZ:  case BRGZ:
160     case BRGEZ:   return 1 << 0;
161
162     default:      return 0;       // By default, don't hack operands...
163     }
164   }
165 };
166
167 inline bool
168 SparcAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
169                                        unsigned int opNum) {
170   switch (MI->getOpCode()) {
171   case JMPLCALL:
172   case JMPLRET: return (opNum == 0);
173   default:      return false;
174   }
175 }
176
177
178 inline bool
179 SparcAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
180                                        unsigned int opNum) {
181   if (Target.getInstrInfo().isLoad(MI->getOpCode()))
182     return (opNum == 0);
183   else if (Target.getInstrInfo().isStore(MI->getOpCode()))
184     return (opNum == 1);
185   else
186     return false;
187 }
188
189
190 #define PrintOp1PlusOp2(Op1, Op2) \
191   printOneOperand(Op1); \
192   toAsm << "+"; \
193   printOneOperand(Op2);
194
195 unsigned int
196 SparcAsmPrinter::printOperands(const MachineInstr *MI,
197                                unsigned int opNum)
198 {
199   const MachineOperand& Op = MI->getOperand(opNum);
200   
201   if (OpIsBranchTargetLabel(MI, opNum))
202     {
203       PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
204       return 2;
205     }
206   else if (OpIsMemoryAddressBase(MI, opNum))
207     {
208       toAsm << "[";
209       PrintOp1PlusOp2(Op, MI->getOperand(opNum+1));
210       toAsm << "]";
211       return 2;
212     }
213   else
214     {
215       printOneOperand(Op);
216       return 1;
217     }
218 }
219
220
221 void
222 SparcAsmPrinter::printOneOperand(const MachineOperand &op)
223 {
224   switch (op.getOperandType())
225     {
226     case MachineOperand::MO_VirtualRegister:
227     case MachineOperand::MO_CCRegister:
228     case MachineOperand::MO_MachineRegister:
229       {
230         int RegNum = (int)op.getAllocatedRegNum();
231         
232         // ****this code is temporary till NULL Values are fixed
233         if (RegNum == 10000) {
234           toAsm << "<NULL VALUE>";
235         } else {
236           toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
237         }
238         break;
239       }
240     
241     case MachineOperand::MO_PCRelativeDisp:
242       {
243         const Value *Val = op.getVRegValue();
244         if (!Val)
245           toAsm << "\t<*NULL Value*>";
246         else if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
247           toAsm << getID(BB);
248         else if (const Method *M = dyn_cast<const Method>(Val))
249           toAsm << getID(M);
250         else if (const GlobalVariable *GV=dyn_cast<const GlobalVariable>(Val))
251           toAsm << getID(GV);
252         else if (const ConstPoolVal *CV = dyn_cast<const ConstPoolVal>(Val))
253           toAsm << getID(CV);
254         else
255           toAsm << "<unknown value=" << Val << ">";
256         break;
257       }
258     
259     case MachineOperand::MO_SignExtendedImmed:
260     case MachineOperand::MO_UnextendedImmed:
261       toAsm << op.getImmedValue();
262       break;
263     
264     default:
265       toAsm << op;      // use dump field
266       break;
267     }
268 }
269
270
271 void
272 SparcAsmPrinter::emitMachineInst(const MachineInstr *MI)
273 {
274   unsigned Opcode = MI->getOpCode();
275
276   if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
277     return;  // IGNORE PHI NODES
278
279   toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
280
281   unsigned Mask = getOperandMask(Opcode);
282   
283   bool NeedComma = false;
284   unsigned N = 1;
285   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
286     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
287       if (NeedComma) toAsm << ", ";         // Handle comma outputing
288       NeedComma = true;
289       N = printOperands(MI, OpNum);
290     }
291   else
292     N = 1;
293   
294   toAsm << endl;
295 }
296
297 void
298 SparcAsmPrinter::emitBasicBlock(const BasicBlock *BB)
299 {
300   // Emit a label for the basic block
301   toAsm << getID(BB) << ":\n";
302
303   // Get the vector of machine instructions corresponding to this bb.
304   const MachineCodeForBasicBlock &MIs = BB->getMachineInstrVec();
305   MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
306
307   // Loop over all of the instructions in the basic block...
308   for (; MII != MIE; ++MII)
309     emitMachineInst(*MII);
310   toAsm << "\n";  // Seperate BB's with newlines
311 }
312
313 void
314 SparcAsmPrinter::emitMethod(const Method *M)
315 {
316   if (M->isExternal()) return;
317
318   // Make sure the slot table has information about this method...
319   Table.incorporateMethod(M);
320
321   string methName = getID(M);
322   toAsm << "!****** Outputing Method: " << methName << " ******\n";
323   enterSection(Text);
324   toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
325   //toAsm << "\t.type\t" << methName << ",#function\n";
326   toAsm << "\t.type\t" << methName << ", 2\n";
327   toAsm << methName << ":\n";
328
329   // Output code for all of the basic blocks in the method...
330   for (Method::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
331     emitBasicBlock(*I);
332
333   // Output a .size directive so the debugger knows the extents of the function
334   toAsm << ".EndOf_" << methName << ":\n\t.size "
335         << methName << ", .EndOf_"
336         << methName << "-" << methName << endl;
337
338   // Put some spaces between the methods
339   toAsm << "\n\n";
340
341   // Forget all about M.
342   Table.purgeMethod();
343 }
344
345 inline bool
346 ArrayTypeIsString(ArrayType* arrayType)
347 {
348   return (arrayType->getElementType() == Type::UByteTy ||
349           arrayType->getElementType() == Type::SByteTy);
350 }
351
352 inline const string
353 TypeToDataDirective(const Type* type)
354 {
355   switch(type->getPrimitiveID())
356     {
357     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
358       return ".byte";
359     case Type::UShortTyID: case Type::ShortTyID:
360       return ".half";
361     case Type::UIntTyID: case Type::IntTyID:
362       return ".word";
363     case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
364       return ".xword";
365     case Type::FloatTyID:
366       return ".single";
367     case Type::DoubleTyID:
368       return ".double";
369     case Type::ArrayTyID:
370       if (ArrayTypeIsString((ArrayType*) type))
371         return ".ascii";
372       else
373         return "<InvaliDataTypeForPrinting>";
374     default:
375       return "<InvaliDataTypeForPrinting>";
376     }
377 }
378
379 inline unsigned int
380 ConstantToSize(const ConstPoolVal* CV, const TargetMachine& target)
381 {
382   if (ConstPoolArray* AV = dyn_cast<ConstPoolArray>(CV))
383     if (ArrayTypeIsString((ArrayType*) CV->getType()))
384       return 1 + AV->getNumOperands();
385   
386   return target.findOptimalStorageSize(CV->getType());
387 }
388
389
390 inline
391 unsigned int TypeToSize(const Type* type, const TargetMachine& target)
392 {
393   return target.findOptimalStorageSize(type);
394 }
395
396
397 // Align data larger than one L1 cache line on L1 cache line boundaries.
398 // Align all smaller types on the next higher 2^x boundary (4, 8, ...).
399 // 
400 inline unsigned int
401 TypeToAlignment(const Type* type, const TargetMachine& target)
402 {
403   unsigned int typeSize = target.findOptimalStorageSize(type);
404   unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); 
405   if (typeSize > (int) cacheLineSize / 2)
406     return cacheLineSize;
407   else
408     for (unsigned sz=1; /*no condition*/; sz *= 2)
409       if (sz >= typeSize)
410         return sz;
411 }
412
413
414 void
415 SparcAsmPrinter::printSingleConstant(const ConstPoolVal* CV,string valID)
416 {
417   if (valID.length() == 0)
418     valID = getID(CV);
419   
420   assert(CV->getType() != Type::VoidTy &&
421          CV->getType() != Type::TypeTy &&
422          CV->getType() != Type::LabelTy &&
423          "Unexpected type for ConstPoolVal");
424   
425   assert((! isa<ConstPoolArray>( CV) && ! isa<ConstPoolStruct>(CV))
426          && "Collective types should be handled outside this function");
427   
428   toAsm << "\t"
429         << TypeToDataDirective(CV->getType()) << "\t";
430   
431   if (CV->getType()->isPrimitiveType())
432     {
433       if (CV->getType() == Type::FloatTy || CV->getType() == Type::DoubleTy)
434         toAsm << "0r";                  // FP constants must have this prefix
435       toAsm << CV->getStrValue() << endl;
436     }
437   else if (ConstPoolPointer* CPP = dyn_cast<ConstPoolPointer>(CV))
438     {
439       if (! CPP->isNullValue())
440         assert(0 && "Cannot yet print non-null pointer constants to assembly");
441       else
442         toAsm << (void*) NULL << endl;
443     }
444   else if (ConstPoolPointerRef* CPRef = dyn_cast<ConstPoolPointerRef>(CV))
445     {
446       assert(0 && "Cannot yet initialize pointer refs in assembly");
447     }
448   else
449     {
450       assert(0 && "Unknown elementary type for constant");
451     }
452 }
453
454 void
455 SparcAsmPrinter::printConstant(const ConstPoolVal* CV, string valID)
456 {
457   if (valID.length() == 0)
458     valID = getID(CV);
459   
460   assert(CV->getType() != Type::VoidTy &&
461          CV->getType() != Type::TypeTy &&
462          CV->getType() != Type::LabelTy &&
463          "Unexpected type for ConstPoolVal");
464   
465   toAsm << "\t.align\t" << TypeToAlignment(CV->getType(), Target)
466         << endl;
467   
468   // Print .size and .type only if it is not a string.
469   ConstPoolArray *CPA = dyn_cast<ConstPoolArray>(CV);
470   
471   if (CPA && isStringCompatible(CPA))
472     { // print it as a string and return
473       toAsm << valID << ":" << endl;
474       toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t"
475             << getAsCString(CPA) << endl;
476       return;
477     }
478       
479   toAsm << "\t.type" << "\t" << valID << ",#object" << endl;
480   toAsm << "\t.size" << "\t" << valID << ","
481         << ConstantToSize(CV, Target) << endl;
482   toAsm << valID << ":" << endl;
483   
484   if (CPA)
485     { // Not a string.  Print the values in successive locations
486       const vector<Use>& constValues = CPA->getValues();
487       for (unsigned i=1; i < constValues.size(); i++)
488         this->printSingleConstant(cast<ConstPoolVal>(constValues[i].get()));
489     }
490   else if (ConstPoolStruct *CPS = dyn_cast<ConstPoolStruct>(CV))
491     { // Print the fields in successive locations
492       const vector<Use>& constValues = CPA->getValues();
493       for (unsigned i=1; i < constValues.size(); i++)
494         this->printSingleConstant(cast<ConstPoolVal>(constValues[i].get()));
495     }
496   else
497     this->printSingleConstant(CV, valID);
498 }
499
500
501 void
502 SparcAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
503 {
504   toAsm << "\t.global\t" << getID(GV) << endl;
505   
506   if (GV->hasInitializer())
507     printConstant(GV->getInitializer(), getID(GV));
508   else {
509     toAsm << "\t.align\t"
510           << TypeToAlignment(GV->getType()->getValueType(), Target) << endl;
511     toAsm << "\t.type\t" << getID(GV) << ",#object" << endl;
512     toAsm << "\t.reserve\t" << getID(GV) << ","
513           << TypeToSize(GV->getType()->getValueType(), Target)
514           << endl;
515   }
516 }
517
518
519 static void
520 FoldConstPools(const Module *M,
521                hash_set<const ConstPoolVal*>& moduleConstPool)
522 {
523   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
524     if (! (*I)->isExternal())
525       {
526         const hash_set<const ConstPoolVal*>& pool =
527           MachineCodeForMethod::get(*I).getConstantPoolValues();
528         moduleConstPool.insert(pool.begin(), pool.end());
529       }
530 }
531
532
533 void
534 SparcAsmPrinter::emitGlobalsAndConstants(const Module *M)
535 {
536   // First, get the constants there were marked by the code generator for
537   // inclusion in the assembly code data area and fold them all into a
538   // single constant pool since there may be lots of duplicates.  Also,
539   // lets force these constants into the slot table so that we can get
540   // unique names for unnamed constants also.
541   // 
542   hash_set<const ConstPoolVal*> moduleConstPool;
543   FoldConstPools(M, moduleConstPool);
544   
545   // Now, emit the three data sections separately; the cost of I/O should
546   // make up for the cost of extra passes over the globals list!
547   // 
548   // Read-only data section (implies initialized)
549   for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
550     {
551       const GlobalVariable* GV = *GI;
552       if (GV->hasInitializer() && GV->isConstant())
553         {
554           if (GI == M->gbegin())
555             enterSection(ReadOnlyData);
556           printGlobalVariable(GV);
557         }
558   }
559   
560   for (hash_set<const ConstPoolVal*>::const_iterator I=moduleConstPool.begin(),
561          E = moduleConstPool.end();  I != E; ++I)
562     printConstant(*I);
563   
564   // Initialized read-write data section
565   for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
566     {
567       const GlobalVariable* GV = *GI;
568       if (GV->hasInitializer() && ! GV->isConstant())
569         {
570           if (GI == M->gbegin())
571             enterSection(InitRWData);
572           printGlobalVariable(GV);
573         }
574   }
575
576   // Uninitialized read-write data section
577   for (Module::const_giterator GI=M->gbegin(), GE=M->gend(); GI != GE; ++GI)
578     {
579       const GlobalVariable* GV = *GI;
580       if (! GV->hasInitializer())
581         {
582           if (GI == M->gbegin())
583             enterSection(UninitRWData);
584           printGlobalVariable(GV);
585         }
586   }
587
588   toAsm << endl;
589 }
590
591
592 void
593 SparcAsmPrinter::emitModule(const Module *M)
594 {
595   // TODO: Look for a filename annotation on M to emit a .file directive
596   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
597     emitMethod(*I);
598   
599   emitGlobalsAndConstants(M);
600 }
601
602 }  // End anonymous namespace
603
604
605 //
606 // emitAssembly - Output assembly language code (a .s file) for the specified
607 // method. The specified method must have been compiled before this may be
608 // used.
609 //
610 void
611 UltraSparc::emitAssembly(const Module *M, ostream &toAsm) const
612 {
613   SparcAsmPrinter Print(toAsm, M, *this);
614 }