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