Asm printer support, based on x86 - only prints mnemonics for now
[oota-llvm.git] / lib / Target / Sparc / SparcAsmPrinter.cpp
1 //===-- SparcV8AsmPrinter.cpp - SparcV8 LLVM assembly writer --------------===//
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 contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format Sparc V8 assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SparcV8.h"
16 #include "SparcV8InstrInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Module.h"
20 #include "llvm/Assembly/Writer.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineInstr.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/Mangler.h"
26 #include "Support/Statistic.h"
27 #include "Support/StringExtras.h"
28 #include "Support/CommandLine.h"
29 using namespace llvm;
30
31 namespace {
32   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
33
34   struct V8Printer : public MachineFunctionPass {
35     /// Output stream on which we're printing assembly code.
36     ///
37     std::ostream &O;
38
39     /// Target machine description which we query for reg. names, data
40     /// layout, etc.
41     ///
42     TargetMachine &TM;
43
44     /// Name-mangler for global names.
45     ///
46     Mangler *Mang;
47
48     V8Printer(std::ostream &o, TargetMachine &tm) : O(o), TM(tm) { }
49
50     /// We name each basic block in a Function with a unique number, so
51     /// that we can consistently refer to them later. This is cleared
52     /// at the beginning of each call to runOnMachineFunction().
53     ///
54     typedef std::map<const Value *, unsigned> ValueMapTy;
55     ValueMapTy NumberForBB;
56
57     /// Cache of mangled name for current function. This is
58     /// recalculated at the beginning of each call to
59     /// runOnMachineFunction().
60     ///
61     std::string CurrentFnName;
62
63     virtual const char *getPassName() const {
64       return "SparcV8 Assembly Printer";
65     }
66
67     void emitConstantValueOnly(const Constant *CV);
68     void emitGlobalConstant(const Constant *CV);
69     void printConstantPool(MachineConstantPool *MCP);
70     void printMachineInstruction(const MachineInstr *MI);
71     bool runOnMachineFunction(MachineFunction &F);    
72     bool doInitialization(Module &M);
73     bool doFinalization(Module &M);
74   };
75 } // end of anonymous namespace
76
77 /// createSparcV8CodePrinterPass - Returns a pass that prints the SparcV8
78 /// assembly code for a MachineFunction to the given output stream,
79 /// using the given target machine description.  This should work
80 /// regardless of whether the function is in SSA form.
81 ///
82 FunctionPass *llvm::createSparcV8CodePrinterPass (std::ostream &o,
83                                                   TargetMachine &tm) {
84   return new V8Printer(o, tm);
85 }
86
87 /// toOctal - Convert the low order bits of X into an octal digit.
88 ///
89 static inline char toOctal(int X) {
90   return (X&7)+'0';
91 }
92
93 /// getAsCString - Return the specified array as a C compatible
94 /// string, only if the predicate isStringCompatible is true.
95 ///
96 static void printAsCString(std::ostream &O, const ConstantArray *CVA) {
97   assert(CVA->isString() && "Array is not string compatible!");
98
99   O << "\"";
100   for (unsigned i = 0; i != CVA->getNumOperands(); ++i) {
101     unsigned char C = cast<ConstantInt>(CVA->getOperand(i))->getRawValue();
102
103     if (C == '"') {
104       O << "\\\"";
105     } else if (C == '\\') {
106       O << "\\\\";
107     } else if (isprint(C)) {
108       O << C;
109     } else {
110       switch(C) {
111       case '\b': O << "\\b"; break;
112       case '\f': O << "\\f"; break;
113       case '\n': O << "\\n"; break;
114       case '\r': O << "\\r"; break;
115       case '\t': O << "\\t"; break;
116       default:
117         O << '\\';
118         O << toOctal(C >> 6);
119         O << toOctal(C >> 3);
120         O << toOctal(C >> 0);
121         break;
122       }
123     }
124   }
125   O << "\"";
126 }
127
128 // Print out the specified constant, without a storage class.  Only the
129 // constants valid in constant expressions can occur here.
130 void V8Printer::emitConstantValueOnly(const Constant *CV) {
131   if (CV->isNullValue())
132     O << "0";
133   else if (const ConstantBool *CB = dyn_cast<ConstantBool>(CV)) {
134     assert(CB == ConstantBool::True);
135     O << "1";
136   } else if (const ConstantSInt *CI = dyn_cast<ConstantSInt>(CV))
137     if (((CI->getValue() << 32) >> 32) == CI->getValue())
138       O << CI->getValue();
139     else
140       O << (unsigned long long)CI->getValue();
141   else if (const ConstantUInt *CI = dyn_cast<ConstantUInt>(CV))
142     O << CI->getValue();
143   else if (const ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(CV))
144     // This is a constant address for a global variable or function.  Use the
145     // name of the variable or function as the address value.
146     O << Mang->getValueName(CPR->getValue());
147   else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
148     const TargetData &TD = TM.getTargetData();
149     switch(CE->getOpcode()) {
150     case Instruction::GetElementPtr: {
151       // generate a symbolic expression for the byte address
152       const Constant *ptrVal = CE->getOperand(0);
153       std::vector<Value*> idxVec(CE->op_begin()+1, CE->op_end());
154       if (unsigned Offset = TD.getIndexedOffset(ptrVal->getType(), idxVec)) {
155         O << "(";
156         emitConstantValueOnly(ptrVal);
157         O << ") + " << Offset;
158       } else {
159         emitConstantValueOnly(ptrVal);
160       }
161       break;
162     }
163     case Instruction::Cast: {
164       // Support only non-converting or widening casts for now, that is, ones
165       // that do not involve a change in value.  This assertion is really gross,
166       // and may not even be a complete check.
167       Constant *Op = CE->getOperand(0);
168       const Type *OpTy = Op->getType(), *Ty = CE->getType();
169
170       // Pointers on ILP32 machines can be losslessly converted back and
171       // forth into 32-bit or wider integers, regardless of signedness.
172       assert(((isa<PointerType>(OpTy)
173                && (Ty == Type::LongTy || Ty == Type::ULongTy
174                    || Ty == Type::IntTy || Ty == Type::UIntTy))
175               || (isa<PointerType>(Ty)
176                   && (OpTy == Type::LongTy || OpTy == Type::ULongTy
177                       || OpTy == Type::IntTy || OpTy == Type::UIntTy))
178               || (((TD.getTypeSize(Ty) >= TD.getTypeSize(OpTy))
179                    && OpTy->isLosslesslyConvertibleTo(Ty))))
180              && "FIXME: Don't yet support this kind of constant cast expr");
181       O << "(";
182       emitConstantValueOnly(Op);
183       O << ")";
184       break;
185     }
186     case Instruction::Add:
187       O << "(";
188       emitConstantValueOnly(CE->getOperand(0));
189       O << ") + (";
190       emitConstantValueOnly(CE->getOperand(1));
191       O << ")";
192       break;
193     default:
194       assert(0 && "Unsupported operator!");
195     }
196   } else {
197     assert(0 && "Unknown constant value!");
198   }
199 }
200
201 // Print a constant value or values, with the appropriate storage class as a
202 // prefix.
203 void V8Printer::emitGlobalConstant(const Constant *CV) {  
204   const TargetData &TD = TM.getTargetData();
205
206   if (CV->isNullValue()) {
207     O << "\t.zero\t " << TD.getTypeSize(CV->getType()) << "\n";      
208     return;
209   } else if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
210     if (CVA->isString()) {
211       O << "\t.ascii\t";
212       printAsCString(O, CVA);
213       O << "\n";
214     } else { // Not a string.  Print the values in successive locations
215       const std::vector<Use> &constValues = CVA->getValues();
216       for (unsigned i=0; i < constValues.size(); i++)
217         emitGlobalConstant(cast<Constant>(constValues[i].get()));
218     }
219     return;
220   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
221     // Print the fields in successive locations. Pad to align if needed!
222     const StructLayout *cvsLayout = TD.getStructLayout(CVS->getType());
223     const std::vector<Use>& constValues = CVS->getValues();
224     unsigned sizeSoFar = 0;
225     for (unsigned i=0, N = constValues.size(); i < N; i++) {
226       const Constant* field = cast<Constant>(constValues[i].get());
227
228       // Check if padding is needed and insert one or more 0s.
229       unsigned fieldSize = TD.getTypeSize(field->getType());
230       unsigned padSize = ((i == N-1? cvsLayout->StructSize
231                            : cvsLayout->MemberOffsets[i+1])
232                           - cvsLayout->MemberOffsets[i]) - fieldSize;
233       sizeSoFar += fieldSize + padSize;
234
235       // Now print the actual field value
236       emitGlobalConstant(field);
237
238       // Insert the field padding unless it's zero bytes...
239       if (padSize)
240         O << "\t.zero\t " << padSize << "\n";      
241     }
242     assert(sizeSoFar == cvsLayout->StructSize &&
243            "Layout of constant struct may be incorrect!");
244     return;
245   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
246     // FP Constants are printed as integer constants to avoid losing
247     // precision...
248     double Val = CFP->getValue();
249     switch (CFP->getType()->getPrimitiveID()) {
250     default: assert(0 && "Unknown floating point type!");
251     case Type::FloatTyID: {
252       union FU {                            // Abide by C TBAA rules
253         float FVal;
254         unsigned UVal;
255       } U;
256       U.FVal = Val;
257       O << ".long\t" << U.UVal << "\t# float " << Val << "\n";
258       return;
259     }
260     case Type::DoubleTyID: {
261       union DU {                            // Abide by C TBAA rules
262         double FVal;
263         uint64_t UVal;
264       } U;
265       U.FVal = Val;
266       O << ".quad\t" << U.UVal << "\t# double " << Val << "\n";
267       return;
268     }
269     }
270   }
271
272   const Type *type = CV->getType();
273   O << "\t";
274   switch (type->getPrimitiveID()) {
275   case Type::BoolTyID: case Type::UByteTyID: case Type::SByteTyID:
276     O << ".byte";
277     break;
278   case Type::UShortTyID: case Type::ShortTyID:
279     O << ".word";
280     break;
281   case Type::FloatTyID: case Type::PointerTyID:
282   case Type::UIntTyID: case Type::IntTyID:
283     O << ".long";
284     break;
285   case Type::DoubleTyID:
286   case Type::ULongTyID: case Type::LongTyID:
287     O << ".quad";
288     break;
289   default:
290     assert (0 && "Can't handle printing this type of thing");
291     break;
292   }
293   O << "\t";
294   emitConstantValueOnly(CV);
295   O << "\n";
296 }
297
298 /// printConstantPool - Print to the current output stream assembly
299 /// representations of the constants in the constant pool MCP. This is
300 /// used to print out constants which have been "spilled to memory" by
301 /// the code generator.
302 ///
303 void V8Printer::printConstantPool(MachineConstantPool *MCP) {
304   const std::vector<Constant*> &CP = MCP->getConstants();
305   const TargetData &TD = TM.getTargetData();
306  
307   if (CP.empty()) return;
308
309   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
310     O << "\t.section .rodata\n";
311     O << "\t.align " << (unsigned)TD.getTypeAlignment(CP[i]->getType())
312       << "\n";
313     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t#"
314       << *CP[i] << "\n";
315     emitGlobalConstant(CP[i]);
316   }
317 }
318
319 /// runOnMachineFunction - This uses the printMachineInstruction()
320 /// method to print assembly for each instruction.
321 ///
322 bool V8Printer::runOnMachineFunction(MachineFunction &MF) {
323   // BBNumber is used here so that a given Printer will never give two
324   // BBs the same name. (If you have a better way, please let me know!)
325   static unsigned BBNumber = 0;
326
327   O << "\n\n";
328   // What's my mangled name?
329   CurrentFnName = Mang->getValueName(MF.getFunction());
330
331   // Print out constants referenced by the function
332   printConstantPool(MF.getConstantPool());
333
334   // Print out labels for the function.
335   O << "\t.text\n";
336   O << "\t.align 16\n";
337   O << "\t.globl\t" << CurrentFnName << "\n";
338   O << "\t.type\t" << CurrentFnName << ", @function\n";
339   O << CurrentFnName << ":\n";
340
341   // Number each basic block so that we can consistently refer to them
342   // in PC-relative references.
343   NumberForBB.clear();
344   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
345        I != E; ++I) {
346     NumberForBB[I->getBasicBlock()] = BBNumber++;
347   }
348
349   // Print out code for the function.
350   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
351        I != E; ++I) {
352     // Print a label for the basic block.
353     O << ".LBB" << NumberForBB[I->getBasicBlock()] << ":\t# "
354       << I->getBasicBlock()->getName() << "\n";
355     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
356          II != E; ++II) {
357       // Print the assembly for the instruction.
358       O << "\t";
359       printMachineInstruction(II);
360     }
361   }
362
363   // We didn't modify anything.
364   return false;
365 }
366
367 /// printMachineInstruction -- Print out a single SparcV8 LLVM instruction
368 /// MI in GAS syntax to the current output stream.
369 ///
370 void V8Printer::printMachineInstruction(const MachineInstr *MI) {
371   unsigned Opcode = MI->getOpcode();
372   const TargetInstrInfo &TII = TM.getInstrInfo();
373   const TargetInstrDescriptor &Desc = TII.get(Opcode);
374   O << Desc.Name << "\n";  // not yet done
375 }
376
377 bool V8Printer::doInitialization(Module &M) {
378   Mang = new Mangler(M);
379   return false; // success
380 }
381
382 // SwitchSection - Switch to the specified section of the executable if we are
383 // not already in it!
384 //
385 static void SwitchSection(std::ostream &OS, std::string &CurSection,
386                           const char *NewSection) {
387   if (CurSection != NewSection) {
388     CurSection = NewSection;
389     if (!CurSection.empty())
390       OS << "\t" << NewSection << "\n";
391   }
392 }
393
394 bool V8Printer::doFinalization(Module &M) {
395   const TargetData &TD = TM.getTargetData();
396   std::string CurSection;
397
398   // Print out module-level global variables here.
399   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
400     if (I->hasInitializer()) {   // External global require no code
401       O << "\n\n";
402       std::string name = Mang->getValueName(I);
403       Constant *C = I->getInitializer();
404       unsigned Size = TD.getTypeSize(C->getType());
405       unsigned Align = TD.getTypeAlignment(C->getType());
406
407       if (C->isNullValue() && 
408           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
409            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
410         SwitchSection(O, CurSection, ".data");
411         if (I->hasInternalLinkage())
412           O << "\t.local " << name << "\n";
413         
414         O << "\t.comm " << name << "," << TD.getTypeSize(C->getType())
415           << "," << (unsigned)TD.getTypeAlignment(C->getType());
416         O << "\t\t# ";
417         WriteAsOperand(O, I, true, true, &M);
418         O << "\n";
419       } else {
420         switch (I->getLinkage()) {
421         case GlobalValue::LinkOnceLinkage:
422         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
423           // Nonnull linkonce -> weak
424           O << "\t.weak " << name << "\n";
425           SwitchSection(O, CurSection, "");
426           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
427           break;
428         
429         case GlobalValue::AppendingLinkage:
430           // FIXME: appending linkage variables should go into a section of
431           // their name or something.  For now, just emit them as external.
432         case GlobalValue::ExternalLinkage:
433           // If external or appending, declare as a global symbol
434           O << "\t.globl " << name << "\n";
435           // FALL THROUGH
436         case GlobalValue::InternalLinkage:
437           if (C->isNullValue())
438             SwitchSection(O, CurSection, ".bss");
439           else
440             SwitchSection(O, CurSection, ".data");
441           break;
442         }
443
444         O << "\t.align " << Align << "\n";
445         O << "\t.type " << name << ",@object\n";
446         O << "\t.size " << name << "," << Size << "\n";
447         O << name << ":\t\t\t\t# ";
448         WriteAsOperand(O, I, true, true, &M);
449         O << " = ";
450         WriteAsOperand(O, C, false, false, &M);
451         O << "\n";
452         emitGlobalConstant(C);
453       }
454     }
455
456   delete Mang;
457   return false; // success
458 }