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