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