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