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