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