rename X86ATTAsmPrinter class -> X86AsmPrinter
[oota-llvm.git] / lib / Target / X86 / AsmPrinter / X86ATTAsmPrinter.cpp
1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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 "X86ATTInstPrinter.h"
19 #include "X86IntelInstPrinter.h"
20 #include "X86MCInstLower.h"
21 #include "X86.h"
22 #include "X86COFF.h"
23 #include "X86COFFMachineModuleInfo.h"
24 #include "X86MachineFunctionInfo.h"
25 #include "X86TargetMachine.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/DerivedTypes.h"
28 #include "llvm/Module.h"
29 #include "llvm/Type.h"
30 #include "llvm/Assembly/Writer.h"
31 #include "llvm/MC/MCContext.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/Mangler.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/ADT/SmallString.h"
44 #include "llvm/ADT/Statistic.h"
45 using namespace llvm;
46
47 STATISTIC(EmittedInsts, "Number of machine instrs printed");
48
49 //===----------------------------------------------------------------------===//
50 // Primitive Helper Functions.
51 //===----------------------------------------------------------------------===//
52
53 void X86AsmPrinter::printMCInst(const MCInst *MI) {
54   if (MAI->getAssemblerDialect() == 0)
55     X86ATTInstPrinter(O, *MAI).printInstruction(MI);
56   else
57     X86IntelInstPrinter(O, *MAI).printInstruction(MI);
58 }
59
60 void X86AsmPrinter::PrintPICBaseSymbol() const {
61   // FIXME: Gross const cast hack.
62   X86AsmPrinter *AP = const_cast<X86AsmPrinter*>(this);
63   X86MCInstLower(OutContext, 0, *AP).GetPICBaseSymbol()->print(O, MAI);
64 }
65
66 void X86AsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
67   unsigned FnAlign = MF.getAlignment();
68   const Function *F = MF.getFunction();
69
70   if (Subtarget->isTargetCygMing()) {
71     X86COFFMachineModuleInfo &COFFMMI = 
72       MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
73     COFFMMI.DecorateCygMingName(CurrentFnName, F, *TM.getTargetData());
74   }
75
76   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
77   EmitAlignment(FnAlign, F);
78
79   switch (F->getLinkage()) {
80   default: llvm_unreachable("Unknown linkage type!");
81   case Function::InternalLinkage:  // Symbols default to internal.
82   case Function::PrivateLinkage:
83     break;
84   case Function::DLLExportLinkage:
85   case Function::ExternalLinkage:
86     O << "\t.globl\t" << CurrentFnName << '\n';
87     break;
88   case Function::LinkerPrivateLinkage:
89   case Function::LinkOnceAnyLinkage:
90   case Function::LinkOnceODRLinkage:
91   case Function::WeakAnyLinkage:
92   case Function::WeakODRLinkage:
93     if (Subtarget->isTargetDarwin()) {
94       O << "\t.globl\t" << CurrentFnName << '\n';
95       O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
96     } else if (Subtarget->isTargetCygMing()) {
97       O << "\t.globl\t" << CurrentFnName << "\n"
98            "\t.linkonce discard\n";
99     } else {
100       O << "\t.weak\t" << CurrentFnName << '\n';
101     }
102     break;
103   }
104
105   printVisibility(CurrentFnName, F->getVisibility());
106
107   if (Subtarget->isTargetELF())
108     O << "\t.type\t" << CurrentFnName << ",@function\n";
109   else if (Subtarget->isTargetCygMing()) {
110     O << "\t.def\t " << CurrentFnName
111       << ";\t.scl\t" <<
112       (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
113       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
114       << ";\t.endef\n";
115   }
116
117   O << CurrentFnName << ':';
118   if (VerboseAsm) {
119     O.PadToColumn(MAI->getCommentColumn());
120     O << MAI->getCommentString() << ' ';
121     WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
122   }
123   O << '\n';
124
125   // Add some workaround for linkonce linkage on Cygwin\MinGW
126   if (Subtarget->isTargetCygMing() &&
127       (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
128     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
129 }
130
131 /// runOnMachineFunction - This uses the printMachineInstruction()
132 /// method to print assembly for each instruction.
133 ///
134 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
135   const Function *F = MF.getFunction();
136   this->MF = &MF;
137   CallingConv::ID CC = F->getCallingConv();
138
139   SetupMachineFunction(MF);
140   O << "\n\n";
141
142   if (Subtarget->isTargetCOFF()) {
143     X86COFFMachineModuleInfo &COFFMMI = 
144     MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
145
146     // Populate function information map.  Don't want to populate
147     // non-stdcall or non-fastcall functions' information right now.
148     if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
149       COFFMMI.AddFunctionInfo(F, *MF.getInfo<X86MachineFunctionInfo>());
150   }
151
152   // Print out constants referenced by the function
153   EmitConstantPool(MF.getConstantPool());
154
155   // Print the 'header' of function
156   emitFunctionHeader(MF);
157
158   // Emit pre-function debug and/or EH information.
159   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
160     DW->BeginFunction(&MF);
161
162   // Print out code for the function.
163   bool hasAnyRealCode = false;
164   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
165        I != E; ++I) {
166     // Print a label for the basic block.
167     if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
168       // This is an entry block or a block that's only reachable via a
169       // fallthrough edge. In non-VerboseAsm mode, don't print the label.
170     } else {
171       EmitBasicBlockStart(I);
172       O << '\n';
173     }
174     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
175          II != IE; ++II) {
176       // Print the assembly for the instruction.
177       if (!II->isLabel())
178         hasAnyRealCode = true;
179       printMachineInstruction(II);
180     }
181   }
182
183   if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
184     // If the function is empty, then we need to emit *something*. Otherwise,
185     // the function's label might be associated with something that it wasn't
186     // meant to be associated with. We emit a noop in this situation.
187     // We are assuming inline asms are code.
188     O << "\tnop\n";
189   }
190
191   if (MAI->hasDotTypeDotSizeDirective())
192     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
193
194   // Emit post-function debug information.
195   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
196     DW->EndFunction(&MF);
197
198   // Print out jump tables referenced by the function.
199   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
200
201   // We didn't modify anything.
202   return false;
203 }
204
205 /// printSymbolOperand - Print a raw symbol reference operand.  This handles
206 /// jump tables, constant pools, global address and external symbols, all of
207 /// which print to a label with various suffixes for relocation types etc.
208 void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
209   switch (MO.getType()) {
210   default: llvm_unreachable("unknown symbol type!");
211   case MachineOperand::MO_JumpTableIndex:
212     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
213       << MO.getIndex();
214     break;
215   case MachineOperand::MO_ConstantPoolIndex:
216     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
217       << MO.getIndex();
218     printOffset(MO.getOffset());
219     break;
220   case MachineOperand::MO_GlobalAddress: {
221     const GlobalValue *GV = MO.getGlobal();
222     
223     const char *Suffix = "";
224     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
225       Suffix = "$stub";
226     else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
227              MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
228              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
229       Suffix = "$non_lazy_ptr";
230     
231     std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
232     if (Subtarget->isTargetCygMing()) {
233       X86COFFMachineModuleInfo &COFFMMI = 
234         MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
235       COFFMMI.DecorateCygMingName(Name, GV, *TM.getTargetData());
236     }
237     
238     // Handle dllimport linkage.
239     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
240       Name = "__imp_" + Name;
241     
242     if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
243         MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
244       SmallString<128> NameStr;
245       Mang->getNameWithPrefix(NameStr, GV, true);
246       NameStr += "$non_lazy_ptr";
247       MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
248       
249       const MCSymbol *&StubSym = 
250         MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
251       if (StubSym == 0) {
252         NameStr.clear();
253         Mang->getNameWithPrefix(NameStr, GV, false);
254         StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
255       }
256     } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
257       SmallString<128> NameStr;
258       Mang->getNameWithPrefix(NameStr, GV, true);
259       NameStr += "$non_lazy_ptr";
260       MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
261       const MCSymbol *&StubSym =
262         MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
263       if (StubSym == 0) {
264         NameStr.clear();
265         Mang->getNameWithPrefix(NameStr, GV, false);
266         StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
267       }
268     } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
269       SmallString<128> NameStr;
270       Mang->getNameWithPrefix(NameStr, GV, true);
271       NameStr += "$stub";
272       MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
273       const MCSymbol *&StubSym =
274         MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
275       if (StubSym == 0) {
276         NameStr.clear();
277         Mang->getNameWithPrefix(NameStr, GV, false);
278         StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
279       }
280     }
281     
282     // If the name begins with a dollar-sign, enclose it in parens.  We do this
283     // to avoid having it look like an integer immediate to the assembler.
284     if (Name[0] == '$') 
285       O << '(' << Name << ')';
286     else
287       O << Name;
288     
289     printOffset(MO.getOffset());
290     break;
291   }
292   case MachineOperand::MO_ExternalSymbol: {
293     std::string Name = Mang->makeNameProper(MO.getSymbolName());
294     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
295       Name += "$stub";
296       MCSymbol *Sym = OutContext.GetOrCreateSymbol(Name);
297       const MCSymbol *&StubSym =
298         MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
299       if (StubSym == 0) {
300         Name.erase(Name.end()-5, Name.end());
301         StubSym = OutContext.GetOrCreateSymbol(Name);
302       }
303     }
304     
305     // If the name begins with a dollar-sign, enclose it in parens.  We do this
306     // to avoid having it look like an integer immediate to the assembler.
307     if (Name[0] == '$') 
308       O << '(' << Name << ')';
309     else
310       O << Name;
311     break;
312   }
313   }
314   
315   switch (MO.getTargetFlags()) {
316   default:
317     llvm_unreachable("Unknown target flag on GV operand");
318   case X86II::MO_NO_FLAG:    // No flag.
319     break;
320   case X86II::MO_DARWIN_NONLAZY:
321   case X86II::MO_DLLIMPORT:
322   case X86II::MO_DARWIN_STUB:
323     // These affect the name of the symbol, not any suffix.
324     break;
325   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
326     O << " + [.-";
327     PrintPICBaseSymbol();
328     O << ']';
329     break;      
330   case X86II::MO_PIC_BASE_OFFSET:
331   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
332   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
333     O << '-';
334     PrintPICBaseSymbol();
335     break;
336   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
337   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
338   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
339   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
340   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
341   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
342   case X86II::MO_GOT:       O << "@GOT";       break;
343   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
344   case X86II::MO_PLT:       O << "@PLT";       break;
345   }
346 }
347
348 /// print_pcrel_imm - This is used to print an immediate value that ends up
349 /// being encoded as a pc-relative value.  These print slightly differently, for
350 /// example, a $ is not emitted.
351 void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
352   const MachineOperand &MO = MI->getOperand(OpNo);
353   switch (MO.getType()) {
354   default: llvm_unreachable("Unknown pcrel immediate operand");
355   case MachineOperand::MO_Immediate:
356     O << MO.getImm();
357     return;
358   case MachineOperand::MO_MachineBasicBlock:
359     GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
360     return;
361   case MachineOperand::MO_GlobalAddress:
362   case MachineOperand::MO_ExternalSymbol:
363     printSymbolOperand(MO);
364     return;
365   }
366 }
367
368
369 void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
370                                     const char *Modifier) {
371   const MachineOperand &MO = MI->getOperand(OpNo);
372   switch (MO.getType()) {
373   default: llvm_unreachable("unknown operand type!");
374   case MachineOperand::MO_Register: {
375     O << '%';
376     unsigned Reg = MO.getReg();
377     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
378       EVT VT = (strcmp(Modifier+6,"64") == 0) ?
379         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
380                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
381       Reg = getX86SubSuperRegister(Reg, VT);
382     }
383     O << X86ATTInstPrinter::getRegisterName(Reg);
384     return;
385   }
386
387   case MachineOperand::MO_Immediate:
388     O << '$' << MO.getImm();
389     return;
390
391   case MachineOperand::MO_JumpTableIndex:
392   case MachineOperand::MO_ConstantPoolIndex:
393   case MachineOperand::MO_GlobalAddress: 
394   case MachineOperand::MO_ExternalSymbol: {
395     O << '$';
396     printSymbolOperand(MO);
397     break;
398   }
399   }
400 }
401
402 void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
403   unsigned char value = MI->getOperand(Op).getImm();
404   assert(value <= 7 && "Invalid ssecc argument!");
405   switch (value) {
406   case 0: O << "eq"; break;
407   case 1: O << "lt"; break;
408   case 2: O << "le"; break;
409   case 3: O << "unord"; break;
410   case 4: O << "neq"; break;
411   case 5: O << "nlt"; break;
412   case 6: O << "nle"; break;
413   case 7: O << "ord"; break;
414   }
415 }
416
417 void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
418                                          const char *Modifier) {
419   const MachineOperand &BaseReg  = MI->getOperand(Op);
420   const MachineOperand &IndexReg = MI->getOperand(Op+2);
421   const MachineOperand &DispSpec = MI->getOperand(Op+3);
422
423   // If we really don't want to print out (rip), don't.
424   bool HasBaseReg = BaseReg.getReg() != 0;
425   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
426       BaseReg.getReg() == X86::RIP)
427     HasBaseReg = false;
428   
429   // HasParenPart - True if we will print out the () part of the mem ref.
430   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
431   
432   if (DispSpec.isImm()) {
433     int DispVal = DispSpec.getImm();
434     if (DispVal || !HasParenPart)
435       O << DispVal;
436   } else {
437     assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
438            DispSpec.isJTI() || DispSpec.isSymbol());
439     printSymbolOperand(MI->getOperand(Op+3));
440   }
441
442   if (HasParenPart) {
443     assert(IndexReg.getReg() != X86::ESP &&
444            "X86 doesn't allow scaling by ESP");
445
446     O << '(';
447     if (HasBaseReg)
448       printOperand(MI, Op, Modifier);
449
450     if (IndexReg.getReg()) {
451       O << ',';
452       printOperand(MI, Op+2, Modifier);
453       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
454       if (ScaleVal != 1)
455         O << ',' << ScaleVal;
456     }
457     O << ')';
458   }
459 }
460
461 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
462                                       const char *Modifier) {
463   assert(isMem(MI, Op) && "Invalid memory reference!");
464   const MachineOperand &Segment = MI->getOperand(Op+4);
465   if (Segment.getReg()) {
466     printOperand(MI, Op+4, Modifier);
467     O << ':';
468   }
469   printLeaMemReference(MI, Op, Modifier);
470 }
471
472 void X86AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
473                                            const MachineBasicBlock *MBB) const {
474   if (!MAI->getSetDirective())
475     return;
476
477   // We don't need .set machinery if we have GOT-style relocations
478   if (Subtarget->isPICStyleGOT())
479     return;
480
481   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
482     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
483   
484   GetMBBSymbol(MBB->getNumber())->print(O, MAI);
485   
486   if (Subtarget->isPICStyleRIPRel())
487     O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
488       << '_' << uid << '\n';
489   else {
490     O << '-';
491     PrintPICBaseSymbol();
492     O << '\n';
493   }
494 }
495
496
497 void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
498   PrintPICBaseSymbol();
499   O << '\n';
500   PrintPICBaseSymbol();
501   O << ':';
502 }
503
504 void X86AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
505                                            const MachineBasicBlock *MBB,
506                                            unsigned uid) const {
507   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
508     MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
509
510   O << JTEntryDirective << ' ';
511
512   if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
513     O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
514       << '_' << uid << "_set_" << MBB->getNumber();
515   } else if (Subtarget->isPICStyleGOT()) {
516     GetMBBSymbol(MBB->getNumber())->print(O, MAI);
517     O << "@GOTOFF";
518   } else
519     GetMBBSymbol(MBB->getNumber())->print(O, MAI);
520 }
521
522 bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
523   unsigned Reg = MO.getReg();
524   switch (Mode) {
525   default: return true;  // Unknown mode.
526   case 'b': // Print QImode register
527     Reg = getX86SubSuperRegister(Reg, MVT::i8);
528     break;
529   case 'h': // Print QImode high register
530     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
531     break;
532   case 'w': // Print HImode register
533     Reg = getX86SubSuperRegister(Reg, MVT::i16);
534     break;
535   case 'k': // Print SImode register
536     Reg = getX86SubSuperRegister(Reg, MVT::i32);
537     break;
538   case 'q': // Print DImode register
539     Reg = getX86SubSuperRegister(Reg, MVT::i64);
540     break;
541   }
542
543   O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
544   return false;
545 }
546
547 /// PrintAsmOperand - Print out an operand for an inline asm expression.
548 ///
549 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
550                                     unsigned AsmVariant,
551                                     const char *ExtraCode) {
552   // Does this asm operand have a single letter operand modifier?
553   if (ExtraCode && ExtraCode[0]) {
554     if (ExtraCode[1] != 0) return true; // Unknown modifier.
555
556     const MachineOperand &MO = MI->getOperand(OpNo);
557     
558     switch (ExtraCode[0]) {
559     default: return true;  // Unknown modifier.
560     case 'a': // This is an address.  Currently only 'i' and 'r' are expected.
561       if (MO.isImm()) {
562         O << MO.getImm();
563         return false;
564       } 
565       if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
566         printSymbolOperand(MO);
567         return false;
568       }
569       if (MO.isReg()) {
570         O << '(';
571         printOperand(MI, OpNo);
572         O << ')';
573         return false;
574       }
575       return true;
576
577     case 'c': // Don't print "$" before a global var name or constant.
578       if (MO.isImm())
579         O << MO.getImm();
580       else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
581         printSymbolOperand(MO);
582       else
583         printOperand(MI, OpNo);
584       return false;
585
586     case 'A': // Print '*' before a register (it must be a register)
587       if (MO.isReg()) {
588         O << '*';
589         printOperand(MI, OpNo);
590         return false;
591       }
592       return true;
593
594     case 'b': // Print QImode register
595     case 'h': // Print QImode high register
596     case 'w': // Print HImode register
597     case 'k': // Print SImode register
598     case 'q': // Print DImode register
599       if (MO.isReg())
600         return printAsmMRegister(MO, ExtraCode[0]);
601       printOperand(MI, OpNo);
602       return false;
603
604     case 'P': // This is the operand of a call, treat specially.
605       print_pcrel_imm(MI, OpNo);
606       return false;
607
608     case 'n':  // Negate the immediate or print a '-' before the operand.
609       // Note: this is a temporary solution. It should be handled target
610       // independently as part of the 'MC' work.
611       if (MO.isImm()) {
612         O << -MO.getImm();
613         return false;
614       }
615       O << '-';
616     }
617   }
618
619   printOperand(MI, OpNo);
620   return false;
621 }
622
623 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
624                                           unsigned OpNo, unsigned AsmVariant,
625                                           const char *ExtraCode) {
626   if (ExtraCode && ExtraCode[0]) {
627     if (ExtraCode[1] != 0) return true; // Unknown modifier.
628
629     switch (ExtraCode[0]) {
630     default: return true;  // Unknown modifier.
631     case 'b': // Print QImode register
632     case 'h': // Print QImode high register
633     case 'w': // Print HImode register
634     case 'k': // Print SImode register
635     case 'q': // Print SImode register
636       // These only apply to registers, ignore on mem.
637       break;
638     case 'P': // Don't print @PLT, but do print as memory.
639       printMemReference(MI, OpNo, "no-rip");
640       return false;
641     }
642   }
643   printMemReference(MI, OpNo);
644   return false;
645 }
646
647
648
649 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
650 /// AT&T syntax to the current output stream.
651 ///
652 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
653   ++EmittedInsts;
654
655   processDebugLoc(MI->getDebugLoc());
656   
657   printInstructionThroughMCStreamer(MI);
658   
659   if (VerboseAsm && !MI->getDebugLoc().isUnknown())
660     EmitComments(*MI);
661   O << '\n';
662 }
663
664 void X86AsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
665   if (!GVar->hasInitializer())
666     return;   // External global require no code
667   
668   // Check to see if this is a special global used by LLVM, if so, emit it.
669   if (EmitSpecialLLVMGlobal(GVar)) {
670     if (Subtarget->isTargetDarwin() &&
671         TM.getRelocationModel() == Reloc::Static) {
672       if (GVar->getName() == "llvm.global_ctors")
673         O << ".reference .constructors_used\n";
674       else if (GVar->getName() == "llvm.global_dtors")
675         O << ".reference .destructors_used\n";
676     }
677     return;
678   }
679   
680   const TargetData *TD = TM.getTargetData();
681
682   std::string name = Mang->getMangledName(GVar);
683   Constant *C = GVar->getInitializer();
684   const Type *Type = C->getType();
685   unsigned Size = TD->getTypeAllocSize(Type);
686   unsigned Align = TD->getPreferredAlignmentLog(GVar);
687
688   printVisibility(name, GVar->getVisibility());
689
690   if (Subtarget->isTargetELF())
691     O << "\t.type\t" << name << ",@object\n";
692
693   
694   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
695   const MCSection *TheSection =
696     getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
697   OutStreamer.SwitchSection(TheSection);
698
699   // FIXME: get this stuff from section kind flags.
700   if (C->isNullValue() && !GVar->hasSection() &&
701       // Don't put things that should go in the cstring section into "comm".
702       !TheSection->getKind().isMergeableCString()) {
703     if (GVar->hasExternalLinkage()) {
704       if (const char *Directive = MAI->getZeroFillDirective()) {
705         O << "\t.globl " << name << '\n';
706         O << Directive << "__DATA, __common, " << name << ", "
707           << Size << ", " << Align << '\n';
708         return;
709       }
710     }
711
712     if (!GVar->isThreadLocal() &&
713         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
714       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
715
716       if (MAI->getLCOMMDirective() != NULL) {
717         if (GVar->hasLocalLinkage()) {
718           O << MAI->getLCOMMDirective() << name << ',' << Size;
719           if (Subtarget->isTargetDarwin())
720             O << ',' << Align;
721         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
722           O << "\t.globl " << name << '\n'
723             << MAI->getWeakDefDirective() << name << '\n';
724           EmitAlignment(Align, GVar);
725           O << name << ":";
726           if (VerboseAsm) {
727             O.PadToColumn(MAI->getCommentColumn());
728             O << MAI->getCommentString() << ' ';
729             WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
730           }
731           O << '\n';
732           EmitGlobalConstant(C);
733           return;
734         } else {
735           O << MAI->getCOMMDirective()  << name << ',' << Size;
736           if (MAI->getCOMMDirectiveTakesAlignment())
737             O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
738         }
739       } else {
740         if (!Subtarget->isTargetCygMing()) {
741           if (GVar->hasLocalLinkage())
742             O << "\t.local\t" << name << '\n';
743         }
744         O << MAI->getCOMMDirective()  << name << ',' << Size;
745         if (MAI->getCOMMDirectiveTakesAlignment())
746           O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
747       }
748       if (VerboseAsm) {
749         O.PadToColumn(MAI->getCommentColumn());
750         O << MAI->getCommentString() << ' ';
751         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
752       }
753       O << '\n';
754       return;
755     }
756   }
757
758   switch (GVar->getLinkage()) {
759   case GlobalValue::CommonLinkage:
760   case GlobalValue::LinkOnceAnyLinkage:
761   case GlobalValue::LinkOnceODRLinkage:
762   case GlobalValue::WeakAnyLinkage:
763   case GlobalValue::WeakODRLinkage:
764   case GlobalValue::LinkerPrivateLinkage:
765     if (Subtarget->isTargetDarwin()) {
766       O << "\t.globl " << name << '\n'
767         << MAI->getWeakDefDirective() << name << '\n';
768     } else if (Subtarget->isTargetCygMing()) {
769       O << "\t.globl\t" << name << "\n"
770            "\t.linkonce same_size\n";
771     } else {
772       O << "\t.weak\t" << name << '\n';
773     }
774     break;
775   case GlobalValue::DLLExportLinkage:
776   case GlobalValue::AppendingLinkage:
777     // FIXME: appending linkage variables should go into a section of
778     // their name or something.  For now, just emit them as external.
779   case GlobalValue::ExternalLinkage:
780     // If external or appending, declare as a global symbol
781     O << "\t.globl " << name << '\n';
782     // FALL THROUGH
783   case GlobalValue::PrivateLinkage:
784   case GlobalValue::InternalLinkage:
785      break;
786   default:
787     llvm_unreachable("Unknown linkage type!");
788   }
789
790   EmitAlignment(Align, GVar);
791   O << name << ":";
792   if (VerboseAsm){
793     O.PadToColumn(MAI->getCommentColumn());
794     O << MAI->getCommentString() << ' ';
795     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
796   }
797   O << '\n';
798
799   EmitGlobalConstant(C);
800
801   if (MAI->hasDotTypeDotSizeDirective())
802     O << "\t.size\t" << name << ", " << Size << '\n';
803 }
804
805 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
806   if (Subtarget->isTargetDarwin()) {
807     // All darwin targets use mach-o.
808     TargetLoweringObjectFileMachO &TLOFMacho = 
809       static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
810     
811     MachineModuleInfoMachO &MMIMacho =
812       MMI->getObjFileInfo<MachineModuleInfoMachO>();
813     
814     // Output stubs for dynamically-linked functions.
815     MachineModuleInfoMachO::SymbolListTy Stubs;
816
817     Stubs = MMIMacho.GetFnStubList();
818     if (!Stubs.empty()) {
819       const MCSection *TheSection = 
820         TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
821                                   MCSectionMachO::S_SYMBOL_STUBS |
822                                   MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
823                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
824                                   5, SectionKind::getMetadata());
825       OutStreamer.SwitchSection(TheSection);
826
827       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
828         Stubs[i].first->print(O, MAI);
829         O << ":\n" << "\t.indirect_symbol ";
830         // Get the MCSymbol without the $stub suffix.
831         Stubs[i].second->print(O, MAI);
832         O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
833       }
834       O << '\n';
835       
836       Stubs.clear();
837     }
838
839     // Output stubs for external and common global variables.
840     Stubs = MMIMacho.GetGVStubList();
841     if (!Stubs.empty()) {
842       const MCSection *TheSection = 
843         TLOFMacho.getMachOSection("__IMPORT", "__pointers",
844                                   MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
845                                   SectionKind::getMetadata());
846       OutStreamer.SwitchSection(TheSection);
847
848       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
849         Stubs[i].first->print(O, MAI);
850         O << ":\n\t.indirect_symbol ";
851         Stubs[i].second->print(O, MAI);
852         O << "\n\t.long\t0\n";
853       }
854       Stubs.clear();
855     }
856
857     Stubs = MMIMacho.GetHiddenGVStubList();
858     if (!Stubs.empty()) {
859       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
860       EmitAlignment(2);
861
862       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
863         Stubs[i].first->print(O, MAI);
864         O << ":\n" << MAI->getData32bitsDirective();
865         Stubs[i].second->print(O, MAI);
866         O << '\n';
867       }
868       Stubs.clear();
869     }
870
871     // Funny Darwin hack: This flag tells the linker that no global symbols
872     // contain code that falls through to other global symbols (e.g. the obvious
873     // implementation of multiple entry points).  If this doesn't occur, the
874     // linker can safely perform dead code stripping.  Since LLVM never
875     // generates code that does this, it is always safe to set.
876     O << "\t.subsections_via_symbols\n";
877   }  
878   
879   if (Subtarget->isTargetCOFF()) {
880     // Necessary for dllexport support
881     std::vector<std::string> DLLExportedFns, DLLExportedGlobals;
882
883     X86COFFMachineModuleInfo &COFFMMI = 
884       MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
885     TargetLoweringObjectFileCOFF &TLOFCOFF = 
886       static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
887
888     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
889       if (I->hasDLLExportLinkage())
890         DLLExportedFns.push_back(Mang->getMangledName(I));
891     
892     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
893          I != E; ++I)
894       if (I->hasDLLExportLinkage())
895         DLLExportedGlobals.push_back(Mang->getMangledName(I));
896     
897     if (Subtarget->isTargetCygMing()) {
898       // Emit type information for external functions
899       for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
900            E = COFFMMI.stub_end(); I != E; ++I) {
901         O << "\t.def\t " << I->getKeyData()
902         << ";\t.scl\t" << COFF::C_EXT
903         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
904         << ";\t.endef\n";
905       }
906     }
907   
908     // Output linker support code for dllexported globals on windows.
909     if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
910       OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
911                                                         true,
912                                                    SectionKind::getMetadata()));
913     
914       for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
915         O << "\t.ascii \" -export:" << DLLExportedGlobals[i] << ",data\"\n";
916     
917       for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
918         O << "\t.ascii \" -export:" << DLLExportedFns[i] << "\"\n";
919     }
920   }
921 }
922