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