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