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