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