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