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