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