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