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