Reduce code duplication on the TLS implementation.
[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           O << "@TLSGD"; // 64 bit intial exec not implemented
459         else
460           O << "@INDNTPOFF";
461         break;
462       case TLSModel::LocalExec:
463         if (Subtarget->is64Bit())
464           O << "@TLSGD"; // 64 bit local exec not implemented
465         else
466           O << "@NTPOFF";
467         break;
468       default:
469         assert (0 && "Unknown TLS model");
470       }
471     } else if (isMemOp) {
472       if (shouldPrintGOT(TM, Subtarget)) {
473         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
474           O << "@GOT";
475         else
476           O << "@GOTOFF";
477       } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel) {
478         if (TM.getRelocationModel() != Reloc::Static) {
479           if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
480             O << "@GOTPCREL";
481
482           if (needCloseParen) {
483             needCloseParen = false;
484             O << ')';
485           }
486         }
487
488         // Use rip when possible to reduce code size, except when
489         // index or base register are also part of the address. e.g.
490         // foo(%rip)(%rcx,%rax,4) is not legal
491         O << "(%rip)";
492       }
493     }
494
495     if (needCloseParen)
496       O << ')';
497
498     return;
499   }
500   case MachineOperand::MO_ExternalSymbol: {
501     bool isCallOp = Modifier && !strcmp(Modifier, "call");
502     bool needCloseParen = false;
503     std::string Name(TAI->getGlobalPrefix());
504     Name += MO.getSymbolName();
505     // Print function stub suffix unless it's Mac OS X 10.5 and up.
506     if (isCallOp && shouldPrintStub(TM, Subtarget) && 
507         !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
508       FnStubs.insert(Name);
509       printSuffixedName(Name, "$stub");
510       return;
511     }
512     if (!isCallOp)
513       O << '$';
514     else if (Name[0] == '$') {
515       // The name begins with a dollar-sign. In order to avoid having it look
516       // like an integer immediate to the assembler, enclose it in parens.
517       O << '(';
518       needCloseParen = true;
519     }
520
521     O << Name;
522
523     if (shouldPrintPLT(TM, Subtarget)) {
524       std::string GOTName(TAI->getGlobalPrefix());
525       GOTName+="_GLOBAL_OFFSET_TABLE_";
526       if (Name == GOTName)
527         // HACK! Emit extra offset to PC during printing GOT offset to
528         // compensate for the size of popl instruction. The resulting code
529         // should look like:
530         //   call .piclabel
531         // piclabel:
532         //   popl %some_register
533         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
534         O << " + [.-"
535           << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
536
537       if (isCallOp)
538         O << "@PLT";
539     }
540
541     if (needCloseParen)
542       O << ')';
543
544     if (!isCallOp && Subtarget->isPICStyleRIPRel())
545       O << "(%rip)";
546
547     return;
548   }
549   default:
550     O << "<unknown operand type>"; return;
551   }
552 }
553
554 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
555   unsigned char value = MI->getOperand(Op).getImm();
556   assert(value <= 7 && "Invalid ssecc argument!");
557   switch (value) {
558   case 0: O << "eq"; break;
559   case 1: O << "lt"; break;
560   case 2: O << "le"; break;
561   case 3: O << "unord"; break;
562   case 4: O << "neq"; break;
563   case 5: O << "nlt"; break;
564   case 6: O << "nle"; break;
565   case 7: O << "ord"; break;
566   }
567 }
568
569 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
570                                             const char *Modifier){
571   MachineOperand BaseReg  = MI->getOperand(Op);
572   MachineOperand IndexReg = MI->getOperand(Op+2);
573   const MachineOperand &DispSpec = MI->getOperand(Op+3);
574
575   bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
576   if (DispSpec.isGlobal() ||
577       DispSpec.isCPI() ||
578       DispSpec.isJTI()) {
579     printOperand(MI, Op+3, "mem", NotRIPRel);
580   } else {
581     int DispVal = DispSpec.getImm();
582     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
583       O << DispVal;
584   }
585
586   if (IndexReg.getReg() || BaseReg.getReg()) {
587     unsigned ScaleVal = MI->getOperand(Op+1).getImm();
588     unsigned BaseRegOperand = 0, IndexRegOperand = 2;
589
590     // There are cases where we can end up with ESP/RSP in the indexreg slot.
591     // If this happens, swap the base/index register to support assemblers that
592     // don't work when the index is *SP.
593     if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
594       assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
595       std::swap(BaseReg, IndexReg);
596       std::swap(BaseRegOperand, IndexRegOperand);
597     }
598
599     O << '(';
600     if (BaseReg.getReg())
601       printOperand(MI, Op+BaseRegOperand, Modifier);
602
603     if (IndexReg.getReg()) {
604       O << ',';
605       printOperand(MI, Op+IndexRegOperand, Modifier);
606       if (ScaleVal != 1)
607         O << ',' << ScaleVal;
608     }
609     O << ')';
610   }
611 }
612
613 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
614                                          const char *Modifier){
615   assert(isMem(MI, Op) && "Invalid memory reference!");
616   MachineOperand Segment = MI->getOperand(Op+4);
617   if (Segment.getReg()) {
618       printOperand(MI, Op+4, Modifier);
619       O << ':';
620     }
621   printLeaMemReference(MI, Op, Modifier);
622 }
623
624 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
625                                            const MachineBasicBlock *MBB) const {
626   if (!TAI->getSetDirective())
627     return;
628
629   // We don't need .set machinery if we have GOT-style relocations
630   if (Subtarget->isPICStyleGOT())
631     return;
632
633   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
634     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
635   printBasicBlockLabel(MBB, false, false, false);
636   if (Subtarget->isPICStyleRIPRel())
637     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
638       << '_' << uid << '\n';
639   else
640     O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
641 }
642
643 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
644   std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
645   O << label << '\n' << label << ':';
646 }
647
648
649 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
650                                               const MachineBasicBlock *MBB,
651                                               unsigned uid) const
652 {
653   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
654     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
655
656   O << JTEntryDirective << ' ';
657
658   if (TM.getRelocationModel() == Reloc::PIC_) {
659     if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
660       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
661         << '_' << uid << "_set_" << MBB->getNumber();
662     } else if (Subtarget->isPICStyleGOT()) {
663       printBasicBlockLabel(MBB, false, false, false);
664       O << "@GOTOFF";
665     } else
666       assert(0 && "Don't know how to print MBB label for this PIC mode");
667   } else
668     printBasicBlockLabel(MBB, false, false, false);
669 }
670
671 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
672                                          const char Mode) {
673   unsigned Reg = MO.getReg();
674   switch (Mode) {
675   default: return true;  // Unknown mode.
676   case 'b': // Print QImode register
677     Reg = getX86SubSuperRegister(Reg, MVT::i8);
678     break;
679   case 'h': // Print QImode high register
680     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
681     break;
682   case 'w': // Print HImode register
683     Reg = getX86SubSuperRegister(Reg, MVT::i16);
684     break;
685   case 'k': // Print SImode register
686     Reg = getX86SubSuperRegister(Reg, MVT::i32);
687     break;
688   case 'q': // Print DImode register
689     Reg = getX86SubSuperRegister(Reg, MVT::i64);
690     break;
691   }
692
693   O << '%'<< TRI->getAsmName(Reg);
694   return false;
695 }
696
697 /// PrintAsmOperand - Print out an operand for an inline asm expression.
698 ///
699 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
700                                        unsigned AsmVariant,
701                                        const char *ExtraCode) {
702   // Does this asm operand have a single letter operand modifier?
703   if (ExtraCode && ExtraCode[0]) {
704     if (ExtraCode[1] != 0) return true; // Unknown modifier.
705
706     switch (ExtraCode[0]) {
707     default: return true;  // Unknown modifier.
708     case 'c': // Don't print "$" before a global var name or constant.
709       printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
710       return false;
711     case 'b': // Print QImode register
712     case 'h': // Print QImode high register
713     case 'w': // Print HImode register
714     case 'k': // Print SImode register
715     case 'q': // Print DImode register
716       if (MI->getOperand(OpNo).isReg())
717         return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
718       printOperand(MI, OpNo);
719       return false;
720
721     case 'P': // Don't print @PLT, but do print as memory.
722       printOperand(MI, OpNo, "mem");
723       return false;
724     }
725   }
726
727   printOperand(MI, OpNo);
728   return false;
729 }
730
731 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
732                                              unsigned OpNo,
733                                              unsigned AsmVariant,
734                                              const char *ExtraCode) {
735   if (ExtraCode && ExtraCode[0]) {
736     if (ExtraCode[1] != 0) return true; // Unknown modifier.
737
738     switch (ExtraCode[0]) {
739     default: return true;  // Unknown modifier.
740     case 'b': // Print QImode register
741     case 'h': // Print QImode high register
742     case 'w': // Print HImode register
743     case 'k': // Print SImode register
744     case 'q': // Print SImode register
745       // These only apply to registers, ignore on mem.
746       break;
747     case 'P': // Don't print @PLT, but do print as memory.
748       printOperand(MI, OpNo, "mem");
749       return false;
750     }
751   }
752   printMemReference(MI, OpNo);
753   return false;
754 }
755
756 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
757 /// AT&T syntax to the current output stream.
758 ///
759 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
760   ++EmittedInsts;
761
762   // Call the autogenerated instruction printer routines.
763   printInstruction(MI);
764 }
765
766 /// doInitialization
767 bool X86ATTAsmPrinter::doInitialization(Module &M) {
768
769   bool Result = AsmPrinter::doInitialization(M);
770
771   if (TAI->doesSupportDebugInformation()) {
772     // Let PassManager know we need debug information and relay
773     // the MachineModuleInfo address on to DwarfWriter.
774     // AsmPrinter::doInitialization did this analysis.
775     MMI = getAnalysisIfAvailable<MachineModuleInfo>();
776     DW = getAnalysisIfAvailable<DwarfWriter>();
777     DW->BeginModule(&M, MMI, O, this, TAI);
778   }
779
780   // Darwin wants symbols to be quoted if they have complex names.
781   if (Subtarget->isTargetDarwin())
782     Mang->setUseQuotes(true);
783
784   return Result;
785 }
786
787
788 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
789   const TargetData *TD = TM.getTargetData();
790
791   if (!GVar->hasInitializer())
792     return;   // External global require no code
793
794   // Check to see if this is a special global used by LLVM, if so, emit it.
795   if (EmitSpecialLLVMGlobal(GVar)) {
796     if (Subtarget->isTargetDarwin() &&
797         TM.getRelocationModel() == Reloc::Static) {
798       if (GVar->getName() == "llvm.global_ctors")
799         O << ".reference .constructors_used\n";
800       else if (GVar->getName() == "llvm.global_dtors")
801         O << ".reference .destructors_used\n";
802     }
803     return;
804   }
805
806   std::string name = Mang->getValueName(GVar);
807   Constant *C = GVar->getInitializer();
808   const Type *Type = C->getType();
809   unsigned Size = TD->getTypePaddedSize(Type);
810   unsigned Align = TD->getPreferredAlignmentLog(GVar);
811
812   printVisibility(name, GVar->getVisibility());
813
814   if (Subtarget->isTargetELF())
815     O << "\t.type\t" << name << ",@object\n";
816
817   SwitchToSection(TAI->SectionForGlobal(GVar));
818
819   if (C->isNullValue() && !GVar->hasSection() &&
820       !(Subtarget->isTargetDarwin() &&
821         TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
822     // FIXME: This seems to be pretty darwin-specific
823     if (GVar->hasExternalLinkage()) {
824       if (const char *Directive = TAI->getZeroFillDirective()) {
825         O << "\t.globl " << name << '\n';
826         O << Directive << "__DATA, __common, " << name << ", "
827           << Size << ", " << Align << '\n';
828         return;
829       }
830     }
831
832     if (!GVar->isThreadLocal() &&
833         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
834       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
835
836       if (TAI->getLCOMMDirective() != NULL) {
837         if (GVar->hasLocalLinkage()) {
838           O << TAI->getLCOMMDirective() << name << ',' << Size;
839           if (Subtarget->isTargetDarwin())
840             O << ',' << Align;
841         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
842           O << "\t.globl " << name << '\n'
843             << TAI->getWeakDefDirective() << name << '\n';
844           EmitAlignment(Align, GVar);
845           O << name << ":";
846           if (VerboseAsm) {
847             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
848             PrintUnmangledNameSafely(GVar, O);
849           }
850           O << '\n';
851           EmitGlobalConstant(C);
852           return;
853         } else {
854           O << TAI->getCOMMDirective()  << name << ',' << Size;
855           if (TAI->getCOMMDirectiveTakesAlignment())
856             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
857         }
858       } else {
859         if (!Subtarget->isTargetCygMing()) {
860           if (GVar->hasLocalLinkage())
861             O << "\t.local\t" << name << '\n';
862         }
863         O << TAI->getCOMMDirective()  << name << ',' << Size;
864         if (TAI->getCOMMDirectiveTakesAlignment())
865           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
866       }
867       if (VerboseAsm) {
868         O << "\t\t" << TAI->getCommentString() << ' ';
869         PrintUnmangledNameSafely(GVar, O);
870       }
871       O << '\n';
872       return;
873     }
874   }
875
876   switch (GVar->getLinkage()) {
877   case GlobalValue::CommonLinkage:
878   case GlobalValue::LinkOnceAnyLinkage:
879   case GlobalValue::LinkOnceODRLinkage:
880   case GlobalValue::WeakAnyLinkage:
881   case GlobalValue::WeakODRLinkage:
882     if (Subtarget->isTargetDarwin()) {
883       O << "\t.globl " << name << '\n'
884         << TAI->getWeakDefDirective() << name << '\n';
885     } else if (Subtarget->isTargetCygMing()) {
886       O << "\t.globl\t" << name << "\n"
887            "\t.linkonce same_size\n";
888     } else {
889       O << "\t.weak\t" << name << '\n';
890     }
891     break;
892   case GlobalValue::DLLExportLinkage:
893   case GlobalValue::AppendingLinkage:
894     // FIXME: appending linkage variables should go into a section of
895     // their name or something.  For now, just emit them as external.
896   case GlobalValue::ExternalLinkage:
897     // If external or appending, declare as a global symbol
898     O << "\t.globl " << name << '\n';
899     // FALL THROUGH
900   case GlobalValue::PrivateLinkage:
901   case GlobalValue::InternalLinkage:
902      break;
903   default:
904     assert(0 && "Unknown linkage type!");
905   }
906
907   EmitAlignment(Align, GVar);
908   O << name << ":";
909   if (VerboseAsm){
910     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
911     PrintUnmangledNameSafely(GVar, O);
912   }
913   O << '\n';
914   if (TAI->hasDotTypeDotSizeDirective())
915     O << "\t.size\t" << name << ", " << Size << '\n';
916
917   EmitGlobalConstant(C);
918 }
919
920 /// printGVStub - Print stub for a global value.
921 ///
922 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
923   printSuffixedName(GV, "$non_lazy_ptr", Prefix);
924   O << ":\n\t.indirect_symbol ";
925   if (Prefix) O << Prefix;
926   O << GV << "\n\t.long\t0\n";
927 }
928
929 /// printHiddenGVStub - Print stub for a hidden global value.
930 ///
931 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV, const char *Prefix) {
932   EmitAlignment(2);
933   printSuffixedName(GV, "$non_lazy_ptr", Prefix);
934   if (Prefix) O << Prefix;
935   O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
936 }
937
938
939 bool X86ATTAsmPrinter::doFinalization(Module &M) {
940   // Print out module-level global variables here.
941   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
942        I != E; ++I) {
943     printModuleLevelGV(I);
944
945     if (I->hasDLLExportLinkage())
946       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
947
948     // If the global is a extern weak symbol, remember to emit the weak
949     // reference!
950     // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
951     // not used. But currently it's the only way to deal with extern weak
952     // initializers hidden deep inside constant expressions.
953     if (I->hasExternalWeakLinkage())
954       ExtWeakSymbols.insert(I);
955   }
956
957   for (Module::const_iterator I = M.begin(), E = M.end();
958        I != E; ++I) {
959     // If the global is a extern weak symbol, remember to emit the weak
960     // reference!
961     // FIXME: This is rather hacky, since we'll emit references to ALL weak stuff,
962     // not used. But currently it's the only way to deal with extern weak
963     // initializers hidden deep inside constant expressions.
964     if (I->hasExternalWeakLinkage())
965       ExtWeakSymbols.insert(I);
966   }
967
968   // Output linker support code for dllexported globals
969   if (!DLLExportedGVs.empty())
970     SwitchToDataSection(".section .drectve");
971
972   for (StringSet<>::iterator i = DLLExportedGVs.begin(),
973          e = DLLExportedGVs.end();
974          i != e; ++i)
975     O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
976
977   if (!DLLExportedFns.empty()) {
978     SwitchToDataSection(".section .drectve");
979   }
980
981   for (StringSet<>::iterator i = DLLExportedFns.begin(),
982          e = DLLExportedFns.end();
983          i != e; ++i)
984     O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
985
986   if (Subtarget->isTargetDarwin()) {
987     SwitchToDataSection("");
988
989     // Output stubs for dynamically-linked functions
990     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
991          i != e; ++i) {
992       SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
993                           "self_modifying_code+pure_instructions,5", 0);
994       const char *p = i->getKeyData();
995       printSuffixedName(p, "$stub");
996       O << ":\n"
997            "\t.indirect_symbol " << p << "\n"
998            "\thlt ; hlt ; hlt ; hlt ; hlt\n";
999     }
1000
1001     O << '\n';
1002
1003     // Print global value stubs.
1004     bool InStubSection = false;
1005     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1006       // Add the (possibly multiple) personalities to the set of global values.
1007       // Only referenced functions get into the Personalities list.
1008       const std::vector<Function *>& Personalities = MMI->getPersonalities();
1009       for (std::vector<Function *>::const_iterator I = Personalities.begin(),
1010              E = Personalities.end(); I != E; ++I) {
1011         if (!*I)
1012           continue;
1013         if (!InStubSection) {
1014           SwitchToDataSection(
1015                      "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1016           InStubSection = true;
1017         }
1018         printGVStub((*I)->getNameStart(), "_");
1019       }
1020     }
1021
1022     // Output stubs for external and common global variables.
1023     if (!InStubSection && !GVStubs.empty())
1024       SwitchToDataSection(
1025                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1026     for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1027          i != e; ++i)
1028       printGVStub(i->getKeyData());
1029
1030     if (!HiddenGVStubs.empty()) {
1031       SwitchToSection(TAI->getDataSection());
1032       for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1033            i != e; ++i)
1034         printHiddenGVStub(i->getKeyData());
1035     }
1036
1037     // Emit final debug information.
1038     DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1039     DW->EndModule();
1040
1041     // Funny Darwin hack: This flag tells the linker that no global symbols
1042     // contain code that falls through to other global symbols (e.g. the obvious
1043     // implementation of multiple entry points).  If this doesn't occur, the
1044     // linker can safely perform dead code stripping.  Since LLVM never
1045     // generates code that does this, it is always safe to set.
1046     O << "\t.subsections_via_symbols\n";
1047   } else if (Subtarget->isTargetCygMing()) {
1048     // Emit type information for external functions
1049     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1050          i != e; ++i) {
1051       O << "\t.def\t " << i->getKeyData()
1052         << ";\t.scl\t" << COFF::C_EXT
1053         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1054         << ";\t.endef\n";
1055     }
1056
1057     // Emit final debug information.
1058     DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1059     DW->EndModule();
1060   } else if (Subtarget->isTargetELF()) {
1061     // Emit final debug information.
1062     DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
1063     DW->EndModule();
1064   }
1065
1066   return AsmPrinter::doFinalization(M);
1067 }
1068
1069 // Include the auto-generated portion of the assembly writer.
1070 #include "X86GenAsmWriter.inc"