Add support to print %hh, %hm, %lm, or %lo in an operand field.
[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 // This code largely consists of two LLVM Pass's: a FunctionPass and a Pass.
8 // The FunctionPass is pipelined together with all of the rest of the code
9 // generation stages, and the Pass runs at the end to emit code for global
10 // variables and such.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "SparcInternals.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineCodeForBasicBlock.h"
17 #include "llvm/CodeGen/MachineCodeForMethod.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Function.h"
23 #include "llvm/Module.h"
24 #include "llvm/SlotCalculator.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "Support/StringExtras.h"
28 #include <iostream>
29 using std::string;
30
31 namespace {
32
33 class GlobalIdTable: public Annotation {
34   static AnnotationID AnnotId;
35   friend class AsmPrinter;              // give access to AnnotId
36   
37   typedef std::hash_map<const Value*, int> ValIdMap;
38   typedef ValIdMap::const_iterator ValIdMapConstIterator;
39   typedef ValIdMap::      iterator ValIdMapIterator;
40 public:
41   SlotCalculator Table;    // map anonymous values to unique integer IDs
42   ValIdMap valToIdMap;     // used for values not handled by SlotCalculator 
43   
44   GlobalIdTable(Module* M) : Annotation(AnnotId), Table(M, true) {}
45 };
46
47 AnnotationID GlobalIdTable::AnnotId =
48   AnnotationManager::getID("ASM PRINTER GLOBAL TABLE ANNOT");
49   
50 //===---------------------------------------------------------------------===//
51 //   Code Shared By the two printer passes, as a mixin
52 //===---------------------------------------------------------------------===//
53
54 class AsmPrinter {
55   GlobalIdTable* idTable;
56 public:
57   std::ostream &toAsm;
58   const TargetMachine &Target;
59   
60   enum Sections {
61     Unknown,
62     Text,
63     ReadOnlyData,
64     InitRWData,
65     UninitRWData,
66   } CurSection;
67
68   AsmPrinter(std::ostream &os, const TargetMachine &T)
69     : idTable(0), toAsm(os), Target(T), CurSection(Unknown) {}
70   
71   // (start|end)(Module|Function) - Callback methods to be invoked by subclasses
72   void startModule(Module &M) {
73     // Create the global id table if it does not already exist
74     idTable = (GlobalIdTable*)M.getAnnotation(GlobalIdTable::AnnotId);
75     if (idTable == NULL) {
76       idTable = new GlobalIdTable(&M);
77       M.addAnnotation(idTable);
78     }
79   }
80   void startFunction(Function &F) {
81     // Make sure the slot table has information about this function...
82     idTable->Table.incorporateFunction(&F);
83   }
84   void endFunction(Function &) {
85     idTable->Table.purgeFunction();  // Forget all about F
86   }
87   void endModule() {
88   }
89
90   // Check if a name is external or accessible from external code.
91   // Only functions can currently be external.  "main" is the only name
92   // that is visible externally.
93   bool isExternal(const Value* V) {
94     const Function *F = dyn_cast<Function>(V);
95     return F && (F->isExternal() || F->getName() == "main");
96   }
97   
98   // enterSection - Use this method to enter a different section of the output
99   // executable.  This is used to only output neccesary section transitions.
100   //
101   void enterSection(enum Sections S) {
102     if (S == CurSection) return;        // Only switch section if neccesary
103     CurSection = S;
104
105     toAsm << "\n\t.section ";
106     switch (S)
107       {
108       default: assert(0 && "Bad section name!");
109       case Text:         toAsm << "\".text\""; break;
110       case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
111       case InitRWData:   toAsm << "\".data\",#alloc,#write"; break;
112       case UninitRWData: toAsm << "\".bss\",#alloc,#write\nBbss.bss:"; break;
113       }
114     toAsm << "\n";
115   }
116
117   static std::string getValidSymbolName(const string &S) {
118     string Result;
119     
120     // Symbol names in Sparc assembly language have these rules:
121     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
122     // (b) A name beginning in "." is treated as a local name.
123     // (c) Names beginning with "_" are reserved by ANSI C and shd not be used.
124     // 
125     if (S[0] == '_' || isdigit(S[0]))
126       Result += "ll";
127     
128     for (unsigned i = 0; i < S.size(); ++i)
129       {
130         char C = S[i];
131         if (C == '_' || C == '.' || C == '$' || isalpha(C) || isdigit(C))
132           Result += C;
133         else
134           {
135             Result += '_';
136             Result += char('0' + ((unsigned char)C >> 4));
137             Result += char('0' + (C & 0xF));
138           }
139       }
140     return Result;
141   }
142
143   // getID - Return a valid identifier for the specified value.  Base it on
144   // the name of the identifier if possible (qualified by the type), and
145   // use a numbered value based on prefix otherwise.
146   // FPrefix is always prepended to the output identifier.
147   //
148   string getID(const Value *V, const char *Prefix, const char *FPrefix = 0) {
149     string Result = FPrefix ? FPrefix : "";  // "Forced prefix"
150     
151     Result = Result + (V->hasName()? V->getName() : string(Prefix));
152     
153     // Qualify all internal names with a unique id.
154     if (!isExternal(V)) {
155       int valId = idTable->Table.getValSlot(V);
156       if (valId == -1) {
157         GlobalIdTable::ValIdMapConstIterator I = idTable->valToIdMap.find(V);
158         if (I == idTable->valToIdMap.end())
159           valId = idTable->valToIdMap[V] = idTable->valToIdMap.size();
160         else
161           valId = I->second;
162       }
163       Result = Result + "_" + itostr(valId);
164     }
165     
166     return getValidSymbolName(Result);
167   }
168   
169   // getID Wrappers - Ensure consistent usage...
170   string getID(const Function *F) {
171     return getID(F, "LLVMFunction_");
172   }
173   string getID(const BasicBlock *BB) {
174     return getID(BB, "LL", (".L_"+getID(BB->getParent())+"_").c_str());
175   }
176   string getID(const GlobalVariable *GV) {
177     return getID(GV, "LLVMGlobal_", ".G_");
178   }
179   string getID(const Constant *CV) {
180     return getID(CV, "LLVMConst_", ".C_");
181   }
182 };
183
184
185
186 //===----------------------------------------------------------------------===//
187 //   SparcFunctionAsmPrinter Code
188 //===----------------------------------------------------------------------===//
189
190 struct SparcFunctionAsmPrinter : public FunctionPass, public AsmPrinter {
191   inline SparcFunctionAsmPrinter(std::ostream &os, const TargetMachine &t)
192     : AsmPrinter(os, t) {}
193
194   const char *getPassName() const {
195     return "Output Sparc Assembly for Functions";
196   }
197
198   virtual bool doInitialization(Module &M) {
199     startModule(M);
200     return false;
201   }
202
203   virtual bool runOnFunction(Function &F) {
204     startFunction(F);
205     emitFunction(F);
206     endFunction(F);
207     return false;
208   }
209
210   virtual bool doFinalization(Module &M) {
211     endModule();
212     return false;
213   }
214
215   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
216     AU.setPreservesAll();
217   }
218
219   void emitFunction(const Function &F);
220 private :
221   void emitBasicBlock(const BasicBlock *BB);
222   void emitMachineInst(const MachineInstr *MI);
223   
224   unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
225   void printOneOperand(const MachineOperand &Op);
226
227   bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
228   bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
229   
230   unsigned getOperandMask(unsigned Opcode) {
231     switch (Opcode) {
232     case SUBcc:   return 1 << 3;  // Remove CC argument
233   //case BA:      return 1 << 0;  // Remove Arg #0, which is always null or xcc
234     default:      return 0;       // By default, don't hack operands...
235     }
236   }
237 };
238
239 inline bool
240 SparcFunctionAsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
241                                                unsigned int opNum) {
242   switch (MI->getOpCode()) {
243   case JMPLCALL:
244   case JMPLRET: return (opNum == 0);
245   default:      return false;
246   }
247 }
248
249
250 inline bool
251 SparcFunctionAsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
252                                                unsigned int opNum) {
253   if (Target.getInstrInfo().isLoad(MI->getOpCode()))
254     return (opNum == 0);
255   else if (Target.getInstrInfo().isStore(MI->getOpCode()))
256     return (opNum == 1);
257   else
258     return false;
259 }
260
261
262 #define PrintOp1PlusOp2(mop1, mop2) \
263   printOneOperand(mop1); \
264   toAsm << "+"; \
265   printOneOperand(mop2);
266
267 unsigned int
268 SparcFunctionAsmPrinter::printOperands(const MachineInstr *MI,
269                                unsigned int opNum)
270 {
271   const MachineOperand& mop = MI->getOperand(opNum);
272   
273   if (OpIsBranchTargetLabel(MI, opNum))
274     {
275       PrintOp1PlusOp2(mop, MI->getOperand(opNum+1));
276       return 2;
277     }
278   else if (OpIsMemoryAddressBase(MI, opNum))
279     {
280       toAsm << "[";
281       PrintOp1PlusOp2(mop, MI->getOperand(opNum+1));
282       toAsm << "]";
283       return 2;
284     }
285   else
286     {
287       printOneOperand(mop);
288       return 1;
289     }
290 }
291
292
293 void
294 SparcFunctionAsmPrinter::printOneOperand(const MachineOperand &mop)
295 {
296   bool needBitsFlag = true;
297   
298   if (mop.opHiBits32())
299     toAsm << "%lm(";
300   else if (mop.opLoBits32())
301     toAsm << "%lo(";
302   else if (mop.opHiBits64())
303     toAsm << "%hh(";
304   else if (mop.opLoBits64())
305     toAsm << "%hm(";
306   else
307     needBitsFlag = false;
308   
309   switch (mop.getOperandType())
310     {
311     case MachineOperand::MO_VirtualRegister:
312     case MachineOperand::MO_CCRegister:
313     case MachineOperand::MO_MachineRegister:
314       {
315         int RegNum = (int)mop.getAllocatedRegNum();
316         
317         // better to print code with NULL registers than to die
318         if (RegNum == Target.getRegInfo().getInvalidRegNum()) {
319           toAsm << "<NULL VALUE>";
320         } else {
321           toAsm << "%" << Target.getRegInfo().getUnifiedRegName(RegNum);
322         }
323         break;
324       }
325     
326     case MachineOperand::MO_PCRelativeDisp:
327       {
328         const Value *Val = mop.getVRegValue();
329         assert(Val && "\tNULL Value in SparcFunctionAsmPrinter");
330         
331         if (const BasicBlock *BB = dyn_cast<const BasicBlock>(Val))
332           toAsm << getID(BB);
333         else if (const Function *M = dyn_cast<Function>(Val))
334           toAsm << getID(M);
335         else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
336           toAsm << getID(GV);
337         else if (const Constant *CV = dyn_cast<Constant>(Val))
338           toAsm << getID(CV);
339         else
340           assert(0 && "Unrecognized value in SparcFunctionAsmPrinter");
341         break;
342       }
343     
344     case MachineOperand::MO_SignExtendedImmed:
345       toAsm << mop.getImmedValue();
346       break;
347
348     case MachineOperand::MO_UnextendedImmed:
349       toAsm << (uint64_t) mop.getImmedValue();
350       break;
351     
352     default:
353       toAsm << mop;      // use dump field
354       break;
355     }
356   
357   if (needBitsFlag)
358     toAsm << ")";
359 }
360
361
362 void
363 SparcFunctionAsmPrinter::emitMachineInst(const MachineInstr *MI)
364 {
365   unsigned Opcode = MI->getOpCode();
366
367   if (TargetInstrDescriptors[Opcode].iclass & M_DUMMY_PHI_FLAG)
368     return;  // IGNORE PHI NODES
369
370   toAsm << "\t" << TargetInstrDescriptors[Opcode].opCodeString << "\t";
371
372   unsigned Mask = getOperandMask(Opcode);
373   
374   bool NeedComma = false;
375   unsigned N = 1;
376   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
377     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
378       if (NeedComma) toAsm << ", ";         // Handle comma outputing
379       NeedComma = true;
380       N = printOperands(MI, OpNum);
381     }
382   else
383     N = 1;
384   
385   toAsm << "\n";
386 }
387
388 void
389 SparcFunctionAsmPrinter::emitBasicBlock(const BasicBlock *BB)
390 {
391   // Emit a label for the basic block
392   toAsm << getID(BB) << ":\n";
393
394   // Get the vector of machine instructions corresponding to this bb.
395   const MachineCodeForBasicBlock &MIs = MachineCodeForBasicBlock::get(BB);
396   MachineCodeForBasicBlock::const_iterator MII = MIs.begin(), MIE = MIs.end();
397
398   // Loop over all of the instructions in the basic block...
399   for (; MII != MIE; ++MII)
400     emitMachineInst(*MII);
401   toAsm << "\n";  // Seperate BB's with newlines
402 }
403
404 void
405 SparcFunctionAsmPrinter::emitFunction(const Function &F)
406 {
407   string methName = getID(&F);
408   toAsm << "!****** Outputing Function: " << methName << " ******\n";
409   enterSection(AsmPrinter::Text);
410   toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
411   //toAsm << "\t.type\t" << methName << ",#function\n";
412   toAsm << "\t.type\t" << methName << ", 2\n";
413   toAsm << methName << ":\n";
414
415   // Output code for all of the basic blocks in the function...
416   for (Function::const_iterator I = F.begin(), E = F.end(); I != E; ++I)
417     emitBasicBlock(I);
418
419   // Output a .size directive so the debugger knows the extents of the function
420   toAsm << ".EndOf_" << methName << ":\n\t.size "
421            << methName << ", .EndOf_"
422            << methName << "-" << methName << "\n";
423
424   // Put some spaces between the functions
425   toAsm << "\n\n";
426 }
427
428 }  // End anonymous namespace
429
430 Pass *UltraSparc::getFunctionAsmPrinterPass(PassManager &PM, std::ostream &Out){
431   return new SparcFunctionAsmPrinter(Out, *this);
432 }
433
434
435
436
437
438 //===----------------------------------------------------------------------===//
439 //   SparcFunctionAsmPrinter Code
440 //===----------------------------------------------------------------------===//
441
442 namespace {
443
444 class SparcModuleAsmPrinter : public Pass, public AsmPrinter {
445 public:
446   SparcModuleAsmPrinter(std::ostream &os, TargetMachine &t)
447     : AsmPrinter(os, t) {}
448
449   const char *getPassName() const { return "Output Sparc Assembly for Module"; }
450
451   virtual bool run(Module &M) {
452     startModule(M);
453     emitGlobalsAndConstants(M);
454     endModule();
455     return false;
456   }
457
458   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
459     AU.setPreservesAll();
460   }
461
462 private:
463   void emitGlobalsAndConstants(const Module &M);
464
465   void printGlobalVariable(const GlobalVariable *GV);
466   void printSingleConstant(   const Constant* CV);
467   void printConstantValueOnly(const Constant* CV);
468   void printConstant(         const Constant* CV, std::string valID = "");
469
470   static void FoldConstants(const Module &M,
471                             std::hash_set<const Constant*> &moduleConstants);
472 };
473
474
475 // Can we treat the specified array as a string?  Only if it is an array of
476 // ubytes or non-negative sbytes.
477 //
478 static bool isStringCompatible(const ConstantArray *CPA) {
479   const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
480   if (ETy == Type::UByteTy) return true;
481   if (ETy != Type::SByteTy) return false;
482
483   for (unsigned i = 0; i < CPA->getNumOperands(); ++i)
484     if (cast<ConstantSInt>(CPA->getOperand(i))->getValue() < 0)
485       return false;
486
487   return true;
488 }
489
490 // toOctal - Convert the low order bits of X into an octal letter
491 static inline char toOctal(int X) {
492   return (X&7)+'0';
493 }
494
495 // getAsCString - Return the specified array as a C compatible string, only if
496 // the predicate isStringCompatible is true.
497 //
498 static string getAsCString(const ConstantArray *CPA) {
499   assert(isStringCompatible(CPA) && "Array is not string compatible!");
500
501   string Result;
502   const Type *ETy = cast<ArrayType>(CPA->getType())->getElementType();
503   Result = "\"";
504   for (unsigned i = 0; i < CPA->getNumOperands(); ++i) {
505     unsigned char C = (ETy == Type::SByteTy) ?
506       (unsigned char)cast<ConstantSInt>(CPA->getOperand(i))->getValue() :
507       (unsigned char)cast<ConstantUInt>(CPA->getOperand(i))->getValue();
508
509     if (C == '"') {
510       Result += "\\\"";
511     } else if (isprint(C)) {
512       Result += C;
513     } else {
514       switch(C) {
515       case '\a': Result += "\\a"; break;
516       case '\b': Result += "\\b"; break;
517       case '\f': Result += "\\f"; break;
518       case '\n': Result += "\\n"; break;
519       case '\r': Result += "\\r"; break;
520       case '\t': Result += "\\t"; break;
521       case '\v': Result += "\\v"; break;
522       default:
523         Result += '\\';
524         Result += toOctal(C >> 6);
525         Result += toOctal(C >> 3);
526         Result += toOctal(C >> 0);
527         break;
528       }
529     }
530   }
531   Result += "\"";
532
533   return Result;
534 }
535
536 inline bool
537 ArrayTypeIsString(const ArrayType* arrayType)
538 {
539   return (arrayType->getElementType() == Type::UByteTy ||
540           arrayType->getElementType() == Type::SByteTy);
541 }
542
543 inline const string
544 TypeToDataDirective(const Type* type)
545 {
546   switch(type->getPrimitiveID())
547     {
548     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
549       return ".byte";
550     case Type::UShortTyID: case Type::ShortTyID:
551       return ".half";
552     case Type::UIntTyID: case Type::IntTyID:
553       return ".word";
554     case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
555       return ".xword";
556     case Type::FloatTyID:
557       return ".word";
558     case Type::DoubleTyID:
559       return ".xword";
560     case Type::ArrayTyID:
561       if (ArrayTypeIsString((ArrayType*) type))
562         return ".ascii";
563       else
564         return "<InvaliDataTypeForPrinting>";
565     default:
566       return "<InvaliDataTypeForPrinting>";
567     }
568 }
569
570 // Get the size of the constant for the given target.
571 // If this is an unsized array, return 0.
572 // 
573 inline unsigned int
574 ConstantToSize(const Constant* CV, const TargetMachine& target)
575 {
576   if (const ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
577     {
578       const ArrayType *aty = cast<ArrayType>(CPA->getType());
579       if (ArrayTypeIsString(aty))
580         return 1 + CPA->getNumOperands();
581     }
582   
583   return target.findOptimalStorageSize(CV->getType());
584 }
585
586
587
588 // Align data larger than one L1 cache line on L1 cache line boundaries.
589 // Align all smaller data on the next higher 2^x boundary (4, 8, ...).
590 // 
591 inline unsigned int
592 SizeToAlignment(unsigned int size, const TargetMachine& target)
593 {
594   unsigned short cacheLineSize = target.getCacheInfo().getCacheLineSize(1); 
595   if (size > (unsigned) cacheLineSize / 2)
596     return cacheLineSize;
597   else
598     for (unsigned sz=1; /*no condition*/; sz *= 2)
599       if (sz >= size)
600         return sz;
601 }
602
603 // Get the size of the type and then use SizeToAlignment.
604 // 
605 inline unsigned int
606 TypeToAlignment(const Type* type, const TargetMachine& target)
607 {
608   return SizeToAlignment(target.findOptimalStorageSize(type), target);
609 }
610
611 // Get the size of the constant and then use SizeToAlignment.
612 // Handles strings as a special case;
613 inline unsigned int
614 ConstantToAlignment(const Constant* CV, const TargetMachine& target)
615 {
616   if (const ConstantArray* CPA = dyn_cast<ConstantArray>(CV))
617     if (ArrayTypeIsString(cast<ArrayType>(CPA->getType())))
618       return SizeToAlignment(1 + CPA->getNumOperands(), target);
619   
620   return TypeToAlignment(CV->getType(), target);
621 }
622
623
624 // Print a single constant value.
625 void
626 SparcModuleAsmPrinter::printSingleConstant(const Constant* CV)
627 {
628   assert(CV->getType() != Type::VoidTy &&
629          CV->getType() != Type::TypeTy &&
630          CV->getType() != Type::LabelTy &&
631          "Unexpected type for Constant");
632   
633   assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
634          && "Aggregate types should be handled outside this function");
635   
636   toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
637   
638   if (CV->getType()->isPrimitiveType())
639     {
640       if (CV->getType()->isFloatingPoint()) {
641         // FP Constants are printed as integer constants to avoid losing
642         // precision...
643         double Val = cast<ConstantFP>(CV)->getValue();
644         if (CV->getType() == Type::FloatTy) {
645           float FVal = (float)Val;
646           char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
647           toAsm << *(unsigned int*)ProxyPtr;            
648         } else if (CV->getType() == Type::DoubleTy) {
649           char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
650           toAsm << *(uint64_t*)ProxyPtr;            
651         } else {
652           assert(0 && "Unknown floating point type!");
653         }
654         
655         toAsm << "\t! " << CV->getType()->getDescription()
656               << " value: " << Val << "\n";
657       } else {
658         WriteAsOperand(toAsm, CV, false, false) << "\n";
659       }
660     }
661   else if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(CV))
662     { // This is a constant address for a global variable or method.
663       // Use the name of the variable or method as the address value.
664       if (const GlobalVariable* GV = dyn_cast<GlobalVariable>(CPR->getValue()))
665         toAsm << getID(GV);
666       else if (const Function* F = dyn_cast<Function>(CPR->getValue()))
667         toAsm << getID(F);
668       else
669         assert(0 && "Unexpected constant reference type");
670     }
671   else if (const ConstantPointer* CPP = dyn_cast<ConstantPointer>(CV))
672     {
673       assert(CPP->isNullValue() &&
674              "Cannot yet print non-null pointer constants to assembly");
675       toAsm << "0\n";
676     }
677   else
678     {
679       assert(0 && "Unknown elementary type for constant");
680     }
681 }
682
683 // Print a constant value or values (it may be an aggregate).
684 // Uses printSingleConstant() to print each individual value.
685 void
686 SparcModuleAsmPrinter::printConstantValueOnly(const Constant* CV)
687 {
688   const ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
689   
690   if (CPA && isStringCompatible(CPA))
691     { // print the string alone and return
692       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
693     }
694   else if (CPA)
695     { // Not a string.  Print the values in successive locations
696       const std::vector<Use> &constValues = CPA->getValues();
697       for (unsigned i=0; i < constValues.size(); i++)
698         printConstantValueOnly(cast<Constant>(constValues[i].get()));
699     }
700   else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CV))
701     { // Print the fields in successive locations
702       const std::vector<Use>& constValues = CPS->getValues();
703       for (unsigned i=0; i < constValues.size(); i++)
704         printConstantValueOnly(cast<Constant>(constValues[i].get()));
705     }
706   else
707     printSingleConstant(CV);
708 }
709
710 // Print a constant (which may be an aggregate) prefixed by all the
711 // appropriate directives.  Uses printConstantValueOnly() to print the
712 // value or values.
713 void
714 SparcModuleAsmPrinter::printConstant(const Constant* CV, string valID)
715 {
716   if (valID.length() == 0)
717     valID = getID(CV);
718   
719   toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
720   
721   // Print .size and .type only if it is not a string.
722   const ConstantArray *CPA = dyn_cast<ConstantArray>(CV);
723   if (CPA && isStringCompatible(CPA))
724     { // print it as a string and return
725       toAsm << valID << ":\n";
726       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CPA) << "\n";
727       return;
728     }
729   
730   toAsm << "\t.type" << "\t" << valID << ",#object\n";
731
732   unsigned int constSize = ConstantToSize(CV, Target);
733   if (constSize)
734     toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
735   
736   toAsm << valID << ":\n";
737   
738   printConstantValueOnly(CV);
739 }
740
741
742 void SparcModuleAsmPrinter::FoldConstants(const Module &M,
743                                           std::hash_set<const Constant*> &MC) {
744   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
745     if (!I->isExternal()) {
746       const std::hash_set<const Constant*> &pool =
747         MachineCodeForMethod::get(I).getConstantPoolValues();
748       MC.insert(pool.begin(), pool.end());
749     }
750 }
751
752 void SparcModuleAsmPrinter::printGlobalVariable(const GlobalVariable* GV)
753 {
754   toAsm << "\t.global\t" << getID(GV) << "\n";
755   
756   if (GV->hasInitializer())
757     printConstant(GV->getInitializer(), getID(GV));
758   else {
759     toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
760                                                 Target) << "\n";
761     toAsm << "\t.type\t" << getID(GV) << ",#object\n";
762     toAsm << "\t.reserve\t" << getID(GV) << ","
763           << Target.findOptimalStorageSize(GV->getType()->getElementType())
764           << "\n";
765   }
766 }
767
768
769 void SparcModuleAsmPrinter::emitGlobalsAndConstants(const Module &M) {
770   // First, get the constants there were marked by the code generator for
771   // inclusion in the assembly code data area and fold them all into a
772   // single constant pool since there may be lots of duplicates.  Also,
773   // lets force these constants into the slot table so that we can get
774   // unique names for unnamed constants also.
775   // 
776   std::hash_set<const Constant*> moduleConstants;
777   FoldConstants(M, moduleConstants);
778     
779   // Now, emit the three data sections separately; the cost of I/O should
780   // make up for the cost of extra passes over the globals list!
781   
782   // Section 1 : Read-only data section (implies initialized)
783   enterSection(AsmPrinter::ReadOnlyData);
784   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
785     if (GI->hasInitializer() && GI->isConstant())
786       printGlobalVariable(GI);
787   
788   for (std::hash_set<const Constant*>::const_iterator
789          I = moduleConstants.begin(),
790          E = moduleConstants.end();  I != E; ++I)
791     printConstant(*I);
792   
793   // Section 2 : Initialized read-write data section
794   enterSection(AsmPrinter::InitRWData);
795   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
796     if (GI->hasInitializer() && !GI->isConstant())
797       printGlobalVariable(GI);
798   
799   // Section 3 : Uninitialized read-write data section
800   enterSection(AsmPrinter::UninitRWData);
801   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
802     if (!GI->hasInitializer())
803       printGlobalVariable(GI);
804   
805   toAsm << "\n";
806 }
807
808 }  // End anonymous namespace
809
810 Pass *UltraSparc::getModuleAsmPrinterPass(PassManager &PM, std::ostream &Out) {
811   return new SparcModuleAsmPrinter(Out, *this);
812 }