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