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