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