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