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