Allow the specification of explicit alignments for constant pool entries.
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9AsmPrinter.cpp
1 //===-- SparcV9AsmPrinter.cpp - Emit SparcV9 Specific .s File --------------==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements all of the stuff necessary to output a .s file from
11 // LLVM.  The code in this file assumes that the specified module has already
12 // been compiled into the internal data structures of the Module.
13 //
14 // This code largely consists of two LLVM Pass's: a FunctionPass and a Pass.
15 // The FunctionPass is pipelined together with all of the rest of the code
16 // generation stages, and the Pass runs at the end to emit code for global
17 // variables and such.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/Support/Mangler.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "SparcV9Internals.h"
33 #include "MachineFunctionInfo.h"
34 #include <string>
35 using namespace llvm;
36
37 namespace {
38   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
39
40   //===--------------------------------------------------------------------===//
41   // Utility functions
42
43   /// getAsCString - Return the specified array as a C compatible string, only
44   /// if the predicate isString() is true.
45   ///
46   std::string getAsCString(const ConstantArray *CVA) {
47     assert(CVA->isString() && "Array is not string compatible!");
48
49     std::string Result = "\"";
50     for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
51       unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
52
53       if (C == '"') {
54         Result += "\\\"";
55       } else if (C == '\\') {
56         Result += "\\\\";
57       } else if (isprint(C)) {
58         Result += C;
59       } else {
60         Result += '\\';    // print all other chars as octal value
61         // Convert C to octal representation
62         Result += ((C >> 6) & 7) + '0';
63         Result += ((C >> 3) & 7) + '0';
64         Result += ((C >> 0) & 7) + '0';
65       }
66     }
67     Result += "\"";
68
69     return Result;
70   }
71
72   inline bool ArrayTypeIsString(const ArrayType* arrayType) {
73     return (arrayType->getElementType() == Type::UByteTy ||
74             arrayType->getElementType() == Type::SByteTy);
75   }
76
77   unsigned findOptimalStorageSize(const TargetMachine &TM, const Type *Ty) {
78     // All integer types smaller than ints promote to 4 byte integers.
79     if (Ty->isIntegral() && Ty->getPrimitiveSize() < 4)
80       return 4;
81
82     return TM.getTargetData().getTypeSize(Ty);
83   }
84
85
86   inline const std::string
87   TypeToDataDirective(const Type* type) {
88     switch(type->getTypeID()) {
89     case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
90       return ".byte";
91     case Type::UShortTyID: case Type::ShortTyID:
92       return ".half";
93     case Type::UIntTyID: case Type::IntTyID:
94       return ".word";
95     case Type::ULongTyID: case Type::LongTyID: case Type::PointerTyID:
96       return ".xword";
97     case Type::FloatTyID:
98       return ".word";
99     case Type::DoubleTyID:
100       return ".xword";
101     case Type::ArrayTyID:
102       if (ArrayTypeIsString((ArrayType*) type))
103         return ".ascii";
104       else
105         return "<InvaliDataTypeForPrinting>";
106     default:
107       return "<InvaliDataTypeForPrinting>";
108     }
109   }
110
111   /// Get the size of the constant for the given target.
112   /// If this is an unsized array, return 0.
113   ///
114   inline unsigned int
115   ConstantToSize(const Constant* CV, const TargetMachine& target) {
116     if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV)) {
117       const ArrayType *aty = cast<ArrayType>(CVA->getType());
118       if (ArrayTypeIsString(aty))
119         return 1 + CVA->getNumOperands();
120     }
121
122     return findOptimalStorageSize(target, CV->getType());
123   }
124
125   /// Align data larger than one L1 cache line on L1 cache line boundaries.
126   /// Align all smaller data on the next higher 2^x boundary (4, 8, ...).
127   ///
128   inline unsigned int
129   SizeToAlignment(unsigned int size, const TargetMachine& target) {
130     const unsigned short cacheLineSize = 16;
131     if (size > (unsigned) cacheLineSize / 2)
132       return cacheLineSize;
133     else
134       for (unsigned sz=1; /*no condition*/; sz *= 2)
135         if (sz >= size)
136           return sz;
137   }
138
139   /// Get the size of the type and then use SizeToAlignment.
140   ///
141   inline unsigned int
142   TypeToAlignment(const Type* type, const TargetMachine& target) {
143     return SizeToAlignment(findOptimalStorageSize(target, type), target);
144   }
145
146   /// Get the size of the constant and then use SizeToAlignment.
147   /// Handles strings as a special case;
148   inline unsigned int
149   ConstantToAlignment(const Constant* CV, const TargetMachine& target) {
150     if (const ConstantArray* CVA = dyn_cast<ConstantArray>(CV))
151       if (ArrayTypeIsString(cast<ArrayType>(CVA->getType())))
152         return SizeToAlignment(1 + CVA->getNumOperands(), target);
153
154     return TypeToAlignment(CV->getType(), target);
155   }
156
157 } // End anonymous namespace
158
159 namespace {
160   enum Sections {
161     Unknown,
162     Text,
163     ReadOnlyData,
164     InitRWData,
165     ZeroInitRWData,
166   };
167
168   class AsmPrinter {
169     // Mangle symbol names appropriately
170     Mangler *Mang;
171
172   public:
173     std::ostream &O;
174     const TargetMachine &TM;
175
176     enum Sections CurSection;
177
178     AsmPrinter(std::ostream &os, const TargetMachine &T)
179       : /* idTable(0), */ O(os), TM(T), CurSection(Unknown) {}
180
181     ~AsmPrinter() {
182       delete Mang;
183     }
184
185     // (start|end)(Module|Function) - Callback methods invoked by subclasses
186     void startModule(Module &M) {
187       Mang = new Mangler(M);
188     }
189
190     void PrintZeroBytesToPad(int numBytes) {
191       //
192       // Always use single unsigned bytes for padding.  We don't know upon
193       // what data size the beginning address is aligned, so using anything
194       // other than a byte may cause alignment errors in the assembler.
195       //
196       while (numBytes--)
197         printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
198     }
199
200     /// Print a single constant value.
201     ///
202     void printSingleConstantValue(const Constant* CV);
203
204     /// Print a constant value or values (it may be an aggregate).
205     /// Uses printSingleConstantValue() to print each individual value.
206     ///
207     void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
208
209     // Print a constant (which may be an aggregate) prefixed by all the
210     // appropriate directives.  Uses printConstantValueOnly() to print the
211     // value or values.
212     void printConstant(const Constant* CV, unsigned Alignment,
213                        std::string valID = "") {
214       if (valID.length() == 0)
215         valID = getID(CV);
216
217       if (Alignment == 0)
218         Alignment = ConstantToAlignment(CV, TM);
219       O << "\t.align\t" << Alignment << "\n";
220
221       // Print .size and .type only if it is not a string.
222       if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
223         if (CVA->isString()) {
224           // print it as a string and return
225           O << valID << ":\n";
226           O << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
227           return;
228         }
229
230       O << "\t.type" << "\t" << valID << ",#object\n";
231
232       unsigned int constSize = ConstantToSize(CV, TM);
233       if (constSize)
234         O << "\t.size" << "\t" << valID << "," << constSize << "\n";
235
236       O << valID << ":\n";
237
238       printConstantValueOnly(CV);
239     }
240
241     // enterSection - Use this method to enter a different section of the output
242     // executable.  This is used to only output necessary section transitions.
243     //
244     void enterSection(enum Sections S) {
245       if (S == CurSection) return;        // Only switch section if necessary
246       CurSection = S;
247
248       O << "\n\t.section ";
249       switch (S)
250       {
251       default: assert(0 && "Bad section name!");
252       case Text:         O << "\".text\""; break;
253       case ReadOnlyData: O << "\".rodata\",#alloc"; break;
254       case InitRWData:   O << "\".data\",#alloc,#write"; break;
255       case ZeroInitRWData: O << "\".bss\",#alloc,#write"; break;
256       }
257       O << "\n";
258     }
259
260     // getID Wrappers - Ensure consistent usage
261     // Symbol names in SparcV9 assembly language have these rules:
262     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
263     // (b) A name beginning in "." is treated as a local name.
264     std::string getID(const Function *F) {
265       return Mang->getValueName(F);
266     }
267     std::string getID(const BasicBlock *BB) {
268       return ".L_" + getID(BB->getParent()) + "_" + Mang->getValueName(BB);
269     }
270     std::string getID(const GlobalVariable *GV) {
271       return Mang->getValueName(GV);
272     }
273     std::string getID(const Constant *CV) {
274       return ".C_" + Mang->getValueName(CV);
275     }
276     std::string getID(const GlobalValue *GV) {
277       if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
278         return getID(V);
279       else if (const Function *F = dyn_cast<Function>(GV))
280         return getID(F);
281       assert(0 && "Unexpected type of GlobalValue!");
282       return "";
283     }
284
285     // Combines expressions
286     inline std::string ConstantArithExprToString(const ConstantExpr* CE,
287                                                  const TargetMachine &TM,
288                                                  const std::string &op) {
289       return "(" + valToExprString(CE->getOperand(0), TM) + op
290         + valToExprString(CE->getOperand(1), TM) + ")";
291     }
292
293     /// ConstantExprToString() - Convert a ConstantExpr to an asm expression
294     /// and return this as a string.
295     ///
296     std::string ConstantExprToString(const ConstantExpr* CE,
297                                      const TargetMachine& target);
298
299     /// valToExprString - Helper function for ConstantExprToString().
300     /// Appends result to argument string S.
301     ///
302     std::string valToExprString(const Value* V, const TargetMachine& target);
303   };
304 } // End anonymous namespace
305
306
307 /// Print a single constant value.
308 ///
309 void AsmPrinter::printSingleConstantValue(const Constant* CV) {
310   assert(CV->getType() != Type::VoidTy &&
311          CV->getType() != Type::LabelTy &&
312          "Unexpected type for Constant");
313
314   assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
315          && "Aggregate types should be handled outside this function");
316
317   O << "\t" << TypeToDataDirective(CV->getType()) << "\t";
318
319   if (const GlobalValue* GV = dyn_cast<GlobalValue>(CV)) {
320     O << getID(GV) << "\n";
321   } else if (isa<ConstantPointerNull>(CV) || isa<UndefValue>(CV)) {
322     // Null pointer value
323     O << "0\n";
324   } else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV)) {
325     // Constant expression built from operators, constants, and symbolic addrs
326     O << ConstantExprToString(CE, TM) << "\n";
327   } else if (CV->getType()->isPrimitiveType()) {
328     // Check primitive types last
329     if (isa<UndefValue>(CV)) {
330       O << "0\n";
331     } else if (CV->getType()->isFloatingPoint()) {
332       // FP Constants are printed as integer constants to avoid losing
333       // precision...
334       double Val = cast<ConstantFP>(CV)->getValue();
335       if (CV->getType() == Type::FloatTy) {
336         float FVal = (float)Val;
337         char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
338         O << *(unsigned int*)ProxyPtr;
339       } else if (CV->getType() == Type::DoubleTy) {
340         char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
341         O << *(uint64_t*)ProxyPtr;
342       } else {
343         assert(0 && "Unknown floating point type!");
344       }
345
346       O << "\t! " << CV->getType()->getDescription()
347             << " value: " << Val << "\n";
348     } else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
349       O << (int)CB->getValue() << "\n";
350     } else {
351       WriteAsOperand(O, CV, false, false) << "\n";
352     }
353   } else {
354     assert(0 && "Unknown elementary type for constant");
355   }
356 }
357
358 /// Print a constant value or values (it may be an aggregate).
359 /// Uses printSingleConstantValue() to print each individual value.
360 ///
361 void AsmPrinter::printConstantValueOnly(const Constant* CV,
362                                         int numPadBytesAfter) {
363   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
364     if (CVA->isString()) {
365       // print the string alone and return
366       O << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
367     } else {
368       // Not a string.  Print the values in successive locations
369       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
370         printConstantValueOnly(CVA->getOperand(i));
371     }
372   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
373     // Print the fields in successive locations. Pad to align if needed!
374     const StructLayout *cvsLayout =
375       TM.getTargetData().getStructLayout(CVS->getType());
376     unsigned sizeSoFar = 0;
377     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
378       const Constant* field = CVS->getOperand(i);
379
380       // Check if padding is needed and insert one or more 0s.
381       unsigned fieldSize =
382         TM.getTargetData().getTypeSize(field->getType());
383       int padSize = ((i == e-1? cvsLayout->StructSize
384                       : cvsLayout->MemberOffsets[i+1])
385                      - cvsLayout->MemberOffsets[i]) - fieldSize;
386       sizeSoFar += (fieldSize + padSize);
387
388       // Now print the actual field value
389       printConstantValueOnly(field, padSize);
390     }
391     assert(sizeSoFar == cvsLayout->StructSize &&
392            "Layout of constant struct may be incorrect!");
393   } else if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
394     PrintZeroBytesToPad(TM.getTargetData().getTypeSize(CV->getType()));
395   } else
396     printSingleConstantValue(CV);
397
398   if (numPadBytesAfter)
399     PrintZeroBytesToPad(numPadBytesAfter);
400 }
401
402 /// ConstantExprToString() - Convert a ConstantExpr to an asm expression
403 /// and return this as a string.
404 ///
405 std::string AsmPrinter::ConstantExprToString(const ConstantExpr* CE,
406                                              const TargetMachine& target) {
407   std::string S;
408   switch(CE->getOpcode()) {
409   case Instruction::GetElementPtr:
410     { // generate a symbolic expression for the byte address
411       const Value* ptrVal = CE->getOperand(0);
412       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
413       const TargetData &TD = target.getTargetData();
414       S += "(" + valToExprString(ptrVal, target) + ") + ("
415         + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
416       break;
417     }
418
419   case Instruction::Cast:
420     // Support only non-converting casts for now, i.e., a no-op.
421     // This assertion is not a complete check.
422     assert(target.getTargetData().getTypeSize(CE->getType()) ==
423            target.getTargetData().getTypeSize(CE->getOperand(0)->getType()));
424     S += "(" + valToExprString(CE->getOperand(0), target) + ")";
425     break;
426
427   case Instruction::Add:
428     S += ConstantArithExprToString(CE, target, ") + (");
429     break;
430
431   case Instruction::Sub:
432     S += ConstantArithExprToString(CE, target, ") - (");
433     break;
434
435   case Instruction::Mul:
436     S += ConstantArithExprToString(CE, target, ") * (");
437     break;
438
439   case Instruction::Div:
440     S += ConstantArithExprToString(CE, target, ") / (");
441     break;
442
443   case Instruction::Rem:
444     S += ConstantArithExprToString(CE, target, ") % (");
445     break;
446
447   case Instruction::And:
448     // Logical && for booleans; bitwise & otherwise
449     S += ConstantArithExprToString(CE, target,
450                                    ((CE->getType() == Type::BoolTy)? ") && (" : ") & ("));
451     break;
452
453   case Instruction::Or:
454     // Logical || for booleans; bitwise | otherwise
455     S += ConstantArithExprToString(CE, target,
456                                    ((CE->getType() == Type::BoolTy)? ") || (" : ") | ("));
457     break;
458
459   case Instruction::Xor:
460     // Bitwise ^ for all types
461     S += ConstantArithExprToString(CE, target, ") ^ (");
462     break;
463
464   default:
465     assert(0 && "Unsupported operator in ConstantExprToString()");
466     break;
467   }
468
469   return S;
470 }
471
472 /// valToExprString - Helper function for ConstantExprToString().
473 /// Appends result to argument string S.
474 ///
475 std::string AsmPrinter::valToExprString(const Value* V,
476                                         const TargetMachine& target) {
477   std::string S;
478   bool failed = false;
479   if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
480     S += getID(GV);
481   } else if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
482     if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
483       S += std::string(CB == ConstantBool::True ? "1" : "0");
484     else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
485       S += itostr(CI->getValue());
486     else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
487       S += utostr(CI->getValue());
488     else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
489       S += ftostr(CFP->getValue());
490     else if (isa<ConstantPointerNull>(CV) || isa<UndefValue>(CV))
491       S += "0";
492     else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
493       S += ConstantExprToString(CE, target);
494     else
495       failed = true;
496   } else
497     failed = true;
498
499   if (failed) {
500     assert(0 && "Cannot convert value to string");
501     S += "<illegal-value>";
502   }
503   return S;
504 }
505
506 namespace {
507
508   struct SparcV9AsmPrinter : public FunctionPass, public AsmPrinter {
509     inline SparcV9AsmPrinter(std::ostream &os, const TargetMachine &t)
510       : AsmPrinter(os, t) {}
511
512     const Function *currFunction;
513
514     const char *getPassName() const {
515       return "Output SparcV9 Assembly for Functions";
516     }
517
518     virtual bool doInitialization(Module &M) {
519       startModule(M);
520       return false;
521     }
522
523     virtual bool runOnFunction(Function &F) {
524       currFunction = &F;
525       emitFunction(F);
526       return false;
527     }
528
529     virtual bool doFinalization(Module &M) {
530       emitGlobals(M);
531       return false;
532     }
533
534     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
535       AU.setPreservesAll();
536     }
537
538     void emitFunction(const Function &F);
539   private :
540     void emitBasicBlock(const MachineBasicBlock &MBB);
541     void emitMachineInst(const MachineInstr *MI);
542
543     unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
544     void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
545
546     bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
547     bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
548
549     unsigned getOperandMask(unsigned Opcode) {
550       switch (Opcode) {
551       case V9::SUBccr:
552       case V9::SUBcci:   return 1 << 3;  // Remove CC argument
553       default:      return 0;       // By default, don't hack operands...
554       }
555     }
556
557     void emitGlobals(const Module &M);
558     void printGlobalVariable(const GlobalVariable *GV);
559   };
560
561 } // End anonymous namespace
562
563 inline bool
564 SparcV9AsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
565                                        unsigned int opNum) {
566   switch (MI->getOpcode()) {
567   case V9::JMPLCALLr:
568   case V9::JMPLCALLi:
569   case V9::JMPLRETr:
570   case V9::JMPLRETi:
571     return (opNum == 0);
572   default:
573     return false;
574   }
575 }
576
577 inline bool
578 SparcV9AsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
579                                        unsigned int opNum) {
580   if (TM.getInstrInfo()->isLoad(MI->getOpcode()))
581     return (opNum == 0);
582   else if (TM.getInstrInfo()->isStore(MI->getOpcode()))
583     return (opNum == 1);
584   else
585     return false;
586 }
587
588 unsigned int
589 SparcV9AsmPrinter::printOperands(const MachineInstr *MI, unsigned opNum) {
590   const MachineOperand& mop = MI->getOperand(opNum);
591   if (OpIsBranchTargetLabel(MI, opNum)) {
592     printOneOperand(mop, MI->getOpcode());
593     O << "+";
594     printOneOperand(MI->getOperand(opNum+1), MI->getOpcode());
595     return 2;
596   } else if (OpIsMemoryAddressBase(MI, opNum)) {
597     O << "[";
598     printOneOperand(mop, MI->getOpcode());
599     O << "+";
600     printOneOperand(MI->getOperand(opNum+1), MI->getOpcode());
601     O << "]";
602     return 2;
603   } else {
604     printOneOperand(mop, MI->getOpcode());
605     return 1;
606   }
607 }
608
609 void
610 SparcV9AsmPrinter::printOneOperand(const MachineOperand &mop,
611                                    MachineOpCode opCode)
612 {
613   bool needBitsFlag = true;
614
615   if (mop.isHiBits32())
616     O << "%lm(";
617   else if (mop.isLoBits32())
618     O << "%lo(";
619   else if (mop.isHiBits64())
620     O << "%hh(";
621   else if (mop.isLoBits64())
622     O << "%hm(";
623   else
624     needBitsFlag = false;
625
626   switch (mop.getType())
627     {
628     case MachineOperand::MO_VirtualRegister:
629     case MachineOperand::MO_CCRegister:
630     case MachineOperand::MO_MachineRegister:
631       {
632         int regNum = (int)mop.getReg();
633
634         if (regNum == TM.getRegInfo()->getInvalidRegNum()) {
635           // better to print code with NULL registers than to die
636           O << "<NULL VALUE>";
637         } else {
638           O << "%" << TM.getRegInfo()->getUnifiedRegName(regNum);
639         }
640         break;
641       }
642
643     case MachineOperand::MO_ConstantPoolIndex:
644       {
645         O << ".CPI_" << getID(currFunction)
646               << "_" << mop.getConstantPoolIndex();
647         break;
648       }
649
650     case MachineOperand::MO_PCRelativeDisp:
651       {
652         const Value *Val = mop.getVRegValue();
653         assert(Val && "\tNULL Value in SparcV9AsmPrinter");
654
655         if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
656           O << getID(BB);
657         else if (const Function *F = dyn_cast<Function>(Val))
658           O << getID(F);
659         else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
660           O << getID(GV);
661         else if (const Constant *CV = dyn_cast<Constant>(Val))
662           O << getID(CV);
663         else
664           assert(0 && "Unrecognized value in SparcV9AsmPrinter");
665         break;
666       }
667
668     case MachineOperand::MO_SignExtendedImmed:
669       O << mop.getImmedValue();
670       break;
671
672     case MachineOperand::MO_UnextendedImmed:
673       O << (uint64_t) mop.getImmedValue();
674       break;
675
676     default:
677       O << mop;      // use dump field
678       break;
679     }
680
681   if (needBitsFlag)
682     O << ")";
683 }
684
685 void SparcV9AsmPrinter::emitMachineInst(const MachineInstr *MI) {
686   unsigned Opcode = MI->getOpcode();
687
688   if (Opcode == V9::PHI)
689     return;  // Ignore Machine-PHI nodes.
690
691   O << "\t" << TM.getInstrInfo()->getName(Opcode) << "\t";
692
693   unsigned Mask = getOperandMask(Opcode);
694
695   bool NeedComma = false;
696   unsigned N = 1;
697   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
698     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
699       if (NeedComma) O << ", ";         // Handle comma outputting
700       NeedComma = true;
701       N = printOperands(MI, OpNum);
702     } else
703       N = 1;
704
705   O << "\n";
706   ++EmittedInsts;
707 }
708
709 void SparcV9AsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB) {
710   // Emit a label for the basic block
711   O << getID(MBB.getBasicBlock()) << ":\n";
712
713   // Loop over all of the instructions in the basic block...
714   for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
715        MII != MIE; ++MII)
716     emitMachineInst(MII);
717   O << "\n";  // Separate BB's with newlines
718 }
719
720 void SparcV9AsmPrinter::emitFunction(const Function &F) {
721   std::string CurrentFnName = getID(&F);
722   MachineFunction &MF = MachineFunction::get(&F);
723   O << "!****** Outputing Function: " << CurrentFnName << " ******\n";
724
725   // Emit constant pool for this function
726   const MachineConstantPool *MCP = MF.getConstantPool();
727   const std::vector<std::pair<Constant*, unsigned> > &CP = MCP->getConstants();
728
729   enterSection(ReadOnlyData);
730   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
731     std::string cpiName = ".CPI_" + CurrentFnName + "_" + utostr(i);
732     printConstant(CP[i].first, CP[i].second, cpiName);
733   }
734
735   enterSection(Text);
736   O << "\t.align\t4\n\t.global\t" << CurrentFnName << "\n";
737   //O << "\t.type\t" << CurrentFnName << ",#function\n";
738   O << "\t.type\t" << CurrentFnName << ", 2\n";
739   O << CurrentFnName << ":\n";
740
741   // Output code for all of the basic blocks in the function...
742   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
743     emitBasicBlock(*I);
744
745   // Output a .size directive so the debugger knows the extents of the function
746   O << ".EndOf_" << CurrentFnName << ":\n\t.size "
747            << CurrentFnName << ", .EndOf_"
748            << CurrentFnName << "-" << CurrentFnName << "\n";
749
750   // Put some spaces between the functions
751   O << "\n\n";
752 }
753
754 void SparcV9AsmPrinter::printGlobalVariable(const GlobalVariable* GV) {
755   if (GV->hasExternalLinkage())
756     O << "\t.global\t" << getID(GV) << "\n";
757
758   if (GV->hasInitializer() &&
759       !(GV->getInitializer()->isNullValue() ||
760         isa<UndefValue>(GV->getInitializer()))) {
761     printConstant(GV->getInitializer(), 0, getID(GV));
762   } else {
763     O << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
764                                                 TM) << "\n";
765     O << "\t.type\t" << getID(GV) << ",#object\n";
766     O << "\t.reserve\t" << getID(GV) << ","
767       << findOptimalStorageSize(TM, GV->getType()->getElementType())
768       << "\n";
769   }
770 }
771
772 void SparcV9AsmPrinter::emitGlobals(const Module &M) {
773   // Output global variables...
774   for (Module::const_global_iterator GI = M.global_begin(), GE = M.global_end(); GI != GE; ++GI)
775     if (! GI->isExternal()) {
776       assert(GI->hasInitializer());
777       if (GI->isConstant())
778         enterSection(ReadOnlyData);   // read-only, initialized data
779       else if (GI->getInitializer()->isNullValue() ||
780                isa<UndefValue>(GI->getInitializer()))
781         enterSection(ZeroInitRWData); // read-write zero data
782       else
783         enterSection(InitRWData);     // read-write non-zero data
784
785       printGlobalVariable(GI);
786     }
787
788   O << "\n";
789 }
790
791 FunctionPass *llvm::createAsmPrinterPass(std::ostream &Out, TargetMachine &TM) {
792   return new SparcV9AsmPrinter(Out, TM);
793 }