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