* Fix one more bug in PIC codegen: extra load is needed for *all*
[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 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
18 #include "X86.h"
19 #include "X86COFF.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetAsmInfo.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/Module.h"
26 #include "llvm/Support/Mangler.h"
27 #include "llvm/Target/TargetAsmInfo.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/ADT/Statistic.h"
30 using namespace llvm;
31
32 STATISTIC(EmittedInsts, "Number of machine instrs printed");
33
34 static std::string computePICLabel(unsigned fnNumber,
35                                    const X86Subtarget* Subtarget) 
36 {
37   std::string label;
38
39   if (Subtarget->isTargetDarwin()) {
40     label =  "\"L" + utostr_32(fnNumber) + "$pb\"";
41   } else if (Subtarget->isTargetELF()) {
42     label = ".Lllvm$" + utostr_32(fnNumber) + "$piclabel";
43   } else
44     assert(0 && "Don't know how to print PIC label!\n");
45
46   return label;
47 }
48
49 /// getSectionForFunction - Return the section that we should emit the
50 /// specified function body into.
51 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
52   switch (F.getLinkage()) {
53   default: assert(0 && "Unknown linkage type!");
54   case Function::InternalLinkage: 
55   case Function::DLLExportLinkage:
56   case Function::ExternalLinkage:
57     return TAI->getTextSection();
58   case Function::WeakLinkage:
59   case Function::LinkOnceLinkage:
60     if (Subtarget->isTargetDarwin()) {
61       return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
62     } else if (Subtarget->isTargetCygMing()) {
63       return "\t.section\t.text$linkonce." + CurrentFnName + ",\"ax\"\n";
64     } else {
65       return "\t.section\t.llvm.linkonce.t." + CurrentFnName +
66              ",\"ax\",@progbits\n";
67     }
68   }
69 }
70
71 /// runOnMachineFunction - This uses the printMachineInstruction()
72 /// method to print assembly for each instruction.
73 ///
74 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
75   if (Subtarget->isTargetDarwin() ||
76       Subtarget->isTargetELF() ||
77       Subtarget->isTargetCygMing()) {
78     // Let PassManager know we need debug information and relay
79     // the MachineDebugInfo address on to DwarfWriter.
80     DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
81   }
82
83   SetupMachineFunction(MF);
84   O << "\n\n";
85
86   // Print out constants referenced by the function
87   EmitConstantPool(MF.getConstantPool());
88
89   // Print out labels for the function.
90   const Function *F = MF.getFunction();
91   unsigned CC = F->getCallingConv();
92
93   // Populate function information map.  Actually, We don't want to populate
94   // non-stdcall or non-fastcall functions' information right now.
95   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
96     FunctionInfoMap[F] = *MF.getInfo<X86FunctionInfo>();
97
98   X86SharedAsmPrinter::decorateName(CurrentFnName, F);
99
100   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
101     
102   switch (F->getLinkage()) {
103   default: assert(0 && "Unknown linkage type!");
104   case Function::InternalLinkage:  // Symbols default to internal.
105     EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
106     break;
107   case Function::DLLExportLinkage:
108     DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
109     //FALLS THROUGH
110   case Function::ExternalLinkage:
111     EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
112     O << "\t.globl\t" << CurrentFnName << "\n";    
113     break;
114   case Function::LinkOnceLinkage:
115   case Function::WeakLinkage:
116     if (Subtarget->isTargetDarwin()) {
117       O << "\t.globl\t" << CurrentFnName << "\n";
118       O << "\t.weak_definition\t" << CurrentFnName << "\n";
119     } else if (Subtarget->isTargetCygMing()) {
120       EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
121       O << "\t.linkonce discard\n";
122       O << "\t.globl " << CurrentFnName << "\n";
123     } else {
124       EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
125       O << "\t.weak " << CurrentFnName << "\n";
126     }
127     break;
128   }
129   if (F->hasHiddenVisibility())
130     if (const char *Directive = TAI->getHiddenDirective())
131       O << Directive << CurrentFnName << "\n";
132
133   if (Subtarget->isTargetELF())
134     O << "\t.type " << CurrentFnName << ",@function\n";
135   else if (Subtarget->isTargetCygMing()) {
136     O << "\t.def\t " << CurrentFnName
137       << ";\t.scl\t" <<
138       (F->getLinkage() == Function::InternalLinkage ? COFF::C_STAT : COFF::C_EXT)
139       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
140       << ";\t.endef\n";
141   }
142
143   O << CurrentFnName << ":\n";
144   // Add some workaround for linkonce linkage on Cygwin\MinGW
145   if (Subtarget->isTargetCygMing() &&
146       (F->getLinkage() == Function::LinkOnceLinkage ||
147        F->getLinkage() == Function::WeakLinkage))
148     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
149
150   if (Subtarget->isTargetDarwin() ||
151       Subtarget->isTargetELF() ||
152       Subtarget->isTargetCygMing()) {
153     // Emit pre-function debug information.
154     DW.BeginFunction(&MF);
155   }
156
157   // Print out code for the function.
158   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
159        I != E; ++I) {
160     // Print a label for the basic block.
161     if (I->pred_begin() != I->pred_end()) {
162       printBasicBlockLabel(I, true);
163       O << '\n';
164     }
165     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
166          II != E; ++II) {
167       // Print the assembly for the instruction.
168       O << "\t";
169       printMachineInstruction(II);
170     }
171   }
172
173   // Print out jump tables referenced by the function.
174   
175   // Mac OS X requires that the jump table follow the function, so that the jump
176   // table is part of the same atom that the function is in.
177   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
178   
179   if (TAI->hasDotTypeDotSizeDirective())
180     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
181
182   if (Subtarget->isTargetDarwin() ||
183       Subtarget->isTargetELF() ||
184       Subtarget->isTargetCygMing()) {
185     // Emit post-function debug information.
186     DW.EndFunction();
187   }
188
189   // We didn't modify anything.
190   return false;
191 }
192
193 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
194                                     const char *Modifier, bool NotRIPRel) {
195   const MachineOperand &MO = MI->getOperand(OpNo);
196   const MRegisterInfo &RI = *TM.getRegisterInfo();
197   switch (MO.getType()) {
198   case MachineOperand::MO_Register: {
199     assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
200            "Virtual registers should not make it this far!");
201     O << '%';
202     unsigned Reg = MO.getReg();
203     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
204       MVT::ValueType VT = (strcmp(Modifier+6,"64") == 0) ?
205         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
206                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
207       Reg = getX86SubSuperRegister(Reg, VT);
208     }
209     for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
210       O << (char)tolower(*Name);
211     return;
212   }
213
214   case MachineOperand::MO_Immediate:
215     if (!Modifier || strcmp(Modifier, "debug") != 0)
216       O << '$';
217     O << MO.getImmedValue();
218     return;
219   case MachineOperand::MO_MachineBasicBlock:
220     printBasicBlockLabel(MO.getMachineBasicBlock());
221     return;
222   case MachineOperand::MO_JumpTableIndex: {
223     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
224     if (!isMemOp) O << '$';
225     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << "_"
226       << MO.getJumpTableIndex();
227
228     if (TM.getRelocationModel() == Reloc::PIC_) {
229       if (Subtarget->isPICStyleStub())
230         O << "-\"L" << getFunctionNumber() << "$pb\"";
231       else if (Subtarget->isPICStyleGOT())
232         O << "@GOTOFF";
233     }
234     
235     if (isMemOp && Subtarget->is64Bit() && !NotRIPRel)
236       O << "(%rip)";
237     return;
238   }
239   case MachineOperand::MO_ConstantPoolIndex: {
240     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
241     if (!isMemOp) O << '$';
242     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
243       << MO.getConstantPoolIndex();
244
245     if (TM.getRelocationModel() == Reloc::PIC_) {
246       if (Subtarget->isPICStyleStub())
247         O << "-\"L" << getFunctionNumber() << "$pb\"";
248       if (Subtarget->isPICStyleGOT())
249         O << "@GOTOFF";
250     }
251     
252     int Offset = MO.getOffset();
253     if (Offset > 0)
254       O << "+" << Offset;
255     else if (Offset < 0)
256       O << Offset;
257
258     if (isMemOp && Subtarget->is64Bit() && !NotRIPRel)
259       O << "(%rip)";
260     return;
261   }
262   case MachineOperand::MO_GlobalAddress: {
263     bool isCallOp = Modifier && !strcmp(Modifier, "call");
264     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
265     if (!isMemOp && !isCallOp) O << '$';
266
267     GlobalValue *GV = MO.getGlobal();
268     std::string Name = Mang->getValueName(GV);
269     
270     bool isExt = (GV->isExternal() || GV->hasWeakLinkage() ||
271                   GV->hasLinkOnceLinkage());
272     bool isHidden = GV->hasHiddenVisibility();
273     
274     X86SharedAsmPrinter::decorateName(Name, GV);
275     
276     if (Subtarget->isPICStyleStub()) {
277       // Link-once, External, or Weakly-linked global variables need
278       // non-lazily-resolved stubs
279       if (isExt) {
280         // Dynamically-resolved functions need a stub for the function.
281         if (isCallOp && isa<Function>(GV)) {
282           FnStubs.insert(Name);
283           O << "L" << Name << "$stub";
284         } else {
285           GVStubs.insert(Name);
286           O << "L" << Name << "$non_lazy_ptr";
287         }
288       } else {
289         if (GV->hasDLLImportLinkage()) {
290           O << "__imp_";          
291         } 
292         O << Name;
293       }
294       
295       if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
296         O << "-\"L" << getFunctionNumber() << "$pb\"";
297     } else {
298       if (GV->hasDLLImportLinkage()) {
299         O << "__imp_";          
300       }       
301       O << Name;
302
303       if (isCallOp && isa<Function>(GV)) {
304         if (Subtarget->isPICStyleGOT()) {
305           // Assemble call via PLT for non-local symbols
306           if (!isHidden || GV->isExternal())
307             O << "@PLT";
308         }
309         if (Subtarget->isTargetCygMing() && GV->isExternal()) {
310           // Save function name for later type emission
311           FnStubs.insert(Name);
312         }
313       }
314     }
315
316     if (GV->hasExternalWeakLinkage())
317       ExtWeakSymbols.insert(GV);
318     
319     int Offset = MO.getOffset();
320     if (Offset > 0)
321       O << "+" << Offset;
322     else if (Offset < 0)
323       O << Offset;
324
325     if (isMemOp) {
326       if (Subtarget->isPICStyleGOT()) {
327         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
328           O << "@GOT";
329         else
330           O << "@GOTOFF";
331       } else     
332         if (isExt && Subtarget->isPICStyleRIPRel())
333           O << "@GOTPCREL(%rip)";
334         else if (Subtarget->is64Bit() && !NotRIPRel)
335           // Use rip when possible to reduce code size, except when
336           // index or base register are also part of the address. e.g.
337           // foo(%rip)(%rcx,%rax,4) is not legal
338           O << "(%rip)";
339     }
340
341     return;
342   }
343   case MachineOperand::MO_ExternalSymbol: {
344     bool isCallOp = Modifier && !strcmp(Modifier, "call");
345     std::string Name(TAI->getGlobalPrefix());
346     Name += MO.getSymbolName();
347     if (isCallOp && Subtarget->isPICStyleStub()) {
348       FnStubs.insert(Name);
349       O << "L" << Name << "$stub";
350       return;
351     }
352     if (!isCallOp) O << '$';
353     O << Name;
354
355     if (Subtarget->isPICStyleGOT()) {
356       std::string GOTName(TAI->getGlobalPrefix());
357       GOTName+="_GLOBAL_OFFSET_TABLE_";
358       if (Name == GOTName)
359         // Really hack! Emit extra offset to PC during printing GOT offset to
360         // compensate size of popl instruction. The resulting code should look
361         // like:
362         //   call .piclabel
363         // piclabel:
364         //   popl %some_register
365         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
366         O << " + [.-" << computePICLabel(getFunctionNumber(), Subtarget) << "]";
367     }
368
369     if (isCallOp && Subtarget->isPICStyleGOT())
370       O << "@PLT";
371
372     if (!isCallOp && Subtarget->is64Bit())
373       O << "(%rip)";
374
375     return;
376   }
377   default:
378     O << "<unknown operand type>"; return;
379   }
380 }
381
382 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
383   unsigned char value = MI->getOperand(Op).getImmedValue();
384   assert(value <= 7 && "Invalid ssecc argument!");
385   switch (value) {
386   case 0: O << "eq"; break;
387   case 1: O << "lt"; break;
388   case 2: O << "le"; break;
389   case 3: O << "unord"; break;
390   case 4: O << "neq"; break;
391   case 5: O << "nlt"; break;
392   case 6: O << "nle"; break;
393   case 7: O << "ord"; break;
394   }
395 }
396
397 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
398                                          const char *Modifier){
399   assert(isMem(MI, Op) && "Invalid memory reference!");
400   MachineOperand BaseReg  = MI->getOperand(Op);
401   MachineOperand IndexReg = MI->getOperand(Op+2);
402   const MachineOperand &DispSpec = MI->getOperand(Op+3);
403
404   bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
405   if (DispSpec.isGlobalAddress() ||
406       DispSpec.isConstantPoolIndex() ||
407       DispSpec.isJumpTableIndex()) {
408     printOperand(MI, Op+3, "mem", NotRIPRel);
409   } else {
410     int DispVal = DispSpec.getImmedValue();
411     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
412       O << DispVal;
413   }
414
415   if (IndexReg.getReg() || BaseReg.getReg()) {
416     unsigned ScaleVal = MI->getOperand(Op+1).getImmedValue();
417     unsigned BaseRegOperand = 0, IndexRegOperand = 2;
418       
419     // There are cases where we can end up with ESP/RSP in the indexreg slot.
420     // If this happens, swap the base/index register to support assemblers that
421     // don't work when the index is *SP.
422     if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
423       assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
424       std::swap(BaseReg, IndexReg);
425       std::swap(BaseRegOperand, IndexRegOperand);
426     }
427     
428     O << "(";
429     if (BaseReg.getReg())
430       printOperand(MI, Op+BaseRegOperand, Modifier);
431
432     if (IndexReg.getReg()) {
433       O << ",";
434       printOperand(MI, Op+IndexRegOperand, Modifier);
435       if (ScaleVal != 1)
436         O << "," << ScaleVal;
437     }
438     O << ")";
439   }
440 }
441
442 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
443   std::string label = computePICLabel(getFunctionNumber(), Subtarget);
444   O << label << "\n" << label << ":";
445 }
446
447
448 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
449                                          const char Mode) {
450   const MRegisterInfo &RI = *TM.getRegisterInfo();
451   unsigned Reg = MO.getReg();
452   switch (Mode) {
453   default: return true;  // Unknown mode.
454   case 'b': // Print QImode register
455     Reg = getX86SubSuperRegister(Reg, MVT::i8);
456     break;
457   case 'h': // Print QImode high register
458     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
459     break;
460   case 'w': // Print HImode register
461     Reg = getX86SubSuperRegister(Reg, MVT::i16);
462     break;
463   case 'k': // Print SImode register
464     Reg = getX86SubSuperRegister(Reg, MVT::i32);
465     break;
466   }
467
468   O << '%';
469   for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
470     O << (char)tolower(*Name);
471   return false;
472 }
473
474 /// PrintAsmOperand - Print out an operand for an inline asm expression.
475 ///
476 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
477                                        unsigned AsmVariant, 
478                                        const char *ExtraCode) {
479   // Does this asm operand have a single letter operand modifier?
480   if (ExtraCode && ExtraCode[0]) {
481     if (ExtraCode[1] != 0) return true; // Unknown modifier.
482     
483     switch (ExtraCode[0]) {
484     default: return true;  // Unknown modifier.
485     case 'c': // Don't print "$" before a global var name.
486       printOperand(MI, OpNo, "mem");
487       return false;
488     case 'b': // Print QImode register
489     case 'h': // Print QImode high register
490     case 'w': // Print HImode register
491     case 'k': // Print SImode register
492       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
493     }
494   }
495   
496   printOperand(MI, OpNo);
497   return false;
498 }
499
500 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
501                                              unsigned OpNo,
502                                              unsigned AsmVariant, 
503                                              const char *ExtraCode) {
504   if (ExtraCode && ExtraCode[0])
505     return true; // Unknown modifier.
506   printMemReference(MI, OpNo);
507   return false;
508 }
509
510 /// printMachineInstruction -- Print out a single X86 LLVM instruction
511 /// MI in Intel syntax to the current output stream.
512 ///
513 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
514   ++EmittedInsts;
515
516   // See if a truncate instruction can be turned into a nop.
517   switch (MI->getOpcode()) {
518   default: break;
519   case X86::TRUNC_64to32:
520   case X86::TRUNC_64to16:
521   case X86::TRUNC_32to16:
522   case X86::TRUNC_32to8:
523   case X86::TRUNC_16to8:
524   case X86::TRUNC_32_to8:
525   case X86::TRUNC_16_to8: {
526     const MachineOperand &MO0 = MI->getOperand(0);
527     const MachineOperand &MO1 = MI->getOperand(1);
528     unsigned Reg0 = MO0.getReg();
529     unsigned Reg1 = MO1.getReg();
530     unsigned Opc = MI->getOpcode();
531     if (Opc == X86::TRUNC_64to32)
532       Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
533     else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
534       Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
535     else
536       Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
537     O << TAI->getCommentString() << " TRUNCATE ";
538     if (Reg0 != Reg1)
539       O << "\n\t";
540     break;
541   }
542   case X86::PsMOVZX64rr32:
543     O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
544     break;
545   }
546
547   // Call the autogenerated instruction printer routines.
548   printInstruction(MI);
549 }
550
551 // Include the auto-generated portion of the assembly writer.
552 #include "X86GenAsmWriter.inc"
553