Split out altivec notes into their own README
[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       if (Alignment != 1)
220         O << "\t.align\t" << Alignment << "\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           O << valID << ":\n";
227           O << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
228           return;
229         }
230
231       O << "\t.type" << "\t" << valID << ",#object\n";
232
233       unsigned int constSize = ConstantToSize(CV, TM);
234       if (constSize)
235         O << "\t.size" << "\t" << valID << "," << constSize << "\n";
236
237       O << 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       O << "\n\t.section ";
250       switch (S)
251       {
252       default: assert(0 && "Bad section name!");
253       case Text:         O << "\".text\""; break;
254       case ReadOnlyData: O << "\".rodata\",#alloc"; break;
255       case InitRWData:   O << "\".data\",#alloc,#write"; break;
256       case ZeroInitRWData: O << "\".bss\",#alloc,#write"; break;
257       }
258       O << "\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   O << "\t" << TypeToDataDirective(CV->getType()) << "\t";
319
320   if (const GlobalValue* GV = dyn_cast<GlobalValue>(CV)) {
321     O << getID(GV) << "\n";
322   } else if (isa<ConstantPointerNull>(CV) || isa<UndefValue>(CV)) {
323     // Null pointer value
324     O << "0\n";
325   } else if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(CV)) {
326     // Constant expression built from operators, constants, and symbolic addrs
327     O << ConstantExprToString(CE, TM) << "\n";
328   } else if (CV->getType()->isPrimitiveType()) {
329     // Check primitive types last
330     if (isa<UndefValue>(CV)) {
331       O << "0\n";
332     } else if (CV->getType()->isFloatingPoint()) {
333       // FP Constants are printed as integer constants to avoid losing
334       // precision...
335       double Val = cast<ConstantFP>(CV)->getValue();
336       if (CV->getType() == Type::FloatTy) {
337         float FVal = (float)Val;
338         char *ProxyPtr = (char*)&FVal;        // Abide by C TBAA rules
339         O << *(unsigned int*)ProxyPtr;
340       } else if (CV->getType() == Type::DoubleTy) {
341         char *ProxyPtr = (char*)&Val;         // Abide by C TBAA rules
342         O << *(uint64_t*)ProxyPtr;
343       } else {
344         assert(0 && "Unknown floating point type!");
345       }
346
347       O << "\t! " << CV->getType()->getDescription()
348             << " value: " << Val << "\n";
349     } else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
350       O << (int)CB->getValue() << "\n";
351     } else {
352       WriteAsOperand(O, CV, false, false) << "\n";
353     }
354   } else {
355     assert(0 && "Unknown elementary type for constant");
356   }
357 }
358
359 /// Print a constant value or values (it may be an aggregate).
360 /// Uses printSingleConstantValue() to print each individual value.
361 ///
362 void AsmPrinter::printConstantValueOnly(const Constant* CV,
363                                         int numPadBytesAfter) {
364   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
365     if (CVA->isString()) {
366       // print the string alone and return
367       O << "\t" << ".ascii" << "\t" << getAsCString(CVA) << "\n";
368     } else {
369       // Not a string.  Print the values in successive locations
370       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
371         printConstantValueOnly(CVA->getOperand(i));
372     }
373   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
374     // Print the fields in successive locations. Pad to align if needed!
375     const StructLayout *cvsLayout =
376       TM.getTargetData().getStructLayout(CVS->getType());
377     unsigned sizeSoFar = 0;
378     for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
379       const Constant* field = CVS->getOperand(i);
380
381       // Check if padding is needed and insert one or more 0s.
382       unsigned fieldSize =
383         TM.getTargetData().getTypeSize(field->getType());
384       int padSize = ((i == e-1? cvsLayout->StructSize
385                       : cvsLayout->MemberOffsets[i+1])
386                      - cvsLayout->MemberOffsets[i]) - fieldSize;
387       sizeSoFar += (fieldSize + padSize);
388
389       // Now print the actual field value
390       printConstantValueOnly(field, padSize);
391     }
392     assert(sizeSoFar == cvsLayout->StructSize &&
393            "Layout of constant struct may be incorrect!");
394   } else if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
395     PrintZeroBytesToPad(TM.getTargetData().getTypeSize(CV->getType()));
396   } else
397     printSingleConstantValue(CV);
398
399   if (numPadBytesAfter)
400     PrintZeroBytesToPad(numPadBytesAfter);
401 }
402
403 /// ConstantExprToString() - Convert a ConstantExpr to an asm expression
404 /// and return this as a string.
405 ///
406 std::string AsmPrinter::ConstantExprToString(const ConstantExpr* CE,
407                                              const TargetMachine& target) {
408   std::string S;
409   switch(CE->getOpcode()) {
410   case Instruction::GetElementPtr:
411     { // generate a symbolic expression for the byte address
412       const Value* ptrVal = CE->getOperand(0);
413       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
414       const TargetData &TD = target.getTargetData();
415       S += "(" + valToExprString(ptrVal, target) + ") + ("
416         + utostr(TD.getIndexedOffset(ptrVal->getType(),idxVec)) + ")";
417       break;
418     }
419
420   case Instruction::Cast:
421     // Support only non-converting casts for now, i.e., a no-op.
422     // This assertion is not a complete check.
423     assert(target.getTargetData().getTypeSize(CE->getType()) ==
424            target.getTargetData().getTypeSize(CE->getOperand(0)->getType()));
425     S += "(" + valToExprString(CE->getOperand(0), target) + ")";
426     break;
427
428   case Instruction::Add:
429     S += ConstantArithExprToString(CE, target, ") + (");
430     break;
431
432   case Instruction::Sub:
433     S += ConstantArithExprToString(CE, target, ") - (");
434     break;
435
436   case Instruction::Mul:
437     S += ConstantArithExprToString(CE, target, ") * (");
438     break;
439
440   case Instruction::Div:
441     S += ConstantArithExprToString(CE, target, ") / (");
442     break;
443
444   case Instruction::Rem:
445     S += ConstantArithExprToString(CE, target, ") % (");
446     break;
447
448   case Instruction::And:
449     // Logical && for booleans; bitwise & otherwise
450     S += ConstantArithExprToString(CE, target,
451                                    ((CE->getType() == Type::BoolTy)? ") && (" : ") & ("));
452     break;
453
454   case Instruction::Or:
455     // Logical || for booleans; bitwise | otherwise
456     S += ConstantArithExprToString(CE, target,
457                                    ((CE->getType() == Type::BoolTy)? ") || (" : ") | ("));
458     break;
459
460   case Instruction::Xor:
461     // Bitwise ^ for all types
462     S += ConstantArithExprToString(CE, target, ") ^ (");
463     break;
464
465   default:
466     assert(0 && "Unsupported operator in ConstantExprToString()");
467     break;
468   }
469
470   return S;
471 }
472
473 /// valToExprString - Helper function for ConstantExprToString().
474 /// Appends result to argument string S.
475 ///
476 std::string AsmPrinter::valToExprString(const Value* V,
477                                         const TargetMachine& target) {
478   std::string S;
479   bool failed = false;
480   if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
481     S += getID(GV);
482   } else if (const Constant* CV = dyn_cast<Constant>(V)) { // symbolic or known
483     if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV))
484       S += std::string(CB == ConstantBool::True ? "1" : "0");
485     else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
486       S += itostr(CI->getValue());
487     else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
488       S += utostr(CI->getValue());
489     else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
490       S += ftostr(CFP->getValue());
491     else if (isa<ConstantPointerNull>(CV) || isa<UndefValue>(CV))
492       S += "0";
493     else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV))
494       S += ConstantExprToString(CE, target);
495     else
496       failed = true;
497   } else
498     failed = true;
499
500   if (failed) {
501     assert(0 && "Cannot convert value to string");
502     S += "<illegal-value>";
503   }
504   return S;
505 }
506
507 namespace {
508
509   struct SparcV9AsmPrinter : public FunctionPass, public AsmPrinter {
510     inline SparcV9AsmPrinter(std::ostream &os, const TargetMachine &t)
511       : AsmPrinter(os, t) {}
512
513     const Function *currFunction;
514
515     const char *getPassName() const {
516       return "Output SparcV9 Assembly for Functions";
517     }
518
519     virtual bool doInitialization(Module &M) {
520       startModule(M);
521       return false;
522     }
523
524     virtual bool runOnFunction(Function &F) {
525       currFunction = &F;
526       emitFunction(F);
527       return false;
528     }
529
530     virtual bool doFinalization(Module &M) {
531       emitGlobals(M);
532       return false;
533     }
534
535     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
536       AU.setPreservesAll();
537     }
538
539     void emitFunction(const Function &F);
540   private :
541     void emitBasicBlock(const MachineBasicBlock &MBB);
542     void emitMachineInst(const MachineInstr *MI);
543
544     unsigned int printOperands(const MachineInstr *MI, unsigned int opNum);
545     void printOneOperand(const MachineOperand &Op, MachineOpCode opCode);
546
547     bool OpIsBranchTargetLabel(const MachineInstr *MI, unsigned int opNum);
548     bool OpIsMemoryAddressBase(const MachineInstr *MI, unsigned int opNum);
549
550     unsigned getOperandMask(unsigned Opcode) {
551       switch (Opcode) {
552       case V9::SUBccr:
553       case V9::SUBcci:   return 1 << 3;  // Remove CC argument
554       default:      return 0;       // By default, don't hack operands...
555       }
556     }
557
558     void emitGlobals(const Module &M);
559     void printGlobalVariable(const GlobalVariable *GV);
560   };
561
562 } // End anonymous namespace
563
564 inline bool
565 SparcV9AsmPrinter::OpIsBranchTargetLabel(const MachineInstr *MI,
566                                        unsigned int opNum) {
567   switch (MI->getOpcode()) {
568   case V9::JMPLCALLr:
569   case V9::JMPLCALLi:
570   case V9::JMPLRETr:
571   case V9::JMPLRETi:
572     return (opNum == 0);
573   default:
574     return false;
575   }
576 }
577
578 inline bool
579 SparcV9AsmPrinter::OpIsMemoryAddressBase(const MachineInstr *MI,
580                                        unsigned int opNum) {
581   if (TM.getInstrInfo()->isLoad(MI->getOpcode()))
582     return (opNum == 0);
583   else if (TM.getInstrInfo()->isStore(MI->getOpcode()))
584     return (opNum == 1);
585   else
586     return false;
587 }
588
589 unsigned int
590 SparcV9AsmPrinter::printOperands(const MachineInstr *MI, unsigned opNum) {
591   const MachineOperand& mop = MI->getOperand(opNum);
592   if (OpIsBranchTargetLabel(MI, opNum)) {
593     printOneOperand(mop, MI->getOpcode());
594     O << "+";
595     printOneOperand(MI->getOperand(opNum+1), MI->getOpcode());
596     return 2;
597   } else if (OpIsMemoryAddressBase(MI, opNum)) {
598     O << "[";
599     printOneOperand(mop, MI->getOpcode());
600     O << "+";
601     printOneOperand(MI->getOperand(opNum+1), MI->getOpcode());
602     O << "]";
603     return 2;
604   } else {
605     printOneOperand(mop, MI->getOpcode());
606     return 1;
607   }
608 }
609
610 void
611 SparcV9AsmPrinter::printOneOperand(const MachineOperand &mop,
612                                    MachineOpCode opCode)
613 {
614   bool needBitsFlag = true;
615
616   if (mop.isHiBits32())
617     O << "%lm(";
618   else if (mop.isLoBits32())
619     O << "%lo(";
620   else if (mop.isHiBits64())
621     O << "%hh(";
622   else if (mop.isLoBits64())
623     O << "%hm(";
624   else
625     needBitsFlag = false;
626
627   switch (mop.getType())
628     {
629     case MachineOperand::MO_VirtualRegister:
630     case MachineOperand::MO_CCRegister:
631     case MachineOperand::MO_MachineRegister:
632       {
633         int regNum = (int)mop.getReg();
634
635         if (regNum == TM.getRegInfo()->getInvalidRegNum()) {
636           // better to print code with NULL registers than to die
637           O << "<NULL VALUE>";
638         } else {
639           O << "%" << TM.getRegInfo()->getUnifiedRegName(regNum);
640         }
641         break;
642       }
643
644     case MachineOperand::MO_ConstantPoolIndex:
645       {
646         O << ".CPI_" << getID(currFunction)
647               << "_" << mop.getConstantPoolIndex();
648         break;
649       }
650
651     case MachineOperand::MO_PCRelativeDisp:
652       {
653         const Value *Val = mop.getVRegValue();
654         assert(Val && "\tNULL Value in SparcV9AsmPrinter");
655
656         if (const BasicBlock *BB = dyn_cast<BasicBlock>(Val))
657           O << getID(BB);
658         else if (const Function *F = dyn_cast<Function>(Val))
659           O << getID(F);
660         else if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Val))
661           O << getID(GV);
662         else if (const Constant *CV = dyn_cast<Constant>(Val))
663           O << getID(CV);
664         else
665           assert(0 && "Unrecognized value in SparcV9AsmPrinter");
666         break;
667       }
668
669     case MachineOperand::MO_SignExtendedImmed:
670       O << mop.getImmedValue();
671       break;
672
673     case MachineOperand::MO_UnextendedImmed:
674       O << (uint64_t) mop.getImmedValue();
675       break;
676
677     default:
678       O << mop;      // use dump field
679       break;
680     }
681
682   if (needBitsFlag)
683     O << ")";
684 }
685
686 void SparcV9AsmPrinter::emitMachineInst(const MachineInstr *MI) {
687   unsigned Opcode = MI->getOpcode();
688
689   if (Opcode == V9::PHI)
690     return;  // Ignore Machine-PHI nodes.
691
692   O << "\t" << TM.getInstrInfo()->getName(Opcode) << "\t";
693
694   unsigned Mask = getOperandMask(Opcode);
695
696   bool NeedComma = false;
697   unsigned N = 1;
698   for (unsigned OpNum = 0; OpNum < MI->getNumOperands(); OpNum += N)
699     if (! ((1 << OpNum) & Mask)) {        // Ignore this operand?
700       if (NeedComma) O << ", ";         // Handle comma outputting
701       NeedComma = true;
702       N = printOperands(MI, OpNum);
703     } else
704       N = 1;
705
706   O << "\n";
707   ++EmittedInsts;
708 }
709
710 void SparcV9AsmPrinter::emitBasicBlock(const MachineBasicBlock &MBB) {
711   // Emit a label for the basic block
712   O << getID(MBB.getBasicBlock()) << ":\n";
713
714   // Loop over all of the instructions in the basic block...
715   for (MachineBasicBlock::const_iterator MII = MBB.begin(), MIE = MBB.end();
716        MII != MIE; ++MII)
717     emitMachineInst(MII);
718   O << "\n";  // Separate BB's with newlines
719 }
720
721 void SparcV9AsmPrinter::emitFunction(const Function &F) {
722   std::string CurrentFnName = getID(&F);
723   MachineFunction &MF = MachineFunction::get(&F);
724   O << "!****** Outputing Function: " << CurrentFnName << " ******\n";
725
726   // Emit constant pool for this function
727   const MachineConstantPool *MCP = MF.getConstantPool();
728   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
729
730   enterSection(ReadOnlyData);
731   O << "\t.align\t" << (1 << MCP->getConstantPoolAlignment()) << "\n";
732   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
733     std::string cpiName = ".CPI_" + CurrentFnName + "_" + utostr(i);
734     printConstant(CP[i].Val, 1, cpiName);
735     
736     if (i != e-1) {
737       unsigned EntSize = TM.getTargetData().getTypeSize(CP[i].Val->getType());
738       unsigned ValEnd = CP[i].Offset + EntSize;
739       // Emit inter-object padding for alignment.
740       for (unsigned NumZeros = CP[i+1].Offset-ValEnd; NumZeros; --NumZeros)
741         O << "\t.byte 0\n";
742     }
743   }
744
745   enterSection(Text);
746   O << "\t.align\t4\n\t.global\t" << CurrentFnName << "\n";
747   //O << "\t.type\t" << CurrentFnName << ",#function\n";
748   O << "\t.type\t" << CurrentFnName << ", 2\n";
749   O << CurrentFnName << ":\n";
750
751   // Output code for all of the basic blocks in the function...
752   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end(); I != E;++I)
753     emitBasicBlock(*I);
754
755   // Output a .size directive so the debugger knows the extents of the function
756   O << ".EndOf_" << CurrentFnName << ":\n\t.size "
757            << CurrentFnName << ", .EndOf_"
758            << CurrentFnName << "-" << CurrentFnName << "\n";
759
760   // Put some spaces between the functions
761   O << "\n\n";
762 }
763
764 void SparcV9AsmPrinter::printGlobalVariable(const GlobalVariable* GV) {
765   if (GV->hasExternalLinkage())
766     O << "\t.global\t" << getID(GV) << "\n";
767
768   if (GV->hasInitializer() &&
769       !(GV->getInitializer()->isNullValue() ||
770         isa<UndefValue>(GV->getInitializer()))) {
771     printConstant(GV->getInitializer(), 0, getID(GV));
772   } else {
773     O << "\t.align\t" << TypeToAlignment(GV->getType()->getElementType(),
774                                                 TM) << "\n";
775     O << "\t.type\t" << getID(GV) << ",#object\n";
776     O << "\t.reserve\t" << getID(GV) << ","
777       << findOptimalStorageSize(TM, GV->getType()->getElementType())
778       << "\n";
779   }
780 }
781
782 void SparcV9AsmPrinter::emitGlobals(const Module &M) {
783   // Output global variables...
784   for (Module::const_global_iterator GI = M.global_begin(), GE = M.global_end(); GI != GE; ++GI)
785     if (! GI->isExternal()) {
786       assert(GI->hasInitializer());
787       if (GI->isConstant())
788         enterSection(ReadOnlyData);   // read-only, initialized data
789       else if (GI->getInitializer()->isNullValue() ||
790                isa<UndefValue>(GI->getInitializer()))
791         enterSection(ZeroInitRWData); // read-write zero data
792       else
793         enterSection(InitRWData);     // read-write non-zero data
794
795       printGlobalVariable(GI);
796     }
797
798   O << "\n";
799 }
800
801 FunctionPass *llvm::createAsmPrinterPass(std::ostream &Out, TargetMachine &TM) {
802   return new SparcV9AsmPrinter(Out, TM);
803 }