Move MachineCodeForInstruction.h and MachineFunctionInfo.h into lib/Target/SparcV9
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9AsmPrinter.cpp
1 //===-- EmitAssembly.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 "Support/StringExtras.h"
31 #include "Support/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
160
161 //===---------------------------------------------------------------------===//
162 //   Code abstracted away from the AsmPrinter
163 //===---------------------------------------------------------------------===//
164
165 namespace {
166   class AsmPrinter {
167     // Mangle symbol names appropriately
168     Mangler *Mang;
169
170   public:
171     std::ostream &toAsm;
172     const TargetMachine &Target;
173   
174     enum Sections {
175       Unknown,
176       Text,
177       ReadOnlyData,
178       InitRWData,
179       ZeroInitRWData,
180     } CurSection;
181
182     AsmPrinter(std::ostream &os, const TargetMachine &T)
183       : /* idTable(0), */ toAsm(os), Target(T), CurSection(Unknown) {}
184   
185     ~AsmPrinter() {
186       delete Mang;
187     }
188
189     // (start|end)(Module|Function) - Callback methods invoked by subclasses
190     void startModule(Module &M) {
191       Mang = new Mangler(M);
192     }
193
194     void PrintZeroBytesToPad(int numBytes) {
195       //
196       // Always use single unsigned bytes for padding.  We don't know upon
197       // what data size the beginning address is aligned, so using anything
198       // other than a byte may cause alignment errors in the assembler.
199       //
200       while (numBytes--)
201         printSingleConstantValue(Constant::getNullValue(Type::UByteTy));
202     }
203
204     /// Print a single constant value.
205     ///
206     void printSingleConstantValue(const Constant* CV);
207
208     /// Print a constant value or values (it may be an aggregate).
209     /// Uses printSingleConstantValue() to print each individual value.
210     ///
211     void printConstantValueOnly(const Constant* CV, int numPadBytesAfter = 0);
212
213     // Print a constant (which may be an aggregate) prefixed by all the
214     // appropriate directives.  Uses printConstantValueOnly() to print the
215     // value or values.
216     void printConstant(const Constant* CV, std::string valID = "") {
217       if (valID.length() == 0)
218         valID = getID(CV);
219   
220       toAsm << "\t.align\t" << ConstantToAlignment(CV, Target) << "\n";
221   
222       // Print .size and .type only if it is not a string.
223       if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
224         if (CVA->isString()) {
225           // print it as a string and return
226           toAsm << valID << ":\n";
227           toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
228           return;
229         }
230   
231       toAsm << "\t.type" << "\t" << valID << ",#object\n";
232
233       unsigned int constSize = ConstantToSize(CV, Target);
234       if (constSize)
235         toAsm << "\t.size" << "\t" << valID << "," << constSize << "\n";
236   
237       toAsm << valID << ":\n";
238   
239       printConstantValueOnly(CV);
240     }
241
242     // enterSection - Use this method to enter a different section of the output
243     // executable.  This is used to only output necessary section transitions.
244     //
245     void enterSection(enum Sections S) {
246       if (S == CurSection) return;        // Only switch section if necessary
247       CurSection = S;
248
249       toAsm << "\n\t.section ";
250       switch (S)
251       {
252       default: assert(0 && "Bad section name!");
253       case Text:         toAsm << "\".text\""; break;
254       case ReadOnlyData: toAsm << "\".rodata\",#alloc"; break;
255       case InitRWData:   toAsm << "\".data\",#alloc,#write"; break;
256       case ZeroInitRWData: toAsm << "\".bss\",#alloc,#write"; break;
257       }
258       toAsm << "\n";
259     }
260
261     // getID Wrappers - Ensure consistent usage
262     // Symbol names in SparcV9 assembly language have these rules:
263     // (a) Must match { letter | _ | . | $ } { letter | _ | . | $ | digit }*
264     // (b) A name beginning in "." is treated as a local name.
265     std::string getID(const Function *F) {
266       return Mang->getValueName(F);
267     }
268     std::string getID(const BasicBlock *BB) {
269       return ".L_" + getID(BB->getParent()) + "_" + Mang->getValueName(BB);
270     }
271     std::string getID(const GlobalVariable *GV) {
272       return Mang->getValueName(GV);
273     }
274     std::string getID(const Constant *CV) {
275       return ".C_" + Mang->getValueName(CV);
276     }
277     std::string getID(const GlobalValue *GV) {
278       if (const GlobalVariable *V = dyn_cast<GlobalVariable>(GV))
279         return getID(V);
280       else if (const Function *F = dyn_cast<Function>(GV))
281         return getID(F);
282       assert(0 && "Unexpected type of GlobalValue!");
283       return "";
284     }
285
286     // Combines expressions 
287     inline std::string ConstantArithExprToString(const ConstantExpr* CE,
288                                                  const TargetMachine &TM,
289                                                  const std::string &op) {
290       return "(" + valToExprString(CE->getOperand(0), TM) + op
291         + valToExprString(CE->getOperand(1), TM) + ")";
292     }
293
294     /// ConstantExprToString() - Convert a ConstantExpr to an asm expression
295     /// and return this as a string.
296     ///
297     std::string ConstantExprToString(const ConstantExpr* CE,
298                                      const TargetMachine& target);
299
300     /// valToExprString - Helper function for ConstantExprToString().
301     /// Appends result to argument string S.
302     /// 
303     std::string valToExprString(const Value* V, const TargetMachine& target);
304   };
305 } // End anonymous namespace
306
307
308 /// Print a single constant value.
309 ///
310 void AsmPrinter::printSingleConstantValue(const Constant* CV) {
311   assert(CV->getType() != Type::VoidTy &&
312          CV->getType() != Type::LabelTy &&
313          "Unexpected type for Constant");
314   
315   assert((!isa<ConstantArray>(CV) && ! isa<ConstantStruct>(CV))
316          && "Aggregate types should be handled outside this function");
317   
318   toAsm << "\t" << TypeToDataDirective(CV->getType()) << "\t";
319   
320   if (const GlobalValue* GV = dyn_cast<GlobalValue>(CV)) {
321     toAsm << getID(GV) << "\n";
322   } else if (isa<ConstantPointerNull>(CV)) {
323     // Null pointer value
324     toAsm << "0\n";
325   } else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV)) { 
326     // Constant expression built from operators, constants, and symbolic addrs
327     toAsm << ConstantExprToString(CE, Target) << "\n";
328   } else if (CV->getType()->isPrimitiveType()) {
329     // Check primitive types last
330     if (CV->getType()->isFloatingPoint()) {
331       // FP Constants are printed as integer constants to avoid losing
332       // precision...
333       double Val = cast<ConstantFP>(CV)->getValue();
334       if (CV->getType() == Type::FloatTy) {
335         float FVal = (float)Val;
336         char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
337         toAsm << *(unsigned int*)ProxyPtr;            
338       } else if (CV->getType() == Type::DoubleTy) {
339         char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
340         toAsm << *(uint64_t*)ProxyPtr;            
341       } else {
342         assert(0 && "Unknown floating point type!");
343       }
344         
345       toAsm << "\t! " << CV->getType()->getDescription()
346             << " value: " << Val << "\n";
347     } else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
348       toAsm << (int)CB->getValue() << "\n";
349     } else {
350       WriteAsOperand(toAsm, CV, false, false) << "\n";
351     }
352   } else {
353     assert(0 && "Unknown elementary type for constant");
354   }
355 }
356
357 /// Print a constant value or values (it may be an aggregate).
358 /// Uses printSingleConstantValue() to print each individual value.
359 ///
360 void AsmPrinter::printConstantValueOnly(const Constant* CV,
361                                         int numPadBytesAfter) {
362   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
363     if (CVA->isString()) {
364       // print the string alone and return
365       toAsm << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
366     } else {
367       // Not a string.  Print the values in successive locations
368       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
369         printConstantValueOnly(CVA->getOperand(i));
370     }
371   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
372     // Print the fields in successive locations. Pad to align if needed!
373     const StructLayout *cvsLayout =
374       Target.getTargetData().getStructLayout(CVS->getType());
375     unsigned sizeSoFar = 0;
376     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
377       const Constant* field = CVS->getOperand(i);
378
379       // Check if padding is needed and insert one or more 0s.
380       unsigned fieldSize =
381         Target.getTargetData().getTypeSize(field->getType());
382       int padSize = ((i == e-1? cvsLayout->StructSize
383                       : cvsLayout->MemberOffsets[i+1])
384                      - cvsLayout->MemberOffsets[i]) - fieldSize;
385       sizeSoFar += (fieldSize + padSize);
386
387       // Now print the actual field value
388       printConstantValueOnly(field, padSize);
389     }
390     assert(sizeSoFar == cvsLayout->StructSize &&
391            "Layout of constant struct may be incorrect!");
392   } else if (isa<ConstantAggregateZero>(CV)) {
393     PrintZeroBytesToPad(Target.getTargetData().getTypeSize(CV->getType()));
394   } else
395     printSingleConstantValue(CV);
396
397   if (numPadBytesAfter)
398     PrintZeroBytesToPad(numPadBytesAfter);
399 }
400
401 /// ConstantExprToString() - Convert a ConstantExpr to an asm expression
402 /// and return this as a string.
403 ///
404 std::string AsmPrinter::ConstantExprToString(const ConstantExpr* CE,
405                                              const TargetMachine& target) {
406   std::string S;
407   switch(CE->getOpcode()) {
408   case Instruction::GetElementPtr:
409     { // generate a symbolic expression for the byte address
410       const Value* ptrVal = CE->getOperand(0);
411       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
412       const TargetData &TD = target.getTargetData();
413       S += "(" + valToExprString(ptrVal, target) + ") + ("
414         + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
415       break;
416     }
417
418   case Instruction::Cast:
419     // Support only non-converting casts for now, i.e., a no-op.
420     // This assertion is not a complete check.
421     assert(target.getTargetData().getTypeSize(CE->getType()) ==
422            target.getTargetData().getTypeSize(CE->getOperand(0)->getType()));
423     S += "(" + valToExprString(CE->getOperand(0), target) + ")";
424     break;
425
426   case Instruction::Add:
427     S += ConstantArithExprToString(CE, target, ") + (");
428     break;
429
430   case Instruction::Sub:
431     S += ConstantArithExprToString(CE, target, ") - (");
432     break;
433
434   case Instruction::Mul:
435     S += ConstantArithExprToString(CE, target, ") * (");
436     break;
437
438   case Instruction::Div:
439     S += ConstantArithExprToString(CE, target, ") / (");
440     break;
441
442   case Instruction::Rem:
443     S += ConstantArithExprToString(CE, target, ") % (");
444     break;
445
446   case Instruction::And:
447     // Logical && for booleans; bitwise & otherwise
448     S += ConstantArithExprToString(CE, target,
449                                    ((CE->getType() == Type::BoolTy)? ") && (" : ") & ("));
450     break;
451
452   case Instruction::Or:
453     // Logical || for booleans; bitwise | otherwise
454     S += ConstantArithExprToString(CE, target,
455                                    ((CE->getType() == Type::BoolTy)? ") || (" : ") | ("));
456     break;
457
458   case Instruction::Xor:
459     // Bitwise ^ for all types
460     S += ConstantArithExprToString(CE, target, ") ^ (");
461     break;
462
463   default:
464     assert(0 && "Unsupported operator in ConstantExprToString()");
465     break;
466   }
467
468   return S;
469 }
470
471 /// valToExprString - Helper function for ConstantExprToString().
472 /// Appends result to argument string S.
473 /// 
474 std::string AsmPrinter::valToExprString(const Value* V,
475                                         const TargetMachine& target) {
476   std::string S;
477   bool failed = false;
478   if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
479     S += getID(GV);
480   } else if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
481     if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
482       S += std::string(CB == ConstantBool::True ? "1" : "0");
483     else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
484       S += itostr(CI->getValue());
485     else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
486       S += utostr(CI->getValue());
487     else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
488       S += ftostr(CFP->getValue());
489     else if (isa<ConstantPointerNull>(CV))
490       S += "0";
491     else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
492       S += ConstantExprToString(CE, target);
493     else
494       failed = true;
495   } else
496     failed = true;
497
498   if (failed) {
499     assert(0 && "Cannot convert value to string");
500     S += "<illegal-value>";
501   }
502   return S;
503 }
504
505
506 //===----------------------------------------------------------------------===//
507 //   SparcV9AsmPrinter Code
508 //===----------------------------------------------------------------------===//
509
510 namespace {
511
512   struct SparcV9AsmPrinter : public FunctionPass, public AsmPrinter {
513     inline SparcV9AsmPrinter(std::ostream &os, const TargetMachine &t)
514       : AsmPrinter(os, t) {}
515
516     const Function *currFunction;
517
518     const char *getPassName() const {
519       return "Output SparcV9 Assembly for Functions";
520     }
521
522     virtual bool doInitialization(Module &M) {
523       startModule(M);
524       return false;
525     }
526
527     virtual bool runOnFunction(Function &F) {
528       currFunction = &F;
529       emitFunction(F);
530       return false;
531     }
532
533     virtual bool doFinalization(Module &M) {
534       emitGlobals(M);
535       return false;
536     }
537
538     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
539       AU.setPreservesAll();
540     }
541
542     void emitFunction(const Function &F);
543   private :
544     void emitBasicBlock(const MachineBasicBlock &MBB);
545     void emitMachineInst(const MachineInstr *MI);
546   
547     unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
548     void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
549
550     bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
551     bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
552   
553     unsigned getOperandMask(unsigned Opcode) {
554       switch (Opcode) {
555       case V9::SUBccr:
556       case V9::SUBcci:   return 1 << 3;  // Remove CC argument
557       default:      return 0;       // By default, don't hack operands...
558       }
559     }
560
561     void emitGlobals(const Module &M);
562     void printGlobalVariable(const GlobalVariable *GV);
563   };
564
565 } // End anonymous namespace
566
567 inline bool
568 SparcV9AsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
569                                        unsigned int opNum) {
570   switch (MI->getOpcode()) {
571   case V9::JMPLCALLr:
572   case V9::JMPLCALLi:
573   case V9::JMPLRETr:
574   case V9::JMPLRETi:
575     return (opNum == 0);
576   default:
577     return false;
578   }
579 }
580
581 inline bool
582 SparcV9AsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
583                                        unsigned int opNum) {
584   if (Target.getInstrInfo()->isLoad(MI->getOpcode()))
585     return (opNum == 0);
586   else if (Target.getInstrInfo()->isStore(MI->getOpcode()))
587     return (opNum == 1);
588   else
589     return false;
590 }
591
592
593 #define PrintOp1PlusOp2(mop1, mop2, opCode) \
594   printOneOperand(mop1, opCode); \
595   toAsm << "+"; \
596   printOneOperand(mop2, opCode);
597
598 unsigned int
599 SparcV9AsmPrinter::printOperands(const MachineInstr *MI,
600                                unsigned int opNum)
601 {
602   const MachineOperand& mop = MI->getOperand(opNum);
603   
604   if (OpIsBranchTargetLabel(MI, opNum)) {
605     PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpcode());
606     return 2;
607   } else if (OpIsMemoryAddressBase(MI, opNum)) {
608     toAsm << "[";
609     PrintOp1PlusOp2(mop, MI->getOperand(opNum+1), MI->getOpcode());
610     toAsm << "]";
611     return 2;
612   } else {
613     printOneOperand(mop, MI->getOpcode());
614     return 1;
615   }
616 }
617
618 void
619 SparcV9AsmPrinter::printOneOperand(const MachineOperand &mop,
620                                  MachineOpCode opCode)
621 {
622   bool needBitsFlag = true;
623   
624   if (mop.isHiBits32())
625     toAsm << "%lm(";
626   else if (mop.isLoBits32())
627     toAsm << "%lo(";
628   else if (mop.isHiBits64())
629     toAsm << "%hh(";
630   else if (mop.isLoBits64())
631     toAsm << "%hm(";
632   else
633     needBitsFlag = false;
634   
635   switch (mop.getType())
636     {
637     case MachineOperand::MO_VirtualRegister:
638     case MachineOperand::MO_CCRegister:
639     case MachineOperand::MO_MachineRegister:
640       {
641         int regNum = (int)mop.getReg();
642         
643         if (regNum == Target.getRegInfo()->getInvalidRegNum()) {
644           // better to print code with NULL registers than to die
645           toAsm << "<NULL VALUE>";
646         } else {
647           toAsm << "%" << Target.getRegInfo()->getUnifiedRegName(regNum);
648         }
649         break;
650       }
651     
652     case MachineOperand::MO_ConstantPoolIndex:
653       {
654         toAsm << ".CPI_" << getID(currFunction)
655               << "_" << mop.getConstantPoolIndex();
656         break;
657       }
658
659     case MachineOperand::MO_PCRelativeDisp:
660       {
661         const Value *Val = mop.getVRegValue();
662         assert(Val && "\tNULL Value in SparcV9AsmPrinter");
663         
664         if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
665           toAsm << getID(BB);
666         else if (const Function *F = dyn_cast<Function>(Val))
667           toAsm << getID(F);
668         else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
669           toAsm << getID(GV);
670         else if (const Constant *CV = dyn_cast<Constant>(Val))
671           toAsm << getID(CV);
672         else
673           assert(0 && "Unrecognized value in SparcV9AsmPrinter");
674         break;
675       }
676     
677     case MachineOperand::MO_SignExtendedImmed:
678       toAsm << mop.getImmedValue();
679       break;
680
681     case MachineOperand::MO_UnextendedImmed:
682       toAsm << (uint64_t) mop.getImmedValue();
683       break;
684     
685     default:
686       toAsm << mop;      // use dump field
687       break;
688     }
689   
690   if (needBitsFlag)
691     toAsm << ")";
692 }
693
694 void SparcV9AsmPrinter::emitMachineInst(const MachineInstr *MI) {
695   unsigned Opcode = MI->getOpcode();
696
697   if (Target.getInstrInfo()->isDummyPhiInstr(Opcode))
698     return;  // IGNORE PHI NODES
699
700   toAsm << "\t" << Target.getInstrInfo()->getName(Opcode) << "\t";
701
702   unsigned Mask = getOperandMask(Opcode);
703   
704   bool NeedComma = false;
705   unsigned N = 1;
706   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
707     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
708       if (NeedComma) toAsm << ", ";         // Handle comma outputting
709       NeedComma = true;
710       N = printOperands(MI, OpNum);
711     } else
712       N = 1;
713   
714   toAsm << "\n";
715   ++EmittedInsts;
716 }
717
718 void SparcV9AsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB) {
719   // Emit a label for the basic block
720   toAsm << getID(MBB.getBasicBlock()) << ":\n";
721
722   // Loop over all of the instructions in the basic block...
723   for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
724        MII != MIE; ++MII)
725     emitMachineInst(MII);
726   toAsm << "\n";  // Separate BB's with newlines
727 }
728
729 void SparcV9AsmPrinter::emitFunction(const Function &F) {
730   std::string methName = getID(&F);
731   toAsm << "!****** Outputing Function: " << methName << " ******\n";
732
733   // Emit constant pool for this function
734   const MachineConstantPool *MCP = MachineFunction::get(&F).getConstantPool();
735   const std::vector<Constant*> &CP = MCP->getConstants();
736
737   enterSection(AsmPrinter::ReadOnlyData);
738   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
739     std::string cpiName = ".CPI_" + methName + "_" + utostr(i);
740     printConstant(CP[i], cpiName);
741   }
742
743   enterSection(AsmPrinter::Text);
744   toAsm << "\t.align\t4\n\t.global\t" << methName << "\n";
745   //toAsm << "\t.type\t" << methName << ",#function\n";
746   toAsm << "\t.type\t" << methName << ", 2\n";
747   toAsm << methName << ":\n";
748
749   // Output code for all of the basic blocks in the function...
750   MachineFunction &MF = MachineFunction::get(&F);
751   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
752     emitBasicBlock(*I);
753
754   // Output a .size directive so the debugger knows the extents of the function
755   toAsm << ".EndOf_" << methName << ":\n\t.size "
756            << methName << ", .EndOf_"
757            << methName << "-" << methName << "\n";
758
759   // Put some spaces between the functions
760   toAsm << "\n\n";
761 }
762
763 void SparcV9AsmPrinter::printGlobalVariable(const GlobalVariable* GV) {
764   if (GV->hasExternalLinkage())
765     toAsm << "\t.global\t" << getID(GV) << "\n";
766   
767   if (GV->hasInitializer() && ! GV->getInitializer()->isNullValue()) {
768     printConstant(GV->getInitializer(), getID(GV));
769   } else {
770     toAsm << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
771                                                 Target) << "\n";
772     toAsm << "\t.type\t" << getID(GV) << ",#object\n";
773     toAsm << "\t.reserve\t" << getID(GV) << ","
774           << findOptimalStorageSize(Target, GV->getType()->getElementType())
775           << "\n";
776   }
777 }
778
779 void SparcV9AsmPrinter::emitGlobals(const Module &M) {
780   // Output global variables...
781   for (Module::const_giterator GI = M.gbegin(), GE = M.gend(); GI != GE; ++GI)
782     if (! GI->isExternal()) {
783       assert(GI->hasInitializer());
784       if (GI->isConstant())
785         enterSection(AsmPrinter::ReadOnlyData);   // read-only, initialized data
786       else if (GI->getInitializer()->isNullValue())
787         enterSection(AsmPrinter::ZeroInitRWData); // read-write zero data
788       else
789         enterSection(AsmPrinter::InitRWData);     // read-write non-zero data
790
791       printGlobalVariable(GI);
792     }
793
794   toAsm << "\n";
795 }
796
797 FunctionPass *llvm::createAsmPrinterPass(std::ostream &Out,
798                                          const TargetMachine &TM) {
799   return new SparcV9AsmPrinter(Out, TM);
800 }