turn on -experimental-asm-printer for x86 / AT&T by default.
[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 "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Type.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/TargetLoweringObjectFile.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/ADT/Statistic.h"
41 using namespace llvm;
42
43 STATISTIC(EmittedInsts, "Number of machine instrs printed");
44
45 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
46                                    cl::Hidden, cl::init(true));
47
48 //===----------------------------------------------------------------------===//
49 // Primitive Helper Functions.
50 //===----------------------------------------------------------------------===//
51
52 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
53   // FIXME: the actual label generated doesn't matter here!  Just mangle in
54   // something unique (the function number) with Private prefix.
55   if (Subtarget->isTargetDarwin())
56     O << "\"L" << getFunctionNumber() << "$pb\"";
57   else {
58     assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
59     O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
60   }
61 }
62
63 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
64                                                     const TargetData *TD) {
65   X86MachineFunctionInfo Info;
66   uint64_t Size = 0;
67
68   switch (F->getCallingConv()) {
69   case CallingConv::X86_StdCall:
70     Info.setDecorationStyle(StdCall);
71     break;
72   case CallingConv::X86_FastCall:
73     Info.setDecorationStyle(FastCall);
74     break;
75   default:
76     return Info;
77   }
78
79   unsigned argNum = 1;
80   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
81        AI != AE; ++AI, ++argNum) {
82     const Type* Ty = AI->getType();
83
84     // 'Dereference' type in case of byval parameter attribute
85     if (F->paramHasAttr(argNum, Attribute::ByVal))
86       Ty = cast<PointerType>(Ty)->getElementType();
87
88     // Size should be aligned to DWORD boundary
89     Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
90   }
91
92   // We're not supporting tooooo huge arguments :)
93   Info.setBytesToPopOnReturn((unsigned int)Size);
94   return Info;
95 }
96
97 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
98 /// various name decorations for Cygwin and MingW.
99 void X86ATTAsmPrinter::DecorateCygMingName(SmallVectorImpl<char> &Name,
100                                            const GlobalValue *GV) {
101   assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
102   
103   const Function *F = dyn_cast<Function>(GV);
104   if (!F) return;
105   
106   // Save function name for later type emission.
107   if (F->isDeclaration())
108     CygMingStubs.insert(StringRef(Name.data(), Name.size()));
109   
110   // We don't want to decorate non-stdcall or non-fastcall functions right now
111   CallingConv::ID CC = F->getCallingConv();
112   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
113     return;
114   
115   
116   const X86MachineFunctionInfo *Info;
117   
118   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
119   if (info_item == FunctionInfoMap.end()) {
120     // Calculate apropriate function info and populate map
121     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
122     Info = &FunctionInfoMap[F];
123   } else {
124     Info = &info_item->second;
125   }
126   
127   if (Info->getDecorationStyle() == None) return;
128   const FunctionType *FT = F->getFunctionType();
129
130   // "Pure" variadic functions do not receive @0 suffix.
131   if (!FT->isVarArg() || FT->getNumParams() == 0 ||
132       (FT->getNumParams() == 1 && F->hasStructRetAttr()))
133     raw_svector_ostream(Name) << '@' << Info->getBytesToPopOnReturn();
134   
135   if (Info->getDecorationStyle() == FastCall) {
136     if (Name[0] == '_')
137       Name[0] = '@';
138     else
139       Name.insert(Name.begin(), '@');
140   }    
141 }
142
143 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
144 /// various name decorations for Cygwin and MingW.
145 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
146                                            const GlobalValue *GV) {
147   SmallString<128> NameStr(Name.begin(), Name.end());
148   DecorateCygMingName(NameStr, GV);
149   Name.assign(NameStr.begin(), NameStr.end());
150 }
151
152 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
153   unsigned FnAlign = MF.getAlignment();
154   const Function *F = MF.getFunction();
155
156   if (Subtarget->isTargetCygMing())
157     DecorateCygMingName(CurrentFnName, F);
158
159   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
160   EmitAlignment(FnAlign, F);
161
162   switch (F->getLinkage()) {
163   default: llvm_unreachable("Unknown linkage type!");
164   case Function::InternalLinkage:  // Symbols default to internal.
165   case Function::PrivateLinkage:
166     break;
167   case Function::DLLExportLinkage:
168   case Function::ExternalLinkage:
169     O << "\t.globl\t" << CurrentFnName << '\n';
170     break;
171   case Function::LinkerPrivateLinkage:
172   case Function::LinkOnceAnyLinkage:
173   case Function::LinkOnceODRLinkage:
174   case Function::WeakAnyLinkage:
175   case Function::WeakODRLinkage:
176     if (Subtarget->isTargetDarwin()) {
177       O << "\t.globl\t" << CurrentFnName << '\n';
178       O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
179     } else if (Subtarget->isTargetCygMing()) {
180       O << "\t.globl\t" << CurrentFnName << "\n"
181            "\t.linkonce discard\n";
182     } else {
183       O << "\t.weak\t" << CurrentFnName << '\n';
184     }
185     break;
186   }
187
188   printVisibility(CurrentFnName, F->getVisibility());
189
190   if (Subtarget->isTargetELF())
191     O << "\t.type\t" << CurrentFnName << ",@function\n";
192   else if (Subtarget->isTargetCygMing()) {
193     O << "\t.def\t " << CurrentFnName
194       << ";\t.scl\t" <<
195       (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
196       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
197       << ";\t.endef\n";
198   }
199
200   O << CurrentFnName << ':';
201   if (VerboseAsm) {
202     O.PadToColumn(MAI->getCommentColumn());
203     O << MAI->getCommentString() << ' ';
204     WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
205   }
206   O << '\n';
207
208   // Add some workaround for linkonce linkage on Cygwin\MinGW
209   if (Subtarget->isTargetCygMing() &&
210       (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
211     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
212 }
213
214 /// runOnMachineFunction - This uses the printMachineInstruction()
215 /// method to print assembly for each instruction.
216 ///
217 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
218   const Function *F = MF.getFunction();
219   this->MF = &MF;
220   CallingConv::ID CC = F->getCallingConv();
221
222   SetupMachineFunction(MF);
223   O << "\n\n";
224
225   // Populate function information map.  Actually, We don't want to populate
226   // non-stdcall or non-fastcall functions' information right now.
227   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
228     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
229
230   // Print out constants referenced by the function
231   EmitConstantPool(MF.getConstantPool());
232
233   if (F->hasDLLExportLinkage())
234     DLLExportedFns.insert(Mang->getMangledName(F));
235
236   // Print the 'header' of function
237   emitFunctionHeader(MF);
238
239   // Emit pre-function debug and/or EH information.
240   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
241     DW->BeginFunction(&MF);
242
243   // Print out code for the function.
244   bool hasAnyRealCode = false;
245   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
246        I != E; ++I) {
247     // Print a label for the basic block.
248     if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
249       // This is an entry block or a block that's only reachable via a
250       // fallthrough edge. In non-VerboseAsm mode, don't print the label.
251     } else {
252       printBasicBlockLabel(I, true, true, VerboseAsm);
253       O << '\n';
254     }
255     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
256          II != IE; ++II) {
257       // Print the assembly for the instruction.
258       if (!II->isLabel())
259         hasAnyRealCode = true;
260       printMachineInstruction(II);
261     }
262   }
263
264   if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
265     // If the function is empty, then we need to emit *something*. Otherwise,
266     // the function's label might be associated with something that it wasn't
267     // meant to be associated with. We emit a noop in this situation.
268     // We are assuming inline asms are code.
269     O << "\tnop\n";
270   }
271
272   if (MAI->hasDotTypeDotSizeDirective())
273     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
274
275   // Emit post-function debug information.
276   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
277     DW->EndFunction(&MF);
278
279   // Print out jump tables referenced by the function.
280   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
281
282   // We didn't modify anything.
283   return false;
284 }
285
286 /// printSymbolOperand - Print a raw symbol reference operand.  This handles
287 /// jump tables, constant pools, global address and external symbols, all of
288 /// which print to a label with various suffixes for relocation types etc.
289 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
290   switch (MO.getType()) {
291   default: llvm_unreachable("unknown symbol type!");
292   case MachineOperand::MO_JumpTableIndex:
293     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
294       << MO.getIndex();
295     break;
296   case MachineOperand::MO_ConstantPoolIndex:
297     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
298       << MO.getIndex();
299     printOffset(MO.getOffset());
300     break;
301   case MachineOperand::MO_GlobalAddress: {
302     const GlobalValue *GV = MO.getGlobal();
303     
304     const char *Suffix = "";
305     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
306       Suffix = "$stub";
307     else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
308              MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
309              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
310       Suffix = "$non_lazy_ptr";
311     
312     std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
313     if (Subtarget->isTargetCygMing())
314       DecorateCygMingName(Name, GV);
315     
316     // Handle dllimport linkage.
317     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
318       Name = "__imp_" + Name;
319     
320     if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
321         MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
322       SmallString<128> NameStr;
323       Mang->getNameWithPrefix(NameStr, GV, true);
324       NameStr += "$non_lazy_ptr";
325       MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
326       MCSymbol *&StubSym = GVStubs[Sym];
327       if (StubSym == 0) {
328         NameStr.clear();
329         Mang->getNameWithPrefix(NameStr, GV, false);
330         StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
331       }
332     } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
333       SmallString<128> NameStr;
334       Mang->getNameWithPrefix(NameStr, GV, true);
335       NameStr += "$non_lazy_ptr";
336       MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
337       MCSymbol *&StubSym = HiddenGVStubs[Sym];
338       if (StubSym == 0) {
339         NameStr.clear();
340         Mang->getNameWithPrefix(NameStr, GV, false);
341         StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
342       }
343     } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
344       SmallString<128> NameStr;
345       Mang->getNameWithPrefix(NameStr, GV, true);
346       NameStr += "$stub";
347       MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
348       MCSymbol *&StubSym = FnStubs[Sym];
349       if (StubSym == 0) {
350         NameStr.clear();
351         Mang->getNameWithPrefix(NameStr, GV, false);
352         StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
353       }
354     }
355     
356     // If the name begins with a dollar-sign, enclose it in parens.  We do this
357     // to avoid having it look like an integer immediate to the assembler.
358     if (Name[0] == '$') 
359       O << '(' << Name << ')';
360     else
361       O << Name;
362     
363     printOffset(MO.getOffset());
364     break;
365   }
366   case MachineOperand::MO_ExternalSymbol: {
367     std::string Name = Mang->makeNameProper(MO.getSymbolName());
368     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
369       Name += "$stub";
370       MCSymbol *&StubSym = FnStubs[OutContext.GetOrCreateSymbol(Name)];
371       if (StubSym == 0) {
372         Name.erase(Name.end()-5, Name.end());
373         StubSym = OutContext.GetOrCreateSymbol(Name);
374       }
375     }
376     
377     // If the name begins with a dollar-sign, enclose it in parens.  We do this
378     // to avoid having it look like an integer immediate to the assembler.
379     if (Name[0] == '$') 
380       O << '(' << Name << ')';
381     else
382       O << Name;
383     break;
384   }
385   }
386   
387   switch (MO.getTargetFlags()) {
388   default:
389     llvm_unreachable("Unknown target flag on GV operand");
390   case X86II::MO_NO_FLAG:    // No flag.
391     break;
392   case X86II::MO_DARWIN_NONLAZY:
393   case X86II::MO_DLLIMPORT:
394   case X86II::MO_DARWIN_STUB:
395     // These affect the name of the symbol, not any suffix.
396     break;
397   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
398     O << " + [.-";
399     PrintPICBaseSymbol();
400     O << ']';
401     break;      
402   case X86II::MO_PIC_BASE_OFFSET:
403   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
404   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
405     O << '-';
406     PrintPICBaseSymbol();
407     break;
408   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
409   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
410   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
411   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
412   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
413   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
414   case X86II::MO_GOT:       O << "@GOT";       break;
415   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
416   case X86II::MO_PLT:       O << "@PLT";       break;
417   }
418 }
419
420 /// print_pcrel_imm - This is used to print an immediate value that ends up
421 /// being encoded as a pc-relative value.  These print slightly differently, for
422 /// example, a $ is not emitted.
423 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
424   const MachineOperand &MO = MI->getOperand(OpNo);
425   switch (MO.getType()) {
426   default: llvm_unreachable("Unknown pcrel immediate operand");
427   case MachineOperand::MO_Immediate:
428     O << MO.getImm();
429     return;
430   case MachineOperand::MO_MachineBasicBlock:
431     printBasicBlockLabel(MO.getMBB(), false, false, false);
432     return;
433   case MachineOperand::MO_GlobalAddress:
434   case MachineOperand::MO_ExternalSymbol:
435     printSymbolOperand(MO);
436     return;
437   }
438 }
439
440
441
442 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
443                                     const char *Modifier) {
444   const MachineOperand &MO = MI->getOperand(OpNo);
445   switch (MO.getType()) {
446   default: llvm_unreachable("unknown operand type!");
447   case MachineOperand::MO_Register: {
448     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
449            "Virtual registers should not make it this far!");
450     O << '%';
451     unsigned Reg = MO.getReg();
452     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
453       EVT VT = (strcmp(Modifier+6,"64") == 0) ?
454         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
455                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
456       Reg = getX86SubSuperRegister(Reg, VT);
457     }
458     O << TRI->getAsmName(Reg);
459     return;
460   }
461
462   case MachineOperand::MO_Immediate:
463     O << '$' << MO.getImm();
464     return;
465
466   case MachineOperand::MO_JumpTableIndex:
467   case MachineOperand::MO_ConstantPoolIndex:
468   case MachineOperand::MO_GlobalAddress: 
469   case MachineOperand::MO_ExternalSymbol: {
470     O << '$';
471     printSymbolOperand(MO);
472     break;
473   }
474   }
475 }
476
477 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
478   unsigned char value = MI->getOperand(Op).getImm();
479   assert(value <= 7 && "Invalid ssecc argument!");
480   switch (value) {
481   case 0: O << "eq"; break;
482   case 1: O << "lt"; break;
483   case 2: O << "le"; break;
484   case 3: O << "unord"; break;
485   case 4: O << "neq"; break;
486   case 5: O << "nlt"; break;
487   case 6: O << "nle"; break;
488   case 7: O << "ord"; break;
489   }
490 }
491
492 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
493                                             const char *Modifier) {
494   const MachineOperand &BaseReg  = MI->getOperand(Op);
495   const MachineOperand &IndexReg = MI->getOperand(Op+2);
496   const MachineOperand &DispSpec = MI->getOperand(Op+3);
497
498   // If we really don't want to print out (rip), don't.
499   bool HasBaseReg = BaseReg.getReg() != 0;
500   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
501       BaseReg.getReg() == X86::RIP)
502     HasBaseReg = false;
503   
504   // HasParenPart - True if we will print out the () part of the mem ref.
505   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
506   
507   if (DispSpec.isImm()) {
508     int DispVal = DispSpec.getImm();
509     if (DispVal || !HasParenPart)
510       O << DispVal;
511   } else {
512     assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
513            DispSpec.isJTI() || DispSpec.isSymbol());
514     printSymbolOperand(MI->getOperand(Op+3));
515   }
516
517   if (HasParenPart) {
518     assert(IndexReg.getReg() != X86::ESP &&
519            "X86 doesn't allow scaling by ESP");
520
521     O << '(';
522     if (HasBaseReg)
523       printOperand(MI, Op, Modifier);
524
525     if (IndexReg.getReg()) {
526       O << ',';
527       printOperand(MI, Op+2, Modifier);
528       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
529       if (ScaleVal != 1)
530         O << ',' << ScaleVal;
531     }
532     O << ')';
533   }
534 }
535
536 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
537                                          const char *Modifier) {
538   assert(isMem(MI, Op) && "Invalid memory reference!");
539   const MachineOperand &Segment = MI->getOperand(Op+4);
540   if (Segment.getReg()) {
541     printOperand(MI, Op+4, Modifier);
542     O << ':';
543   }
544   printLeaMemReference(MI, Op, Modifier);
545 }
546
547 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
548                                            const MachineBasicBlock *MBB) const {
549   if (!MAI->getSetDirective())
550     return;
551
552   // We don't need .set machinery if we have GOT-style relocations
553   if (Subtarget->isPICStyleGOT())
554     return;
555
556   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
557     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
558   printBasicBlockLabel(MBB, false, false, false);
559   if (Subtarget->isPICStyleRIPRel())
560     O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
561       << '_' << uid << '\n';
562   else {
563     O << '-';
564     PrintPICBaseSymbol();
565     O << '\n';
566   }
567 }
568
569
570 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
571   PrintPICBaseSymbol();
572   O << '\n';
573   PrintPICBaseSymbol();
574   O << ':';
575 }
576
577
578 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
579                                               const MachineBasicBlock *MBB,
580                                               unsigned uid) const {
581   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
582     MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
583
584   O << JTEntryDirective << ' ';
585
586   if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
587     O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
588       << '_' << uid << "_set_" << MBB->getNumber();
589   } else if (Subtarget->isPICStyleGOT()) {
590     printBasicBlockLabel(MBB, false, false, false);
591     O << "@GOTOFF";
592   } else
593     printBasicBlockLabel(MBB, false, false, false);
594 }
595
596 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
597   unsigned Reg = MO.getReg();
598   switch (Mode) {
599   default: return true;  // Unknown mode.
600   case 'b': // Print QImode register
601     Reg = getX86SubSuperRegister(Reg, MVT::i8);
602     break;
603   case 'h': // Print QImode high register
604     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
605     break;
606   case 'w': // Print HImode register
607     Reg = getX86SubSuperRegister(Reg, MVT::i16);
608     break;
609   case 'k': // Print SImode register
610     Reg = getX86SubSuperRegister(Reg, MVT::i32);
611     break;
612   case 'q': // Print DImode register
613     Reg = getX86SubSuperRegister(Reg, MVT::i64);
614     break;
615   }
616
617   O << '%'<< TRI->getAsmName(Reg);
618   return false;
619 }
620
621 /// PrintAsmOperand - Print out an operand for an inline asm expression.
622 ///
623 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
624                                        unsigned AsmVariant,
625                                        const char *ExtraCode) {
626   // Does this asm operand have a single letter operand modifier?
627   if (ExtraCode && ExtraCode[0]) {
628     if (ExtraCode[1] != 0) return true; // Unknown modifier.
629
630     const MachineOperand &MO = MI->getOperand(OpNo);
631     
632     switch (ExtraCode[0]) {
633     default: return true;  // Unknown modifier.
634     case 'a': // This is an address.  Currently only 'i' and 'r' are expected.
635       if (MO.isImm()) {
636         O << MO.getImm();
637         return false;
638       } 
639       if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
640         printSymbolOperand(MO);
641         return false;
642       }
643       if (MO.isReg()) {
644         O << '(';
645         printOperand(MI, OpNo);
646         O << ')';
647         return false;
648       }
649       return true;
650
651     case 'c': // Don't print "$" before a global var name or constant.
652       if (MO.isImm())
653         O << MO.getImm();
654       else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
655         printSymbolOperand(MO);
656       else
657         printOperand(MI, OpNo);
658       return false;
659
660     case 'A': // Print '*' before a register (it must be a register)
661       if (MO.isReg()) {
662         O << '*';
663         printOperand(MI, OpNo);
664         return false;
665       }
666       return true;
667
668     case 'b': // Print QImode register
669     case 'h': // Print QImode high register
670     case 'w': // Print HImode register
671     case 'k': // Print SImode register
672     case 'q': // Print DImode register
673       if (MO.isReg())
674         return printAsmMRegister(MO, ExtraCode[0]);
675       printOperand(MI, OpNo);
676       return false;
677
678     case 'P': // This is the operand of a call, treat specially.
679       print_pcrel_imm(MI, OpNo);
680       return false;
681
682     case 'n':  // Negate the immediate or print a '-' before the operand.
683       // Note: this is a temporary solution. It should be handled target
684       // independently as part of the 'MC' work.
685       if (MO.isImm()) {
686         O << -MO.getImm();
687         return false;
688       }
689       O << '-';
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       printMemReference(MI, OpNo, "no-rip");
715       return false;
716     }
717   }
718   printMemReference(MI, OpNo);
719   return false;
720 }
721
722
723
724 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
725 /// AT&T syntax to the current output stream.
726 ///
727 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
728   ++EmittedInsts;
729
730   processDebugLoc(MI->getDebugLoc());
731   
732   // Call the autogenerated instruction printer routines.
733   if (NewAsmPrinter)
734     printInstructionThroughMCStreamer(MI);
735   else
736     printInstruction(MI);
737   
738   if (VerboseAsm && !MI->getDebugLoc().isUnknown())
739     EmitComments(*MI);
740   O << '\n';
741 }
742
743 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
744   const TargetData *TD = TM.getTargetData();
745
746   if (!GVar->hasInitializer())
747     return;   // External global require no code
748
749   // Check to see if this is a special global used by LLVM, if so, emit it.
750   if (EmitSpecialLLVMGlobal(GVar)) {
751     if (Subtarget->isTargetDarwin() &&
752         TM.getRelocationModel() == Reloc::Static) {
753       if (GVar->getName() == "llvm.global_ctors")
754         O << ".reference .constructors_used\n";
755       else if (GVar->getName() == "llvm.global_dtors")
756         O << ".reference .destructors_used\n";
757     }
758     return;
759   }
760
761   std::string name = Mang->getMangledName(GVar);
762   Constant *C = GVar->getInitializer();
763   const Type *Type = C->getType();
764   unsigned Size = TD->getTypeAllocSize(Type);
765   unsigned Align = TD->getPreferredAlignmentLog(GVar);
766
767   printVisibility(name, GVar->getVisibility());
768
769   if (Subtarget->isTargetELF())
770     O << "\t.type\t" << name << ",@object\n";
771
772   
773   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
774   const MCSection *TheSection =
775     getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
776   OutStreamer.SwitchSection(TheSection);
777
778   // FIXME: get this stuff from section kind flags.
779   if (C->isNullValue() && !GVar->hasSection() &&
780       // Don't put things that should go in the cstring section into "comm".
781       !TheSection->getKind().isMergeableCString()) {
782     if (GVar->hasExternalLinkage()) {
783       if (const char *Directive = MAI->getZeroFillDirective()) {
784         O << "\t.globl " << name << '\n';
785         O << Directive << "__DATA, __common, " << name << ", "
786           << Size << ", " << Align << '\n';
787         return;
788       }
789     }
790
791     if (!GVar->isThreadLocal() &&
792         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
793       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
794
795       if (MAI->getLCOMMDirective() != NULL) {
796         if (GVar->hasLocalLinkage()) {
797           O << MAI->getLCOMMDirective() << name << ',' << Size;
798           if (Subtarget->isTargetDarwin())
799             O << ',' << Align;
800         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
801           O << "\t.globl " << name << '\n'
802             << MAI->getWeakDefDirective() << name << '\n';
803           EmitAlignment(Align, GVar);
804           O << name << ":";
805           if (VerboseAsm) {
806             O.PadToColumn(MAI->getCommentColumn());
807             O << MAI->getCommentString() << ' ';
808             WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
809           }
810           O << '\n';
811           EmitGlobalConstant(C);
812           return;
813         } else {
814           O << MAI->getCOMMDirective()  << name << ',' << Size;
815           if (MAI->getCOMMDirectiveTakesAlignment())
816             O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
817         }
818       } else {
819         if (!Subtarget->isTargetCygMing()) {
820           if (GVar->hasLocalLinkage())
821             O << "\t.local\t" << name << '\n';
822         }
823         O << MAI->getCOMMDirective()  << name << ',' << Size;
824         if (MAI->getCOMMDirectiveTakesAlignment())
825           O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
826       }
827       if (VerboseAsm) {
828         O.PadToColumn(MAI->getCommentColumn());
829         O << MAI->getCommentString() << ' ';
830         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
831       }
832       O << '\n';
833       return;
834     }
835   }
836
837   switch (GVar->getLinkage()) {
838   case GlobalValue::CommonLinkage:
839   case GlobalValue::LinkOnceAnyLinkage:
840   case GlobalValue::LinkOnceODRLinkage:
841   case GlobalValue::WeakAnyLinkage:
842   case GlobalValue::WeakODRLinkage:
843   case GlobalValue::LinkerPrivateLinkage:
844     if (Subtarget->isTargetDarwin()) {
845       O << "\t.globl " << name << '\n'
846         << MAI->getWeakDefDirective() << name << '\n';
847     } else if (Subtarget->isTargetCygMing()) {
848       O << "\t.globl\t" << name << "\n"
849            "\t.linkonce same_size\n";
850     } else {
851       O << "\t.weak\t" << name << '\n';
852     }
853     break;
854   case GlobalValue::DLLExportLinkage:
855   case GlobalValue::AppendingLinkage:
856     // FIXME: appending linkage variables should go into a section of
857     // their name or something.  For now, just emit them as external.
858   case GlobalValue::ExternalLinkage:
859     // If external or appending, declare as a global symbol
860     O << "\t.globl " << name << '\n';
861     // FALL THROUGH
862   case GlobalValue::PrivateLinkage:
863   case GlobalValue::InternalLinkage:
864      break;
865   default:
866     llvm_unreachable("Unknown linkage type!");
867   }
868
869   EmitAlignment(Align, GVar);
870   O << name << ":";
871   if (VerboseAsm){
872     O.PadToColumn(MAI->getCommentColumn());
873     O << MAI->getCommentString() << ' ';
874     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
875   }
876   O << '\n';
877
878   EmitGlobalConstant(C);
879
880   if (MAI->hasDotTypeDotSizeDirective())
881     O << "\t.size\t" << name << ", " << Size << '\n';
882 }
883
884 bool X86ATTAsmPrinter::doFinalization(Module &M) {
885   // Print out module-level global variables here.
886   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
887        I != E; ++I) {
888     if (I->hasDLLExportLinkage())
889       DLLExportedGVs.insert(Mang->getMangledName(I));
890   }
891
892   if (Subtarget->isTargetDarwin()) {
893     // All darwin targets use mach-o.
894     TargetLoweringObjectFileMachO &TLOFMacho = 
895       static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
896     
897     // Add the (possibly multiple) personalities to the set of global value
898     // stubs.  Only referenced functions get into the Personalities list.
899     if (MAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
900       const std::vector<Function*> &Personalities = MMI->getPersonalities();
901       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
902         if (Personalities[i] == 0)
903           continue;
904         
905         SmallString<128> Name;
906         Mang->getNameWithPrefix(Name, Personalities[i], true /*private label*/);
907         Name += "$non_lazy_ptr";
908         MCSymbol *NLPName = OutContext.GetOrCreateSymbol(Name.str());
909
910         MCSymbol *&StubName = GVStubs[NLPName];
911         if (StubName != 0) continue;
912         
913
914         Name.clear();
915         Mang->getNameWithPrefix(Name, Personalities[i], false);
916         StubName = OutContext.GetOrCreateSymbol(Name.str());
917       }
918     }
919
920     // Output stubs for dynamically-linked functions
921     if (!FnStubs.empty()) {
922       const MCSection *TheSection = 
923         TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
924                                   MCSectionMachO::S_SYMBOL_STUBS |
925                                   MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
926                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
927                                   5, SectionKind::getMetadata());
928       OutStreamer.SwitchSection(TheSection);
929       // FIXME: This iteration order is unstable!!
930       for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = FnStubs.begin(),
931            E = FnStubs.end(); I != E; ++I) {
932         I->first->print(O, MAI);
933         O << ":\n" << "\t.indirect_symbol ";
934         // Get the MCSymbol without the $stub suffix.
935         I->second->print(O, MAI);
936         O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
937       }
938       O << '\n';
939     }
940
941     // Output stubs for external and common global variables.
942     if (!GVStubs.empty()) {
943       const MCSection *TheSection = 
944         TLOFMacho.getMachOSection("__IMPORT", "__pointers",
945                                   MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
946                                   SectionKind::getMetadata());
947       OutStreamer.SwitchSection(TheSection);
948       // FIXME: This iteration order is unstable!!
949       for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = GVStubs.begin(),
950            E = GVStubs.end(); I != E; ++I) {
951         I->first->print(O, MAI);
952         O << ":\n\t.indirect_symbol ";
953         I->second->print(O, MAI);
954         O << "\n\t.long\t0\n";
955       }
956     }
957
958     if (!HiddenGVStubs.empty()) {
959       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
960       EmitAlignment(2);
961       for (DenseMap<MCSymbol*, MCSymbol*>::iterator I = HiddenGVStubs.begin(),
962            E = HiddenGVStubs.end(); I != E; ++I) {
963         I->first->print(O, MAI);
964         O << ":\n" << MAI->getData32bitsDirective();
965         I->second->print(O, MAI);
966         O << '\n';
967       }
968     }
969
970     // Funny Darwin hack: This flag tells the linker that no global symbols
971     // contain code that falls through to other global symbols (e.g. the obvious
972     // implementation of multiple entry points).  If this doesn't occur, the
973     // linker can safely perform dead code stripping.  Since LLVM never
974     // generates code that does this, it is always safe to set.
975     O << "\t.subsections_via_symbols\n";
976   } else if (Subtarget->isTargetCygMing()) {
977     // Emit type information for external functions
978     for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
979          i != e; ++i) {
980       O << "\t.def\t " << i->getKeyData()
981         << ";\t.scl\t" << COFF::C_EXT
982         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
983         << ";\t.endef\n";
984     }
985   }
986   
987   
988   // Output linker support code for dllexported globals on windows.
989   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
990     // dllexport symbols only exist on coff targets.
991     TargetLoweringObjectFileCOFF &TLOFMacho = 
992       static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
993     
994     OutStreamer.SwitchSection(TLOFMacho.getCOFFSection(".section .drectve",true,
995                                                  SectionKind::getMetadata()));
996   
997     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
998          e = DLLExportedGVs.end(); i != e; ++i)
999       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1000   
1001     for (StringSet<>::iterator i = DLLExportedFns.begin(),
1002          e = DLLExportedFns.end();
1003          i != e; ++i)
1004       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1005   }
1006   
1007   // Do common shutdown.
1008   return AsmPrinter::doFinalization(M);
1009 }
1010
1011 // Include the auto-generated portion of the assembly writer.
1012 #include "X86GenAsmWriter.inc"