LLVM API Documentation

X86ATTAsmPrinter.cpp

Go to the documentation of this file.
00001 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains a printer that converts from our internal representation
00011 // of machine-dependent LLVM code to AT&T format assembly
00012 // language. This printer is the output mechanism used by `llc'.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #define DEBUG_TYPE "asm-printer"
00017 #include "X86ATTAsmPrinter.h"
00018 #include "X86.h"
00019 #include "X86COFF.h"
00020 #include "X86MachineFunctionInfo.h"
00021 #include "X86TargetMachine.h"
00022 #include "X86TargetAsmInfo.h"
00023 #include "llvm/CallingConv.h"
00024 #include "llvm/DerivedTypes.h"
00025 #include "llvm/Module.h"
00026 #include "llvm/Type.h"
00027 #include "llvm/ADT/Statistic.h"
00028 #include "llvm/ADT/StringExtras.h"
00029 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00030 #include "llvm/Support/Mangler.h"
00031 #include "llvm/Support/raw_ostream.h"
00032 #include "llvm/Target/TargetAsmInfo.h"
00033 #include "llvm/Target/TargetOptions.h"
00034 using namespace llvm;
00035 
00036 STATISTIC(EmittedInsts, "Number of machine instrs printed");
00037 
00038 static std::string getPICLabelString(unsigned FnNum,
00039                                      const TargetAsmInfo *TAI,
00040                                      const X86Subtarget* Subtarget) {
00041   std::string label;
00042   if (Subtarget->isTargetDarwin())
00043     label =  "\"L" + utostr_32(FnNum) + "$pb\"";
00044   else if (Subtarget->isTargetELF())
00045     label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
00046   else
00047     assert(0 && "Don't know how to print PIC label!\n");
00048 
00049   return label;
00050 }
00051 
00052 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
00053                                                     const TargetData *TD) {
00054   X86MachineFunctionInfo Info;
00055   uint64_t Size = 0;
00056 
00057   switch (F->getCallingConv()) {
00058   case CallingConv::X86_StdCall:
00059     Info.setDecorationStyle(StdCall);
00060     break;
00061   case CallingConv::X86_FastCall:
00062     Info.setDecorationStyle(FastCall);
00063     break;
00064   default:
00065     return Info;
00066   }
00067 
00068   unsigned argNum = 1;
00069   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
00070        AI != AE; ++AI, ++argNum) {
00071     const Type* Ty = AI->getType();
00072 
00073     // 'Dereference' type in case of byval parameter attribute
00074     if (F->paramHasAttr(argNum, Attribute::ByVal))
00075       Ty = cast<PointerType>(Ty)->getElementType();
00076 
00077     // Size should be aligned to DWORD boundary
00078     Size += ((TD->getTypePaddedSize(Ty) + 3)/4)*4;
00079   }
00080 
00081   // We're not supporting tooooo huge arguments :)
00082   Info.setBytesToPopOnReturn((unsigned int)Size);
00083   return Info;
00084 }
00085 
00086 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
00087 /// Don't print things like \n or \0.
00088 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
00089   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
00090        Name != E; ++Name)
00091     if (isprint(*Name))
00092       OS << *Name;
00093 }
00094 
00095 /// decorateName - Query FunctionInfoMap and use this information for various
00096 /// name decoration.
00097 void X86ATTAsmPrinter::decorateName(std::string &Name,
00098                                     const GlobalValue *GV) {
00099   const Function *F = dyn_cast<Function>(GV);
00100   if (!F) return;
00101 
00102   // We don't want to decorate non-stdcall or non-fastcall functions right now
00103   unsigned CC = F->getCallingConv();
00104   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
00105     return;
00106 
00107   // Decorate names only when we're targeting Cygwin/Mingw32 targets
00108   if (!Subtarget->isTargetCygMing())
00109     return;
00110 
00111   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
00112 
00113   const X86MachineFunctionInfo *Info;
00114   if (info_item == FunctionInfoMap.end()) {
00115     // Calculate apropriate function info and populate map
00116     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
00117     Info = &FunctionInfoMap[F];
00118   } else {
00119     Info = &info_item->second;
00120   }
00121 
00122   const FunctionType *FT = F->getFunctionType();
00123   switch (Info->getDecorationStyle()) {
00124   case None:
00125     break;
00126   case StdCall:
00127     // "Pure" variadic functions do not receive @0 suffix.
00128     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
00129         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
00130       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
00131     break;
00132   case FastCall:
00133     // "Pure" variadic functions do not receive @0 suffix.
00134     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
00135         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
00136       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
00137 
00138     if (Name[0] == '_') {
00139       Name[0] = '@';
00140     } else {
00141       Name = '@' + Name;
00142     }
00143     break;
00144   default:
00145     assert(0 && "Unsupported DecorationStyle");
00146   }
00147 }
00148 
00149 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
00150   const Function *F = MF.getFunction();
00151 
00152   decorateName(CurrentFnName, F);
00153 
00154   SwitchToSection(TAI->SectionForGlobal(F));
00155 
00156   unsigned FnAlign = 4;
00157   if (F->hasFnAttr(Attribute::OptimizeForSize))
00158     FnAlign = 1;
00159   switch (F->getLinkage()) {
00160   default: assert(0 && "Unknown linkage type!");
00161   case Function::InternalLinkage:  // Symbols default to internal.
00162   case Function::PrivateLinkage:
00163     EmitAlignment(FnAlign, F);
00164     break;
00165   case Function::DLLExportLinkage:
00166   case Function::ExternalLinkage:
00167     EmitAlignment(FnAlign, F);
00168     O << "\t.globl\t" << CurrentFnName << '\n';
00169     break;
00170   case Function::LinkOnceLinkage:
00171   case Function::WeakLinkage:
00172     EmitAlignment(FnAlign, F);
00173     if (Subtarget->isTargetDarwin()) {
00174       O << "\t.globl\t" << CurrentFnName << '\n';
00175       O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
00176     } else if (Subtarget->isTargetCygMing()) {
00177       O << "\t.globl\t" << CurrentFnName << "\n"
00178            "\t.linkonce discard\n";
00179     } else {
00180       O << "\t.weak\t" << CurrentFnName << '\n';
00181     }
00182     break;
00183   }
00184 
00185   printVisibility(CurrentFnName, F->getVisibility());
00186 
00187   if (Subtarget->isTargetELF())
00188     O << "\t.type\t" << CurrentFnName << ",@function\n";
00189   else if (Subtarget->isTargetCygMing()) {
00190     O << "\t.def\t " << CurrentFnName
00191       << ";\t.scl\t" <<
00192       (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
00193       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
00194       << ";\t.endef\n";
00195   }
00196 
00197   O << CurrentFnName << ":\n";
00198   // Add some workaround for linkonce linkage on Cygwin\MinGW
00199   if (Subtarget->isTargetCygMing() &&
00200       (F->getLinkage() == Function::LinkOnceLinkage ||
00201        F->getLinkage() == Function::WeakLinkage))
00202     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
00203 }
00204 
00205 /// runOnMachineFunction - This uses the printMachineInstruction()
00206 /// method to print assembly for each instruction.
00207 ///
00208 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
00209   const Function *F = MF.getFunction();
00210   unsigned CC = F->getCallingConv();
00211 
00212   SetupMachineFunction(MF);
00213   O << "\n\n";
00214 
00215   // Populate function information map.  Actually, We don't want to populate
00216   // non-stdcall or non-fastcall functions' information right now.
00217   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
00218     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
00219 
00220   // Print out constants referenced by the function
00221   EmitConstantPool(MF.getConstantPool());
00222 
00223   if (F->hasDLLExportLinkage())
00224     DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
00225 
00226   // Print the 'header' of function
00227   emitFunctionHeader(MF);
00228 
00229   // Emit pre-function debug and/or EH information.
00230   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
00231     DW->BeginFunction(&MF);
00232 
00233   // Print out code for the function.
00234   bool hasAnyRealCode = false;
00235   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
00236        I != E; ++I) {
00237     // Print a label for the basic block.
00238     if (!I->pred_empty()) {
00239       printBasicBlockLabel(I, true, true);
00240       O << '\n';
00241     }
00242     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
00243          II != IE; ++II) {
00244       // Print the assembly for the instruction.
00245       if (!II->isLabel())
00246         hasAnyRealCode = true;
00247       printMachineInstruction(II);
00248     }
00249   }
00250 
00251   if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
00252     // If the function is empty, then we need to emit *something*. Otherwise,
00253     // the function's label might be associated with something that it wasn't
00254     // meant to be associated with. We emit a noop in this situation.
00255     // We are assuming inline asms are code.
00256     O << "\tnop\n";
00257   }
00258 
00259   if (TAI->hasDotTypeDotSizeDirective())
00260     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
00261 
00262   // Emit post-function debug information.
00263   if (TAI->doesSupportDebugInformation())
00264     DW->EndFunction(&MF);
00265 
00266   // Print out jump tables referenced by the function.
00267   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
00268 
00269   O.flush();
00270 
00271   // We didn't modify anything.
00272   return false;
00273 }
00274 
00275 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
00276   return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
00277 }
00278 
00279 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
00280   return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
00281       (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
00282 }
00283 
00284 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
00285   return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
00286 }
00287 
00288 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
00289                                     const char *Modifier, bool NotRIPRel) {
00290   const MachineOperand &MO = MI->getOperand(OpNo);
00291   switch (MO.getType()) {
00292   case MachineOperand::MO_Register: {
00293     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
00294            "Virtual registers should not make it this far!");
00295     O << '%';
00296     unsigned Reg = MO.getReg();
00297     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
00298       MVT VT = (strcmp(Modifier+6,"64") == 0) ?
00299         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
00300                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
00301       Reg = getX86SubSuperRegister(Reg, VT);
00302     }
00303     O << TRI->getAsmName(Reg);
00304     return;
00305   }
00306 
00307   case MachineOperand::MO_Immediate:
00308     if (!Modifier ||
00309         (strcmp(Modifier, "debug") && strcmp(Modifier, "mem")))
00310       O << '$';
00311     O << MO.getImm();
00312     return;
00313   case MachineOperand::MO_MachineBasicBlock:
00314     printBasicBlockLabel(MO.getMBB());
00315     return;
00316   case MachineOperand::MO_JumpTableIndex: {
00317     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
00318     if (!isMemOp) O << '$';
00319     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
00320       << MO.getIndex();
00321 
00322     if (TM.getRelocationModel() == Reloc::PIC_) {
00323       if (Subtarget->isPICStyleStub())
00324         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
00325           << "$pb\"";
00326       else if (Subtarget->isPICStyleGOT())
00327         O << "@GOTOFF";
00328     }
00329 
00330     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
00331       O << "(%rip)";
00332     return;
00333   }
00334   case MachineOperand::MO_ConstantPoolIndex: {
00335     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
00336     if (!isMemOp) O << '$';
00337     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
00338       << MO.getIndex();
00339 
00340     if (TM.getRelocationModel() == Reloc::PIC_) {
00341       if (Subtarget->isPICStyleStub())
00342         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
00343           << "$pb\"";
00344       else if (Subtarget->isPICStyleGOT())
00345         O << "@GOTOFF";
00346     }
00347 
00348     printOffset(MO.getOffset());
00349 
00350     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
00351       O << "(%rip)";
00352     return;
00353   }
00354   case MachineOperand::MO_GlobalAddress: {
00355     bool isCallOp = Modifier && !strcmp(Modifier, "call");
00356     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
00357     bool needCloseParen = false;
00358 
00359     const GlobalValue *GV = MO.getGlobal();
00360     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
00361     if (!GVar) {
00362       // If GV is an alias then use the aliasee for determining
00363       // thread-localness.
00364       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
00365         GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
00366     }
00367 
00368     bool isThreadLocal = GVar && GVar->isThreadLocal();
00369 
00370     std::string Name = Mang->getValueName(GV);
00371     decorateName(Name, GV);
00372 
00373     if (!isMemOp && !isCallOp)
00374       O << '$';
00375     else if (Name[0] == '$') {
00376       // The name begins with a dollar-sign. In order to avoid having it look
00377       // like an integer immediate to the assembler, enclose it in parens.
00378       O << '(';
00379       needCloseParen = true;
00380     }
00381 
00382     if (shouldPrintStub(TM, Subtarget)) {
00383       // Link-once, declaration, or Weakly-linked global variables need
00384       // non-lazily-resolved stubs
00385       if (GV->isDeclaration() || GV->mayBeOverridden()) {
00386         // Dynamically-resolved functions need a stub for the function.
00387         if (isCallOp && isa<Function>(GV)) {
00388           // Function stubs are no longer needed for Mac OS X 10.5 and up.
00389           if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
00390             O << Name;
00391           } else {
00392             FnStubs.insert(Name);
00393             printSuffixedName(Name, "$stub");
00394           }
00395         } else if (GV->hasHiddenVisibility()) {
00396           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
00397             // Definition is not definitely in the current translation unit.
00398             O << Name;
00399           else {
00400             HiddenGVStubs.insert(Name);
00401             printSuffixedName(Name, "$non_lazy_ptr");
00402           }
00403         } else {
00404           GVStubs.insert(Name);
00405           printSuffixedName(Name, "$non_lazy_ptr");
00406         }
00407       } else {
00408         if (GV->hasDLLImportLinkage())
00409           O << "__imp_";
00410         O << Name;
00411       }
00412 
00413       if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
00414         O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
00415     } else {
00416       if (GV->hasDLLImportLinkage()) {
00417         O << "__imp_";
00418       }
00419       O << Name;
00420 
00421       if (isCallOp) {
00422         if (shouldPrintPLT(TM, Subtarget)) {
00423           // Assemble call via PLT for externally visible symbols
00424           if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
00425               !GV->hasLocalLinkage())
00426             O << "@PLT";
00427         }
00428         if (Subtarget->isTargetCygMing() && GV->isDeclaration())
00429           // Save function name for later type emission
00430           FnStubs.insert(Name);
00431       }
00432     }
00433 
00434     if (GV->hasExternalWeakLinkage())
00435       ExtWeakSymbols.insert(GV);
00436 
00437     printOffset(MO.getOffset());
00438 
00439     if (isThreadLocal) {
00440       if (TM.getRelocationModel() == Reloc::PIC_ || Subtarget->is64Bit())
00441         O << "@TLSGD"; // general dynamic TLS model
00442       else
00443         if (GV->isDeclaration())
00444           O << "@INDNTPOFF"; // initial exec TLS model
00445         else
00446           O << "@NTPOFF"; // local exec TLS model
00447     } else if (isMemOp) {
00448       if (shouldPrintGOT(TM, Subtarget)) {
00449         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
00450           O << "@GOT";
00451         else
00452           O << "@GOTOFF";
00453       } else if (Subtarget->isPICStyleRIPRel() && !NotRIPRel &&
00454                  TM.getRelocationModel() != Reloc::Static) {
00455         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
00456           O << "@GOTPCREL";
00457 
00458         if (needCloseParen) {
00459           needCloseParen = false;
00460           O << ')';
00461         }
00462 
00463         // Use rip when possible to reduce code size, except when
00464         // index or base register are also part of the address. e.g.
00465         // foo(%rip)(%rcx,%rax,4) is not legal
00466         O << "(%rip)";
00467       }
00468     }
00469 
00470     if (needCloseParen)
00471       O << ')';
00472 
00473     return;
00474   }
00475   case MachineOperand::MO_ExternalSymbol: {
00476     bool isCallOp = Modifier && !strcmp(Modifier, "call");
00477     bool needCloseParen = false;
00478     std::string Name(TAI->getGlobalPrefix());
00479     Name += MO.getSymbolName();
00480     // Print function stub suffix unless it's Mac OS X 10.5 and up.
00481     if (isCallOp && shouldPrintStub(TM, Subtarget) && 
00482         !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
00483       FnStubs.insert(Name);
00484       printSuffixedName(Name, "$stub");
00485       return;
00486     }
00487     if (!isCallOp)
00488       O << '$';
00489     else if (Name[0] == '$') {
00490       // The name begins with a dollar-sign. In order to avoid having it look
00491       // like an integer immediate to the assembler, enclose it in parens.
00492       O << '(';
00493       needCloseParen = true;
00494     }
00495 
00496     O << Name;
00497 
00498     if (shouldPrintPLT(TM, Subtarget)) {
00499       std::string GOTName(TAI->getGlobalPrefix());
00500       GOTName+="_GLOBAL_OFFSET_TABLE_";
00501       if (Name == GOTName)
00502         // HACK! Emit extra offset to PC during printing GOT offset to
00503         // compensate for the size of popl instruction. The resulting code
00504         // should look like:
00505         //   call .piclabel
00506         // piclabel:
00507         //   popl %some_register
00508         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
00509         O << " + [.-"
00510           << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
00511 
00512       if (isCallOp)
00513         O << "@PLT";
00514     }
00515 
00516     if (needCloseParen)
00517       O << ')';
00518 
00519     if (!isCallOp && Subtarget->isPICStyleRIPRel())
00520       O << "(%rip)";
00521 
00522     return;
00523   }
00524   default:
00525     O << "<unknown operand type>"; return;
00526   }
00527 }
00528 
00529 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
00530   unsigned char value = MI->getOperand(Op).getImm();
00531   assert(value <= 7 && "Invalid ssecc argument!");
00532   switch (value) {
00533   case 0: O << "eq"; break;
00534   case 1: O << "lt"; break;
00535   case 2: O << "le"; break;
00536   case 3: O << "unord"; break;
00537   case 4: O << "neq"; break;
00538   case 5: O << "nlt"; break;
00539   case 6: O << "nle"; break;
00540   case 7: O << "ord"; break;
00541   }
00542 }
00543 
00544 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
00545                                          const char *Modifier){
00546   assert(isMem(MI, Op) && "Invalid memory reference!");
00547   MachineOperand BaseReg  = MI->getOperand(Op);
00548   MachineOperand IndexReg = MI->getOperand(Op+2);
00549   const MachineOperand &DispSpec = MI->getOperand(Op+3);
00550 
00551   bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
00552   if (DispSpec.isGlobal() ||
00553       DispSpec.isCPI() ||
00554       DispSpec.isJTI()) {
00555     printOperand(MI, Op+3, "mem", NotRIPRel);
00556   } else {
00557     int DispVal = DispSpec.getImm();
00558     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
00559       O << DispVal;
00560   }
00561 
00562   if (IndexReg.getReg() || BaseReg.getReg()) {
00563     unsigned ScaleVal = MI->getOperand(Op+1).getImm();
00564     unsigned BaseRegOperand = 0, IndexRegOperand = 2;
00565 
00566     // There are cases where we can end up with ESP/RSP in the indexreg slot.
00567     // If this happens, swap the base/index register to support assemblers that
00568     // don't work when the index is *SP.
00569     if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
00570       assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
00571       std::swap(BaseReg, IndexReg);
00572       std::swap(BaseRegOperand, IndexRegOperand);
00573     }
00574 
00575     O << '(';
00576     if (BaseReg.getReg())
00577       printOperand(MI, Op+BaseRegOperand, Modifier);
00578 
00579     if (IndexReg.getReg()) {
00580       O << ',';
00581       printOperand(MI, Op+IndexRegOperand, Modifier);
00582       if (ScaleVal != 1)
00583         O << ',' << ScaleVal;
00584     }
00585     O << ')';
00586   }
00587 }
00588 
00589 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
00590                                            const MachineBasicBlock *MBB) const {
00591   if (!TAI->getSetDirective())
00592     return;
00593 
00594   // We don't need .set machinery if we have GOT-style relocations
00595   if (Subtarget->isPICStyleGOT())
00596     return;
00597 
00598   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
00599     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
00600   printBasicBlockLabel(MBB, false, false, false);
00601   if (Subtarget->isPICStyleRIPRel())
00602     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
00603       << '_' << uid << '\n';
00604   else
00605     O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
00606 }
00607 
00608 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
00609   std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
00610   O << label << '\n' << label << ':';
00611 }
00612 
00613 
00614 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
00615                                               const MachineBasicBlock *MBB,
00616                                               unsigned uid) const
00617 {
00618   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
00619     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
00620 
00621   O << JTEntryDirective << ' ';
00622 
00623   if (TM.getRelocationModel() == Reloc::PIC_) {
00624     if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
00625       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
00626         << '_' << uid << "_set_" << MBB->getNumber();
00627     } else if (Subtarget->isPICStyleGOT()) {
00628       printBasicBlockLabel(MBB, false, false, false);
00629       O << "@GOTOFF";
00630     } else
00631       assert(0 && "Don't know how to print MBB label for this PIC mode");
00632   } else
00633     printBasicBlockLabel(MBB, false, false, false);
00634 }
00635 
00636 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
00637                                          const char Mode) {
00638   unsigned Reg = MO.getReg();
00639   switch (Mode) {
00640   default: return true;  // Unknown mode.
00641   case 'b': // Print QImode register
00642     Reg = getX86SubSuperRegister(Reg, MVT::i8);
00643     break;
00644   case 'h': // Print QImode high register
00645     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
00646     break;
00647   case 'w': // Print HImode register
00648     Reg = getX86SubSuperRegister(Reg, MVT::i16);
00649     break;
00650   case 'k': // Print SImode register
00651     Reg = getX86SubSuperRegister(Reg, MVT::i32);
00652     break;
00653   case 'q': // Print DImode register
00654     Reg = getX86SubSuperRegister(Reg, MVT::i64);
00655     break;
00656   }
00657 
00658   O << '%'<< TRI->getAsmName(Reg);
00659   return false;
00660 }
00661 
00662 /// PrintAsmOperand - Print out an operand for an inline asm expression.
00663 ///
00664 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
00665                                        unsigned AsmVariant,
00666                                        const char *ExtraCode) {
00667   // Does this asm operand have a single letter operand modifier?
00668   if (ExtraCode && ExtraCode[0]) {
00669     if (ExtraCode[1] != 0) return true; // Unknown modifier.
00670 
00671     switch (ExtraCode[0]) {
00672     default: return true;  // Unknown modifier.
00673     case 'c': // Don't print "$" before a global var name or constant.
00674       printOperand(MI, OpNo, "mem");
00675       return false;
00676     case 'b': // Print QImode register
00677     case 'h': // Print QImode high register
00678     case 'w': // Print HImode register
00679     case 'k': // Print SImode register
00680     case 'q': // Print DImode register
00681       if (MI->getOperand(OpNo).isReg())
00682         return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
00683       printOperand(MI, OpNo);
00684       return false;
00685 
00686     case 'P': // Don't print @PLT, but do print as memory.
00687       printOperand(MI, OpNo, "mem");
00688       return false;
00689     }
00690   }
00691 
00692   printOperand(MI, OpNo);
00693   return false;
00694 }
00695 
00696 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
00697                                              unsigned OpNo,
00698                                              unsigned AsmVariant,
00699                                              const char *ExtraCode) {
00700   if (ExtraCode && ExtraCode[0]) {
00701     if (ExtraCode[1] != 0) return true; // Unknown modifier.
00702 
00703     switch (ExtraCode[0]) {
00704     default: return true;  // Unknown modifier.
00705     case 'b': // Print QImode register
00706     case 'h': // Print QImode high register
00707     case 'w': // Print HImode register
00708     case 'k': // Print SImode register
00709     case 'q': // Print SImode register
00710       // These only apply to registers, ignore on mem.
00711       break;
00712     case 'P': // Don't print @PLT, but do print as memory.
00713       printOperand(MI, OpNo, "mem");
00714       return false;
00715     }
00716   }
00717   printMemReference(MI, OpNo);
00718   return false;
00719 }
00720 
00721 /// printMachineInstruction -- Print out a single X86 LLVM instruction
00722 /// MI in AT&T syntax to the current output stream.
00723 ///
00724 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
00725   ++EmittedInsts;
00726 
00727   // Call the autogenerated instruction printer routines.
00728   printInstruction(MI);
00729 }
00730 
00731 /// doInitialization
00732 bool X86ATTAsmPrinter::doInitialization(Module &M) {
00733 
00734   bool Result = AsmPrinter::doInitialization(M);
00735 
00736   if (TAI->doesSupportDebugInformation()) {
00737     // Let PassManager know we need debug information and relay
00738     // the MachineModuleInfo address on to DwarfWriter.
00739     // AsmPrinter::doInitialization did this analysis.
00740     MMI = getAnalysisIfAvailable<MachineModuleInfo>();
00741     DW = getAnalysisIfAvailable<DwarfWriter>();
00742     DW->BeginModule(&M, MMI, O, this, TAI);
00743   }
00744 
00745   // Darwin wants symbols to be quoted if they have complex names.
00746   if (Subtarget->isTargetDarwin())
00747     Mang->setUseQuotes(true);
00748 
00749   return Result;
00750 }
00751 
00752 
00753 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
00754   const TargetData *TD = TM.getTargetData();
00755 
00756   if (!GVar->hasInitializer())
00757     return;   // External global require no code
00758 
00759   // Check to see if this is a special global used by LLVM, if so, emit it.
00760   if (EmitSpecialLLVMGlobal(GVar)) {
00761     if (Subtarget->isTargetDarwin() &&
00762         TM.getRelocationModel() == Reloc::Static) {
00763       if (GVar->getName() == "llvm.global_ctors")
00764         O << ".reference .constructors_used\n";
00765       else if (GVar->getName() == "llvm.global_dtors")
00766         O << ".reference .destructors_used\n";
00767     }
00768     return;
00769   }
00770 
00771   std::string name = Mang->getValueName(GVar);
00772   Constant *C = GVar->getInitializer();
00773   const Type *Type = C->getType();
00774   unsigned Size = TD->getTypePaddedSize(Type);
00775   unsigned Align = TD->getPreferredAlignmentLog(GVar);
00776 
00777   printVisibility(name, GVar->getVisibility());
00778 
00779   if (Subtarget->isTargetELF())
00780     O << "\t.type\t" << name << ",@object\n";
00781 
00782   SwitchToSection(TAI->SectionForGlobal(GVar));
00783 
00784   if (C->isNullValue() && !GVar->hasSection()) {
00785     // FIXME: This seems to be pretty darwin-specific
00786     if (GVar->hasExternalLinkage()) {
00787       if (const char *Directive = TAI->getZeroFillDirective()) {
00788         O << "\t.globl " << name << '\n';
00789         O << Directive << "__DATA, __common, " << name << ", "
00790           << Size << ", " << Align << '\n';
00791         return;
00792       }
00793     }
00794 
00795     if (!GVar->isThreadLocal() &&
00796         (GVar->hasLocalLinkage() || GVar->mayBeOverridden())) {
00797       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
00798 
00799       if (TAI->getLCOMMDirective() != NULL) {
00800         if (GVar->hasLocalLinkage()) {
00801           O << TAI->getLCOMMDirective() << name << ',' << Size;
00802           if (Subtarget->isTargetDarwin())
00803             O << ',' << Align;
00804         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
00805           O << "\t.globl " << name << '\n'
00806             << TAI->getWeakDefDirective() << name << '\n';
00807           EmitAlignment(Align, GVar);
00808           O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
00809           PrintUnmangledNameSafely(GVar, O);
00810           O << '\n';
00811           EmitGlobalConstant(C);
00812           return;
00813         } else {
00814           O << TAI->getCOMMDirective()  << name << ',' << Size;
00815           if (TAI->getCOMMDirectiveTakesAlignment())
00816             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
00817         }
00818       } else {
00819         if (!Subtarget->isTargetCygMing()) {
00820           if (GVar->hasLocalLinkage())
00821             O << "\t.local\t" << name << '\n';
00822         }
00823         O << TAI->getCOMMDirective()  << name << ',' << Size;
00824         if (TAI->getCOMMDirectiveTakesAlignment())
00825           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
00826       }
00827       O << "\t\t" << TAI->getCommentString() << ' ';
00828       PrintUnmangledNameSafely(GVar, O);
00829       O << '\n';
00830       return;
00831     }
00832   }
00833 
00834   switch (GVar->getLinkage()) {
00835   case GlobalValue::CommonLinkage:
00836   case GlobalValue::LinkOnceLinkage:
00837   case GlobalValue::WeakLinkage:
00838     if (Subtarget->isTargetDarwin()) {
00839       O << "\t.globl " << name << '\n'
00840         << TAI->getWeakDefDirective() << name << '\n';
00841     } else if (Subtarget->isTargetCygMing()) {
00842       O << "\t.globl\t" << name << "\n"
00843            "\t.linkonce same_size\n";
00844     } else {
00845       O << "\t.weak\t" << name << '\n';
00846     }
00847     break;
00848   case GlobalValue::DLLExportLinkage:
00849   case GlobalValue::AppendingLinkage:
00850     // FIXME: appending linkage variables should go into a section of
00851     // their name or something.  For now, just emit them as external.
00852   case GlobalValue::ExternalLinkage:
00853     // If external or appending, declare as a global symbol
00854     O << "\t.globl " << name << '\n';
00855     // FALL THROUGH
00856   case GlobalValue::PrivateLinkage:
00857   case GlobalValue::InternalLinkage:
00858      break;
00859   default:
00860     assert(0 && "Unknown linkage type!");
00861   }
00862 
00863   EmitAlignment(Align, GVar);
00864   O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
00865   PrintUnmangledNameSafely(GVar, O);
00866   O << '\n';
00867   if (TAI->hasDotTypeDotSizeDirective())
00868     O << "\t.size\t" << name << ", " << Size << '\n';
00869 
00870   // If the initializer is a extern weak symbol, remember to emit the weak
00871   // reference!
00872   if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
00873     if (GV->hasExternalWeakLinkage())
00874       ExtWeakSymbols.insert(GV);
00875 
00876   EmitGlobalConstant(C);
00877 }
00878 
00879 /// printGVStub - Print stub for a global value.
00880 ///
00881 void X86ATTAsmPrinter::printGVStub(const char *GV, const char *Prefix) {
00882   printSuffixedName(GV, "$non_lazy_ptr", Prefix);
00883   O << ":\n\t.indirect_symbol ";
00884   if (Prefix) O << Prefix;
00885   O << GV << "\n\t.long\t0\n";
00886 }
00887 
00888 /// printHiddenGVStub - Print stub for a hidden global value.
00889 ///
00890 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV, const char *Prefix) {
00891   EmitAlignment(2);
00892   printSuffixedName(GV, "$non_lazy_ptr", Prefix);
00893   if (Prefix) O << Prefix;
00894   O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
00895 }
00896 
00897 
00898 bool X86ATTAsmPrinter::doFinalization(Module &M) {
00899   // Print out module-level global variables here.
00900   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
00901        I != E; ++I) {
00902     printModuleLevelGV(I);
00903 
00904     if (I->hasDLLExportLinkage())
00905       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
00906   }
00907 
00908   // Output linker support code for dllexported globals
00909   if (!DLLExportedGVs.empty())
00910     SwitchToDataSection(".section .drectve");
00911 
00912   for (StringSet<>::iterator i = DLLExportedGVs.begin(),
00913          e = DLLExportedGVs.end();
00914          i != e; ++i)
00915     O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
00916 
00917   if (!DLLExportedFns.empty()) {
00918     SwitchToDataSection(".section .drectve");
00919   }
00920 
00921   for (StringSet<>::iterator i = DLLExportedFns.begin(),
00922          e = DLLExportedFns.end();
00923          i != e; ++i)
00924     O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
00925 
00926   if (Subtarget->isTargetDarwin()) {
00927     SwitchToDataSection("");
00928 
00929     // Output stubs for dynamically-linked functions
00930     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
00931          i != e; ++i) {
00932       SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
00933                           "self_modifying_code+pure_instructions,5", 0);
00934       const char *p = i->getKeyData();
00935       printSuffixedName(p, "$stub");
00936       O << ":\n"
00937            "\t.indirect_symbol " << p << "\n"
00938            "\thlt ; hlt ; hlt ; hlt ; hlt\n";
00939     }
00940 
00941     O << '\n';
00942 
00943     // Print global value stubs.
00944     bool InStubSection = false;
00945     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
00946       // Add the (possibly multiple) personalities to the set of global values.
00947       // Only referenced functions get into the Personalities list.
00948       const std::vector<Function *>& Personalities = MMI->getPersonalities();
00949       for (std::vector<Function *>::const_iterator I = Personalities.begin(),
00950              E = Personalities.end(); I != E; ++I) {
00951         if (!*I)
00952           continue;
00953         if (!InStubSection) {
00954           SwitchToDataSection(
00955                      "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
00956           InStubSection = true;
00957         }
00958         printGVStub((*I)->getNameStart(), "_");
00959       }
00960     }
00961 
00962     // Output stubs for external and common global variables.
00963     if (!InStubSection && !GVStubs.empty())
00964       SwitchToDataSection(
00965                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
00966     for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
00967          i != e; ++i)
00968       printGVStub(i->getKeyData());
00969 
00970     if (!HiddenGVStubs.empty()) {
00971       SwitchToSection(TAI->getDataSection());
00972       for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
00973            i != e; ++i)
00974         printHiddenGVStub(i->getKeyData());
00975     }
00976 
00977     // Emit final debug information.
00978     DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
00979     DW->EndModule();
00980 
00981     // Funny Darwin hack: This flag tells the linker that no global symbols
00982     // contain code that falls through to other global symbols (e.g. the obvious
00983     // implementation of multiple entry points).  If this doesn't occur, the
00984     // linker can safely perform dead code stripping.  Since LLVM never
00985     // generates code that does this, it is always safe to set.
00986     O << "\t.subsections_via_symbols\n";
00987   } else if (Subtarget->isTargetCygMing()) {
00988     // Emit type information for external functions
00989     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
00990          i != e; ++i) {
00991       O << "\t.def\t " << i->getKeyData()
00992         << ";\t.scl\t" << COFF::C_EXT
00993         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
00994         << ";\t.endef\n";
00995     }
00996 
00997     // Emit final debug information.
00998     DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
00999     DW->EndModule();
01000   } else if (Subtarget->isTargetELF()) {
01001     // Emit final debug information.
01002     DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
01003     DW->EndModule();
01004   }
01005 
01006   return AsmPrinter::doFinalization(M);
01007 }
01008 
01009 // Include the auto-generated portion of the assembly writer.
01010 #include "X86GenAsmWriter.inc"