isPICStyleStub() is now never true in -static mode, so simplify code.
[oota-llvm.git] / lib / Target / X86 / AsmPrinter / X86ATTAsmPrinter.cpp
1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86ATTAsmPrinter.h"
18 #include "X86.h"
19 #include "X86COFF.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetAsmInfo.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/MDNode.h"
27 #include "llvm/Type.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/CodeGen/DwarfWriter.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Mangler.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetAsmInfo.h"
39 #include "llvm/Target/TargetOptions.h"
40 using namespace llvm;
41
42 STATISTIC(EmittedInsts, "Number of machine instrs printed");
43
44 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
45                                    cl::Hidden);
46
47 //===----------------------------------------------------------------------===//
48 // Primitive Helper Functions.
49 //===----------------------------------------------------------------------===//
50
51 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
52   if (Subtarget->isTargetDarwin())
53     O << "\"L" << getFunctionNumber() << "$pb\"";
54   else if (Subtarget->isTargetELF())
55     O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
56   else
57     assert(0 && "Don't know how to print PIC label!\n");
58 }
59
60 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
61 /// Don't print things like \\n or \\0.
62 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
63   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
64        Name != E; ++Name)
65     if (isprint(*Name))
66       OS << *Name;
67 }
68
69 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
70                                                     const TargetData *TD) {
71   X86MachineFunctionInfo Info;
72   uint64_t Size = 0;
73
74   switch (F->getCallingConv()) {
75   case CallingConv::X86_StdCall:
76     Info.setDecorationStyle(StdCall);
77     break;
78   case CallingConv::X86_FastCall:
79     Info.setDecorationStyle(FastCall);
80     break;
81   default:
82     return Info;
83   }
84
85   unsigned argNum = 1;
86   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
87        AI != AE; ++AI, ++argNum) {
88     const Type* Ty = AI->getType();
89
90     // 'Dereference' type in case of byval parameter attribute
91     if (F->paramHasAttr(argNum, Attribute::ByVal))
92       Ty = cast<PointerType>(Ty)->getElementType();
93
94     // Size should be aligned to DWORD boundary
95     Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
96   }
97
98   // We're not supporting tooooo huge arguments :)
99   Info.setBytesToPopOnReturn((unsigned int)Size);
100   return Info;
101 }
102
103 /// decorateName - Query FunctionInfoMap and use this information for various
104 /// name decoration.
105 void X86ATTAsmPrinter::decorateName(std::string &Name,
106                                     const GlobalValue *GV) {
107   const Function *F = dyn_cast<Function>(GV);
108   if (!F) return;
109
110   // We don't want to decorate non-stdcall or non-fastcall functions right now
111   unsigned CC = F->getCallingConv();
112   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
113     return;
114
115   // Decorate names only when we're targeting Cygwin/Mingw32 targets
116   if (!Subtarget->isTargetCygMing())
117     return;
118
119   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
120
121   const X86MachineFunctionInfo *Info;
122   if (info_item == FunctionInfoMap.end()) {
123     // Calculate apropriate function info and populate map
124     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
125     Info = &FunctionInfoMap[F];
126   } else {
127     Info = &info_item->second;
128   }
129
130   const FunctionType *FT = F->getFunctionType();
131   switch (Info->getDecorationStyle()) {
132   case None:
133     break;
134   case StdCall:
135     // "Pure" variadic functions do not receive @0 suffix.
136     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
137         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
138       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
139     break;
140   case FastCall:
141     // "Pure" variadic functions do not receive @0 suffix.
142     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
143         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
144       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
145
146     if (Name[0] == '_') {
147       Name[0] = '@';
148     } else {
149       Name = '@' + Name;
150     }
151     break;
152   default:
153     assert(0 && "Unsupported DecorationStyle");
154   }
155 }
156
157 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
158   unsigned FnAlign = MF.getAlignment();
159   const Function *F = MF.getFunction();
160
161   decorateName(CurrentFnName, F);
162
163   SwitchToSection(TAI->SectionForGlobal(F));
164   switch (F->getLinkage()) {
165   default: assert(0 && "Unknown linkage type!");
166   case Function::InternalLinkage:  // Symbols default to internal.
167   case Function::PrivateLinkage:
168     EmitAlignment(FnAlign, F);
169     break;
170   case Function::DLLExportLinkage:
171   case Function::ExternalLinkage:
172     EmitAlignment(FnAlign, F);
173     O << "\t.globl\t" << CurrentFnName << '\n';
174     break;
175   case Function::LinkOnceAnyLinkage:
176   case Function::LinkOnceODRLinkage:
177   case Function::WeakAnyLinkage:
178   case Function::WeakODRLinkage:
179     EmitAlignment(FnAlign, F);
180     if (Subtarget->isTargetDarwin()) {
181       O << "\t.globl\t" << CurrentFnName << '\n';
182       O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
183     } else if (Subtarget->isTargetCygMing()) {
184       O << "\t.globl\t" << CurrentFnName << "\n"
185            "\t.linkonce discard\n";
186     } else {
187       O << "\t.weak\t" << CurrentFnName << '\n';
188     }
189     break;
190   }
191
192   printVisibility(CurrentFnName, F->getVisibility());
193
194   if (Subtarget->isTargetELF())
195     O << "\t.type\t" << CurrentFnName << ",@function\n";
196   else if (Subtarget->isTargetCygMing()) {
197     O << "\t.def\t " << CurrentFnName
198       << ";\t.scl\t" <<
199       (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
200       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
201       << ";\t.endef\n";
202   }
203
204   O << CurrentFnName << ":\n";
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   unsigned 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->makeNameProper(F->getName(), ""));
232
233   // Print the 'header' of function
234   emitFunctionHeader(MF);
235
236   // Emit pre-function debug and/or EH information.
237   if (TAI->doesSupportDebugInformation() || TAI->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       printBasicBlockLabel(I, true, true, VerboseAsm);
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 (TAI->hasDotTypeDotSizeDirective())
270     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
271
272   // Emit post-function debug information.
273   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
274     DW->EndFunction(&MF);
275
276   // Print out jump tables referenced by the function.
277   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
278
279   O.flush();
280
281   // We didn't modify anything.
282   return false;
283 }
284
285 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
286   return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_;
287 }
288
289 /// print_pcrel_imm - This is used to print an immediate value that ends up
290 /// being encoded as a pc-relative value.  These print slightly differently, for
291 /// example, a $ is not emitted.
292 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
293   const MachineOperand &MO = MI->getOperand(OpNo);
294   switch (MO.getType()) {
295   default: assert(0 && "Unknown pcrel immediate operand");
296   case MachineOperand::MO_Immediate:
297     O << MO.getImm();
298     return;
299   case MachineOperand::MO_MachineBasicBlock:
300     printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
301     return;
302       
303   case MachineOperand::MO_GlobalAddress: {
304     const GlobalValue *GV = MO.getGlobal();
305     std::string Name = Mang->getValueName(GV);
306     decorateName(Name, GV);
307     
308     bool needCloseParen = false;
309     if (Name[0] == '$') {
310       // The name begins with a dollar-sign. In order to avoid having it look
311       // like an integer immediate to the assembler, enclose it in parens.
312       O << '(';
313       needCloseParen = true;
314     }
315     
316     if (Subtarget->isPICStyleStub()) {
317       // DARWIN/X86-32 in != static mode.
318       
319       // Link-once, declaration, or Weakly-linked global variables need
320       // non-lazily-resolved stubs
321       if (GV->isDeclaration() || GV->isWeakForLinker()) {
322         // Dynamically-resolved functions need a stub for the function.
323         if (isa<Function>(GV)) {
324           // Function stubs are no longer needed for Mac OS X 10.5 and up.
325           if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
326             O << Name;
327           } else {
328             FnStubs.insert(Name);
329             printSuffixedName(Name, "$stub");
330           }
331           assert(MO.getTargetFlags() == 0);
332         } else if (GV->hasHiddenVisibility()) {
333           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
334             // Definition is not definitely in the current translation unit.
335             O << Name;
336           else {
337             HiddenGVStubs.insert(Name);
338             printSuffixedName(Name, "$non_lazy_ptr");
339             assert(MO.getTargetFlags() == 0);
340           }
341         } else {
342           GVStubs.insert(Name);
343           printSuffixedName(Name, "$non_lazy_ptr");
344           assert(MO.getTargetFlags() == 0);
345         }
346       } else {
347         O << Name;
348       }
349     } else {
350       // Handle dllimport linkage.
351       if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
352         O << "__imp_";
353       O << Name;
354       
355       if (shouldPrintPLT(TM, Subtarget)) {
356         // Assemble call via PLT for externally visible symbols
357         if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
358             !GV->hasLocalLinkage()) {
359           O << "@PLT";
360           assert(MO.getTargetFlags() == 0);
361         }
362       }
363       if (Subtarget->isTargetCygMing() && GV->isDeclaration())
364         // Save function name for later type emission
365         FnStubs.insert(Name);
366     }
367     
368     printOffset(MO.getOffset());
369     
370     if (needCloseParen)
371       O << ')';
372     return;
373   }
374       
375   case MachineOperand::MO_ExternalSymbol: {
376     bool needCloseParen = false;
377     std::string Name(TAI->getGlobalPrefix());
378     Name += MO.getSymbolName();
379     // Print function stub suffix unless it's Mac OS X 10.5 and up.
380     if (Subtarget->isPICStyleStub() && 
381         // DARWIN/X86-32 in != static mode.
382         Subtarget->getDarwinVers() < 9) {
383       FnStubs.insert(Name);
384       printSuffixedName(Name, "$stub");
385       return;
386     }
387     
388     if (Name[0] == '$') {
389       // The name begins with a dollar-sign. In order to avoid having it look
390       // like an integer immediate to the assembler, enclose it in parens.
391       O << '(';
392       needCloseParen = true;
393     }
394     
395     O << Name;
396     
397     if (MO.getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS) {
398       O << " + [.-";
399       PrintPICBaseSymbol();
400       O << ']';
401     }
402     
403     if (shouldPrintPLT(TM, Subtarget)) {
404       O << "@PLT";
405       assert(MO.getTargetFlags() == 0);
406     }
407     
408     if (needCloseParen)
409       O << ')';
410     
411     return;
412   }
413   }
414 }
415
416 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
417                                     const char *Modifier) {
418   const MachineOperand &MO = MI->getOperand(OpNo);
419   switch (MO.getType()) {
420   default: assert(0 && "unknown operand type!");
421   case MachineOperand::MO_Register: {
422     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
423            "Virtual registers should not make it this far!");
424     O << '%';
425     unsigned Reg = MO.getReg();
426     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
427       MVT VT = (strcmp(Modifier+6,"64") == 0) ?
428         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
429                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
430       Reg = getX86SubSuperRegister(Reg, VT);
431     }
432     O << TRI->getAsmName(Reg);
433     return;
434   }
435
436   case MachineOperand::MO_Immediate:
437     if (!Modifier || (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
438       O << '$';
439     O << MO.getImm();
440     return;
441   case MachineOperand::MO_JumpTableIndex: {
442     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
443     if (!isMemOp) O << '$';
444     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
445       << MO.getIndex();
446     break;
447   }
448   case MachineOperand::MO_ConstantPoolIndex: {
449     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
450     if (!isMemOp) O << '$';
451     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
452       << MO.getIndex();
453
454     printOffset(MO.getOffset());
455     break;
456   }
457   case MachineOperand::MO_GlobalAddress: {
458     bool isMemOp = Modifier && !strcmp(Modifier, "mem");
459     const GlobalValue *GV = MO.getGlobal();
460     std::string Name = Mang->getValueName(GV);
461     decorateName(Name, GV);
462
463     bool needCloseParen = false;
464     if (!isMemOp)
465       O << '$';
466     else if (Name[0] == '$') {
467       // The name begins with a dollar-sign. In order to avoid having it look
468       // like an integer immediate to the assembler, enclose it in parens.
469       O << '(';
470       needCloseParen = true;
471     }
472
473     if (Subtarget->isPICStyleStub()) {
474       // DARWIN/X86-32 in != static mode.
475
476       // Link-once, declaration, or Weakly-linked global variables need
477       // non-lazily-resolved stubs
478       if (GV->isDeclaration() || GV->isWeakForLinker()) {
479         if (GV->hasHiddenVisibility()) {
480           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
481             // Definition is not definitely in the current translation unit.
482             O << Name;
483           else {
484             HiddenGVStubs.insert(Name);
485             printSuffixedName(Name, "$non_lazy_ptr");
486             assert(MO.getTargetFlags() == 0);
487           }
488         } else {
489           GVStubs.insert(Name);
490           printSuffixedName(Name, "$non_lazy_ptr");
491           assert(MO.getTargetFlags() == 0);
492         }
493       } else {
494         O << Name;
495       }
496
497       if (TM.getRelocationModel() == Reloc::PIC_) {
498         O << '-';
499         PrintPICBaseSymbol();
500       }        
501     } else {
502       // Handle dllimport linkage.
503       if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
504         O << "__imp_";
505       O << Name;
506     }
507
508     printOffset(MO.getOffset());
509
510     if (needCloseParen)
511       O << ')';
512     
513     break;
514   }
515   case MachineOperand::MO_ExternalSymbol:
516     /// NOTE: MO_ExternalSymbol in a non-pcrel_imm context is *only* generated
517     /// by _GLOBAL_OFFSET_TABLE_ on X86-32.  All others are call operands, which
518     /// are pcrel_imm's.
519     assert(!Subtarget->is64Bit() && !Subtarget->isPICStyleRIPRel());
520     // These are never used as memory operands.
521     assert(Modifier == 0 || strcmp(Modifier, "mem"));
522     O << '$';
523     O << TAI->getGlobalPrefix();
524     O << MO.getSymbolName();
525     break;
526   }
527   
528   switch (MO.getTargetFlags()) {
529   default:
530     assert(0 && "Unknown target flag on GV operand");
531   case X86II::MO_NO_FLAG:    // No flag.
532   case X86II::MO_DLLIMPORT:  // Prefix, not a suffix.
533     break;
534   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
535     O << " + [.-";
536     PrintPICBaseSymbol();
537     O << ']';
538     break;      
539   case X86II::MO_PIC_BASE_OFFSET:
540     O << '-';
541     PrintPICBaseSymbol();
542     break;
543   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
544   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
545   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
546   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
547   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
548   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
549   case X86II::MO_GOT:       O << "@GOT";       break;
550   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
551   }
552 }
553
554 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
555   unsigned char value = MI->getOperand(Op).getImm();
556   assert(value <= 7 && "Invalid ssecc argument!");
557   switch (value) {
558   case 0: O << "eq"; break;
559   case 1: O << "lt"; break;
560   case 2: O << "le"; break;
561   case 3: O << "unord"; break;
562   case 4: O << "neq"; break;
563   case 5: O << "nlt"; break;
564   case 6: O << "nle"; break;
565   case 7: O << "ord"; break;
566   }
567 }
568
569 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
570                                             const char *Modifier) {
571   const MachineOperand &BaseReg  = MI->getOperand(Op);
572   const MachineOperand &IndexReg = MI->getOperand(Op+2);
573   const MachineOperand &DispSpec = MI->getOperand(Op+3);
574
575   // If we really don't want to print out (rip), don't.
576   bool HasBaseReg = BaseReg.getReg() != 0;
577   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
578       BaseReg.getReg() == X86::RIP)
579     HasBaseReg = false;
580   
581   // HasParenPart - True if we will print out the () part of the mem ref.
582   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
583   
584   if (DispSpec.isImm()) {
585     int DispVal = DispSpec.getImm();
586     if (DispVal || !HasParenPart)
587       O << DispVal;
588   } else {
589     assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
590            DispSpec.isJTI() || DispSpec.isSymbol());
591     printOperand(MI, Op+3, "mem");
592   }
593
594   if (HasParenPart) {
595     assert(IndexReg.getReg() != X86::ESP &&
596            "X86 doesn't allow scaling by ESP");
597
598     O << '(';
599     if (HasBaseReg)
600       printOperand(MI, Op, Modifier);
601
602     if (IndexReg.getReg()) {
603       O << ',';
604       printOperand(MI, Op+2, Modifier);
605       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
606       if (ScaleVal != 1)
607         O << ',' << ScaleVal;
608     }
609     O << ')';
610   }
611 }
612
613 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
614                                          const char *Modifier) {
615   assert(isMem(MI, Op) && "Invalid memory reference!");
616   const MachineOperand &Segment = MI->getOperand(Op+4);
617   if (Segment.getReg()) {
618     printOperand(MI, Op+4, Modifier);
619     O << ':';
620   }
621   printLeaMemReference(MI, Op, Modifier);
622 }
623
624 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
625                                            const MachineBasicBlock *MBB) const {
626   if (!TAI->getSetDirective())
627     return;
628
629   // We don't need .set machinery if we have GOT-style relocations
630   if (Subtarget->isPICStyleGOT())
631     return;
632
633   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
634     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
635   printBasicBlockLabel(MBB, false, false, false);
636   if (Subtarget->isPICStyleRIPRel())
637     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
638       << '_' << uid << '\n';
639   else {
640     O << '-';
641     PrintPICBaseSymbol();
642     O << '\n';
643   }
644 }
645
646
647 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
648   PrintPICBaseSymbol();
649   O << '\n';
650   PrintPICBaseSymbol();
651   O << ':';
652 }
653
654
655 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
656                                               const MachineBasicBlock *MBB,
657                                               unsigned uid) const
658 {
659   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
660     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
661
662   O << JTEntryDirective << ' ';
663
664   if (TM.getRelocationModel() == Reloc::PIC_) {
665     if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
666       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
667         << '_' << uid << "_set_" << MBB->getNumber();
668     } else if (Subtarget->isPICStyleGOT()) {
669       printBasicBlockLabel(MBB, false, false, false);
670       O << "@GOTOFF";
671     } else
672       assert(0 && "Don't know how to print MBB label for this PIC mode");
673   } else
674     printBasicBlockLabel(MBB, false, false, false);
675 }
676
677 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
678   unsigned Reg = MO.getReg();
679   switch (Mode) {
680   default: return true;  // Unknown mode.
681   case 'b': // Print QImode register
682     Reg = getX86SubSuperRegister(Reg, MVT::i8);
683     break;
684   case 'h': // Print QImode high register
685     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
686     break;
687   case 'w': // Print HImode register
688     Reg = getX86SubSuperRegister(Reg, MVT::i16);
689     break;
690   case 'k': // Print SImode register
691     Reg = getX86SubSuperRegister(Reg, MVT::i32);
692     break;
693   case 'q': // Print DImode register
694     Reg = getX86SubSuperRegister(Reg, MVT::i64);
695     break;
696   }
697
698   O << '%'<< TRI->getAsmName(Reg);
699   return false;
700 }
701
702 /// PrintAsmOperand - Print out an operand for an inline asm expression.
703 ///
704 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
705                                        unsigned AsmVariant,
706                                        const char *ExtraCode) {
707   // Does this asm operand have a single letter operand modifier?
708   if (ExtraCode && ExtraCode[0]) {
709     if (ExtraCode[1] != 0) return true; // Unknown modifier.
710
711     switch (ExtraCode[0]) {
712     default: return true;  // Unknown modifier.
713     case 'c': // Don't print "$" before a global var name or constant.
714       printOperand(MI, OpNo, "mem");
715       return false;
716     case 'b': // Print QImode register
717     case 'h': // Print QImode high register
718     case 'w': // Print HImode register
719     case 'k': // Print SImode register
720     case 'q': // Print DImode register
721       if (MI->getOperand(OpNo).isReg())
722         return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
723       printOperand(MI, OpNo);
724       return false;
725
726     case 'P': // This is the operand of a call, treat specially.
727       print_pcrel_imm(MI, OpNo);
728       return false;
729
730     case 'n': { // Negate the immediate or print a '-' before the operand.
731       // Note: this is a temporary solution. It should be handled target
732       // independently as part of the 'MC' work.
733       const MachineOperand &MO = MI->getOperand(OpNo);
734       if (MO.isImm()) {
735         O << -MO.getImm();
736         return false;
737       }
738       O << '-';
739     }
740     }
741   }
742
743   printOperand(MI, OpNo);
744   return false;
745 }
746
747 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
748                                              unsigned OpNo,
749                                              unsigned AsmVariant,
750                                              const char *ExtraCode) {
751   if (ExtraCode && ExtraCode[0]) {
752     if (ExtraCode[1] != 0) return true; // Unknown modifier.
753
754     switch (ExtraCode[0]) {
755     default: return true;  // Unknown modifier.
756     case 'b': // Print QImode register
757     case 'h': // Print QImode high register
758     case 'w': // Print HImode register
759     case 'k': // Print SImode register
760     case 'q': // Print SImode register
761       // These only apply to registers, ignore on mem.
762       break;
763     case 'P': // Don't print @PLT, but do print as memory.
764       printMemReference(MI, OpNo, "no-rip");
765       return false;
766     }
767   }
768   printMemReference(MI, OpNo);
769   return false;
770 }
771
772 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
773   // Convert registers in the addr mode according to subreg64.
774   for (unsigned i = 0; i != 4; ++i) {
775     if (!MI->getOperand(i).isReg()) continue;
776     
777     unsigned Reg = MI->getOperand(i).getReg();
778     if (Reg == 0) continue;
779     
780     MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
781   }
782 }
783
784 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
785 /// AT&T syntax to the current output stream.
786 ///
787 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
788   ++EmittedInsts;
789
790   if (NewAsmPrinter) {
791     if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
792       O << "\t";
793       printInlineAsm(MI);
794       return;
795     } else if (MI->isLabel()) {
796       printLabel(MI);
797       return;
798     } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
799       printDeclare(MI);
800       return;
801     } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
802       printImplicitDef(MI);
803       return;
804     }
805     
806     O << "NEW: ";
807     MCInst TmpInst;
808     
809     TmpInst.setOpcode(MI->getOpcode());
810     
811     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
812       const MachineOperand &MO = MI->getOperand(i);
813       
814       MCOperand MCOp;
815       if (MO.isReg()) {
816         MCOp.MakeReg(MO.getReg());
817       } else if (MO.isImm()) {
818         MCOp.MakeImm(MO.getImm());
819       } else if (MO.isMBB()) {
820         MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
821       } else {
822         assert(0 && "Unimp");
823       }
824       
825       TmpInst.addOperand(MCOp);
826     }
827     
828     switch (TmpInst.getOpcode()) {
829     case X86::LEA64_32r:
830       // Handle the 'subreg rewriting' for the lea64_32mem operand.
831       lower_lea64_32mem(&TmpInst, 1);
832       break;
833     }
834     
835     // FIXME: Convert TmpInst.
836     printInstruction(&TmpInst);
837     O << "OLD: ";
838   }
839   
840   // Call the autogenerated instruction printer routines.
841   printInstruction(MI);
842 }
843
844 /// doInitialization
845 bool X86ATTAsmPrinter::doInitialization(Module &M) {
846   if (NewAsmPrinter) {
847     Context = new MCContext();
848     // FIXME: Send this to "O" instead of outs().  For now, we force it to
849     // stdout to make it easy to compare.
850     Streamer = createAsmStreamer(*Context, outs());
851   }
852   
853   return AsmPrinter::doInitialization(M);
854 }
855
856 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
857   const TargetData *TD = TM.getTargetData();
858
859   if (!GVar->hasInitializer())
860     return;   // External global require no code
861
862   // Check to see if this is a special global used by LLVM, if so, emit it.
863   if (EmitSpecialLLVMGlobal(GVar)) {
864     if (Subtarget->isTargetDarwin() &&
865         TM.getRelocationModel() == Reloc::Static) {
866       if (GVar->getName() == "llvm.global_ctors")
867         O << ".reference .constructors_used\n";
868       else if (GVar->getName() == "llvm.global_dtors")
869         O << ".reference .destructors_used\n";
870     }
871     return;
872   }
873
874   std::string name = Mang->getValueName(GVar);
875   Constant *C = GVar->getInitializer();
876   if (isa<MDNode>(C) || isa<MDString>(C))
877     return;
878   const Type *Type = C->getType();
879   unsigned Size = TD->getTypeAllocSize(Type);
880   unsigned Align = TD->getPreferredAlignmentLog(GVar);
881
882   printVisibility(name, GVar->getVisibility());
883
884   if (Subtarget->isTargetELF())
885     O << "\t.type\t" << name << ",@object\n";
886
887   SwitchToSection(TAI->SectionForGlobal(GVar));
888
889   if (C->isNullValue() && !GVar->hasSection() &&
890       !(Subtarget->isTargetDarwin() &&
891         TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
892     // FIXME: This seems to be pretty darwin-specific
893     if (GVar->hasExternalLinkage()) {
894       if (const char *Directive = TAI->getZeroFillDirective()) {
895         O << "\t.globl " << name << '\n';
896         O << Directive << "__DATA, __common, " << name << ", "
897           << Size << ", " << Align << '\n';
898         return;
899       }
900     }
901
902     if (!GVar->isThreadLocal() &&
903         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
904       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
905
906       if (TAI->getLCOMMDirective() != NULL) {
907         if (GVar->hasLocalLinkage()) {
908           O << TAI->getLCOMMDirective() << name << ',' << Size;
909           if (Subtarget->isTargetDarwin())
910             O << ',' << Align;
911         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
912           O << "\t.globl " << name << '\n'
913             << TAI->getWeakDefDirective() << name << '\n';
914           EmitAlignment(Align, GVar);
915           O << name << ":";
916           if (VerboseAsm) {
917             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
918             PrintUnmangledNameSafely(GVar, O);
919           }
920           O << '\n';
921           EmitGlobalConstant(C);
922           return;
923         } else {
924           O << TAI->getCOMMDirective()  << name << ',' << Size;
925           if (TAI->getCOMMDirectiveTakesAlignment())
926             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
927         }
928       } else {
929         if (!Subtarget->isTargetCygMing()) {
930           if (GVar->hasLocalLinkage())
931             O << "\t.local\t" << name << '\n';
932         }
933         O << TAI->getCOMMDirective()  << name << ',' << Size;
934         if (TAI->getCOMMDirectiveTakesAlignment())
935           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
936       }
937       if (VerboseAsm) {
938         O << "\t\t" << TAI->getCommentString() << ' ';
939         PrintUnmangledNameSafely(GVar, O);
940       }
941       O << '\n';
942       return;
943     }
944   }
945
946   switch (GVar->getLinkage()) {
947   case GlobalValue::CommonLinkage:
948   case GlobalValue::LinkOnceAnyLinkage:
949   case GlobalValue::LinkOnceODRLinkage:
950   case GlobalValue::WeakAnyLinkage:
951   case GlobalValue::WeakODRLinkage:
952     if (Subtarget->isTargetDarwin()) {
953       O << "\t.globl " << name << '\n'
954         << TAI->getWeakDefDirective() << name << '\n';
955     } else if (Subtarget->isTargetCygMing()) {
956       O << "\t.globl\t" << name << "\n"
957            "\t.linkonce same_size\n";
958     } else {
959       O << "\t.weak\t" << name << '\n';
960     }
961     break;
962   case GlobalValue::DLLExportLinkage:
963   case GlobalValue::AppendingLinkage:
964     // FIXME: appending linkage variables should go into a section of
965     // their name or something.  For now, just emit them as external.
966   case GlobalValue::ExternalLinkage:
967     // If external or appending, declare as a global symbol
968     O << "\t.globl " << name << '\n';
969     // FALL THROUGH
970   case GlobalValue::PrivateLinkage:
971   case GlobalValue::InternalLinkage:
972      break;
973   default:
974     assert(0 && "Unknown linkage type!");
975   }
976
977   EmitAlignment(Align, GVar);
978   O << name << ":";
979   if (VerboseAsm){
980     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
981     PrintUnmangledNameSafely(GVar, O);
982   }
983   O << '\n';
984   if (TAI->hasDotTypeDotSizeDirective())
985     O << "\t.size\t" << name << ", " << Size << '\n';
986
987   EmitGlobalConstant(C);
988 }
989
990 bool X86ATTAsmPrinter::doFinalization(Module &M) {
991   // Print out module-level global variables here.
992   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
993        I != E; ++I) {
994     printModuleLevelGV(I);
995
996     if (I->hasDLLExportLinkage())
997       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
998   }
999
1000   if (Subtarget->isTargetDarwin()) {
1001     SwitchToDataSection("");
1002     
1003     // Add the (possibly multiple) personalities to the set of global value
1004     // stubs.  Only referenced functions get into the Personalities list.
1005     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1006       const std::vector<Function*> &Personalities = MMI->getPersonalities();
1007       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1008         if (Personalities[i] == 0)
1009           continue;
1010         std::string Name = Mang->getValueName(Personalities[i]);
1011         decorateName(Name, Personalities[i]);
1012         GVStubs.insert(Name);
1013       }
1014     }
1015
1016     // Output stubs for dynamically-linked functions
1017     if (!FnStubs.empty()) {
1018       for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1019            I != E; ++I) {
1020         SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1021                             "self_modifying_code+pure_instructions,5", 0);
1022         const char *Name = I->getKeyData();
1023         printSuffixedName(Name, "$stub");
1024         O << ":\n"
1025              "\t.indirect_symbol " << Name << "\n"
1026              "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1027       }
1028       O << '\n';
1029     }
1030
1031     // Output stubs for external and common global variables.
1032     if (!GVStubs.empty()) {
1033       SwitchToDataSection(
1034                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1035       for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1036            I != E; ++I) {
1037         const char *Name = I->getKeyData();
1038         printSuffixedName(Name, "$non_lazy_ptr");
1039         O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1040       }
1041     }
1042
1043     if (!HiddenGVStubs.empty()) {
1044       SwitchToSection(TAI->getDataSection());
1045       EmitAlignment(2);
1046       for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1047            E = HiddenGVStubs.end(); I != E; ++I) {
1048         const char *Name = I->getKeyData();
1049         printSuffixedName(Name, "$non_lazy_ptr");
1050         O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1051       }
1052     }
1053
1054     // Funny Darwin hack: This flag tells the linker that no global symbols
1055     // contain code that falls through to other global symbols (e.g. the obvious
1056     // implementation of multiple entry points).  If this doesn't occur, the
1057     // linker can safely perform dead code stripping.  Since LLVM never
1058     // generates code that does this, it is always safe to set.
1059     O << "\t.subsections_via_symbols\n";
1060   } else if (Subtarget->isTargetCygMing()) {
1061     // Emit type information for external functions
1062     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1063          i != e; ++i) {
1064       O << "\t.def\t " << i->getKeyData()
1065         << ";\t.scl\t" << COFF::C_EXT
1066         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1067         << ";\t.endef\n";
1068     }
1069   }
1070   
1071   
1072   // Output linker support code for dllexported globals on windows.
1073   if (!DLLExportedGVs.empty()) {
1074     SwitchToDataSection(".section .drectve");
1075   
1076     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1077          e = DLLExportedGVs.end(); i != e; ++i)
1078       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1079   }
1080   
1081   if (!DLLExportedFns.empty()) {
1082     SwitchToDataSection(".section .drectve");
1083   
1084     for (StringSet<>::iterator i = DLLExportedFns.begin(),
1085          e = DLLExportedFns.end();
1086          i != e; ++i)
1087       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1088   }
1089   
1090   // Do common shutdown.
1091   bool Changed = AsmPrinter::doFinalization(M);
1092   
1093   if (NewAsmPrinter) {
1094     Streamer->Finish();
1095     
1096     delete Streamer;
1097     delete Context;
1098     Streamer = 0;
1099     Context = 0;
1100   }
1101   
1102   return Changed;
1103 }
1104
1105 // Include the auto-generated portion of the assembly writer.
1106 #include "X86GenAsmWriter.inc"