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