Add debug support for X86/ELF targets (Linux). This allows llvm-gcc4
[oota-llvm.git] / lib / Target / X86 / X86ATTAsmPrinter.cpp
1 //===-- X86ATTAsmPrinter.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 AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86ATTAsmPrinter.h"
17 #include "X86.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetAsmInfo.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Module.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include <iostream>
27 using namespace llvm;
28
29 /// getSectionForFunction - Return the section that we should emit the
30 /// specified function body into.
31 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
32   switch (F.getLinkage()) {
33   default: assert(0 && "Unknown linkage type!");
34   case Function::InternalLinkage: 
35   case Function::DLLExportLinkage:
36   case Function::ExternalLinkage:
37     return TAI->getTextSection();
38   case Function::WeakLinkage:
39   case Function::LinkOnceLinkage:
40     if (Subtarget->isTargetDarwin()) {
41       return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
42     } else if (Subtarget->isTargetCygwin()) {
43       return "\t.section\t.text$linkonce." + CurrentFnName + ",\"ax\"\n";
44     } else {
45       return "\t.section\t.llvm.linkonce.t." + CurrentFnName +
46              ",\"ax\",@progbits\n";
47     }
48   }
49 }
50
51 /// runOnMachineFunction - This uses the printMachineInstruction()
52 /// method to print assembly for each instruction.
53 ///
54 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
55   if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF()) {
56     // Let PassManager know we need debug information and relay
57     // the MachineDebugInfo address on to DwarfWriter.
58     DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
59   }
60
61   SetupMachineFunction(MF);
62   O << "\n\n";
63
64   // Print out constants referenced by the function
65   EmitConstantPool(MF.getConstantPool());
66
67   // Print out labels for the function.
68   const Function *F = MF.getFunction();
69   unsigned CC = F->getCallingConv();
70
71   // Populate function information map.  Actually, We don't want to populate
72   // non-stdcall or non-fastcall functions' information right now.
73   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
74     FunctionInfoMap[F] = *MF.getInfo<X86FunctionInfo>();
75
76   X86SharedAsmPrinter::decorateName(CurrentFnName, F);
77
78   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
79   
80   switch (F->getLinkage()) {
81   default: assert(0 && "Unknown linkage type!");
82   case Function::InternalLinkage:  // Symbols default to internal.
83     EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
84     break;
85   case Function::DLLExportLinkage:
86     DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
87     //FALLS THROUGH
88   case Function::ExternalLinkage:
89     EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
90     O << "\t.globl\t" << CurrentFnName << "\n";    
91     break;
92   case Function::LinkOnceLinkage:
93   case Function::WeakLinkage:
94     if (Subtarget->isTargetDarwin()) {
95       O << "\t.globl\t" << CurrentFnName << "\n";
96       O << "\t.weak_definition\t" << CurrentFnName << "\n";
97     } else if (Subtarget->isTargetCygwin()) {
98       EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
99       O << "\t.linkonce discard\n";
100       O << "\t.globl " << CurrentFnName << "\n";
101     } else {
102       EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
103       O << "\t.weak " << CurrentFnName << "\n";
104     }
105     break;
106   }
107   O << CurrentFnName << ":\n";
108   // Add some workaround for linkonce linkage on Cygwin\MinGW
109   if (Subtarget->isTargetCygwin() &&
110       (F->getLinkage() == Function::LinkOnceLinkage ||
111        F->getLinkage() == Function::WeakLinkage))
112     O << "_llvm$workaround$fake$stub_" << CurrentFnName << ":\n";
113
114   if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF()) {
115     // Emit pre-function debug information.
116     DW.BeginFunction(&MF);
117   }
118
119   // Print out code for the function.
120   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
121        I != E; ++I) {
122     // Print a label for the basic block.
123     if (I->pred_begin() != I->pred_end()) {
124       printBasicBlockLabel(I, true);
125       O << '\n';
126     }
127     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
128          II != E; ++II) {
129       // Print the assembly for the instruction.
130       O << "\t";
131       printMachineInstruction(II);
132     }
133   }
134
135   // Print out jump tables referenced by the function.
136   
137   // Mac OS X requires that the jump table follow the function, so that the jump
138   // table is part of the same atom that the function is in.
139   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
140   
141   if (TAI->hasDotTypeDotSizeDirective())
142     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
143
144   if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF()) {
145     // Emit post-function debug information.
146     DW.EndFunction();
147   }
148
149   // We didn't modify anything.
150   return false;
151 }
152
153 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
154                                     const char *Modifier) {
155   const MachineOperand &MO = MI->getOperand(OpNo);
156   const MRegisterInfo &RI = *TM.getRegisterInfo();
157   switch (MO.getType()) {
158   case MachineOperand::MO_Register: {
159     assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
160            "Virtual registers should not make it this far!");
161     O << '%';
162     unsigned Reg = MO.getReg();
163     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
164       MVT::ValueType VT = (strcmp(Modifier+6,"64") == 0) ?
165         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
166                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
167       Reg = getX86SubSuperRegister(Reg, VT);
168     }
169     for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
170       O << (char)tolower(*Name);
171     return;
172   }
173
174   case MachineOperand::MO_Immediate:
175     if (!Modifier || strcmp(Modifier, "debug") != 0)
176       O << '$';
177     O << MO.getImmedValue();
178     return;
179   case MachineOperand::MO_MachineBasicBlock:
180     printBasicBlockLabel(MO.getMachineBasicBlock());
181     return;
182   case MachineOperand::MO_JumpTableIndex: {
183     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
184     if (!isMemOp) O << '$';
185     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << "_"
186       << MO.getJumpTableIndex();
187     if (X86PICStyle == PICStyle::Stub &&
188         TM.getRelocationModel() == Reloc::PIC_)
189       O << "-\"L" << getFunctionNumber() << "$pb\"";
190     if (Subtarget->is64Bit())
191       O << "(%rip)";
192     return;
193   }
194   case MachineOperand::MO_ConstantPoolIndex: {
195     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
196     if (!isMemOp) O << '$';
197     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
198       << MO.getConstantPoolIndex();
199     if (X86PICStyle == PICStyle::Stub &&
200         TM.getRelocationModel() == Reloc::PIC_)
201       O << "-\"L" << getFunctionNumber() << "$pb\"";
202     int Offset = MO.getOffset();
203     if (Offset > 0)
204       O << "+" << Offset;
205     else if (Offset < 0)
206       O << Offset;
207
208     if (Subtarget->is64Bit())
209       O << "(%rip)";
210     return;
211   }
212   case MachineOperand::MO_GlobalAddress: {
213     bool isCallOp = Modifier && !strcmp(Modifier, "call");
214     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
215     if (!isMemOp && !isCallOp) O << '$';
216
217     GlobalValue *GV = MO.getGlobal();
218     std::string Name = Mang->getValueName(GV);
219     
220     bool isExt = (GV->isExternal() || GV->hasWeakLinkage() ||
221                   GV->hasLinkOnceLinkage());
222     
223     X86SharedAsmPrinter::decorateName(Name, GV);
224     
225     if (X86PICStyle == PICStyle::Stub &&
226         TM.getRelocationModel() != Reloc::Static) {
227       // Link-once, External, or Weakly-linked global variables need
228       // non-lazily-resolved stubs
229       if (isExt) {
230         // Dynamically-resolved functions need a stub for the function.
231         if (isCallOp && isa<Function>(GV)) {
232           FnStubs.insert(Name);
233           O << "L" << Name << "$stub";
234         } else {
235           GVStubs.insert(Name);
236           O << "L" << Name << "$non_lazy_ptr";
237         }
238       } else {
239         if (GV->hasDLLImportLinkage()) {
240           O << "__imp_";          
241         } 
242         O << Name;
243       }
244       
245       if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
246         O << "-\"L" << getFunctionNumber() << "$pb\"";
247     } else {
248       if (GV->hasDLLImportLinkage()) {
249         O << "__imp_";          
250       }       
251       O << Name;
252     }
253     
254     int Offset = MO.getOffset();
255     if (Offset > 0)
256       O << "+" << Offset;
257     else if (Offset < 0)
258       O << Offset;
259
260     if (!isCallOp &&
261         Subtarget->is64Bit()) {
262       if (isExt && TM.getRelocationModel() != Reloc::Static)
263         O << "@GOTPCREL";
264       O << "(%rip)";
265     }
266
267     return;
268   }
269   case MachineOperand::MO_ExternalSymbol: {
270     bool isCallOp = Modifier && !strcmp(Modifier, "call");
271     if (isCallOp && 
272         X86PICStyle == PICStyle::Stub &&
273         TM.getRelocationModel() != Reloc::Static) {
274       std::string Name(TAI->getGlobalPrefix());
275       Name += MO.getSymbolName();
276       FnStubs.insert(Name);
277       O << "L" << Name << "$stub";
278       return;
279     }
280     if (!isCallOp) O << '$';
281     O << TAI->getGlobalPrefix() << MO.getSymbolName();
282
283     if (!isCallOp &&
284         Subtarget->is64Bit())
285       O << "(%rip)";
286
287     return;
288   }
289   default:
290     O << "<unknown operand type>"; return;
291   }
292 }
293
294 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
295   unsigned char value = MI->getOperand(Op).getImmedValue();
296   assert(value <= 7 && "Invalid ssecc argument!");
297   switch (value) {
298   case 0: O << "eq"; break;
299   case 1: O << "lt"; break;
300   case 2: O << "le"; break;
301   case 3: O << "unord"; break;
302   case 4: O << "neq"; break;
303   case 5: O << "nlt"; break;
304   case 6: O << "nle"; break;
305   case 7: O << "ord"; break;
306   }
307 }
308
309 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
310                                          const char *Modifier){
311   assert(isMem(MI, Op) && "Invalid memory reference!");
312
313   const MachineOperand &BaseReg  = MI->getOperand(Op);
314   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
315   const MachineOperand &IndexReg = MI->getOperand(Op+2);
316   const MachineOperand &DispSpec = MI->getOperand(Op+3);
317
318   if (BaseReg.isFrameIndex()) {
319     O << "[frame slot #" << BaseReg.getFrameIndex();
320     if (DispSpec.getImmedValue())
321       O << " + " << DispSpec.getImmedValue();
322     O << "]";
323     return;
324   }
325
326   if (DispSpec.isGlobalAddress() ||
327       DispSpec.isConstantPoolIndex() ||
328       DispSpec.isJumpTableIndex()) {
329     printOperand(MI, Op+3, "mem");
330   } else {
331     int DispVal = DispSpec.getImmedValue();
332     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
333       O << DispVal;
334   }
335
336   if (IndexReg.getReg() || BaseReg.getReg()) {
337     O << "(";
338     if (BaseReg.getReg()) {
339       printOperand(MI, Op, Modifier);
340     }
341
342     if (IndexReg.getReg()) {
343       O << ",";
344       printOperand(MI, Op+2, Modifier);
345       if (ScaleVal != 1)
346         O << "," << ScaleVal;
347     }
348
349     O << ")";
350   }
351 }
352
353 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
354   O << "\"L" << getFunctionNumber() << "$pb\"\n";
355   O << "\"L" << getFunctionNumber() << "$pb\":";
356 }
357
358
359 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
360                                          const char Mode) {
361   const MRegisterInfo &RI = *TM.getRegisterInfo();
362   unsigned Reg = MO.getReg();
363   switch (Mode) {
364   default: return true;  // Unknown mode.
365   case 'b': // Print QImode register
366     Reg = getX86SubSuperRegister(Reg, MVT::i8);
367     break;
368   case 'h': // Print QImode high register
369     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
370     break;
371   case 'w': // Print HImode register
372     Reg = getX86SubSuperRegister(Reg, MVT::i16);
373     break;
374   case 'k': // Print SImode register
375     Reg = getX86SubSuperRegister(Reg, MVT::i32);
376     break;
377   }
378
379   O << '%';
380   for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
381     O << (char)tolower(*Name);
382   return false;
383 }
384
385 /// PrintAsmOperand - Print out an operand for an inline asm expression.
386 ///
387 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
388                                        unsigned AsmVariant, 
389                                        const char *ExtraCode) {
390   // Does this asm operand have a single letter operand modifier?
391   if (ExtraCode && ExtraCode[0]) {
392     if (ExtraCode[1] != 0) return true; // Unknown modifier.
393     
394     switch (ExtraCode[0]) {
395     default: return true;  // Unknown modifier.
396     case 'b': // Print QImode register
397     case 'h': // Print QImode high register
398     case 'w': // Print HImode register
399     case 'k': // Print SImode register
400       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
401     }
402   }
403   
404   printOperand(MI, OpNo);
405   return false;
406 }
407
408 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
409                                              unsigned OpNo,
410                                              unsigned AsmVariant, 
411                                              const char *ExtraCode) {
412   if (ExtraCode && ExtraCode[0])
413     return true; // Unknown modifier.
414   printMemReference(MI, OpNo);
415   return false;
416 }
417
418 /// printMachineInstruction -- Print out a single X86 LLVM instruction
419 /// MI in Intel syntax to the current output stream.
420 ///
421 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
422   ++EmittedInsts;
423
424   // See if a truncate instruction can be turned into a nop.
425   switch (MI->getOpcode()) {
426   default: break;
427   case X86::TRUNC_64to32:
428   case X86::TRUNC_64to16:
429   case X86::TRUNC_32to16:
430   case X86::TRUNC_32to8:
431   case X86::TRUNC_16to8:
432   case X86::TRUNC_32_to8:
433   case X86::TRUNC_16_to8: {
434     const MachineOperand &MO0 = MI->getOperand(0);
435     const MachineOperand &MO1 = MI->getOperand(1);
436     unsigned Reg0 = MO0.getReg();
437     unsigned Reg1 = MO1.getReg();
438     unsigned Opc = MI->getOpcode();
439     if (Opc == X86::TRUNC_64to32)
440       Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
441     else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
442       Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
443     else
444       Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
445     O << TAI->getCommentString() << " TRUNCATE ";
446     if (Reg0 != Reg1)
447       O << "\n\t";
448     break;
449   }
450   case X86::PsMOVZX64rr32:
451     O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
452     break;
453   }
454
455   // Call the autogenerated instruction printer routines.
456   printInstruction(MI);
457 }
458
459 // Include the auto-generated portion of the assembly writer.
460 #include "X86GenAsmWriter.inc"
461