Committing X86-64 support.
[oota-llvm.git] / lib / Target / X86 / X86IntelAsmPrinter.cpp
1 //===-- X86IntelAsmPrinter.cpp - Convert X86 LLVM code to Intel assembly --===//
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 Intel format assembly language.
12 // This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86IntelAsmPrinter.h"
17 #include "X86TargetAsmInfo.h"
18 #include "X86.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Module.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/Mangler.h"
23 #include "llvm/Target/TargetAsmInfo.h"
24 #include "llvm/Target/TargetOptions.h"
25 using namespace llvm;
26
27 /// runOnMachineFunction - This uses the printMachineInstruction()
28 /// method to print assembly for each instruction.
29 ///
30 bool X86IntelAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
31   SetupMachineFunction(MF);
32   O << "\n\n";
33
34   // Print out constants referenced by the function
35   EmitConstantPool(MF.getConstantPool());
36
37   // Print out labels for the function.
38   SwitchToTextSection("_text", MF.getFunction());
39   EmitAlignment(4);
40   if (MF.getFunction()->getLinkage() == GlobalValue::ExternalLinkage)
41     O << "\tpublic " << CurrentFnName << "\n";
42   O << CurrentFnName << "\tproc near\n";
43   
44   // Print out code for the function.
45   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
46        I != E; ++I) {
47     // Print a label for the basic block if there are any predecessors.
48     if (I->pred_begin() != I->pred_end()) {
49       printBasicBlockLabel(I, true);
50       O << '\n';
51     }
52     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
53          II != E; ++II) {
54       // Print the assembly for the instruction.
55       O << "\t";
56       printMachineInstruction(II);
57     }
58   }
59
60   O << CurrentFnName << "\tendp\n";
61
62   // We didn't modify anything.
63   return false;
64 }
65
66 void X86IntelAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
67   unsigned char value = MI->getOperand(Op).getImmedValue();
68   assert(value <= 7 && "Invalid ssecc argument!");
69   switch (value) {
70   case 0: O << "eq"; break;
71   case 1: O << "lt"; break;
72   case 2: O << "le"; break;
73   case 3: O << "unord"; break;
74   case 4: O << "neq"; break;
75   case 5: O << "nlt"; break;
76   case 6: O << "nle"; break;
77   case 7: O << "ord"; break;
78   }
79 }
80
81 void X86IntelAsmPrinter::printOp(const MachineOperand &MO, 
82                                  const char *Modifier) {
83   const MRegisterInfo &RI = *TM.getRegisterInfo();
84   switch (MO.getType()) {
85   case MachineOperand::MO_Register:
86     if (MRegisterInfo::isPhysicalRegister(MO.getReg())) {
87       unsigned Reg = MO.getReg();
88       if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
89         MVT::ValueType VT = (strcmp(Modifier,"subreg64") == 0) ?
90           MVT::i64 : ((strcmp(Modifier, "subreg32") == 0) ? MVT::i32 :
91                       ((strcmp(Modifier,"subreg16") == 0) ? MVT::i16 :MVT::i8));
92         Reg = getX86SubSuperRegister(Reg, VT);
93       }
94       O << RI.get(Reg).Name;
95     } else
96       O << "reg" << MO.getReg();
97     return;
98
99   case MachineOperand::MO_Immediate:
100     O << MO.getImmedValue();
101     return;
102   case MachineOperand::MO_MachineBasicBlock:
103     printBasicBlockLabel(MO.getMachineBasicBlock());
104     return;
105   case MachineOperand::MO_ConstantPoolIndex: {
106     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
107     if (!isMemOp) O << "OFFSET ";
108     O << "[" << TAI->getPrivateGlobalPrefix() << "CPI"
109       << getFunctionNumber() << "_" << MO.getConstantPoolIndex();
110     int Offset = MO.getOffset();
111     if (Offset > 0)
112       O << " + " << Offset;
113     else if (Offset < 0)
114       O << Offset;
115     O << "]";
116     return;
117   }
118   case MachineOperand::MO_GlobalAddress: {
119     bool isCallOp = Modifier && !strcmp(Modifier, "call");
120     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
121     if (!isMemOp && !isCallOp) O << "OFFSET ";
122     O << Mang->getValueName(MO.getGlobal());
123     int Offset = MO.getOffset();
124     if (Offset > 0)
125       O << " + " << Offset;
126     else if (Offset < 0)
127       O << Offset;
128     return;
129   }
130   case MachineOperand::MO_ExternalSymbol: {
131     bool isCallOp = Modifier && !strcmp(Modifier, "call");
132     if (!isCallOp) O << "OFFSET ";
133     O << TAI->getGlobalPrefix() << MO.getSymbolName();
134     return;
135   }
136   default:
137     O << "<unknown operand type>"; return;
138   }
139 }
140
141 void X86IntelAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
142                                            const char *Modifier) {
143   assert(isMem(MI, Op) && "Invalid memory reference!");
144
145   const MachineOperand &BaseReg  = MI->getOperand(Op);
146   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
147   const MachineOperand &IndexReg = MI->getOperand(Op+2);
148   const MachineOperand &DispSpec = MI->getOperand(Op+3);
149
150   if (BaseReg.isFrameIndex()) {
151     O << "[frame slot #" << BaseReg.getFrameIndex();
152     if (DispSpec.getImmedValue())
153       O << " + " << DispSpec.getImmedValue();
154     O << "]";
155     return;
156   }
157
158   O << "[";
159   bool NeedPlus = false;
160   if (BaseReg.getReg()) {
161     printOp(BaseReg, Modifier);
162     NeedPlus = true;
163   }
164
165   if (IndexReg.getReg()) {
166     if (NeedPlus) O << " + ";
167     if (ScaleVal != 1)
168       O << ScaleVal << "*";
169     printOp(IndexReg, Modifier);
170     NeedPlus = true;
171   }
172
173   if (DispSpec.isGlobalAddress() || DispSpec.isConstantPoolIndex()) {
174     if (NeedPlus)
175       O << " + ";
176     printOp(DispSpec, "mem");
177   } else {
178     int DispVal = DispSpec.getImmedValue();
179     if (DispVal || (!BaseReg.getReg() && !IndexReg.getReg())) {
180       if (NeedPlus)
181         if (DispVal > 0)
182           O << " + ";
183         else {
184           O << " - ";
185           DispVal = -DispVal;
186         }
187       O << DispVal;
188     }
189   }
190   O << "]";
191 }
192
193 void X86IntelAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
194   O << "\"L" << getFunctionNumber() << "$pb\"\n";
195   O << "\"L" << getFunctionNumber() << "$pb\":";
196 }
197
198 bool X86IntelAsmPrinter::printAsmMRegister(const MachineOperand &MO,
199                                            const char Mode) {
200   const MRegisterInfo &RI = *TM.getRegisterInfo();
201   unsigned Reg = MO.getReg();
202   switch (Mode) {
203   default: return true;  // Unknown mode.
204   case 'b': // Print QImode register
205     Reg = getX86SubSuperRegister(Reg, MVT::i8);
206     break;
207   case 'h': // Print QImode high register
208     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
209     break;
210   case 'w': // Print HImode register
211     Reg = getX86SubSuperRegister(Reg, MVT::i16);
212     break;
213   case 'k': // Print SImode register
214     Reg = getX86SubSuperRegister(Reg, MVT::i32);
215     break;
216   }
217
218   O << '%' << RI.get(Reg).Name;
219   return false;
220 }
221
222 /// PrintAsmOperand - Print out an operand for an inline asm expression.
223 ///
224 bool X86IntelAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
225                                          unsigned AsmVariant, 
226                                          const char *ExtraCode) {
227   // Does this asm operand have a single letter operand modifier?
228   if (ExtraCode && ExtraCode[0]) {
229     if (ExtraCode[1] != 0) return true; // Unknown modifier.
230     
231     switch (ExtraCode[0]) {
232     default: return true;  // Unknown modifier.
233     case 'b': // Print QImode register
234     case 'h': // Print QImode high register
235     case 'w': // Print HImode register
236     case 'k': // Print SImode register
237       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
238     }
239   }
240   
241   printOperand(MI, OpNo);
242   return false;
243 }
244
245 bool X86IntelAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
246                                                unsigned OpNo,
247                                                unsigned AsmVariant, 
248                                                const char *ExtraCode) {
249   if (ExtraCode && ExtraCode[0])
250     return true; // Unknown modifier.
251   printMemReference(MI, OpNo);
252   return false;
253 }
254
255 /// printMachineInstruction -- Print out a single X86 LLVM instruction
256 /// MI in Intel syntax to the current output stream.
257 ///
258 void X86IntelAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
259   ++EmittedInsts;
260
261   // See if a truncate instruction can be turned into a nop.
262   switch (MI->getOpcode()) {
263   default: break;
264   case X86::TRUNC_64to32:
265   case X86::TRUNC_64to16:
266   case X86::TRUNC_32to16:
267   case X86::TRUNC_32to8:
268   case X86::TRUNC_16to8:
269   case X86::TRUNC_32_to8:
270   case X86::TRUNC_16_to8: {
271     const MachineOperand &MO0 = MI->getOperand(0);
272     const MachineOperand &MO1 = MI->getOperand(1);
273     unsigned Reg0 = MO0.getReg();
274     unsigned Reg1 = MO1.getReg();
275     unsigned Opc = MI->getOpcode();
276     if (Opc == X86::TRUNC_64to32)
277       Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
278     else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
279       Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
280     else
281       Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
282     O << TAI->getCommentString() << " TRUNCATE ";
283     if (Reg0 != Reg1)
284       O << "\n\t";
285     break;
286   }
287   case X86::PsMOVZX64rr32:
288     O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
289     break;
290   }
291
292   // Call the autogenerated instruction printer routines.
293   printInstruction(MI);
294 }
295
296 bool X86IntelAsmPrinter::doInitialization(Module &M) {
297   X86SharedAsmPrinter::doInitialization(M);
298   
299   Mang->markCharUnacceptable('.');
300
301   O << "\t.686\n\t.model flat\n\n";
302
303   // Emit declarations for external functions.
304   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
305     if (I->isExternal())
306       O << "\textern " << Mang->getValueName(I) << ":near\n";
307
308   // Emit declarations for external globals.  Note that VC++ always declares
309   // external globals to have type byte, and if that's good enough for VC++...
310   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
311        I != E; ++I) {
312     if (I->isExternal())
313       O << "\textern " << Mang->getValueName(I) << ":byte\n";
314   }
315
316   return false;
317 }
318
319 bool X86IntelAsmPrinter::doFinalization(Module &M) {
320   const TargetData *TD = TM.getTargetData();
321
322   // Print out module-level global variables here.
323   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
324        I != E; ++I) {
325     if (I->isExternal()) continue;   // External global require no code
326     
327     // Check to see if this is a special global used by LLVM, if so, emit it.
328     if (EmitSpecialLLVMGlobal(I))
329       continue;
330     
331     std::string name = Mang->getValueName(I);
332     Constant *C = I->getInitializer();
333     unsigned Size = TD->getTypeSize(C->getType());
334     unsigned Align = getPreferredAlignmentLog(I);
335     bool bCustomSegment = false;
336
337     switch (I->getLinkage()) {
338     case GlobalValue::LinkOnceLinkage:
339     case GlobalValue::WeakLinkage:
340       SwitchToDataSection("", 0);
341       O << name << "?\tsegment common 'COMMON'\n";
342       bCustomSegment = true;
343       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
344       // are also available.
345       break;
346     case GlobalValue::AppendingLinkage:
347       SwitchToDataSection("", 0);
348       O << name << "?\tsegment public 'DATA'\n";
349       bCustomSegment = true;
350       // FIXME: the default alignment is 16 bytes, but 1, 2, 4, and 256
351       // are also available.
352       break;
353     case GlobalValue::ExternalLinkage:
354       O << "\tpublic " << name << "\n";
355       // FALL THROUGH
356     case GlobalValue::InternalLinkage:
357       SwitchToDataSection(TAI->getDataSection(), I);
358       break;
359     default:
360       assert(0 && "Unknown linkage type!");
361     }
362
363     if (!bCustomSegment)
364       EmitAlignment(Align, I);
365
366     O << name << ":\t\t\t\t" << TAI->getCommentString()
367       << " " << I->getName() << '\n';
368
369     EmitGlobalConstant(C);
370
371     if (bCustomSegment)
372       O << name << "?\tends\n";
373   }
374   
375   // Bypass X86SharedAsmPrinter::doFinalization().
376   AsmPrinter::doFinalization(M);
377   SwitchToDataSection("", 0);
378   O << "\tend\n";
379   return false; // success
380 }
381
382 void X86IntelAsmPrinter::EmitString(const ConstantArray *CVA) const {
383   unsigned NumElts = CVA->getNumOperands();
384   if (NumElts) {
385     // ML does not have escape sequences except '' for '.  It also has a maximum
386     // string length of 255.
387     unsigned len = 0;
388     bool inString = false;
389     for (unsigned i = 0; i < NumElts; i++) {
390       int n = cast<ConstantInt>(CVA->getOperand(i))->getRawValue() & 255;
391       if (len == 0)
392         O << "\tdb ";
393
394       if (n >= 32 && n <= 127) {
395         if (!inString) {
396           if (len > 0) {
397             O << ",'";
398             len += 2;
399           } else {
400             O << "'";
401             len++;
402           }
403           inString = true;
404         }
405         if (n == '\'') {
406           O << "'";
407           len++;
408         }
409         O << char(n);
410       } else {
411         if (inString) {
412           O << "'";
413           len++;
414           inString = false;
415         }
416         if (len > 0) {
417           O << ",";
418           len++;
419         }
420         O << n;
421         len += 1 + (n > 9) + (n > 99);
422       }
423
424       if (len > 60) {
425         if (inString) {
426           O << "'";
427           inString = false;
428         }
429         O << "\n";
430         len = 0;
431       }
432     }
433
434     if (len > 0) {
435       if (inString)
436         O << "'";
437       O << "\n";
438     }
439   }
440 }
441
442 // Include the auto-generated portion of the assembly writer.
443 #include "X86GenAsmWriter1.inc"