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