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