convert some uses of printBasicBlockLabel to use GetMBBSymbol
[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     GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
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   
554   GetMBBSymbol(MBB->getNumber())->print(O, MAI);
555   
556   if (Subtarget->isPICStyleRIPRel())
557     O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
558       << '_' << uid << '\n';
559   else {
560     O << '-';
561     PrintPICBaseSymbol();
562     O << '\n';
563   }
564 }
565
566
567 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
568   PrintPICBaseSymbol();
569   O << '\n';
570   PrintPICBaseSymbol();
571   O << ':';
572 }
573
574 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
575                                               const MachineBasicBlock *MBB,
576                                               unsigned uid) const {
577   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
578     MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
579
580   O << JTEntryDirective << ' ';
581
582   if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
583     O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
584       << '_' << uid << "_set_" << MBB->getNumber();
585   } else if (Subtarget->isPICStyleGOT()) {
586     GetMBBSymbol(MBB->getNumber())->print(O, MAI);
587     O << "@GOTOFF";
588   } else
589     GetMBBSymbol(MBB->getNumber())->print(O, MAI);
590 }
591
592 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
593   unsigned Reg = MO.getReg();
594   switch (Mode) {
595   default: return true;  // Unknown mode.
596   case 'b': // Print QImode register
597     Reg = getX86SubSuperRegister(Reg, MVT::i8);
598     break;
599   case 'h': // Print QImode high register
600     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
601     break;
602   case 'w': // Print HImode register
603     Reg = getX86SubSuperRegister(Reg, MVT::i16);
604     break;
605   case 'k': // Print SImode register
606     Reg = getX86SubSuperRegister(Reg, MVT::i32);
607     break;
608   case 'q': // Print DImode register
609     Reg = getX86SubSuperRegister(Reg, MVT::i64);
610     break;
611   }
612
613   O << '%'<< TRI->getAsmName(Reg);
614   return false;
615 }
616
617 /// PrintAsmOperand - Print out an operand for an inline asm expression.
618 ///
619 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
620                                        unsigned AsmVariant,
621                                        const char *ExtraCode) {
622   // Does this asm operand have a single letter operand modifier?
623   if (ExtraCode && ExtraCode[0]) {
624     if (ExtraCode[1] != 0) return true; // Unknown modifier.
625
626     const MachineOperand &MO = MI->getOperand(OpNo);
627     
628     switch (ExtraCode[0]) {
629     default: return true;  // Unknown modifier.
630     case 'a': // This is an address.  Currently only 'i' and 'r' are expected.
631       if (MO.isImm()) {
632         O << MO.getImm();
633         return false;
634       } 
635       if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
636         printSymbolOperand(MO);
637         return false;
638       }
639       if (MO.isReg()) {
640         O << '(';
641         printOperand(MI, OpNo);
642         O << ')';
643         return false;
644       }
645       return true;
646
647     case 'c': // Don't print "$" before a global var name or constant.
648       if (MO.isImm())
649         O << MO.getImm();
650       else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
651         printSymbolOperand(MO);
652       else
653         printOperand(MI, OpNo);
654       return false;
655
656     case 'A': // Print '*' before a register (it must be a register)
657       if (MO.isReg()) {
658         O << '*';
659         printOperand(MI, OpNo);
660         return false;
661       }
662       return true;
663
664     case 'b': // Print QImode register
665     case 'h': // Print QImode high register
666     case 'w': // Print HImode register
667     case 'k': // Print SImode register
668     case 'q': // Print DImode register
669       if (MO.isReg())
670         return printAsmMRegister(MO, ExtraCode[0]);
671       printOperand(MI, OpNo);
672       return false;
673
674     case 'P': // This is the operand of a call, treat specially.
675       print_pcrel_imm(MI, OpNo);
676       return false;
677
678     case 'n':  // Negate the immediate or print a '-' before the operand.
679       // Note: this is a temporary solution. It should be handled target
680       // independently as part of the 'MC' work.
681       if (MO.isImm()) {
682         O << -MO.getImm();
683         return false;
684       }
685       O << '-';
686     }
687   }
688
689   printOperand(MI, OpNo);
690   return false;
691 }
692
693 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
694                                              unsigned OpNo,
695                                              unsigned AsmVariant,
696                                              const char *ExtraCode) {
697   if (ExtraCode && ExtraCode[0]) {
698     if (ExtraCode[1] != 0) return true; // Unknown modifier.
699
700     switch (ExtraCode[0]) {
701     default: return true;  // Unknown modifier.
702     case 'b': // Print QImode register
703     case 'h': // Print QImode high register
704     case 'w': // Print HImode register
705     case 'k': // Print SImode register
706     case 'q': // Print SImode register
707       // These only apply to registers, ignore on mem.
708       break;
709     case 'P': // Don't print @PLT, but do print as memory.
710       printMemReference(MI, OpNo, "no-rip");
711       return false;
712     }
713   }
714   printMemReference(MI, OpNo);
715   return false;
716 }
717
718
719
720 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
721 /// AT&T syntax to the current output stream.
722 ///
723 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
724   ++EmittedInsts;
725
726   processDebugLoc(MI->getDebugLoc());
727   
728   printInstructionThroughMCStreamer(MI);
729   
730   if (VerboseAsm && !MI->getDebugLoc().isUnknown())
731     EmitComments(*MI);
732   O << '\n';
733 }
734
735 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
736   const TargetData *TD = TM.getTargetData();
737
738   if (!GVar->hasInitializer())
739     return;   // External global require no code
740
741   // Check to see if this is a special global used by LLVM, if so, emit it.
742   if (EmitSpecialLLVMGlobal(GVar)) {
743     if (Subtarget->isTargetDarwin() &&
744         TM.getRelocationModel() == Reloc::Static) {
745       if (GVar->getName() == "llvm.global_ctors")
746         O << ".reference .constructors_used\n";
747       else if (GVar->getName() == "llvm.global_dtors")
748         O << ".reference .destructors_used\n";
749     }
750     return;
751   }
752
753   std::string name = Mang->getMangledName(GVar);
754   Constant *C = GVar->getInitializer();
755   const Type *Type = C->getType();
756   unsigned Size = TD->getTypeAllocSize(Type);
757   unsigned Align = TD->getPreferredAlignmentLog(GVar);
758
759   printVisibility(name, GVar->getVisibility());
760
761   if (Subtarget->isTargetELF())
762     O << "\t.type\t" << name << ",@object\n";
763
764   
765   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
766   const MCSection *TheSection =
767     getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
768   OutStreamer.SwitchSection(TheSection);
769
770   // FIXME: get this stuff from section kind flags.
771   if (C->isNullValue() && !GVar->hasSection() &&
772       // Don't put things that should go in the cstring section into "comm".
773       !TheSection->getKind().isMergeableCString()) {
774     if (GVar->hasExternalLinkage()) {
775       if (const char *Directive = MAI->getZeroFillDirective()) {
776         O << "\t.globl " << name << '\n';
777         O << Directive << "__DATA, __common, " << name << ", "
778           << Size << ", " << Align << '\n';
779         return;
780       }
781     }
782
783     if (!GVar->isThreadLocal() &&
784         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
785       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
786
787       if (MAI->getLCOMMDirective() != NULL) {
788         if (GVar->hasLocalLinkage()) {
789           O << MAI->getLCOMMDirective() << name << ',' << Size;
790           if (Subtarget->isTargetDarwin())
791             O << ',' << Align;
792         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
793           O << "\t.globl " << name << '\n'
794             << MAI->getWeakDefDirective() << name << '\n';
795           EmitAlignment(Align, GVar);
796           O << name << ":";
797           if (VerboseAsm) {
798             O.PadToColumn(MAI->getCommentColumn());
799             O << MAI->getCommentString() << ' ';
800             WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
801           }
802           O << '\n';
803           EmitGlobalConstant(C);
804           return;
805         } else {
806           O << MAI->getCOMMDirective()  << name << ',' << Size;
807           if (MAI->getCOMMDirectiveTakesAlignment())
808             O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
809         }
810       } else {
811         if (!Subtarget->isTargetCygMing()) {
812           if (GVar->hasLocalLinkage())
813             O << "\t.local\t" << name << '\n';
814         }
815         O << MAI->getCOMMDirective()  << name << ',' << Size;
816         if (MAI->getCOMMDirectiveTakesAlignment())
817           O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
818       }
819       if (VerboseAsm) {
820         O.PadToColumn(MAI->getCommentColumn());
821         O << MAI->getCommentString() << ' ';
822         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
823       }
824       O << '\n';
825       return;
826     }
827   }
828
829   switch (GVar->getLinkage()) {
830   case GlobalValue::CommonLinkage:
831   case GlobalValue::LinkOnceAnyLinkage:
832   case GlobalValue::LinkOnceODRLinkage:
833   case GlobalValue::WeakAnyLinkage:
834   case GlobalValue::WeakODRLinkage:
835   case GlobalValue::LinkerPrivateLinkage:
836     if (Subtarget->isTargetDarwin()) {
837       O << "\t.globl " << name << '\n'
838         << MAI->getWeakDefDirective() << name << '\n';
839     } else if (Subtarget->isTargetCygMing()) {
840       O << "\t.globl\t" << name << "\n"
841            "\t.linkonce same_size\n";
842     } else {
843       O << "\t.weak\t" << name << '\n';
844     }
845     break;
846   case GlobalValue::DLLExportLinkage:
847   case GlobalValue::AppendingLinkage:
848     // FIXME: appending linkage variables should go into a section of
849     // their name or something.  For now, just emit them as external.
850   case GlobalValue::ExternalLinkage:
851     // If external or appending, declare as a global symbol
852     O << "\t.globl " << name << '\n';
853     // FALL THROUGH
854   case GlobalValue::PrivateLinkage:
855   case GlobalValue::InternalLinkage:
856      break;
857   default:
858     llvm_unreachable("Unknown linkage type!");
859   }
860
861   EmitAlignment(Align, GVar);
862   O << name << ":";
863   if (VerboseAsm){
864     O.PadToColumn(MAI->getCommentColumn());
865     O << MAI->getCommentString() << ' ';
866     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
867   }
868   O << '\n';
869
870   EmitGlobalConstant(C);
871
872   if (MAI->hasDotTypeDotSizeDirective())
873     O << "\t.size\t" << name << ", " << Size << '\n';
874 }
875
876 static int SortSymbolPair(const void *LHS, const void *RHS) {
877   MCSymbol *LHSS = ((const std::pair<MCSymbol*, MCSymbol*>*)LHS)->first;
878   MCSymbol *RHSS = ((const std::pair<MCSymbol*, MCSymbol*>*)RHS)->first;
879   return LHSS->getName().compare(RHSS->getName());
880 }
881
882 /// GetSortedStubs - Return the entries from a DenseMap in a deterministic
883 /// sorted orer.
884 static std::vector<std::pair<MCSymbol*, MCSymbol*> >
885 GetSortedStubs(const DenseMap<MCSymbol*, MCSymbol*> &Map) {
886   assert(!Map.empty());
887   std::vector<std::pair<MCSymbol*, MCSymbol*> > List(Map.begin(), Map.end());
888   qsort(&List[0], List.size(), sizeof(List[0]), SortSymbolPair);
889   return List;
890 }
891
892 bool X86ATTAsmPrinter::doFinalization(Module &M) {
893   // Print out module-level global variables here.
894   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
895        I != E; ++I) {
896     if (I->hasDLLExportLinkage())
897       DLLExportedGVs.insert(Mang->getMangledName(I));
898   }
899
900   if (Subtarget->isTargetDarwin()) {
901     // All darwin targets use mach-o.
902     TargetLoweringObjectFileMachO &TLOFMacho = 
903       static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
904     
905     // Add the (possibly multiple) personalities to the set of global value
906     // stubs.  Only referenced functions get into the Personalities list.
907     if (MAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
908       const std::vector<Function*> &Personalities = MMI->getPersonalities();
909       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
910         if (Personalities[i] == 0)
911           continue;
912         
913         SmallString<128> Name;
914         Mang->getNameWithPrefix(Name, Personalities[i], true /*private label*/);
915         Name += "$non_lazy_ptr";
916         MCSymbol *NLPName = OutContext.GetOrCreateSymbol(Name.str());
917
918         MCSymbol *&StubName = GVStubs[NLPName];
919         if (StubName != 0) continue;
920         
921
922         Name.clear();
923         Mang->getNameWithPrefix(Name, Personalities[i], false);
924         StubName = OutContext.GetOrCreateSymbol(Name.str());
925       }
926     }
927
928     // Output stubs for dynamically-linked functions
929     if (!FnStubs.empty()) {
930       const MCSection *TheSection = 
931         TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
932                                   MCSectionMachO::S_SYMBOL_STUBS |
933                                   MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
934                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
935                                   5, SectionKind::getMetadata());
936       OutStreamer.SwitchSection(TheSection);
937
938       std::vector<std::pair<MCSymbol*, MCSymbol*> > Stubs
939         = GetSortedStubs(FnStubs);
940       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
941         Stubs[i].first->print(O, MAI);
942         O << ":\n" << "\t.indirect_symbol ";
943         // Get the MCSymbol without the $stub suffix.
944         Stubs[i].second->print(O, MAI);
945         O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
946       }
947       O << '\n';
948     }
949
950     // Output stubs for external and common global variables.
951     if (!GVStubs.empty()) {
952       const MCSection *TheSection = 
953         TLOFMacho.getMachOSection("__IMPORT", "__pointers",
954                                   MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
955                                   SectionKind::getMetadata());
956       OutStreamer.SwitchSection(TheSection);
957
958       std::vector<std::pair<MCSymbol*, MCSymbol*> > Stubs
959         = GetSortedStubs(GVStubs);
960       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
961         Stubs[i].first->print(O, MAI);
962         O << ":\n\t.indirect_symbol ";
963         Stubs[i].second->print(O, MAI);
964         O << "\n\t.long\t0\n";
965       }
966     }
967
968     if (!HiddenGVStubs.empty()) {
969       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
970       EmitAlignment(2);
971
972       std::vector<std::pair<MCSymbol*, MCSymbol*> > Stubs
973         = GetSortedStubs(HiddenGVStubs);
974       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
975         Stubs[i].first->print(O, MAI);
976         O << ":\n" << MAI->getData32bitsDirective();
977         Stubs[i].second->print(O, MAI);
978         O << '\n';
979       }
980     }
981
982     // Funny Darwin hack: This flag tells the linker that no global symbols
983     // contain code that falls through to other global symbols (e.g. the obvious
984     // implementation of multiple entry points).  If this doesn't occur, the
985     // linker can safely perform dead code stripping.  Since LLVM never
986     // generates code that does this, it is always safe to set.
987     O << "\t.subsections_via_symbols\n";
988   } else if (Subtarget->isTargetCygMing()) {
989     // Emit type information for external functions
990     for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
991          i != e; ++i) {
992       O << "\t.def\t " << i->getKeyData()
993         << ";\t.scl\t" << COFF::C_EXT
994         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
995         << ";\t.endef\n";
996     }
997   }
998   
999   
1000   // Output linker support code for dllexported globals on windows.
1001   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
1002     // dllexport symbols only exist on coff targets.
1003     TargetLoweringObjectFileCOFF &TLOFMacho = 
1004       static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
1005     
1006     OutStreamer.SwitchSection(TLOFMacho.getCOFFSection(".section .drectve",true,
1007                                                  SectionKind::getMetadata()));
1008   
1009     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1010          e = DLLExportedGVs.end(); i != e; ++i)
1011       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1012   
1013     for (StringSet<>::iterator i = DLLExportedFns.begin(),
1014          e = DLLExportedFns.end();
1015          i != e; ++i)
1016       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1017   }
1018   
1019   // Do common shutdown.
1020   return AsmPrinter::doFinalization(M);
1021 }
1022