LLVM API Documentation

SPUAsmPrinter.cpp

Go to the documentation of this file.
00001 //===-- SPUAsmPrinter.cpp - Print machine instrs to Cell SPU 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 Cell SPU assembly language. This printer
00012 // is the output mechanism used by `llc'.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #define DEBUG_TYPE "asmprinter"
00017 #include "SPU.h"
00018 #include "SPUTargetMachine.h"
00019 #include "llvm/Constants.h"
00020 #include "llvm/DerivedTypes.h"
00021 #include "llvm/Module.h"
00022 #include "llvm/Assembly/Writer.h"
00023 #include "llvm/CodeGen/AsmPrinter.h"
00024 #include "llvm/CodeGen/DwarfWriter.h"
00025 #include "llvm/CodeGen/MachineModuleInfo.h"
00026 #include "llvm/CodeGen/MachineFunctionPass.h"
00027 #include "llvm/CodeGen/MachineInstr.h"
00028 #include "llvm/MC/MCStreamer.h"
00029 #include "llvm/Target/TargetAsmInfo.h"
00030 #include "llvm/Target/TargetLoweringObjectFile.h"
00031 #include "llvm/Target/TargetInstrInfo.h"
00032 #include "llvm/Target/TargetOptions.h"
00033 #include "llvm/Target/TargetRegisterInfo.h"
00034 #include "llvm/Target/TargetRegistry.h"
00035 #include "llvm/ADT/Statistic.h"
00036 #include "llvm/ADT/StringExtras.h"
00037 #include "llvm/Support/CommandLine.h"
00038 #include "llvm/Support/Compiler.h"
00039 #include "llvm/Support/Debug.h"
00040 #include "llvm/Support/ErrorHandling.h"
00041 #include "llvm/Support/FormattedStream.h"
00042 #include "llvm/Support/Mangler.h"
00043 #include "llvm/Support/MathExtras.h"
00044 #include <set>
00045 using namespace llvm;
00046 
00047 namespace {
00048   STATISTIC(EmittedInsts, "Number of machine instrs printed");
00049 
00050   const std::string bss_section(".bss");
00051 
00052   class VISIBILITY_HIDDEN SPUAsmPrinter : public AsmPrinter {
00053     std::set<std::string> FnStubs, GVStubs;
00054   public:
00055     explicit SPUAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
00056                            const TargetAsmInfo *T, bool V) :
00057       AsmPrinter(O, TM, T, V) {}
00058 
00059     virtual const char *getPassName() const {
00060       return "STI CBEA SPU Assembly Printer";
00061     }
00062 
00063     SPUTargetMachine &getTM() {
00064       return static_cast<SPUTargetMachine&>(TM);
00065     }
00066 
00067     /// printInstruction - This method is automatically generated by tablegen
00068     /// from the instruction set description.  This method returns true if the
00069     /// machine instruction was sufficiently described to print it, otherwise it
00070     /// returns false.
00071     void printInstruction(const MachineInstr *MI);
00072 
00073     void printMachineInstruction(const MachineInstr *MI);
00074     void printOp(const MachineOperand &MO);
00075 
00076     /// printRegister - Print register according to target requirements.
00077     ///
00078     void printRegister(const MachineOperand &MO, bool R0AsZero) {
00079       unsigned RegNo = MO.getReg();
00080       assert(TargetRegisterInfo::isPhysicalRegister(RegNo) &&
00081              "Not physreg??");
00082       O << TM.getRegisterInfo()->get(RegNo).AsmName;
00083     }
00084 
00085     void printOperand(const MachineInstr *MI, unsigned OpNo) {
00086       const MachineOperand &MO = MI->getOperand(OpNo);
00087       if (MO.isReg()) {
00088         assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physreg??");
00089         O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
00090       } else if (MO.isImm()) {
00091         O << MO.getImm();
00092       } else {
00093         printOp(MO);
00094       }
00095     }
00096 
00097     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
00098                          unsigned AsmVariant, const char *ExtraCode);
00099     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
00100                                unsigned AsmVariant, const char *ExtraCode);
00101 
00102 
00103     void
00104     printS7ImmOperand(const MachineInstr *MI, unsigned OpNo)
00105     {
00106       int value = MI->getOperand(OpNo).getImm();
00107       value = (value << (32 - 7)) >> (32 - 7);
00108 
00109       assert((value >= -(1 << 8) && value <= (1 << 7) - 1)
00110              && "Invalid s7 argument");
00111       O << value;
00112     }
00113 
00114     void
00115     printU7ImmOperand(const MachineInstr *MI, unsigned OpNo)
00116     {
00117       unsigned int value = MI->getOperand(OpNo).getImm();
00118       assert(value < (1 << 8) && "Invalid u7 argument");
00119       O << value;
00120     }
00121 
00122     void
00123     printShufAddr(const MachineInstr *MI, unsigned OpNo)
00124     {
00125       char value = MI->getOperand(OpNo).getImm();
00126       O << (int) value;
00127       O << "(";
00128       printOperand(MI, OpNo+1);
00129       O << ")";
00130     }
00131 
00132     void
00133     printS16ImmOperand(const MachineInstr *MI, unsigned OpNo)
00134     {
00135       O << (short) MI->getOperand(OpNo).getImm();
00136     }
00137 
00138     void
00139     printU16ImmOperand(const MachineInstr *MI, unsigned OpNo)
00140     {
00141       O << (unsigned short)MI->getOperand(OpNo).getImm();
00142     }
00143 
00144     void
00145     printU32ImmOperand(const MachineInstr *MI, unsigned OpNo)
00146     {
00147       O << (unsigned)MI->getOperand(OpNo).getImm();
00148     }
00149 
00150     void
00151     printMemRegReg(const MachineInstr *MI, unsigned OpNo) {
00152       // When used as the base register, r0 reads constant zero rather than
00153       // the value contained in the register.  For this reason, the darwin
00154       // assembler requires that we print r0 as 0 (no r) when used as the base.
00155       const MachineOperand &MO = MI->getOperand(OpNo);
00156       O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
00157       O << ", ";
00158       printOperand(MI, OpNo+1);
00159     }
00160 
00161     void
00162     printU18ImmOperand(const MachineInstr *MI, unsigned OpNo)
00163     {
00164       unsigned int value = MI->getOperand(OpNo).getImm();
00165       assert(value <= (1 << 19) - 1 && "Invalid u18 argument");
00166       O << value;
00167     }
00168 
00169     void
00170     printS10ImmOperand(const MachineInstr *MI, unsigned OpNo)
00171     {
00172       short value = (short) (((int) MI->getOperand(OpNo).getImm() << 16)
00173                              >> 16);
00174       assert((value >= -(1 << 9) && value <= (1 << 9) - 1)
00175              && "Invalid s10 argument");
00176       O << value;
00177     }
00178 
00179     void
00180     printU10ImmOperand(const MachineInstr *MI, unsigned OpNo)
00181     {
00182       short value = (short) (((int) MI->getOperand(OpNo).getImm() << 16)
00183                              >> 16);
00184       assert((value <= (1 << 10) - 1) && "Invalid u10 argument");
00185       O << value;
00186     }
00187 
00188     void
00189     printDFormAddr(const MachineInstr *MI, unsigned OpNo)
00190     {
00191       assert(MI->getOperand(OpNo).isImm() &&
00192              "printDFormAddr first operand is not immediate");
00193       int64_t value = int64_t(MI->getOperand(OpNo).getImm());
00194       int16_t value16 = int16_t(value);
00195       assert((value16 >= -(1 << (9+4)) && value16 <= (1 << (9+4)) - 1)
00196              && "Invalid dform s10 offset argument");
00197       O << (value16 & ~0xf) << "(";
00198       printOperand(MI, OpNo+1);
00199       O << ")";
00200     }
00201 
00202     void
00203     printAddr256K(const MachineInstr *MI, unsigned OpNo)
00204     {
00205       /* Note: operand 1 is an offset or symbol name. */
00206       if (MI->getOperand(OpNo).isImm()) {
00207         printS16ImmOperand(MI, OpNo);
00208       } else {
00209         printOp(MI->getOperand(OpNo));
00210         if (MI->getOperand(OpNo+1).isImm()) {
00211           int displ = int(MI->getOperand(OpNo+1).getImm());
00212           if (displ > 0)
00213             O << "+" << displ;
00214           else if (displ < 0)
00215             O << displ;
00216         }
00217       }
00218     }
00219 
00220     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
00221       printOp(MI->getOperand(OpNo));
00222     }
00223 
00224     void printPCRelativeOperand(const MachineInstr *MI, unsigned OpNo) {
00225       // Used to generate a ".-<target>", but it turns out that the assembler
00226       // really wants the target.
00227       //
00228       // N.B.: This operand is used for call targets. Branch hints are another
00229       // animal entirely.
00230       printOp(MI->getOperand(OpNo));
00231     }
00232 
00233     void printHBROperand(const MachineInstr *MI, unsigned OpNo) {
00234       // HBR operands are generated in front of branches, hence, the
00235       // program counter plus the target.
00236       O << ".+";
00237       printOp(MI->getOperand(OpNo));
00238     }
00239 
00240     void printSymbolHi(const MachineInstr *MI, unsigned OpNo) {
00241       if (MI->getOperand(OpNo).isImm()) {
00242         printS16ImmOperand(MI, OpNo);
00243       } else {
00244         printOp(MI->getOperand(OpNo));
00245         O << "@h";
00246       }
00247     }
00248 
00249     void printSymbolLo(const MachineInstr *MI, unsigned OpNo) {
00250       if (MI->getOperand(OpNo).isImm()) {
00251         printS16ImmOperand(MI, OpNo);
00252       } else {
00253         printOp(MI->getOperand(OpNo));
00254         O << "@l";
00255       }
00256     }
00257 
00258     /// Print local store address
00259     void printSymbolLSA(const MachineInstr *MI, unsigned OpNo) {
00260       printOp(MI->getOperand(OpNo));
00261     }
00262 
00263     void printROTHNeg7Imm(const MachineInstr *MI, unsigned OpNo) {
00264       if (MI->getOperand(OpNo).isImm()) {
00265         int value = (int) MI->getOperand(OpNo).getImm();
00266         assert((value >= 0 && value < 16)
00267                && "Invalid negated immediate rotate 7-bit argument");
00268         O << -value;
00269       } else {
00270         llvm_unreachable("Invalid/non-immediate rotate amount in printRotateNeg7Imm");
00271       }
00272     }
00273 
00274     void printROTNeg7Imm(const MachineInstr *MI, unsigned OpNo) {
00275       if (MI->getOperand(OpNo).isImm()) {
00276         int value = (int) MI->getOperand(OpNo).getImm();
00277         assert((value >= 0 && value <= 32)
00278                && "Invalid negated immediate rotate 7-bit argument");
00279         O << -value;
00280       } else {
00281         llvm_unreachable("Invalid/non-immediate rotate amount in printRotateNeg7Imm");
00282       }
00283     }
00284 
00285     virtual bool runOnMachineFunction(MachineFunction &F) = 0;
00286   };
00287 
00288   /// LinuxAsmPrinter - SPU assembly printer, customized for Linux
00289   class VISIBILITY_HIDDEN LinuxAsmPrinter : public SPUAsmPrinter {
00290     DwarfWriter *DW;
00291   public:
00292     explicit LinuxAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
00293                              const TargetAsmInfo *T, bool V)
00294       : SPUAsmPrinter(O, TM, T, V), DW(0) {}
00295 
00296     virtual const char *getPassName() const {
00297       return "STI CBEA SPU Assembly Printer";
00298     }
00299 
00300     bool runOnMachineFunction(MachineFunction &F);
00301     bool doInitialization(Module &M);
00302 
00303     void getAnalysisUsage(AnalysisUsage &AU) const {
00304       AU.setPreservesAll();
00305       AU.addRequired<MachineModuleInfo>();
00306       AU.addRequired<DwarfWriter>();
00307       SPUAsmPrinter::getAnalysisUsage(AU);
00308     }
00309 
00310     //! Emit a global variable according to its section and type
00311     void PrintGlobalVariable(const GlobalVariable* GVar);
00312   };
00313 } // end of anonymous namespace
00314 
00315 // Include the auto-generated portion of the assembly writer
00316 #include "SPUGenAsmWriter.inc"
00317 
00318 void SPUAsmPrinter::printOp(const MachineOperand &MO) {
00319   switch (MO.getType()) {
00320   case MachineOperand::MO_Immediate:
00321     llvm_report_error("printOp() does not handle immediate values");
00322     return;
00323 
00324   case MachineOperand::MO_MachineBasicBlock:
00325     printBasicBlockLabel(MO.getMBB());
00326     return;
00327   case MachineOperand::MO_JumpTableIndex:
00328     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
00329       << '_' << MO.getIndex();
00330     return;
00331   case MachineOperand::MO_ConstantPoolIndex:
00332     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
00333       << '_' << MO.getIndex();
00334     return;
00335   case MachineOperand::MO_ExternalSymbol:
00336     // Computing the address of an external symbol, not calling it.
00337     if (TM.getRelocationModel() != Reloc::Static) {
00338       std::string Name(TAI->getGlobalPrefix()); Name += MO.getSymbolName();
00339       GVStubs.insert(Name);
00340       O << "L" << Name << "$non_lazy_ptr";
00341       return;
00342     }
00343     O << TAI->getGlobalPrefix() << MO.getSymbolName();
00344     return;
00345   case MachineOperand::MO_GlobalAddress: {
00346     // Computing the address of a global symbol, not calling it.
00347     GlobalValue *GV = MO.getGlobal();
00348     std::string Name = Mang->getMangledName(GV);
00349 
00350     // External or weakly linked global variables need non-lazily-resolved
00351     // stubs
00352     if (TM.getRelocationModel() != Reloc::Static) {
00353       if (((GV->isDeclaration() || GV->hasWeakLinkage() ||
00354             GV->hasLinkOnceLinkage() || GV->hasCommonLinkage()))) {
00355         GVStubs.insert(Name);
00356         O << "L" << Name << "$non_lazy_ptr";
00357         return;
00358       }
00359     }
00360     O << Name;
00361     return;
00362   }
00363 
00364   default:
00365     O << "<unknown operand type: " << MO.getType() << ">";
00366     return;
00367   }
00368 }
00369 
00370 /// PrintAsmOperand - Print out an operand for an inline asm expression.
00371 ///
00372 bool SPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
00373                                     unsigned AsmVariant,
00374                                     const char *ExtraCode) {
00375   // Does this asm operand have a single letter operand modifier?
00376   if (ExtraCode && ExtraCode[0]) {
00377     if (ExtraCode[1] != 0) return true; // Unknown modifier.
00378 
00379     switch (ExtraCode[0]) {
00380     default: return true;  // Unknown modifier.
00381     case 'L': // Write second word of DImode reference.
00382       // Verify that this operand has two consecutive registers.
00383       if (!MI->getOperand(OpNo).isReg() ||
00384           OpNo+1 == MI->getNumOperands() ||
00385           !MI->getOperand(OpNo+1).isReg())
00386         return true;
00387       ++OpNo;   // Return the high-part.
00388       break;
00389     }
00390   }
00391 
00392   printOperand(MI, OpNo);
00393   return false;
00394 }
00395 
00396 bool SPUAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
00397                                           unsigned OpNo,
00398                                           unsigned AsmVariant,
00399                                           const char *ExtraCode) {
00400   if (ExtraCode && ExtraCode[0])
00401     return true; // Unknown modifier.
00402   printMemRegReg(MI, OpNo);
00403   return false;
00404 }
00405 
00406 /// printMachineInstruction -- Print out a single PowerPC MI in Darwin syntax
00407 /// to the current output stream.
00408 ///
00409 void SPUAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
00410   ++EmittedInsts;
00411   printInstruction(MI);
00412 }
00413 
00414 /// runOnMachineFunction - This uses the printMachineInstruction()
00415 /// method to print assembly for each instruction.
00416 ///
00417 bool
00418 LinuxAsmPrinter::runOnMachineFunction(MachineFunction &MF)
00419 {
00420   this->MF = &MF;
00421 
00422   SetupMachineFunction(MF);
00423   O << "\n\n";
00424 
00425   // Print out constants referenced by the function
00426   EmitConstantPool(MF.getConstantPool());
00427 
00428   // Print out labels for the function.
00429   const Function *F = MF.getFunction();
00430 
00431   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
00432   EmitAlignment(MF.getAlignment(), F);
00433 
00434   switch (F->getLinkage()) {
00435   default: llvm_unreachable("Unknown linkage type!");
00436   case Function::PrivateLinkage:
00437   case Function::LinkerPrivateLinkage:
00438   case Function::InternalLinkage:  // Symbols default to internal.
00439     break;
00440   case Function::ExternalLinkage:
00441     O << "\t.global\t" << CurrentFnName << "\n"
00442       << "\t.type\t" << CurrentFnName << ", @function\n";
00443     break;
00444   case Function::WeakAnyLinkage:
00445   case Function::WeakODRLinkage:
00446   case Function::LinkOnceAnyLinkage:
00447   case Function::LinkOnceODRLinkage:
00448     O << "\t.global\t" << CurrentFnName << "\n";
00449     O << "\t.weak_definition\t" << CurrentFnName << "\n";
00450     break;
00451   }
00452   O << CurrentFnName << ":\n";
00453 
00454   // Emit pre-function debug information.
00455   DW->BeginFunction(&MF);
00456 
00457   // Print out code for the function.
00458   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
00459        I != E; ++I) {
00460     // Print a label for the basic block.
00461     if (I != MF.begin()) {
00462       printBasicBlockLabel(I, true, true);
00463       O << '\n';
00464     }
00465     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
00466          II != E; ++II) {
00467       // Print the assembly for the instruction.
00468       printMachineInstruction(II);
00469     }
00470   }
00471 
00472   O << "\t.size\t" << CurrentFnName << ",.-" << CurrentFnName << "\n";
00473 
00474   // Print out jump tables referenced by the function.
00475   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
00476 
00477   // Emit post-function debug information.
00478   DW->EndFunction(&MF);
00479 
00480   // We didn't modify anything.
00481   return false;
00482 }
00483 
00484 
00485 bool LinuxAsmPrinter::doInitialization(Module &M) {
00486   bool Result = AsmPrinter::doInitialization(M);
00487   DW = getAnalysisIfAvailable<DwarfWriter>();
00488   return Result;
00489 }
00490 
00491 /*!
00492   Emit a global variable according to its section, alignment, etc.
00493 
00494   \note This code was shamelessly copied from the PowerPC's assembly printer,
00495   which sort of screams for some kind of refactorization of common code.
00496  */
00497 void LinuxAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
00498   const TargetData *TD = TM.getTargetData();
00499 
00500   if (!GVar->hasInitializer())
00501     return;
00502 
00503   // Check to see if this is a special global used by LLVM, if so, emit it.
00504   if (EmitSpecialLLVMGlobal(GVar))
00505     return;
00506 
00507   std::string name = Mang->getMangledName(GVar);
00508 
00509   printVisibility(name, GVar->getVisibility());
00510 
00511   Constant *C = GVar->getInitializer();
00512   const Type *Type = C->getType();
00513   unsigned Size = TD->getTypeAllocSize(Type);
00514   unsigned Align = TD->getPreferredAlignmentLog(GVar);
00515 
00516   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
00517                                                                   TM));
00518 
00519   if (C->isNullValue() && /* FIXME: Verify correct */
00520       !GVar->hasSection() &&
00521       (GVar->hasLocalLinkage() || GVar->hasExternalLinkage() ||
00522        GVar->isWeakForLinker())) {
00523       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
00524 
00525       if (GVar->hasExternalLinkage()) {
00526         O << "\t.global " << name << '\n';
00527         O << "\t.type " << name << ", @object\n";
00528         O << name << ":\n";
00529         O << "\t.zero " << Size << '\n';
00530       } else if (GVar->hasLocalLinkage()) {
00531         O << TAI->getLCOMMDirective() << name << ',' << Size;
00532       } else {
00533         O << ".comm " << name << ',' << Size;
00534       }
00535       O << "\t\t" << TAI->getCommentString() << " '";
00536       WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
00537       O << "'\n";
00538       return;
00539   }
00540 
00541   switch (GVar->getLinkage()) {
00542     // Should never be seen for the CellSPU platform...
00543    case GlobalValue::LinkOnceAnyLinkage:
00544    case GlobalValue::LinkOnceODRLinkage:
00545    case GlobalValue::WeakAnyLinkage:
00546    case GlobalValue::WeakODRLinkage:
00547    case GlobalValue::CommonLinkage:
00548     O << "\t.global " << name << '\n'
00549       << "\t.type " << name << ", @object\n"
00550       << "\t.weak " << name << '\n';
00551     break;
00552    case GlobalValue::AppendingLinkage:
00553     // FIXME: appending linkage variables should go into a section of
00554     // their name or something.  For now, just emit them as external.
00555    case GlobalValue::ExternalLinkage:
00556     // If external or appending, declare as a global symbol
00557     O << "\t.global " << name << '\n'
00558       << "\t.type " << name << ", @object\n";
00559     // FALL THROUGH
00560    case GlobalValue::PrivateLinkage:
00561    case GlobalValue::LinkerPrivateLinkage:
00562    case GlobalValue::InternalLinkage:
00563     break;
00564    default:
00565     llvm_report_error("Unknown linkage type!");
00566   }
00567 
00568   EmitAlignment(Align, GVar);
00569   O << name << ":\t\t\t\t" << TAI->getCommentString() << " '";
00570   WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
00571   O << "'\n";
00572 
00573   EmitGlobalConstant(C);
00574   O << '\n';
00575 }
00576 
00577 // Force static initialization.
00578 extern "C" void LLVMInitializeCellSPUAsmPrinter() { 
00579   RegisterAsmPrinter<LinuxAsmPrinter> X(TheCellSPUTarget);
00580 }