add some more assertions. Remove code to handle dllimport on darwin.
[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 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
290   return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
291 }
292
293 /// print_pcrel_imm - This is used to print an immediate value that ends up
294 /// being encoded as a pc-relative value.  These print slightly differently, for
295 /// example, a $ is not emitted.
296 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
297   const MachineOperand &MO = MI->getOperand(OpNo);
298   switch (MO.getType()) {
299   default: assert(0 && "Unknown pcrel immediate operand");
300   case MachineOperand::MO_Immediate:
301     O << MO.getImm();
302     return;
303   case MachineOperand::MO_MachineBasicBlock:
304     printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
305     return;
306       
307   case MachineOperand::MO_GlobalAddress: {
308     const GlobalValue *GV = MO.getGlobal();
309     std::string Name = Mang->getValueName(GV);
310     decorateName(Name, GV);
311     
312     bool needCloseParen = false;
313     if (Name[0] == '$') {
314       // The name begins with a dollar-sign. In order to avoid having it look
315       // like an integer immediate to the assembler, enclose it in parens.
316       O << '(';
317       needCloseParen = true;
318     }
319     
320     if (shouldPrintStub(TM, Subtarget)) {
321       // DARWIN/X86-32 in != static mode.
322       
323       // Link-once, declaration, or Weakly-linked global variables need
324       // non-lazily-resolved stubs
325       if (GV->isDeclaration() || GV->isWeakForLinker()) {
326         // Dynamically-resolved functions need a stub for the function.
327         if (isa<Function>(GV)) {
328           // Function stubs are no longer needed for Mac OS X 10.5 and up.
329           if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
330             O << Name;
331           } else {
332             FnStubs.insert(Name);
333             printSuffixedName(Name, "$stub");
334           }
335           assert(MO.getTargetFlags() == 0);
336         } else if (GV->hasHiddenVisibility()) {
337           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
338             // Definition is not definitely in the current translation unit.
339             O << Name;
340           else {
341             HiddenGVStubs.insert(Name);
342             printSuffixedName(Name, "$non_lazy_ptr");
343             assert(MO.getTargetFlags() == 0);
344           }
345         } else {
346           GVStubs.insert(Name);
347           printSuffixedName(Name, "$non_lazy_ptr");
348           assert(MO.getTargetFlags() == 0);
349         }
350       } else {
351         O << Name;
352       }
353     } else {
354       if (GV->hasDLLImportLinkage()) {
355         assert(MO.getTargetFlags() == 0);
356         O << "__imp_";
357       }
358       O << Name;
359       
360       if (shouldPrintPLT(TM, Subtarget)) {
361         // Assemble call via PLT for externally visible symbols
362         if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
363             !GV->hasLocalLinkage())
364           O << "@PLT";
365       }
366       if (Subtarget->isTargetCygMing() && GV->isDeclaration())
367         // Save function name for later type emission
368         FnStubs.insert(Name);
369     }
370     
371     printOffset(MO.getOffset());
372     
373     if (needCloseParen)
374       O << ')';
375     return;
376   }
377       
378   case MachineOperand::MO_ExternalSymbol: {
379     bool needCloseParen = false;
380     std::string Name(TAI->getGlobalPrefix());
381     Name += MO.getSymbolName();
382     // Print function stub suffix unless it's Mac OS X 10.5 and up.
383     if (shouldPrintStub(TM, Subtarget) && 
384         // DARWIN/X86-32 in != static mode.
385         !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
386       
387       FnStubs.insert(Name);
388       printSuffixedName(Name, "$stub");
389       return;
390     }
391     
392     if (Name[0] == '$') {
393       // The name begins with a dollar-sign. In order to avoid having it look
394       // like an integer immediate to the assembler, enclose it in parens.
395       O << '(';
396       needCloseParen = true;
397     }
398     
399     O << Name;
400     
401     if (MO.getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS) {
402       O << " + [.-";
403       PrintPICBaseSymbol();
404       O << ']';
405     }
406     
407     if (shouldPrintPLT(TM, Subtarget))
408       O << "@PLT";
409     
410     if (needCloseParen)
411       O << ')';
412     
413     return;
414   }
415   }
416 }
417
418 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
419                                     const char *Modifier) {
420   const MachineOperand &MO = MI->getOperand(OpNo);
421   switch (MO.getType()) {
422   default: assert(0 && "unknown operand type!");
423   case MachineOperand::MO_Register: {
424     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
425            "Virtual registers should not make it this far!");
426     O << '%';
427     unsigned Reg = MO.getReg();
428     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
429       MVT VT = (strcmp(Modifier+6,"64") == 0) ?
430         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
431                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
432       Reg = getX86SubSuperRegister(Reg, VT);
433     }
434     O << TRI->getAsmName(Reg);
435     return;
436   }
437
438   case MachineOperand::MO_Immediate:
439     if (!Modifier || (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
440       O << '$';
441     O << MO.getImm();
442     return;
443   case MachineOperand::MO_JumpTableIndex: {
444     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
445     if (!isMemOp) O << '$';
446     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
447       << MO.getIndex();
448     break;
449   }
450   case MachineOperand::MO_ConstantPoolIndex: {
451     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
452     if (!isMemOp) O << '$';
453     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
454       << MO.getIndex();
455
456     printOffset(MO.getOffset());
457     break;
458   }
459   case MachineOperand::MO_GlobalAddress: {
460     bool isMemOp = Modifier && !strcmp(Modifier, "mem");
461     const GlobalValue *GV = MO.getGlobal();
462     std::string Name = Mang->getValueName(GV);
463     decorateName(Name, GV);
464
465     bool needCloseParen = false;
466     if (!isMemOp)
467       O << '$';
468     else if (Name[0] == '$') {
469       // The name begins with a dollar-sign. In order to avoid having it look
470       // like an integer immediate to the assembler, enclose it in parens.
471       O << '(';
472       needCloseParen = true;
473     }
474
475     if (shouldPrintStub(TM, Subtarget)) {
476       // DARWIN/X86-32 in != static mode.
477
478       // Link-once, declaration, or Weakly-linked global variables need
479       // non-lazily-resolved stubs
480       if (GV->isDeclaration() || GV->isWeakForLinker()) {
481         if (GV->hasHiddenVisibility()) {
482           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
483             // Definition is not definitely in the current translation unit.
484             O << Name;
485           else {
486             HiddenGVStubs.insert(Name);
487             printSuffixedName(Name, "$non_lazy_ptr");
488             assert(MO.getTargetFlags() == 0);
489           }
490         } else {
491           GVStubs.insert(Name);
492           printSuffixedName(Name, "$non_lazy_ptr");
493           assert(MO.getTargetFlags() == 0);
494         }
495       } else {
496         O << Name;
497       }
498
499       if (TM.getRelocationModel() == Reloc::PIC_) {
500         O << '-';
501         PrintPICBaseSymbol();
502       }        
503     } else {
504       if (GV->hasDLLImportLinkage()) {
505         O << "__imp_";
506         assert(MO.getTargetFlags() == 0);
507       }
508       O << Name;
509     }
510
511     printOffset(MO.getOffset());
512
513     if (needCloseParen)
514       O << ')';
515     
516     break;
517   }
518   case MachineOperand::MO_ExternalSymbol:
519     /// NOTE: MO_ExternalSymbol in a non-pcrel_imm context is *only* generated
520     /// by _GLOBAL_OFFSET_TABLE_ on X86-32.  All others are call operands, which
521     /// are pcrel_imm's.
522     assert(!Subtarget->is64Bit() && !Subtarget->isPICStyleRIPRel());
523     // These are never used as memory operands.
524     assert(Modifier == 0 || strcmp(Modifier, "mem"));
525     O << '$';
526     O << TAI->getGlobalPrefix();
527     O << MO.getSymbolName();
528     break;
529   }
530   
531   switch (MO.getTargetFlags()) {
532   default:
533     assert(0 && "Unknown target flag on GV operand");
534   case X86II::MO_NO_FLAG:
535     break;
536   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
537     O << " + [.-";
538     PrintPICBaseSymbol();
539     O << ']';
540     break;      
541   case X86II::MO_PIC_BASE_OFFSET:
542     O << '-';
543     PrintPICBaseSymbol();
544     break;
545   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
546   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
547   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
548   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
549   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
550   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
551   case X86II::MO_GOT:       O << "@GOT";       break;
552   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
553   }
554 }
555
556 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
557   unsigned char value = MI->getOperand(Op).getImm();
558   assert(value <= 7 && "Invalid ssecc argument!");
559   switch (value) {
560   case 0: O << "eq"; break;
561   case 1: O << "lt"; break;
562   case 2: O << "le"; break;
563   case 3: O << "unord"; break;
564   case 4: O << "neq"; break;
565   case 5: O << "nlt"; break;
566   case 6: O << "nle"; break;
567   case 7: O << "ord"; break;
568   }
569 }
570
571 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
572                                             const char *Modifier) {
573   const MachineOperand &BaseReg  = MI->getOperand(Op);
574   const MachineOperand &IndexReg = MI->getOperand(Op+2);
575   const MachineOperand &DispSpec = MI->getOperand(Op+3);
576
577   // If we really don't want to print out (rip), don't.
578   bool HasBaseReg = BaseReg.getReg() != 0;
579   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
580       BaseReg.getReg() == X86::RIP)
581     HasBaseReg = false;
582   
583   // HasParenPart - True if we will print out the () part of the mem ref.
584   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
585   
586   if (DispSpec.isImm()) {
587     int DispVal = DispSpec.getImm();
588     if (DispVal || !HasParenPart)
589       O << DispVal;
590   } else {
591     assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
592            DispSpec.isJTI() || DispSpec.isSymbol());
593     printOperand(MI, Op+3, "mem");
594   }
595
596   if (HasParenPart) {
597     assert(IndexReg.getReg() != X86::ESP &&
598            "X86 doesn't allow scaling by ESP");
599
600     O << '(';
601     if (HasBaseReg)
602       printOperand(MI, Op, Modifier);
603
604     if (IndexReg.getReg()) {
605       O << ',';
606       printOperand(MI, Op+2, Modifier);
607       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
608       if (ScaleVal != 1)
609         O << ',' << ScaleVal;
610     }
611     O << ')';
612   }
613 }
614
615 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
616                                          const char *Modifier) {
617   assert(isMem(MI, Op) && "Invalid memory reference!");
618   const MachineOperand &Segment = MI->getOperand(Op+4);
619   if (Segment.getReg()) {
620     printOperand(MI, Op+4, Modifier);
621     O << ':';
622   }
623   printLeaMemReference(MI, Op, Modifier);
624 }
625
626 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
627                                            const MachineBasicBlock *MBB) const {
628   if (!TAI->getSetDirective())
629     return;
630
631   // We don't need .set machinery if we have GOT-style relocations
632   if (Subtarget->isPICStyleGOT())
633     return;
634
635   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
636     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
637   printBasicBlockLabel(MBB, false, false, false);
638   if (Subtarget->isPICStyleRIPRel())
639     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
640       << '_' << uid << '\n';
641   else {
642     O << '-';
643     PrintPICBaseSymbol();
644     O << '\n';
645   }
646 }
647
648
649 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
650   PrintPICBaseSymbol();
651   O << '\n';
652   PrintPICBaseSymbol();
653   O << ':';
654 }
655
656
657 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
658                                               const MachineBasicBlock *MBB,
659                                               unsigned uid) const
660 {
661   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
662     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
663
664   O << JTEntryDirective << ' ';
665
666   if (TM.getRelocationModel() == Reloc::PIC_) {
667     if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
668       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
669         << '_' << uid << "_set_" << MBB->getNumber();
670     } else if (Subtarget->isPICStyleGOT()) {
671       printBasicBlockLabel(MBB, false, false, false);
672       O << "@GOTOFF";
673     } else
674       assert(0 && "Don't know how to print MBB label for this PIC mode");
675   } else
676     printBasicBlockLabel(MBB, false, false, false);
677 }
678
679 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
680   unsigned Reg = MO.getReg();
681   switch (Mode) {
682   default: return true;  // Unknown mode.
683   case 'b': // Print QImode register
684     Reg = getX86SubSuperRegister(Reg, MVT::i8);
685     break;
686   case 'h': // Print QImode high register
687     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
688     break;
689   case 'w': // Print HImode register
690     Reg = getX86SubSuperRegister(Reg, MVT::i16);
691     break;
692   case 'k': // Print SImode register
693     Reg = getX86SubSuperRegister(Reg, MVT::i32);
694     break;
695   case 'q': // Print DImode register
696     Reg = getX86SubSuperRegister(Reg, MVT::i64);
697     break;
698   }
699
700   O << '%'<< TRI->getAsmName(Reg);
701   return false;
702 }
703
704 /// PrintAsmOperand - Print out an operand for an inline asm expression.
705 ///
706 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
707                                        unsigned AsmVariant,
708                                        const char *ExtraCode) {
709   // Does this asm operand have a single letter operand modifier?
710   if (ExtraCode && ExtraCode[0]) {
711     if (ExtraCode[1] != 0) return true; // Unknown modifier.
712
713     switch (ExtraCode[0]) {
714     default: return true;  // Unknown modifier.
715     case 'c': // Don't print "$" before a global var name or constant.
716       printOperand(MI, OpNo, "mem");
717       return false;
718     case 'b': // Print QImode register
719     case 'h': // Print QImode high register
720     case 'w': // Print HImode register
721     case 'k': // Print SImode register
722     case 'q': // Print DImode register
723       if (MI->getOperand(OpNo).isReg())
724         return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
725       printOperand(MI, OpNo);
726       return false;
727
728     case 'P': // This is the operand of a call, treat specially.
729       print_pcrel_imm(MI, OpNo);
730       return false;
731
732     case 'n': { // Negate the immediate or print a '-' before the operand.
733       // Note: this is a temporary solution. It should be handled target
734       // independently as part of the 'MC' work.
735       const MachineOperand &MO = MI->getOperand(OpNo);
736       if (MO.isImm()) {
737         O << -MO.getImm();
738         return false;
739       }
740       O << '-';
741     }
742     }
743   }
744
745   printOperand(MI, OpNo);
746   return false;
747 }
748
749 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
750                                              unsigned OpNo,
751                                              unsigned AsmVariant,
752                                              const char *ExtraCode) {
753   if (ExtraCode && ExtraCode[0]) {
754     if (ExtraCode[1] != 0) return true; // Unknown modifier.
755
756     switch (ExtraCode[0]) {
757     default: return true;  // Unknown modifier.
758     case 'b': // Print QImode register
759     case 'h': // Print QImode high register
760     case 'w': // Print HImode register
761     case 'k': // Print SImode register
762     case 'q': // Print SImode register
763       // These only apply to registers, ignore on mem.
764       break;
765     case 'P': // Don't print @PLT, but do print as memory.
766       printMemReference(MI, OpNo, "no-rip");
767       return false;
768     }
769   }
770   printMemReference(MI, OpNo);
771   return false;
772 }
773
774 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
775   // Convert registers in the addr mode according to subreg64.
776   for (unsigned i = 0; i != 4; ++i) {
777     if (!MI->getOperand(i).isReg()) continue;
778     
779     unsigned Reg = MI->getOperand(i).getReg();
780     if (Reg == 0) continue;
781     
782     MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
783   }
784 }
785
786 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
787 /// AT&T syntax to the current output stream.
788 ///
789 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
790   ++EmittedInsts;
791
792   if (NewAsmPrinter) {
793     if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
794       O << "\t";
795       printInlineAsm(MI);
796       return;
797     } else if (MI->isLabel()) {
798       printLabel(MI);
799       return;
800     } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
801       printDeclare(MI);
802       return;
803     } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
804       printImplicitDef(MI);
805       return;
806     }
807     
808     O << "NEW: ";
809     MCInst TmpInst;
810     
811     TmpInst.setOpcode(MI->getOpcode());
812     
813     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
814       const MachineOperand &MO = MI->getOperand(i);
815       
816       MCOperand MCOp;
817       if (MO.isReg()) {
818         MCOp.MakeReg(MO.getReg());
819       } else if (MO.isImm()) {
820         MCOp.MakeImm(MO.getImm());
821       } else if (MO.isMBB()) {
822         MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
823       } else {
824         assert(0 && "Unimp");
825       }
826       
827       TmpInst.addOperand(MCOp);
828     }
829     
830     switch (TmpInst.getOpcode()) {
831     case X86::LEA64_32r:
832       // Handle the 'subreg rewriting' for the lea64_32mem operand.
833       lower_lea64_32mem(&TmpInst, 1);
834       break;
835     }
836     
837     // FIXME: Convert TmpInst.
838     printInstruction(&TmpInst);
839     O << "OLD: ";
840   }
841   
842   // Call the autogenerated instruction printer routines.
843   printInstruction(MI);
844 }
845
846 /// doInitialization
847 bool X86ATTAsmPrinter::doInitialization(Module &M) {
848   if (NewAsmPrinter) {
849     Context = new MCContext();
850     // FIXME: Send this to "O" instead of outs().  For now, we force it to
851     // stdout to make it easy to compare.
852     Streamer = createAsmStreamer(*Context, outs());
853   }
854   
855   return AsmPrinter::doInitialization(M);
856 }
857
858 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
859   const TargetData *TD = TM.getTargetData();
860
861   if (!GVar->hasInitializer())
862     return;   // External global require no code
863
864   // Check to see if this is a special global used by LLVM, if so, emit it.
865   if (EmitSpecialLLVMGlobal(GVar)) {
866     if (Subtarget->isTargetDarwin() &&
867         TM.getRelocationModel() == Reloc::Static) {
868       if (GVar->getName() == "llvm.global_ctors")
869         O << ".reference .constructors_used\n";
870       else if (GVar->getName() == "llvm.global_dtors")
871         O << ".reference .destructors_used\n";
872     }
873     return;
874   }
875
876   std::string name = Mang->getValueName(GVar);
877   Constant *C = GVar->getInitializer();
878   if (isa<MDNode>(C) || isa<MDString>(C))
879     return;
880   const Type *Type = C->getType();
881   unsigned Size = TD->getTypeAllocSize(Type);
882   unsigned Align = TD->getPreferredAlignmentLog(GVar);
883
884   printVisibility(name, GVar->getVisibility());
885
886   if (Subtarget->isTargetELF())
887     O << "\t.type\t" << name << ",@object\n";
888
889   SwitchToSection(TAI->SectionForGlobal(GVar));
890
891   if (C->isNullValue() && !GVar->hasSection() &&
892       !(Subtarget->isTargetDarwin() &&
893         TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
894     // FIXME: This seems to be pretty darwin-specific
895     if (GVar->hasExternalLinkage()) {
896       if (const char *Directive = TAI->getZeroFillDirective()) {
897         O << "\t.globl " << name << '\n';
898         O << Directive << "__DATA, __common, " << name << ", "
899           << Size << ", " << Align << '\n';
900         return;
901       }
902     }
903
904     if (!GVar->isThreadLocal() &&
905         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
906       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
907
908       if (TAI->getLCOMMDirective() != NULL) {
909         if (GVar->hasLocalLinkage()) {
910           O << TAI->getLCOMMDirective() << name << ',' << Size;
911           if (Subtarget->isTargetDarwin())
912             O << ',' << Align;
913         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
914           O << "\t.globl " << name << '\n'
915             << TAI->getWeakDefDirective() << name << '\n';
916           EmitAlignment(Align, GVar);
917           O << name << ":";
918           if (VerboseAsm) {
919             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
920             PrintUnmangledNameSafely(GVar, O);
921           }
922           O << '\n';
923           EmitGlobalConstant(C);
924           return;
925         } else {
926           O << TAI->getCOMMDirective()  << name << ',' << Size;
927           if (TAI->getCOMMDirectiveTakesAlignment())
928             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
929         }
930       } else {
931         if (!Subtarget->isTargetCygMing()) {
932           if (GVar->hasLocalLinkage())
933             O << "\t.local\t" << name << '\n';
934         }
935         O << TAI->getCOMMDirective()  << name << ',' << Size;
936         if (TAI->getCOMMDirectiveTakesAlignment())
937           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
938       }
939       if (VerboseAsm) {
940         O << "\t\t" << TAI->getCommentString() << ' ';
941         PrintUnmangledNameSafely(GVar, O);
942       }
943       O << '\n';
944       return;
945     }
946   }
947
948   switch (GVar->getLinkage()) {
949   case GlobalValue::CommonLinkage:
950   case GlobalValue::LinkOnceAnyLinkage:
951   case GlobalValue::LinkOnceODRLinkage:
952   case GlobalValue::WeakAnyLinkage:
953   case GlobalValue::WeakODRLinkage:
954     if (Subtarget->isTargetDarwin()) {
955       O << "\t.globl " << name << '\n'
956         << TAI->getWeakDefDirective() << name << '\n';
957     } else if (Subtarget->isTargetCygMing()) {
958       O << "\t.globl\t" << name << "\n"
959            "\t.linkonce same_size\n";
960     } else {
961       O << "\t.weak\t" << name << '\n';
962     }
963     break;
964   case GlobalValue::DLLExportLinkage:
965   case GlobalValue::AppendingLinkage:
966     // FIXME: appending linkage variables should go into a section of
967     // their name or something.  For now, just emit them as external.
968   case GlobalValue::ExternalLinkage:
969     // If external or appending, declare as a global symbol
970     O << "\t.globl " << name << '\n';
971     // FALL THROUGH
972   case GlobalValue::PrivateLinkage:
973   case GlobalValue::InternalLinkage:
974      break;
975   default:
976     assert(0 && "Unknown linkage type!");
977   }
978
979   EmitAlignment(Align, GVar);
980   O << name << ":";
981   if (VerboseAsm){
982     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
983     PrintUnmangledNameSafely(GVar, O);
984   }
985   O << '\n';
986   if (TAI->hasDotTypeDotSizeDirective())
987     O << "\t.size\t" << name << ", " << Size << '\n';
988
989   EmitGlobalConstant(C);
990 }
991
992 bool X86ATTAsmPrinter::doFinalization(Module &M) {
993   // Print out module-level global variables here.
994   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
995        I != E; ++I) {
996     printModuleLevelGV(I);
997
998     if (I->hasDLLExportLinkage())
999       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1000   }
1001
1002   if (Subtarget->isTargetDarwin()) {
1003     SwitchToDataSection("");
1004     
1005     // Add the (possibly multiple) personalities to the set of global value
1006     // stubs.  Only referenced functions get into the Personalities list.
1007     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1008       const std::vector<Function*> &Personalities = MMI->getPersonalities();
1009       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1010         if (Personalities[i] == 0)
1011           continue;
1012         std::string Name = Mang->getValueName(Personalities[i]);
1013         decorateName(Name, Personalities[i]);
1014         GVStubs.insert(Name);
1015       }
1016     }
1017
1018     // Output stubs for dynamically-linked functions
1019     if (!FnStubs.empty()) {
1020       for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1021            I != E; ++I) {
1022         SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1023                             "self_modifying_code+pure_instructions,5", 0);
1024         const char *Name = I->getKeyData();
1025         printSuffixedName(Name, "$stub");
1026         O << ":\n"
1027              "\t.indirect_symbol " << Name << "\n"
1028              "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1029       }
1030       O << '\n';
1031     }
1032
1033     // Output stubs for external and common global variables.
1034     if (!GVStubs.empty()) {
1035       SwitchToDataSection(
1036                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1037       for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1038            I != E; ++I) {
1039         const char *Name = I->getKeyData();
1040         printSuffixedName(Name, "$non_lazy_ptr");
1041         O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1042       }
1043     }
1044
1045     if (!HiddenGVStubs.empty()) {
1046       SwitchToSection(TAI->getDataSection());
1047       EmitAlignment(2);
1048       for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1049            E = HiddenGVStubs.end(); I != E; ++I) {
1050         const char *Name = I->getKeyData();
1051         printSuffixedName(Name, "$non_lazy_ptr");
1052         O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1053       }
1054     }
1055
1056     // Funny Darwin hack: This flag tells the linker that no global symbols
1057     // contain code that falls through to other global symbols (e.g. the obvious
1058     // implementation of multiple entry points).  If this doesn't occur, the
1059     // linker can safely perform dead code stripping.  Since LLVM never
1060     // generates code that does this, it is always safe to set.
1061     O << "\t.subsections_via_symbols\n";
1062   } else if (Subtarget->isTargetCygMing()) {
1063     // Emit type information for external functions
1064     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1065          i != e; ++i) {
1066       O << "\t.def\t " << i->getKeyData()
1067         << ";\t.scl\t" << COFF::C_EXT
1068         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1069         << ";\t.endef\n";
1070     }
1071   }
1072   
1073   
1074   // Output linker support code for dllexported globals on windows.
1075   if (!DLLExportedGVs.empty()) {
1076     SwitchToDataSection(".section .drectve");
1077   
1078     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1079          e = DLLExportedGVs.end(); i != e; ++i)
1080       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1081   }
1082   
1083   if (!DLLExportedFns.empty()) {
1084     SwitchToDataSection(".section .drectve");
1085   
1086     for (StringSet<>::iterator i = DLLExportedFns.begin(),
1087          e = DLLExportedFns.end();
1088          i != e; ++i)
1089       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1090   }
1091   
1092   // Do common shutdown.
1093   bool Changed = AsmPrinter::doFinalization(M);
1094   
1095   if (NewAsmPrinter) {
1096     Streamer->Finish();
1097     
1098     delete Streamer;
1099     delete Context;
1100     Streamer = 0;
1101     Context = 0;
1102   }
1103   
1104   return Changed;
1105 }
1106
1107 // Include the auto-generated portion of the assembly writer.
1108 #include "X86GenAsmWriter.inc"