rearrange some code, export a SmallString version of DecorateCygMingName.
[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/MCStreamer.h"
28 #include "llvm/MC/MCSectionMachO.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Mangler.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/Statistic.h"
39 using namespace llvm;
40
41 STATISTIC(EmittedInsts, "Number of machine instrs printed");
42
43 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
44                                    cl::Hidden, cl::init(false));
45
46 //===----------------------------------------------------------------------===//
47 // Primitive Helper Functions.
48 //===----------------------------------------------------------------------===//
49
50 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
51   // FIXME: the actual label generated doesn't matter here!  Just mangle in
52   // something unique (the function number) with Private prefix.
53   if (Subtarget->isTargetDarwin())
54     O << "\"L" << getFunctionNumber() << "$pb\"";
55   else {
56     assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
57     O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
58   }
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       printBasicBlockLabel(I, true, true, VerboseAsm);
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       GVStubs[Name] = Mang->getMangledName(GV);
321     else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
322       HiddenGVStubs[Name] = Mang->getMangledName(GV);
323     else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
324       FnStubs[Name] = Mang->getMangledName(GV);
325     
326     // If the name begins with a dollar-sign, enclose it in parens.  We do this
327     // to avoid having it look like an integer immediate to the assembler.
328     if (Name[0] == '$') 
329       O << '(' << Name << ')';
330     else
331       O << Name;
332     
333     printOffset(MO.getOffset());
334     break;
335   }
336   case MachineOperand::MO_ExternalSymbol: {
337     std::string Name = Mang->makeNameProper(MO.getSymbolName());
338     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
339       FnStubs[Name+"$stub"] = Name;
340       Name += "$stub";
341     }
342     
343     // If the name begins with a dollar-sign, enclose it in parens.  We do this
344     // to avoid having it look like an integer immediate to the assembler.
345     if (Name[0] == '$') 
346       O << '(' << Name << ')';
347     else
348       O << Name;
349     break;
350   }
351   }
352   
353   switch (MO.getTargetFlags()) {
354   default:
355     llvm_unreachable("Unknown target flag on GV operand");
356   case X86II::MO_NO_FLAG:    // No flag.
357     break;
358   case X86II::MO_DARWIN_NONLAZY:
359   case X86II::MO_DLLIMPORT:
360   case X86II::MO_DARWIN_STUB:
361     // These affect the name of the symbol, not any suffix.
362     break;
363   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
364     O << " + [.-";
365     PrintPICBaseSymbol();
366     O << ']';
367     break;      
368   case X86II::MO_PIC_BASE_OFFSET:
369   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
370   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
371     O << '-';
372     PrintPICBaseSymbol();
373     break;
374   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
375   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
376   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
377   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
378   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
379   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
380   case X86II::MO_GOT:       O << "@GOT";       break;
381   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
382   case X86II::MO_PLT:       O << "@PLT";       break;
383   }
384 }
385
386 /// print_pcrel_imm - This is used to print an immediate value that ends up
387 /// being encoded as a pc-relative value.  These print slightly differently, for
388 /// example, a $ is not emitted.
389 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
390   const MachineOperand &MO = MI->getOperand(OpNo);
391   switch (MO.getType()) {
392   default: llvm_unreachable("Unknown pcrel immediate operand");
393   case MachineOperand::MO_Immediate:
394     O << MO.getImm();
395     return;
396   case MachineOperand::MO_MachineBasicBlock:
397     printBasicBlockLabel(MO.getMBB(), false, false, false);
398     return;
399   case MachineOperand::MO_GlobalAddress:
400   case MachineOperand::MO_ExternalSymbol:
401     printSymbolOperand(MO);
402     return;
403   }
404 }
405
406
407
408 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
409                                     const char *Modifier) {
410   const MachineOperand &MO = MI->getOperand(OpNo);
411   switch (MO.getType()) {
412   default: llvm_unreachable("unknown operand type!");
413   case MachineOperand::MO_Register: {
414     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
415            "Virtual registers should not make it this far!");
416     O << '%';
417     unsigned Reg = MO.getReg();
418     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
419       EVT VT = (strcmp(Modifier+6,"64") == 0) ?
420         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
421                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
422       Reg = getX86SubSuperRegister(Reg, VT);
423     }
424     O << TRI->getAsmName(Reg);
425     return;
426   }
427
428   case MachineOperand::MO_Immediate:
429     O << '$' << MO.getImm();
430     return;
431
432   case MachineOperand::MO_JumpTableIndex:
433   case MachineOperand::MO_ConstantPoolIndex:
434   case MachineOperand::MO_GlobalAddress: 
435   case MachineOperand::MO_ExternalSymbol: {
436     O << '$';
437     printSymbolOperand(MO);
438     break;
439   }
440   }
441 }
442
443 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
444   unsigned char value = MI->getOperand(Op).getImm();
445   assert(value <= 7 && "Invalid ssecc argument!");
446   switch (value) {
447   case 0: O << "eq"; break;
448   case 1: O << "lt"; break;
449   case 2: O << "le"; break;
450   case 3: O << "unord"; break;
451   case 4: O << "neq"; break;
452   case 5: O << "nlt"; break;
453   case 6: O << "nle"; break;
454   case 7: O << "ord"; break;
455   }
456 }
457
458 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
459                                             const char *Modifier) {
460   const MachineOperand &BaseReg  = MI->getOperand(Op);
461   const MachineOperand &IndexReg = MI->getOperand(Op+2);
462   const MachineOperand &DispSpec = MI->getOperand(Op+3);
463
464   // If we really don't want to print out (rip), don't.
465   bool HasBaseReg = BaseReg.getReg() != 0;
466   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
467       BaseReg.getReg() == X86::RIP)
468     HasBaseReg = false;
469   
470   // HasParenPart - True if we will print out the () part of the mem ref.
471   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
472   
473   if (DispSpec.isImm()) {
474     int DispVal = DispSpec.getImm();
475     if (DispVal || !HasParenPart)
476       O << DispVal;
477   } else {
478     assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
479            DispSpec.isJTI() || DispSpec.isSymbol());
480     printSymbolOperand(MI->getOperand(Op+3));
481   }
482
483   if (HasParenPart) {
484     assert(IndexReg.getReg() != X86::ESP &&
485            "X86 doesn't allow scaling by ESP");
486
487     O << '(';
488     if (HasBaseReg)
489       printOperand(MI, Op, Modifier);
490
491     if (IndexReg.getReg()) {
492       O << ',';
493       printOperand(MI, Op+2, Modifier);
494       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
495       if (ScaleVal != 1)
496         O << ',' << ScaleVal;
497     }
498     O << ')';
499   }
500 }
501
502 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
503                                          const char *Modifier) {
504   assert(isMem(MI, Op) && "Invalid memory reference!");
505   const MachineOperand &Segment = MI->getOperand(Op+4);
506   if (Segment.getReg()) {
507     printOperand(MI, Op+4, Modifier);
508     O << ':';
509   }
510   printLeaMemReference(MI, Op, Modifier);
511 }
512
513 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
514                                            const MachineBasicBlock *MBB) const {
515   if (!MAI->getSetDirective())
516     return;
517
518   // We don't need .set machinery if we have GOT-style relocations
519   if (Subtarget->isPICStyleGOT())
520     return;
521
522   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
523     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
524   printBasicBlockLabel(MBB, false, false, false);
525   if (Subtarget->isPICStyleRIPRel())
526     O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
527       << '_' << uid << '\n';
528   else {
529     O << '-';
530     PrintPICBaseSymbol();
531     O << '\n';
532   }
533 }
534
535
536 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
537   PrintPICBaseSymbol();
538   O << '\n';
539   PrintPICBaseSymbol();
540   O << ':';
541 }
542
543
544 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
545                                               const MachineBasicBlock *MBB,
546                                               unsigned uid) const {
547   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
548     MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
549
550   O << JTEntryDirective << ' ';
551
552   if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
553     O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
554       << '_' << uid << "_set_" << MBB->getNumber();
555   } else if (Subtarget->isPICStyleGOT()) {
556     printBasicBlockLabel(MBB, false, false, false);
557     O << "@GOTOFF";
558   } else
559     printBasicBlockLabel(MBB, false, false, false);
560 }
561
562 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
563   unsigned Reg = MO.getReg();
564   switch (Mode) {
565   default: return true;  // Unknown mode.
566   case 'b': // Print QImode register
567     Reg = getX86SubSuperRegister(Reg, MVT::i8);
568     break;
569   case 'h': // Print QImode high register
570     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
571     break;
572   case 'w': // Print HImode register
573     Reg = getX86SubSuperRegister(Reg, MVT::i16);
574     break;
575   case 'k': // Print SImode register
576     Reg = getX86SubSuperRegister(Reg, MVT::i32);
577     break;
578   case 'q': // Print DImode register
579     Reg = getX86SubSuperRegister(Reg, MVT::i64);
580     break;
581   }
582
583   O << '%'<< TRI->getAsmName(Reg);
584   return false;
585 }
586
587 /// PrintAsmOperand - Print out an operand for an inline asm expression.
588 ///
589 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
590                                        unsigned AsmVariant,
591                                        const char *ExtraCode) {
592   // Does this asm operand have a single letter operand modifier?
593   if (ExtraCode && ExtraCode[0]) {
594     if (ExtraCode[1] != 0) return true; // Unknown modifier.
595
596     const MachineOperand &MO = MI->getOperand(OpNo);
597     
598     switch (ExtraCode[0]) {
599     default: return true;  // Unknown modifier.
600     case 'a': // This is an address.  Currently only 'i' and 'r' are expected.
601       if (MO.isImm()) {
602         O << MO.getImm();
603         return false;
604       } 
605       if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
606         printSymbolOperand(MO);
607         return false;
608       }
609       if (MO.isReg()) {
610         O << '(';
611         printOperand(MI, OpNo);
612         O << ')';
613         return false;
614       }
615       return true;
616
617     case 'c': // Don't print "$" before a global var name or constant.
618       if (MO.isImm())
619         O << MO.getImm();
620       else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
621         printSymbolOperand(MO);
622       else
623         printOperand(MI, OpNo);
624       return false;
625
626     case 'A': // Print '*' before a register (it must be a register)
627       if (MO.isReg()) {
628         O << '*';
629         printOperand(MI, OpNo);
630         return false;
631       }
632       return true;
633
634     case 'b': // Print QImode register
635     case 'h': // Print QImode high register
636     case 'w': // Print HImode register
637     case 'k': // Print SImode register
638     case 'q': // Print DImode register
639       if (MO.isReg())
640         return printAsmMRegister(MO, ExtraCode[0]);
641       printOperand(MI, OpNo);
642       return false;
643
644     case 'P': // This is the operand of a call, treat specially.
645       print_pcrel_imm(MI, OpNo);
646       return false;
647
648     case 'n':  // Negate the immediate or print a '-' before the operand.
649       // Note: this is a temporary solution. It should be handled target
650       // independently as part of the 'MC' work.
651       if (MO.isImm()) {
652         O << -MO.getImm();
653         return false;
654       }
655       O << '-';
656     }
657   }
658
659   printOperand(MI, OpNo);
660   return false;
661 }
662
663 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
664                                              unsigned OpNo,
665                                              unsigned AsmVariant,
666                                              const char *ExtraCode) {
667   if (ExtraCode && ExtraCode[0]) {
668     if (ExtraCode[1] != 0) return true; // Unknown modifier.
669
670     switch (ExtraCode[0]) {
671     default: return true;  // Unknown modifier.
672     case 'b': // Print QImode register
673     case 'h': // Print QImode high register
674     case 'w': // Print HImode register
675     case 'k': // Print SImode register
676     case 'q': // Print SImode register
677       // These only apply to registers, ignore on mem.
678       break;
679     case 'P': // Don't print @PLT, but do print as memory.
680       printMemReference(MI, OpNo, "no-rip");
681       return false;
682     }
683   }
684   printMemReference(MI, OpNo);
685   return false;
686 }
687
688
689
690 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
691 /// AT&T syntax to the current output stream.
692 ///
693 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
694   ++EmittedInsts;
695
696   processDebugLoc(MI->getDebugLoc());
697   
698   // Call the autogenerated instruction printer routines.
699   if (NewAsmPrinter)
700     printInstructionThroughMCStreamer(MI);
701   else
702     printInstruction(MI);
703   
704   if (VerboseAsm && !MI->getDebugLoc().isUnknown())
705     EmitComments(*MI);
706   O << '\n';
707 }
708
709 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
710   const TargetData *TD = TM.getTargetData();
711
712   if (!GVar->hasInitializer())
713     return;   // External global require no code
714
715   // Check to see if this is a special global used by LLVM, if so, emit it.
716   if (EmitSpecialLLVMGlobal(GVar)) {
717     if (Subtarget->isTargetDarwin() &&
718         TM.getRelocationModel() == Reloc::Static) {
719       if (GVar->getName() == "llvm.global_ctors")
720         O << ".reference .constructors_used\n";
721       else if (GVar->getName() == "llvm.global_dtors")
722         O << ".reference .destructors_used\n";
723     }
724     return;
725   }
726
727   std::string name = Mang->getMangledName(GVar);
728   Constant *C = GVar->getInitializer();
729   const Type *Type = C->getType();
730   unsigned Size = TD->getTypeAllocSize(Type);
731   unsigned Align = TD->getPreferredAlignmentLog(GVar);
732
733   printVisibility(name, GVar->getVisibility());
734
735   if (Subtarget->isTargetELF())
736     O << "\t.type\t" << name << ",@object\n";
737
738   
739   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
740   const MCSection *TheSection =
741     getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
742   OutStreamer.SwitchSection(TheSection);
743
744   // FIXME: get this stuff from section kind flags.
745   if (C->isNullValue() && !GVar->hasSection() &&
746       // Don't put things that should go in the cstring section into "comm".
747       !TheSection->getKind().isMergeableCString()) {
748     if (GVar->hasExternalLinkage()) {
749       if (const char *Directive = MAI->getZeroFillDirective()) {
750         O << "\t.globl " << name << '\n';
751         O << Directive << "__DATA, __common, " << name << ", "
752           << Size << ", " << Align << '\n';
753         return;
754       }
755     }
756
757     if (!GVar->isThreadLocal() &&
758         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
759       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
760
761       if (MAI->getLCOMMDirective() != NULL) {
762         if (GVar->hasLocalLinkage()) {
763           O << MAI->getLCOMMDirective() << name << ',' << Size;
764           if (Subtarget->isTargetDarwin())
765             O << ',' << Align;
766         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
767           O << "\t.globl " << name << '\n'
768             << MAI->getWeakDefDirective() << name << '\n';
769           EmitAlignment(Align, GVar);
770           O << name << ":";
771           if (VerboseAsm) {
772             O.PadToColumn(MAI->getCommentColumn());
773             O << MAI->getCommentString() << ' ';
774             WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
775           }
776           O << '\n';
777           EmitGlobalConstant(C);
778           return;
779         } else {
780           O << MAI->getCOMMDirective()  << name << ',' << Size;
781           if (MAI->getCOMMDirectiveTakesAlignment())
782             O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
783         }
784       } else {
785         if (!Subtarget->isTargetCygMing()) {
786           if (GVar->hasLocalLinkage())
787             O << "\t.local\t" << name << '\n';
788         }
789         O << MAI->getCOMMDirective()  << name << ',' << Size;
790         if (MAI->getCOMMDirectiveTakesAlignment())
791           O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
792       }
793       if (VerboseAsm) {
794         O.PadToColumn(MAI->getCommentColumn());
795         O << MAI->getCommentString() << ' ';
796         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
797       }
798       O << '\n';
799       return;
800     }
801   }
802
803   switch (GVar->getLinkage()) {
804   case GlobalValue::CommonLinkage:
805   case GlobalValue::LinkOnceAnyLinkage:
806   case GlobalValue::LinkOnceODRLinkage:
807   case GlobalValue::WeakAnyLinkage:
808   case GlobalValue::WeakODRLinkage:
809   case GlobalValue::LinkerPrivateLinkage:
810     if (Subtarget->isTargetDarwin()) {
811       O << "\t.globl " << name << '\n'
812         << MAI->getWeakDefDirective() << name << '\n';
813     } else if (Subtarget->isTargetCygMing()) {
814       O << "\t.globl\t" << name << "\n"
815            "\t.linkonce same_size\n";
816     } else {
817       O << "\t.weak\t" << name << '\n';
818     }
819     break;
820   case GlobalValue::DLLExportLinkage:
821   case GlobalValue::AppendingLinkage:
822     // FIXME: appending linkage variables should go into a section of
823     // their name or something.  For now, just emit them as external.
824   case GlobalValue::ExternalLinkage:
825     // If external or appending, declare as a global symbol
826     O << "\t.globl " << name << '\n';
827     // FALL THROUGH
828   case GlobalValue::PrivateLinkage:
829   case GlobalValue::InternalLinkage:
830      break;
831   default:
832     llvm_unreachable("Unknown linkage type!");
833   }
834
835   EmitAlignment(Align, GVar);
836   O << name << ":";
837   if (VerboseAsm){
838     O.PadToColumn(MAI->getCommentColumn());
839     O << MAI->getCommentString() << ' ';
840     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
841   }
842   O << '\n';
843
844   EmitGlobalConstant(C);
845
846   if (MAI->hasDotTypeDotSizeDirective())
847     O << "\t.size\t" << name << ", " << Size << '\n';
848 }
849
850 bool X86ATTAsmPrinter::doFinalization(Module &M) {
851   // Print out module-level global variables here.
852   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
853        I != E; ++I) {
854     if (I->hasDLLExportLinkage())
855       DLLExportedGVs.insert(Mang->getMangledName(I));
856   }
857
858   if (Subtarget->isTargetDarwin()) {
859     // All darwin targets use mach-o.
860     TargetLoweringObjectFileMachO &TLOFMacho = 
861       static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
862     
863     // Add the (possibly multiple) personalities to the set of global value
864     // stubs.  Only referenced functions get into the Personalities list.
865     if (MAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
866       const std::vector<Function*> &Personalities = MMI->getPersonalities();
867       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
868         if (Personalities[i])
869           GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
870                                        true /*private label*/)] = 
871             Mang->getMangledName(Personalities[i]);
872       }
873     }
874
875     // Output stubs for dynamically-linked functions
876     if (!FnStubs.empty()) {
877       const MCSection *TheSection = 
878         TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
879                                   MCSectionMachO::S_SYMBOL_STUBS |
880                                   MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
881                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
882                                   5, SectionKind::getMetadata());
883       OutStreamer.SwitchSection(TheSection);
884       for (StringMap<std::string>::iterator I = FnStubs.begin(),
885            E = FnStubs.end(); I != E; ++I)
886         O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
887           << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
888       O << '\n';
889     }
890
891     // Output stubs for external and common global variables.
892     if (!GVStubs.empty()) {
893       const MCSection *TheSection = 
894         TLOFMacho.getMachOSection("__IMPORT", "__pointers",
895                                   MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
896                                   SectionKind::getMetadata());
897       OutStreamer.SwitchSection(TheSection);
898       for (StringMap<std::string>::iterator I = GVStubs.begin(),
899            E = GVStubs.end(); I != E; ++I)
900         O << I->getKeyData() << ":\n\t.indirect_symbol "
901           << I->second << "\n\t.long\t0\n";
902     }
903
904     if (!HiddenGVStubs.empty()) {
905       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
906       EmitAlignment(2);
907       for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
908            E = HiddenGVStubs.end(); I != E; ++I)
909         O << I->getKeyData() << ":\n" << MAI->getData32bitsDirective()
910           << I->second << '\n';
911     }
912
913     // Funny Darwin hack: This flag tells the linker that no global symbols
914     // contain code that falls through to other global symbols (e.g. the obvious
915     // implementation of multiple entry points).  If this doesn't occur, the
916     // linker can safely perform dead code stripping.  Since LLVM never
917     // generates code that does this, it is always safe to set.
918     O << "\t.subsections_via_symbols\n";
919   } else if (Subtarget->isTargetCygMing()) {
920     // Emit type information for external functions
921     for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
922          i != e; ++i) {
923       O << "\t.def\t " << i->getKeyData()
924         << ";\t.scl\t" << COFF::C_EXT
925         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
926         << ";\t.endef\n";
927     }
928   }
929   
930   
931   // Output linker support code for dllexported globals on windows.
932   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
933     // dllexport symbols only exist on coff targets.
934     TargetLoweringObjectFileCOFF &TLOFMacho = 
935       static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
936     
937     OutStreamer.SwitchSection(TLOFMacho.getCOFFSection(".section .drectve",true,
938                                                  SectionKind::getMetadata()));
939   
940     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
941          e = DLLExportedGVs.end(); i != e; ++i)
942       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
943   
944     for (StringSet<>::iterator i = DLLExportedFns.begin(),
945          e = DLLExportedFns.end();
946          i != e; ++i)
947       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
948   }
949   
950   // Do common shutdown.
951   return AsmPrinter::doFinalization(M);
952 }
953
954 // Include the auto-generated portion of the assembly writer.
955 #include "X86GenAsmWriter.inc"