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