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