LLVM  mainline
ARMAsmPrinter.cpp
Go to the documentation of this file.
00001 //===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
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 GAS-format ARM assembly language.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "ARMAsmPrinter.h"
00016 #include "ARM.h"
00017 #include "ARMConstantPoolValue.h"
00018 #include "ARMMachineFunctionInfo.h"
00019 #include "ARMTargetMachine.h"
00020 #include "ARMTargetObjectFile.h"
00021 #include "InstPrinter/ARMInstPrinter.h"
00022 #include "MCTargetDesc/ARMAddressingModes.h"
00023 #include "MCTargetDesc/ARMMCExpr.h"
00024 #include "llvm/ADT/SetVector.h"
00025 #include "llvm/ADT/SmallString.h"
00026 #include "llvm/CodeGen/MachineFunctionPass.h"
00027 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00028 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
00029 #include "llvm/IR/Constants.h"
00030 #include "llvm/IR/DataLayout.h"
00031 #include "llvm/IR/DebugInfo.h"
00032 #include "llvm/IR/Mangler.h"
00033 #include "llvm/IR/Module.h"
00034 #include "llvm/IR/Type.h"
00035 #include "llvm/MC/MCAsmInfo.h"
00036 #include "llvm/MC/MCAssembler.h"
00037 #include "llvm/MC/MCContext.h"
00038 #include "llvm/MC/MCELFStreamer.h"
00039 #include "llvm/MC/MCInst.h"
00040 #include "llvm/MC/MCInstBuilder.h"
00041 #include "llvm/MC/MCObjectStreamer.h"
00042 #include "llvm/MC/MCSectionMachO.h"
00043 #include "llvm/MC/MCStreamer.h"
00044 #include "llvm/MC/MCSymbol.h"
00045 #include "llvm/Support/ARMBuildAttributes.h"
00046 #include "llvm/Support/TargetParser.h"
00047 #include "llvm/Support/COFF.h"
00048 #include "llvm/Support/CommandLine.h"
00049 #include "llvm/Support/Debug.h"
00050 #include "llvm/Support/ELF.h"
00051 #include "llvm/Support/ErrorHandling.h"
00052 #include "llvm/Support/TargetRegistry.h"
00053 #include "llvm/Support/raw_ostream.h"
00054 #include "llvm/Target/TargetMachine.h"
00055 #include <cctype>
00056 using namespace llvm;
00057 
00058 #define DEBUG_TYPE "asm-printer"
00059 
00060 ARMAsmPrinter::ARMAsmPrinter(TargetMachine &TM,
00061                              std::unique_ptr<MCStreamer> Streamer)
00062     : AsmPrinter(TM, std::move(Streamer)), AFI(nullptr), MCP(nullptr),
00063       InConstantPool(false) {}
00064 
00065 void ARMAsmPrinter::EmitFunctionBodyEnd() {
00066   // Make sure to terminate any constant pools that were at the end
00067   // of the function.
00068   if (!InConstantPool)
00069     return;
00070   InConstantPool = false;
00071   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
00072 }
00073 
00074 void ARMAsmPrinter::EmitFunctionEntryLabel() {
00075   if (AFI->isThumbFunction()) {
00076     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
00077     OutStreamer->EmitThumbFunc(CurrentFnSym);
00078   }
00079 
00080   OutStreamer->EmitLabel(CurrentFnSym);
00081 }
00082 
00083 void ARMAsmPrinter::EmitXXStructor(const Constant *CV) {
00084   uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
00085   assert(Size && "C++ constructor pointer had zero size!");
00086 
00087   const GlobalValue *GV = dyn_cast<GlobalValue>(CV->stripPointerCasts());
00088   assert(GV && "C++ constructor pointer was not a GlobalValue!");
00089 
00090   const MCExpr *E = MCSymbolRefExpr::create(GetARMGVSymbol(GV,
00091                                                            ARMII::MO_NO_FLAG),
00092                                             (Subtarget->isTargetELF()
00093                                              ? MCSymbolRefExpr::VK_ARM_TARGET1
00094                                              : MCSymbolRefExpr::VK_None),
00095                                             OutContext);
00096 
00097   OutStreamer->EmitValue(E, Size);
00098 }
00099 
00100 /// runOnMachineFunction - This uses the EmitInstruction()
00101 /// method to print assembly for each instruction.
00102 ///
00103 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
00104   AFI = MF.getInfo<ARMFunctionInfo>();
00105   MCP = MF.getConstantPool();
00106   Subtarget = &MF.getSubtarget<ARMSubtarget>();
00107 
00108   SetupMachineFunction(MF);
00109 
00110   if (Subtarget->isTargetCOFF()) {
00111     bool Internal = MF.getFunction()->hasInternalLinkage();
00112     COFF::SymbolStorageClass Scl = Internal ? COFF::IMAGE_SYM_CLASS_STATIC
00113                                             : COFF::IMAGE_SYM_CLASS_EXTERNAL;
00114     int Type = COFF::IMAGE_SYM_DTYPE_FUNCTION << COFF::SCT_COMPLEX_TYPE_SHIFT;
00115 
00116     OutStreamer->BeginCOFFSymbolDef(CurrentFnSym);
00117     OutStreamer->EmitCOFFSymbolStorageClass(Scl);
00118     OutStreamer->EmitCOFFSymbolType(Type);
00119     OutStreamer->EndCOFFSymbolDef();
00120   }
00121 
00122   // Emit the rest of the function body.
00123   EmitFunctionBody();
00124 
00125   // If we need V4T thumb mode Register Indirect Jump pads, emit them.
00126   // These are created per function, rather than per TU, since it's
00127   // relatively easy to exceed the thumb branch range within a TU.
00128   if (! ThumbIndirectPads.empty()) {
00129     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
00130     EmitAlignment(1);
00131     for (unsigned i = 0, e = ThumbIndirectPads.size(); i < e; i++) {
00132       OutStreamer->EmitLabel(ThumbIndirectPads[i].second);
00133       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
00134         .addReg(ThumbIndirectPads[i].first)
00135         // Add predicate operands.
00136         .addImm(ARMCC::AL)
00137         .addReg(0));
00138     }
00139     ThumbIndirectPads.clear();
00140   }
00141 
00142   // We didn't modify anything.
00143   return false;
00144 }
00145 
00146 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
00147                                  raw_ostream &O) {
00148   const MachineOperand &MO = MI->getOperand(OpNum);
00149   unsigned TF = MO.getTargetFlags();
00150 
00151   switch (MO.getType()) {
00152   default: llvm_unreachable("<unknown operand type>");
00153   case MachineOperand::MO_Register: {
00154     unsigned Reg = MO.getReg();
00155     assert(TargetRegisterInfo::isPhysicalRegister(Reg));
00156     assert(!MO.getSubReg() && "Subregs should be eliminated!");
00157     if(ARM::GPRPairRegClass.contains(Reg)) {
00158       const MachineFunction &MF = *MI->getParent()->getParent();
00159       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
00160       Reg = TRI->getSubReg(Reg, ARM::gsub_0);
00161     }
00162     O << ARMInstPrinter::getRegisterName(Reg);
00163     break;
00164   }
00165   case MachineOperand::MO_Immediate: {
00166     int64_t Imm = MO.getImm();
00167     O << '#';
00168     if (TF == ARMII::MO_LO16)
00169       O << ":lower16:";
00170     else if (TF == ARMII::MO_HI16)
00171       O << ":upper16:";
00172     O << Imm;
00173     break;
00174   }
00175   case MachineOperand::MO_MachineBasicBlock:
00176     MO.getMBB()->getSymbol()->print(O, MAI);
00177     return;
00178   case MachineOperand::MO_GlobalAddress: {
00179     const GlobalValue *GV = MO.getGlobal();
00180     if (TF & ARMII::MO_LO16)
00181       O << ":lower16:";
00182     else if (TF & ARMII::MO_HI16)
00183       O << ":upper16:";
00184     GetARMGVSymbol(GV, TF)->print(O, MAI);
00185 
00186     printOffset(MO.getOffset(), O);
00187     if (TF == ARMII::MO_PLT)
00188       O << "(PLT)";
00189     break;
00190   }
00191   case MachineOperand::MO_ConstantPoolIndex:
00192     GetCPISymbol(MO.getIndex())->print(O, MAI);
00193     break;
00194   }
00195 }
00196 
00197 //===--------------------------------------------------------------------===//
00198 
00199 MCSymbol *ARMAsmPrinter::
00200 GetARMJTIPICJumpTableLabel(unsigned uid) const {
00201   const DataLayout *DL = TM.getDataLayout();
00202   SmallString<60> Name;
00203   raw_svector_ostream(Name) << DL->getPrivateGlobalPrefix() << "JTI"
00204                             << getFunctionNumber() << '_' << uid;
00205   return OutContext.getOrCreateSymbol(Name);
00206 }
00207 
00208 
00209 MCSymbol *ARMAsmPrinter::GetARMSJLJEHLabel() const {
00210   const DataLayout *DL = TM.getDataLayout();
00211   SmallString<60> Name;
00212   raw_svector_ostream(Name) << DL->getPrivateGlobalPrefix() << "SJLJEH"
00213     << getFunctionNumber();
00214   return OutContext.getOrCreateSymbol(Name);
00215 }
00216 
00217 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
00218                                     unsigned AsmVariant, const char *ExtraCode,
00219                                     raw_ostream &O) {
00220   // Does this asm operand have a single letter operand modifier?
00221   if (ExtraCode && ExtraCode[0]) {
00222     if (ExtraCode[1] != 0) return true; // Unknown modifier.
00223 
00224     switch (ExtraCode[0]) {
00225     default:
00226       // See if this is a generic print operand
00227       return AsmPrinter::PrintAsmOperand(MI, OpNum, AsmVariant, ExtraCode, O);
00228     case 'a': // Print as a memory address.
00229       if (MI->getOperand(OpNum).isReg()) {
00230         O << "["
00231           << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg())
00232           << "]";
00233         return false;
00234       }
00235       // Fallthrough
00236     case 'c': // Don't print "#" before an immediate operand.
00237       if (!MI->getOperand(OpNum).isImm())
00238         return true;
00239       O << MI->getOperand(OpNum).getImm();
00240       return false;
00241     case 'P': // Print a VFP double precision register.
00242     case 'q': // Print a NEON quad precision register.
00243       printOperand(MI, OpNum, O);
00244       return false;
00245     case 'y': // Print a VFP single precision register as indexed double.
00246       if (MI->getOperand(OpNum).isReg()) {
00247         unsigned Reg = MI->getOperand(OpNum).getReg();
00248         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00249         // Find the 'd' register that has this 's' register as a sub-register,
00250         // and determine the lane number.
00251         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
00252           if (!ARM::DPRRegClass.contains(*SR))
00253             continue;
00254           bool Lane0 = TRI->getSubReg(*SR, ARM::ssub_0) == Reg;
00255           O << ARMInstPrinter::getRegisterName(*SR) << (Lane0 ? "[0]" : "[1]");
00256           return false;
00257         }
00258       }
00259       return true;
00260     case 'B': // Bitwise inverse of integer or symbol without a preceding #.
00261       if (!MI->getOperand(OpNum).isImm())
00262         return true;
00263       O << ~(MI->getOperand(OpNum).getImm());
00264       return false;
00265     case 'L': // The low 16 bits of an immediate constant.
00266       if (!MI->getOperand(OpNum).isImm())
00267         return true;
00268       O << (MI->getOperand(OpNum).getImm() & 0xffff);
00269       return false;
00270     case 'M': { // A register range suitable for LDM/STM.
00271       if (!MI->getOperand(OpNum).isReg())
00272         return true;
00273       const MachineOperand &MO = MI->getOperand(OpNum);
00274       unsigned RegBegin = MO.getReg();
00275       // This takes advantage of the 2 operand-ness of ldm/stm and that we've
00276       // already got the operands in registers that are operands to the
00277       // inline asm statement.
00278       O << "{";
00279       if (ARM::GPRPairRegClass.contains(RegBegin)) {
00280         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00281         unsigned Reg0 = TRI->getSubReg(RegBegin, ARM::gsub_0);
00282         O << ARMInstPrinter::getRegisterName(Reg0) << ", ";
00283         RegBegin = TRI->getSubReg(RegBegin, ARM::gsub_1);
00284       }
00285       O << ARMInstPrinter::getRegisterName(RegBegin);
00286 
00287       // FIXME: The register allocator not only may not have given us the
00288       // registers in sequence, but may not be in ascending registers. This
00289       // will require changes in the register allocator that'll need to be
00290       // propagated down here if the operands change.
00291       unsigned RegOps = OpNum + 1;
00292       while (MI->getOperand(RegOps).isReg()) {
00293         O << ", "
00294           << ARMInstPrinter::getRegisterName(MI->getOperand(RegOps).getReg());
00295         RegOps++;
00296       }
00297 
00298       O << "}";
00299 
00300       return false;
00301     }
00302     case 'R': // The most significant register of a pair.
00303     case 'Q': { // The least significant register of a pair.
00304       if (OpNum == 0)
00305         return true;
00306       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
00307       if (!FlagsOP.isImm())
00308         return true;
00309       unsigned Flags = FlagsOP.getImm();
00310 
00311       // This operand may not be the one that actually provides the register. If
00312       // it's tied to a previous one then we should refer instead to that one
00313       // for registers and their classes.
00314       unsigned TiedIdx;
00315       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedIdx)) {
00316         for (OpNum = InlineAsm::MIOp_FirstOperand; TiedIdx; --TiedIdx) {
00317           unsigned OpFlags = MI->getOperand(OpNum).getImm();
00318           OpNum += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
00319         }
00320         Flags = MI->getOperand(OpNum).getImm();
00321 
00322         // Later code expects OpNum to be pointing at the register rather than
00323         // the flags.
00324         OpNum += 1;
00325       }
00326 
00327       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
00328       unsigned RC;
00329       InlineAsm::hasRegClassConstraint(Flags, RC);
00330       if (RC == ARM::GPRPairRegClassID) {
00331         if (NumVals != 1)
00332           return true;
00333         const MachineOperand &MO = MI->getOperand(OpNum);
00334         if (!MO.isReg())
00335           return true;
00336         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00337         unsigned Reg = TRI->getSubReg(MO.getReg(), ExtraCode[0] == 'Q' ?
00338             ARM::gsub_0 : ARM::gsub_1);
00339         O << ARMInstPrinter::getRegisterName(Reg);
00340         return false;
00341       }
00342       if (NumVals != 2)
00343         return true;
00344       unsigned RegOp = ExtraCode[0] == 'Q' ? OpNum : OpNum + 1;
00345       if (RegOp >= MI->getNumOperands())
00346         return true;
00347       const MachineOperand &MO = MI->getOperand(RegOp);
00348       if (!MO.isReg())
00349         return true;
00350       unsigned Reg = MO.getReg();
00351       O << ARMInstPrinter::getRegisterName(Reg);
00352       return false;
00353     }
00354 
00355     case 'e': // The low doubleword register of a NEON quad register.
00356     case 'f': { // The high doubleword register of a NEON quad register.
00357       if (!MI->getOperand(OpNum).isReg())
00358         return true;
00359       unsigned Reg = MI->getOperand(OpNum).getReg();
00360       if (!ARM::QPRRegClass.contains(Reg))
00361         return true;
00362       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
00363       unsigned SubReg = TRI->getSubReg(Reg, ExtraCode[0] == 'e' ?
00364                                        ARM::dsub_0 : ARM::dsub_1);
00365       O << ARMInstPrinter::getRegisterName(SubReg);
00366       return false;
00367     }
00368 
00369     // This modifier is not yet supported.
00370     case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
00371       return true;
00372     case 'H': { // The highest-numbered register of a pair.
00373       const MachineOperand &MO = MI->getOperand(OpNum);
00374       if (!MO.isReg())
00375         return true;
00376       const MachineFunction &MF = *MI->getParent()->getParent();
00377       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
00378       unsigned Reg = MO.getReg();
00379       if(!ARM::GPRPairRegClass.contains(Reg))
00380         return false;
00381       Reg = TRI->getSubReg(Reg, ARM::gsub_1);
00382       O << ARMInstPrinter::getRegisterName(Reg);
00383       return false;
00384     }
00385     }
00386   }
00387 
00388   printOperand(MI, OpNum, O);
00389   return false;
00390 }
00391 
00392 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
00393                                           unsigned OpNum, unsigned AsmVariant,
00394                                           const char *ExtraCode,
00395                                           raw_ostream &O) {
00396   // Does this asm operand have a single letter operand modifier?
00397   if (ExtraCode && ExtraCode[0]) {
00398     if (ExtraCode[1] != 0) return true; // Unknown modifier.
00399 
00400     switch (ExtraCode[0]) {
00401       case 'A': // A memory operand for a VLD1/VST1 instruction.
00402       default: return true;  // Unknown modifier.
00403       case 'm': // The base register of a memory operand.
00404         if (!MI->getOperand(OpNum).isReg())
00405           return true;
00406         O << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg());
00407         return false;
00408     }
00409   }
00410 
00411   const MachineOperand &MO = MI->getOperand(OpNum);
00412   assert(MO.isReg() && "unexpected inline asm memory operand");
00413   O << "[" << ARMInstPrinter::getRegisterName(MO.getReg()) << "]";
00414   return false;
00415 }
00416 
00417 static bool isThumb(const MCSubtargetInfo& STI) {
00418   return STI.getFeatureBits()[ARM::ModeThumb];
00419 }
00420 
00421 void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
00422                                      const MCSubtargetInfo *EndInfo) const {
00423   // If either end mode is unknown (EndInfo == NULL) or different than
00424   // the start mode, then restore the start mode.
00425   const bool WasThumb = isThumb(StartInfo);
00426   if (!EndInfo || WasThumb != isThumb(*EndInfo)) {
00427     OutStreamer->EmitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
00428   }
00429 }
00430 
00431 void ARMAsmPrinter::EmitStartOfAsmFile(Module &M) {
00432   const Triple &TT = TM.getTargetTriple();
00433   // Use unified assembler syntax.
00434   OutStreamer->EmitAssemblerFlag(MCAF_SyntaxUnified);
00435 
00436   // Emit ARM Build Attributes
00437   if (TT.isOSBinFormatELF())
00438     emitAttributes();
00439 
00440   // Use the triple's architecture and subarchitecture to determine
00441   // if we're thumb for the purposes of the top level code16 assembler
00442   // flag.
00443   bool isThumb = TT.getArch() == Triple::thumb ||
00444                  TT.getArch() == Triple::thumbeb ||
00445                  TT.getSubArch() == Triple::ARMSubArch_v7m ||
00446                  TT.getSubArch() == Triple::ARMSubArch_v6m;
00447   if (!M.getModuleInlineAsm().empty() && isThumb)
00448     OutStreamer->EmitAssemblerFlag(MCAF_Code16);
00449 }
00450 
00451 static void
00452 emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
00453                          MachineModuleInfoImpl::StubValueTy &MCSym) {
00454   // L_foo$stub:
00455   OutStreamer.EmitLabel(StubLabel);
00456   //   .indirect_symbol _foo
00457   OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
00458 
00459   if (MCSym.getInt())
00460     // External to current translation unit.
00461     OutStreamer.EmitIntValue(0, 4/*size*/);
00462   else
00463     // Internal to current translation unit.
00464     //
00465     // When we place the LSDA into the TEXT section, the type info
00466     // pointers need to be indirect and pc-rel. We accomplish this by
00467     // using NLPs; however, sometimes the types are local to the file.
00468     // We need to fill in the value for the NLP in those cases.
00469     OutStreamer.EmitValue(
00470         MCSymbolRefExpr::create(MCSym.getPointer(), OutStreamer.getContext()),
00471         4 /*size*/);
00472 }
00473 
00474 
00475 void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
00476   const Triple &TT = TM.getTargetTriple();
00477   if (TT.isOSBinFormatMachO()) {
00478     // All darwin targets use mach-o.
00479     const TargetLoweringObjectFileMachO &TLOFMacho =
00480       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
00481     MachineModuleInfoMachO &MMIMacho =
00482       MMI->getObjFileInfo<MachineModuleInfoMachO>();
00483 
00484     // Output non-lazy-pointers for external and common global variables.
00485     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
00486 
00487     if (!Stubs.empty()) {
00488       // Switch with ".non_lazy_symbol_pointer" directive.
00489       OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
00490       EmitAlignment(2);
00491 
00492       for (auto &Stub : Stubs)
00493         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
00494 
00495       Stubs.clear();
00496       OutStreamer->AddBlankLine();
00497     }
00498 
00499     Stubs = MMIMacho.GetHiddenGVStubList();
00500     if (!Stubs.empty()) {
00501       OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
00502       EmitAlignment(2);
00503 
00504       for (auto &Stub : Stubs)
00505         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
00506 
00507       Stubs.clear();
00508       OutStreamer->AddBlankLine();
00509     }
00510 
00511     // Funny Darwin hack: This flag tells the linker that no global symbols
00512     // contain code that falls through to other global symbols (e.g. the obvious
00513     // implementation of multiple entry points).  If this doesn't occur, the
00514     // linker can safely perform dead code stripping.  Since LLVM never
00515     // generates code that does this, it is always safe to set.
00516     OutStreamer->EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
00517   }
00518 }
00519 
00520 //===----------------------------------------------------------------------===//
00521 // Helper routines for EmitStartOfAsmFile() and EmitEndOfAsmFile()
00522 // FIXME:
00523 // The following seem like one-off assembler flags, but they actually need
00524 // to appear in the .ARM.attributes section in ELF.
00525 // Instead of subclassing the MCELFStreamer, we do the work here.
00526 
00527 static ARMBuildAttrs::CPUArch getArchForCPU(StringRef CPU,
00528                                             const ARMSubtarget *Subtarget) {
00529   if (CPU == "xscale")
00530     return ARMBuildAttrs::v5TEJ;
00531 
00532   if (Subtarget->hasV8Ops())
00533     return ARMBuildAttrs::v8;
00534   else if (Subtarget->hasV7Ops()) {
00535     if (Subtarget->isMClass() && Subtarget->hasThumb2DSP())
00536       return ARMBuildAttrs::v7E_M;
00537     return ARMBuildAttrs::v7;
00538   } else if (Subtarget->hasV6T2Ops())
00539     return ARMBuildAttrs::v6T2;
00540   else if (Subtarget->hasV6MOps())
00541     return ARMBuildAttrs::v6S_M;
00542   else if (Subtarget->hasV6Ops())
00543     return ARMBuildAttrs::v6;
00544   else if (Subtarget->hasV5TEOps())
00545     return ARMBuildAttrs::v5TE;
00546   else if (Subtarget->hasV5TOps())
00547     return ARMBuildAttrs::v5T;
00548   else if (Subtarget->hasV4TOps())
00549     return ARMBuildAttrs::v4T;
00550   else
00551     return ARMBuildAttrs::v4;
00552 }
00553 
00554 void ARMAsmPrinter::emitAttributes() {
00555   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
00556   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
00557 
00558   ATS.emitTextAttribute(ARMBuildAttrs::conformance, "2.09");
00559 
00560   ATS.switchVendor("aeabi");
00561 
00562   // Compute ARM ELF Attributes based on the default subtarget that
00563   // we'd have constructed. The existing ARM behavior isn't LTO clean
00564   // anyhow.
00565   // FIXME: For ifunc related functions we could iterate over and look
00566   // for a feature string that doesn't match the default one.
00567   const Triple &TT = TM.getTargetTriple();
00568   StringRef CPU = TM.getTargetCPU();
00569   StringRef FS = TM.getTargetFeatureString();
00570   std::string ArchFS = ARM_MC::ParseARMTriple(TT, CPU);
00571   if (!FS.empty()) {
00572     if (!ArchFS.empty())
00573       ArchFS = (Twine(ArchFS) + "," + FS).str();
00574     else
00575       ArchFS = FS;
00576   }
00577   const ARMBaseTargetMachine &ATM =
00578       static_cast<const ARMBaseTargetMachine &>(TM);
00579   const ARMSubtarget STI(TT, CPU, ArchFS, ATM, ATM.isLittleEndian());
00580 
00581   std::string CPUString = STI.getCPUString();
00582 
00583   if (CPUString.find("generic") != 0) { //CPUString doesn't start with "generic"
00584     // FIXME: remove krait check when GNU tools support krait cpu
00585     if (STI.isKrait()) {
00586       ATS.emitTextAttribute(ARMBuildAttrs::CPU_name, "cortex-a9");
00587       // We consider krait as a "cortex-a9" + hwdiv CPU
00588       // Enable hwdiv through ".arch_extension idiv"
00589       if (STI.hasDivide() || STI.hasDivideInARMMode())
00590         ATS.emitArchExtension(ARM::AEK_HWDIV);
00591     } else
00592       ATS.emitTextAttribute(ARMBuildAttrs::CPU_name, CPUString);
00593   }
00594 
00595   ATS.emitAttribute(ARMBuildAttrs::CPU_arch, getArchForCPU(CPUString, &STI));
00596 
00597   // Tag_CPU_arch_profile must have the default value of 0 when "Architecture
00598   // profile is not applicable (e.g. pre v7, or cross-profile code)".
00599   if (STI.hasV7Ops()) {
00600     if (STI.isAClass()) {
00601       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
00602                         ARMBuildAttrs::ApplicationProfile);
00603     } else if (STI.isRClass()) {
00604       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
00605                         ARMBuildAttrs::RealTimeProfile);
00606     } else if (STI.isMClass()) {
00607       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
00608                         ARMBuildAttrs::MicroControllerProfile);
00609     }
00610   }
00611 
00612   ATS.emitAttribute(ARMBuildAttrs::ARM_ISA_use,
00613                     STI.hasARMOps() ? ARMBuildAttrs::Allowed
00614                                     : ARMBuildAttrs::Not_Allowed);
00615   if (STI.isThumb1Only()) {
00616     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use, ARMBuildAttrs::Allowed);
00617   } else if (STI.hasThumb2()) {
00618     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
00619                       ARMBuildAttrs::AllowThumb32);
00620   }
00621 
00622   if (STI.hasNEON()) {
00623     /* NEON is not exactly a VFP architecture, but GAS emit one of
00624      * neon/neon-fp-armv8/neon-vfpv4/vfpv3/vfpv2 for .fpu parameters */
00625     if (STI.hasFPARMv8()) {
00626       if (STI.hasCrypto())
00627         ATS.emitFPU(ARM::FK_CRYPTO_NEON_FP_ARMV8);
00628       else
00629         ATS.emitFPU(ARM::FK_NEON_FP_ARMV8);
00630     } else if (STI.hasVFP4())
00631       ATS.emitFPU(ARM::FK_NEON_VFPV4);
00632     else
00633       ATS.emitFPU(ARM::FK_NEON);
00634     // Emit Tag_Advanced_SIMD_arch for ARMv8 architecture
00635     if (STI.hasV8Ops())
00636       ATS.emitAttribute(ARMBuildAttrs::Advanced_SIMD_arch,
00637                         STI.hasV8_1aOps() ? ARMBuildAttrs::AllowNeonARMv8_1a:
00638                                             ARMBuildAttrs::AllowNeonARMv8);
00639   } else {
00640     if (STI.hasFPARMv8())
00641       // FPv5 and FP-ARMv8 have the same instructions, so are modeled as one
00642       // FPU, but there are two different names for it depending on the CPU.
00643       ATS.emitFPU(STI.hasD16()
00644                   ? (STI.isFPOnlySP() ? ARM::FK_FPV5_SP_D16 : ARM::FK_FPV5_D16)
00645                   : ARM::FK_FP_ARMV8);
00646     else if (STI.hasVFP4())
00647       ATS.emitFPU(STI.hasD16()
00648                   ? (STI.isFPOnlySP() ? ARM::FK_FPV4_SP_D16 : ARM::FK_VFPV4_D16)
00649                   : ARM::FK_VFPV4);
00650     else if (STI.hasVFP3())
00651       ATS.emitFPU(STI.hasD16() ? ARM::FK_VFPV3_D16 : ARM::FK_VFPV3);
00652     else if (STI.hasVFP2())
00653       ATS.emitFPU(ARM::FK_VFPV2);
00654   }
00655 
00656   if (TM.getRelocationModel() == Reloc::PIC_) {
00657     // PIC specific attributes.
00658     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
00659                       ARMBuildAttrs::AddressRWPCRel);
00660     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
00661                       ARMBuildAttrs::AddressROPCRel);
00662     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
00663                       ARMBuildAttrs::AddressGOT);
00664   } else {
00665     // Allow direct addressing of imported data for all other relocation models.
00666     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
00667                       ARMBuildAttrs::AddressDirect);
00668   }
00669 
00670   // Signal various FP modes.
00671   if (!TM.Options.UnsafeFPMath) {
00672     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
00673                       ARMBuildAttrs::IEEEDenormals);
00674     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions, ARMBuildAttrs::Allowed);
00675 
00676     // If the user has permitted this code to choose the IEEE 754
00677     // rounding at run-time, emit the rounding attribute.
00678     if (TM.Options.HonorSignDependentRoundingFPMathOption)
00679       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_rounding, ARMBuildAttrs::Allowed);
00680   } else {
00681     if (!STI.hasVFP2()) {
00682       // When the target doesn't have an FPU (by design or
00683       // intention), the assumptions made on the software support
00684       // mirror that of the equivalent hardware support *if it
00685       // existed*. For v7 and better we indicate that denormals are
00686       // flushed preserving sign, and for V6 we indicate that
00687       // denormals are flushed to positive zero.
00688       if (STI.hasV7Ops())
00689         ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
00690                           ARMBuildAttrs::PreserveFPSign);
00691     } else if (STI.hasVFP3()) {
00692       // In VFPv4, VFPv4U, VFPv3, or VFPv3U, it is preserved. That is,
00693       // the sign bit of the zero matches the sign bit of the input or
00694       // result that is being flushed to zero.
00695       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
00696                         ARMBuildAttrs::PreserveFPSign);
00697     }
00698     // For VFPv2 implementations it is implementation defined as
00699     // to whether denormals are flushed to positive zero or to
00700     // whatever the sign of zero is (ARM v7AR ARM 2.7.5). Historically
00701     // LLVM has chosen to flush this to positive zero (most likely for
00702     // GCC compatibility), so that's the chosen value here (the
00703     // absence of its emission implies zero).
00704   }
00705 
00706   // TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath is the
00707   // equivalent of GCC's -ffinite-math-only flag.
00708   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
00709     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
00710                       ARMBuildAttrs::Allowed);
00711   else
00712     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
00713                       ARMBuildAttrs::AllowIEE754);
00714 
00715   if (STI.allowsUnalignedMem())
00716     ATS.emitAttribute(ARMBuildAttrs::CPU_unaligned_access,
00717                       ARMBuildAttrs::Allowed);
00718   else
00719     ATS.emitAttribute(ARMBuildAttrs::CPU_unaligned_access,
00720                       ARMBuildAttrs::Not_Allowed);
00721 
00722   // FIXME: add more flags to ARMBuildAttributes.h
00723   // 8-bytes alignment stuff.
00724   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
00725   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
00726 
00727   // ABI_HardFP_use attribute to indicate single precision FP.
00728   if (STI.isFPOnlySP())
00729     ATS.emitAttribute(ARMBuildAttrs::ABI_HardFP_use,
00730                       ARMBuildAttrs::HardFPSinglePrecision);
00731 
00732   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
00733   if (STI.isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
00734     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
00735 
00736   // FIXME: Should we signal R9 usage?
00737 
00738   if (STI.hasFP16())
00739     ATS.emitAttribute(ARMBuildAttrs::FP_HP_extension, ARMBuildAttrs::AllowHPFP);
00740 
00741   // FIXME: To support emitting this build attribute as GCC does, the
00742   // -mfp16-format option and associated plumbing must be
00743   // supported. For now the __fp16 type is exposed by default, so this
00744   // attribute should be emitted with value 1.
00745   ATS.emitAttribute(ARMBuildAttrs::ABI_FP_16bit_format,
00746                     ARMBuildAttrs::FP16FormatIEEE);
00747 
00748   if (STI.hasMPExtension())
00749     ATS.emitAttribute(ARMBuildAttrs::MPextension_use, ARMBuildAttrs::AllowMP);
00750 
00751   // Hardware divide in ARM mode is part of base arch, starting from ARMv8.
00752   // If only Thumb hwdiv is present, it must also be in base arch (ARMv7-R/M).
00753   // It is not possible to produce DisallowDIV: if hwdiv is present in the base
00754   // arch, supplying -hwdiv downgrades the effective arch, via ClearImpliedBits.
00755   // AllowDIVExt is only emitted if hwdiv isn't available in the base arch;
00756   // otherwise, the default value (AllowDIVIfExists) applies.
00757   if (STI.hasDivideInARMMode() && !STI.hasV8Ops())
00758     ATS.emitAttribute(ARMBuildAttrs::DIV_use, ARMBuildAttrs::AllowDIVExt);
00759 
00760   if (MMI) {
00761     if (const Module *SourceModule = MMI->getModule()) {
00762       // ABI_PCS_wchar_t to indicate wchar_t width
00763       // FIXME: There is no way to emit value 0 (wchar_t prohibited).
00764       if (auto WCharWidthValue = mdconst::extract_or_null<ConstantInt>(
00765               SourceModule->getModuleFlag("wchar_size"))) {
00766         int WCharWidth = WCharWidthValue->getZExtValue();
00767         assert((WCharWidth == 2 || WCharWidth == 4) &&
00768                "wchar_t width must be 2 or 4 bytes");
00769         ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
00770       }
00771 
00772       // ABI_enum_size to indicate enum width
00773       // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
00774       //        (all enums contain a value needing 32 bits to encode).
00775       if (auto EnumWidthValue = mdconst::extract_or_null<ConstantInt>(
00776               SourceModule->getModuleFlag("min_enum_size"))) {
00777         int EnumWidth = EnumWidthValue->getZExtValue();
00778         assert((EnumWidth == 1 || EnumWidth == 4) &&
00779                "Minimum enum width must be 1 or 4 bytes");
00780         int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
00781         ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
00782       }
00783     }
00784   }
00785 
00786   // TODO: We currently only support either reserving the register, or treating
00787   // it as another callee-saved register, but not as SB or a TLS pointer; It
00788   // would instead be nicer to push this from the frontend as metadata, as we do
00789   // for the wchar and enum size tags
00790   if (STI.isR9Reserved())
00791     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use, ARMBuildAttrs::R9Reserved);
00792   else
00793     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use, ARMBuildAttrs::R9IsGPR);
00794 
00795   if (STI.hasTrustZone() && STI.hasVirtualization())
00796     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
00797                       ARMBuildAttrs::AllowTZVirtualization);
00798   else if (STI.hasTrustZone())
00799     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
00800                       ARMBuildAttrs::AllowTZ);
00801   else if (STI.hasVirtualization())
00802     ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
00803                       ARMBuildAttrs::AllowVirtualization);
00804 
00805   ATS.finishAttributeSection();
00806 }
00807 
00808 //===----------------------------------------------------------------------===//
00809 
00810 static MCSymbol *getPICLabel(const char *Prefix, unsigned FunctionNumber,
00811                              unsigned LabelId, MCContext &Ctx) {
00812 
00813   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
00814                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
00815   return Label;
00816 }
00817 
00818 static MCSymbolRefExpr::VariantKind
00819 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
00820   switch (Modifier) {
00821   case ARMCP::no_modifier: return MCSymbolRefExpr::VK_None;
00822   case ARMCP::TLSGD:       return MCSymbolRefExpr::VK_TLSGD;
00823   case ARMCP::TPOFF:       return MCSymbolRefExpr::VK_TPOFF;
00824   case ARMCP::GOTTPOFF:    return MCSymbolRefExpr::VK_GOTTPOFF;
00825   case ARMCP::GOT:         return MCSymbolRefExpr::VK_GOT;
00826   case ARMCP::GOTOFF:      return MCSymbolRefExpr::VK_GOTOFF;
00827   }
00828   llvm_unreachable("Invalid ARMCPModifier!");
00829 }
00830 
00831 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
00832                                         unsigned char TargetFlags) {
00833   if (Subtarget->isTargetMachO()) {
00834     bool IsIndirect = (TargetFlags & ARMII::MO_NONLAZY) &&
00835       Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
00836 
00837     if (!IsIndirect)
00838       return getSymbol(GV);
00839 
00840     // FIXME: Remove this when Darwin transition to @GOT like syntax.
00841     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
00842     MachineModuleInfoMachO &MMIMachO =
00843       MMI->getObjFileInfo<MachineModuleInfoMachO>();
00844     MachineModuleInfoImpl::StubValueTy &StubSym =
00845       GV->hasHiddenVisibility() ? MMIMachO.getHiddenGVStubEntry(MCSym)
00846                                 : MMIMachO.getGVStubEntry(MCSym);
00847     if (!StubSym.getPointer())
00848       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
00849                                                    !GV->hasInternalLinkage());
00850     return MCSym;
00851   } else if (Subtarget->isTargetCOFF()) {
00852     assert(Subtarget->isTargetWindows() &&
00853            "Windows is the only supported COFF target");
00854 
00855     bool IsIndirect = (TargetFlags & ARMII::MO_DLLIMPORT);
00856     if (!IsIndirect)
00857       return getSymbol(GV);
00858 
00859     SmallString<128> Name;
00860     Name = "__imp_";
00861     getNameWithPrefix(Name, GV);
00862 
00863     return OutContext.getOrCreateSymbol(Name);
00864   } else if (Subtarget->isTargetELF()) {
00865     return getSymbol(GV);
00866   }
00867   llvm_unreachable("unexpected target");
00868 }
00869 
00870 void ARMAsmPrinter::
00871 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
00872   const DataLayout *DL = TM.getDataLayout();
00873   int Size = TM.getDataLayout()->getTypeAllocSize(MCPV->getType());
00874 
00875   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
00876 
00877   MCSymbol *MCSym;
00878   if (ACPV->isLSDA()) {
00879     MCSym = getCurExceptionSym();
00880   } else if (ACPV->isBlockAddress()) {
00881     const BlockAddress *BA =
00882       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
00883     MCSym = GetBlockAddressSymbol(BA);
00884   } else if (ACPV->isGlobalValue()) {
00885     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
00886 
00887     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
00888     // flag the global as MO_NONLAZY.
00889     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
00890     MCSym = GetARMGVSymbol(GV, TF);
00891   } else if (ACPV->isMachineBasicBlock()) {
00892     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
00893     MCSym = MBB->getSymbol();
00894   } else {
00895     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
00896     const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
00897     MCSym = GetExternalSymbolSymbol(Sym);
00898   }
00899 
00900   // Create an MCSymbol for the reference.
00901   const MCExpr *Expr =
00902     MCSymbolRefExpr::create(MCSym, getModifierVariantKind(ACPV->getModifier()),
00903                             OutContext);
00904 
00905   if (ACPV->getPCAdjustment()) {
00906     MCSymbol *PCLabel = getPICLabel(DL->getPrivateGlobalPrefix(),
00907                                     getFunctionNumber(),
00908                                     ACPV->getLabelId(),
00909                                     OutContext);
00910     const MCExpr *PCRelExpr = MCSymbolRefExpr::create(PCLabel, OutContext);
00911     PCRelExpr =
00912       MCBinaryExpr::createAdd(PCRelExpr,
00913                               MCConstantExpr::create(ACPV->getPCAdjustment(),
00914                                                      OutContext),
00915                               OutContext);
00916     if (ACPV->mustAddCurrentAddress()) {
00917       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
00918       // label, so just emit a local label end reference that instead.
00919       MCSymbol *DotSym = OutContext.createTempSymbol();
00920       OutStreamer->EmitLabel(DotSym);
00921       const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
00922       PCRelExpr = MCBinaryExpr::createSub(PCRelExpr, DotExpr, OutContext);
00923     }
00924     Expr = MCBinaryExpr::createSub(Expr, PCRelExpr, OutContext);
00925   }
00926   OutStreamer->EmitValue(Expr, Size);
00927 }
00928 
00929 void ARMAsmPrinter::EmitJumpTableAddrs(const MachineInstr *MI) {
00930   const MachineOperand &MO1 = MI->getOperand(1);
00931   unsigned JTI = MO1.getIndex();
00932 
00933   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
00934   // ARM mode tables.
00935   EmitAlignment(2);
00936 
00937   // Emit a label for the jump table.
00938   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
00939   OutStreamer->EmitLabel(JTISymbol);
00940 
00941   // Mark the jump table as data-in-code.
00942   OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
00943 
00944   // Emit each entry of the table.
00945   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
00946   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
00947   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
00948 
00949   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
00950     MachineBasicBlock *MBB = JTBBs[i];
00951     // Construct an MCExpr for the entry. We want a value of the form:
00952     // (BasicBlockAddr - TableBeginAddr)
00953     //
00954     // For example, a table with entries jumping to basic blocks BB0 and BB1
00955     // would look like:
00956     // LJTI_0_0:
00957     //    .word (LBB0 - LJTI_0_0)
00958     //    .word (LBB1 - LJTI_0_0)
00959     const MCExpr *Expr = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
00960 
00961     if (TM.getRelocationModel() == Reloc::PIC_)
00962       Expr = MCBinaryExpr::createSub(Expr, MCSymbolRefExpr::create(JTISymbol,
00963                                                                    OutContext),
00964                                      OutContext);
00965     // If we're generating a table of Thumb addresses in static relocation
00966     // model, we need to add one to keep interworking correctly.
00967     else if (AFI->isThumbFunction())
00968       Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(1,OutContext),
00969                                      OutContext);
00970     OutStreamer->EmitValue(Expr, 4);
00971   }
00972   // Mark the end of jump table data-in-code region.
00973   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
00974 }
00975 
00976 void ARMAsmPrinter::EmitJumpTableInsts(const MachineInstr *MI) {
00977   const MachineOperand &MO1 = MI->getOperand(1);
00978   unsigned JTI = MO1.getIndex();
00979 
00980   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
00981   OutStreamer->EmitLabel(JTISymbol);
00982 
00983   // Emit each entry of the table.
00984   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
00985   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
00986   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
00987 
00988   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
00989     MachineBasicBlock *MBB = JTBBs[i];
00990     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
00991                                                           OutContext);
00992     // If this isn't a TBB or TBH, the entries are direct branch instructions.
00993     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2B)
00994         .addExpr(MBBSymbolExpr)
00995         .addImm(ARMCC::AL)
00996         .addReg(0));
00997   }
00998 }
00999 
01000 void ARMAsmPrinter::EmitJumpTableTBInst(const MachineInstr *MI,
01001                                         unsigned OffsetWidth) {
01002   assert((OffsetWidth == 1 || OffsetWidth == 2) && "invalid tbb/tbh width");
01003   const MachineOperand &MO1 = MI->getOperand(1);
01004   unsigned JTI = MO1.getIndex();
01005 
01006   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
01007   OutStreamer->EmitLabel(JTISymbol);
01008 
01009   // Emit each entry of the table.
01010   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
01011   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
01012   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
01013 
01014   // Mark the jump table as data-in-code.
01015   OutStreamer->EmitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
01016                                                : MCDR_DataRegionJT16);
01017 
01018   for (auto MBB : JTBBs) {
01019     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
01020                                                           OutContext);
01021     // Otherwise it's an offset from the dispatch instruction. Construct an
01022     // MCExpr for the entry. We want a value of the form:
01023     // (BasicBlockAddr - TBBInstAddr + 4) / 2
01024     //
01025     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
01026     // would look like:
01027     // LJTI_0_0:
01028     //    .byte (LBB0 - (LCPI0_0 + 4)) / 2
01029     //    .byte (LBB1 - (LCPI0_0 + 4)) / 2
01030     // where LCPI0_0 is a label defined just before the TBB instruction using
01031     // this table.
01032     MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
01033     const MCExpr *Expr = MCBinaryExpr::createAdd(
01034         MCSymbolRefExpr::create(TBInstPC, OutContext),
01035         MCConstantExpr::create(4, OutContext), OutContext);
01036     Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
01037     Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
01038                                    OutContext);
01039     OutStreamer->EmitValue(Expr, OffsetWidth);
01040   }
01041   // Mark the end of jump table data-in-code region. 32-bit offsets use
01042   // actual branch instructions here, so we don't mark those as a data-region
01043   // at all.
01044   OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
01045 
01046   // Make sure the next instruction is 2-byte aligned.
01047   EmitAlignment(1);
01048 }
01049 
01050 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
01051   assert(MI->getFlag(MachineInstr::FrameSetup) &&
01052       "Only instruction which are involved into frame setup code are allowed");
01053 
01054   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
01055   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
01056   const MachineFunction &MF = *MI->getParent()->getParent();
01057   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
01058   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
01059 
01060   unsigned FramePtr = RegInfo->getFrameRegister(MF);
01061   unsigned Opc = MI->getOpcode();
01062   unsigned SrcReg, DstReg;
01063 
01064   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
01065     // Two special cases:
01066     // 1) tPUSH does not have src/dst regs.
01067     // 2) for Thumb1 code we sometimes materialize the constant via constpool
01068     // load. Yes, this is pretty fragile, but for now I don't see better
01069     // way... :(
01070     SrcReg = DstReg = ARM::SP;
01071   } else {
01072     SrcReg = MI->getOperand(1).getReg();
01073     DstReg = MI->getOperand(0).getReg();
01074   }
01075 
01076   // Try to figure out the unwinding opcode out of src / dst regs.
01077   if (MI->mayStore()) {
01078     // Register saves.
01079     assert(DstReg == ARM::SP &&
01080            "Only stack pointer as a destination reg is supported");
01081 
01082     SmallVector<unsigned, 4> RegList;
01083     // Skip src & dst reg, and pred ops.
01084     unsigned StartOp = 2 + 2;
01085     // Use all the operands.
01086     unsigned NumOffset = 0;
01087 
01088     switch (Opc) {
01089     default:
01090       MI->dump();
01091       llvm_unreachable("Unsupported opcode for unwinding information");
01092     case ARM::tPUSH:
01093       // Special case here: no src & dst reg, but two extra imp ops.
01094       StartOp = 2; NumOffset = 2;
01095     case ARM::STMDB_UPD:
01096     case ARM::t2STMDB_UPD:
01097     case ARM::VSTMDDB_UPD:
01098       assert(SrcReg == ARM::SP &&
01099              "Only stack pointer as a source reg is supported");
01100       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
01101            i != NumOps; ++i) {
01102         const MachineOperand &MO = MI->getOperand(i);
01103         // Actually, there should never be any impdef stuff here. Skip it
01104         // temporary to workaround PR11902.
01105         if (MO.isImplicit())
01106           continue;
01107         RegList.push_back(MO.getReg());
01108       }
01109       break;
01110     case ARM::STR_PRE_IMM:
01111     case ARM::STR_PRE_REG:
01112     case ARM::t2STR_PRE:
01113       assert(MI->getOperand(2).getReg() == ARM::SP &&
01114              "Only stack pointer as a source reg is supported");
01115       RegList.push_back(SrcReg);
01116       break;
01117     }
01118     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM)
01119       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
01120   } else {
01121     // Changes of stack / frame pointer.
01122     if (SrcReg == ARM::SP) {
01123       int64_t Offset = 0;
01124       switch (Opc) {
01125       default:
01126         MI->dump();
01127         llvm_unreachable("Unsupported opcode for unwinding information");
01128       case ARM::MOVr:
01129       case ARM::tMOVr:
01130         Offset = 0;
01131         break;
01132       case ARM::ADDri:
01133         Offset = -MI->getOperand(2).getImm();
01134         break;
01135       case ARM::SUBri:
01136       case ARM::t2SUBri:
01137         Offset = MI->getOperand(2).getImm();
01138         break;
01139       case ARM::tSUBspi:
01140         Offset = MI->getOperand(2).getImm()*4;
01141         break;
01142       case ARM::tADDspi:
01143       case ARM::tADDrSPi:
01144         Offset = -MI->getOperand(2).getImm()*4;
01145         break;
01146       case ARM::tLDRpci: {
01147         // Grab the constpool index and check, whether it corresponds to
01148         // original or cloned constpool entry.
01149         unsigned CPI = MI->getOperand(1).getIndex();
01150         const MachineConstantPool *MCP = MF.getConstantPool();
01151         if (CPI >= MCP->getConstants().size())
01152           CPI = AFI.getOriginalCPIdx(CPI);
01153         assert(CPI != -1U && "Invalid constpool index");
01154 
01155         // Derive the actual offset.
01156         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
01157         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
01158         // FIXME: Check for user, it should be "add" instruction!
01159         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
01160         break;
01161       }
01162       }
01163 
01164       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
01165         if (DstReg == FramePtr && FramePtr != ARM::SP)
01166           // Set-up of the frame pointer. Positive values correspond to "add"
01167           // instruction.
01168           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
01169         else if (DstReg == ARM::SP) {
01170           // Change of SP by an offset. Positive values correspond to "sub"
01171           // instruction.
01172           ATS.emitPad(Offset);
01173         } else {
01174           // Move of SP to a register.  Positive values correspond to an "add"
01175           // instruction.
01176           ATS.emitMovSP(DstReg, -Offset);
01177         }
01178       }
01179     } else if (DstReg == ARM::SP) {
01180       MI->dump();
01181       llvm_unreachable("Unsupported opcode for unwinding information");
01182     }
01183     else {
01184       MI->dump();
01185       llvm_unreachable("Unsupported opcode for unwinding information");
01186     }
01187   }
01188 }
01189 
01190 // Simple pseudo-instructions have their lowering (with expansion to real
01191 // instructions) auto-generated.
01192 #include "ARMGenMCPseudoLowering.inc"
01193 
01194 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
01195   const DataLayout *DL = TM.getDataLayout();
01196 
01197   // If we just ended a constant pool, mark it as such.
01198   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
01199     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
01200     InConstantPool = false;
01201   }
01202 
01203   // Emit unwinding stuff for frame-related instructions
01204   if (Subtarget->isTargetEHABICompatible() &&
01205        MI->getFlag(MachineInstr::FrameSetup))
01206     EmitUnwindingInstruction(MI);
01207 
01208   // Do any auto-generated pseudo lowerings.
01209   if (emitPseudoExpansionLowering(*OutStreamer, MI))
01210     return;
01211 
01212   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
01213          "Pseudo flag setting opcode should be expanded early");
01214 
01215   // Check for manual lowerings.
01216   unsigned Opc = MI->getOpcode();
01217   switch (Opc) {
01218   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
01219   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
01220   case ARM::LEApcrel:
01221   case ARM::tLEApcrel:
01222   case ARM::t2LEApcrel: {
01223     // FIXME: Need to also handle globals and externals
01224     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
01225     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
01226                                                ARM::t2LEApcrel ? ARM::t2ADR
01227                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
01228                      : ARM::ADR))
01229       .addReg(MI->getOperand(0).getReg())
01230       .addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
01231       // Add predicate operands.
01232       .addImm(MI->getOperand(2).getImm())
01233       .addReg(MI->getOperand(3).getReg()));
01234     return;
01235   }
01236   case ARM::LEApcrelJT:
01237   case ARM::tLEApcrelJT:
01238   case ARM::t2LEApcrelJT: {
01239     MCSymbol *JTIPICSymbol =
01240       GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
01241     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
01242                                                ARM::t2LEApcrelJT ? ARM::t2ADR
01243                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
01244                      : ARM::ADR))
01245       .addReg(MI->getOperand(0).getReg())
01246       .addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
01247       // Add predicate operands.
01248       .addImm(MI->getOperand(2).getImm())
01249       .addReg(MI->getOperand(3).getReg()));
01250     return;
01251   }
01252   // Darwin call instructions are just normal call instructions with different
01253   // clobber semantics (they clobber R9).
01254   case ARM::BX_CALL: {
01255     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
01256       .addReg(ARM::LR)
01257       .addReg(ARM::PC)
01258       // Add predicate operands.
01259       .addImm(ARMCC::AL)
01260       .addReg(0)
01261       // Add 's' bit operand (always reg0 for this)
01262       .addReg(0));
01263 
01264     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
01265       .addReg(MI->getOperand(0).getReg()));
01266     return;
01267   }
01268   case ARM::tBX_CALL: {
01269     if (Subtarget->hasV5TOps())
01270       llvm_unreachable("Expected BLX to be selected for v5t+");
01271 
01272     // On ARM v4t, when doing a call from thumb mode, we need to ensure
01273     // that the saved lr has its LSB set correctly (the arch doesn't
01274     // have blx).
01275     // So here we generate a bl to a small jump pad that does bx rN.
01276     // The jump pads are emitted after the function body.
01277 
01278     unsigned TReg = MI->getOperand(0).getReg();
01279     MCSymbol *TRegSym = nullptr;
01280     for (unsigned i = 0, e = ThumbIndirectPads.size(); i < e; i++) {
01281       if (ThumbIndirectPads[i].first == TReg) {
01282         TRegSym = ThumbIndirectPads[i].second;
01283         break;
01284       }
01285     }
01286 
01287     if (!TRegSym) {
01288       TRegSym = OutContext.createTempSymbol();
01289       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
01290     }
01291 
01292     // Create a link-saving branch to the Reg Indirect Jump Pad.
01293     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
01294         // Predicate comes first here.
01295         .addImm(ARMCC::AL).addReg(0)
01296         .addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
01297     return;
01298   }
01299   case ARM::BMOVPCRX_CALL: {
01300     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
01301       .addReg(ARM::LR)
01302       .addReg(ARM::PC)
01303       // Add predicate operands.
01304       .addImm(ARMCC::AL)
01305       .addReg(0)
01306       // Add 's' bit operand (always reg0 for this)
01307       .addReg(0));
01308 
01309     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
01310       .addReg(ARM::PC)
01311       .addReg(MI->getOperand(0).getReg())
01312       // Add predicate operands.
01313       .addImm(ARMCC::AL)
01314       .addReg(0)
01315       // Add 's' bit operand (always reg0 for this)
01316       .addReg(0));
01317     return;
01318   }
01319   case ARM::BMOVPCB_CALL: {
01320     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
01321       .addReg(ARM::LR)
01322       .addReg(ARM::PC)
01323       // Add predicate operands.
01324       .addImm(ARMCC::AL)
01325       .addReg(0)
01326       // Add 's' bit operand (always reg0 for this)
01327       .addReg(0));
01328 
01329     const MachineOperand &Op = MI->getOperand(0);
01330     const GlobalValue *GV = Op.getGlobal();
01331     const unsigned TF = Op.getTargetFlags();
01332     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
01333     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
01334     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
01335       .addExpr(GVSymExpr)
01336       // Add predicate operands.
01337       .addImm(ARMCC::AL)
01338       .addReg(0));
01339     return;
01340   }
01341   case ARM::MOVi16_ga_pcrel:
01342   case ARM::t2MOVi16_ga_pcrel: {
01343     MCInst TmpInst;
01344     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
01345     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
01346 
01347     unsigned TF = MI->getOperand(1).getTargetFlags();
01348     const GlobalValue *GV = MI->getOperand(1).getGlobal();
01349     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
01350     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
01351 
01352     MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
01353                                      getFunctionNumber(),
01354                                      MI->getOperand(2).getImm(), OutContext);
01355     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
01356     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
01357     const MCExpr *PCRelExpr =
01358       ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
01359                                       MCBinaryExpr::createAdd(LabelSymExpr,
01360                                       MCConstantExpr::create(PCAdj, OutContext),
01361                                       OutContext), OutContext), OutContext);
01362       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
01363 
01364     // Add predicate operands.
01365     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
01366     TmpInst.addOperand(MCOperand::createReg(0));
01367     // Add 's' bit operand (always reg0 for this)
01368     TmpInst.addOperand(MCOperand::createReg(0));
01369     EmitToStreamer(*OutStreamer, TmpInst);
01370     return;
01371   }
01372   case ARM::MOVTi16_ga_pcrel:
01373   case ARM::t2MOVTi16_ga_pcrel: {
01374     MCInst TmpInst;
01375     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
01376                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
01377     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
01378     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
01379 
01380     unsigned TF = MI->getOperand(2).getTargetFlags();
01381     const GlobalValue *GV = MI->getOperand(2).getGlobal();
01382     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
01383     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
01384 
01385     MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
01386                                      getFunctionNumber(),
01387                                      MI->getOperand(3).getImm(), OutContext);
01388     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
01389     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
01390     const MCExpr *PCRelExpr =
01391         ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
01392                                    MCBinaryExpr::createAdd(LabelSymExpr,
01393                                       MCConstantExpr::create(PCAdj, OutContext),
01394                                           OutContext), OutContext), OutContext);
01395       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
01396     // Add predicate operands.
01397     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
01398     TmpInst.addOperand(MCOperand::createReg(0));
01399     // Add 's' bit operand (always reg0 for this)
01400     TmpInst.addOperand(MCOperand::createReg(0));
01401     EmitToStreamer(*OutStreamer, TmpInst);
01402     return;
01403   }
01404   case ARM::tPICADD: {
01405     // This is a pseudo op for a label + instruction sequence, which looks like:
01406     // LPC0:
01407     //     add r0, pc
01408     // This adds the address of LPC0 to r0.
01409 
01410     // Emit the label.
01411     OutStreamer->EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
01412                                        getFunctionNumber(),
01413                                        MI->getOperand(2).getImm(),
01414                                        OutContext));
01415 
01416     // Form and emit the add.
01417     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
01418       .addReg(MI->getOperand(0).getReg())
01419       .addReg(MI->getOperand(0).getReg())
01420       .addReg(ARM::PC)
01421       // Add predicate operands.
01422       .addImm(ARMCC::AL)
01423       .addReg(0));
01424     return;
01425   }
01426   case ARM::PICADD: {
01427     // This is a pseudo op for a label + instruction sequence, which looks like:
01428     // LPC0:
01429     //     add r0, pc, r0
01430     // This adds the address of LPC0 to r0.
01431 
01432     // Emit the label.
01433     OutStreamer->EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
01434                                        getFunctionNumber(),
01435                                        MI->getOperand(2).getImm(),
01436                                        OutContext));
01437 
01438     // Form and emit the add.
01439     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
01440       .addReg(MI->getOperand(0).getReg())
01441       .addReg(ARM::PC)
01442       .addReg(MI->getOperand(1).getReg())
01443       // Add predicate operands.
01444       .addImm(MI->getOperand(3).getImm())
01445       .addReg(MI->getOperand(4).getReg())
01446       // Add 's' bit operand (always reg0 for this)
01447       .addReg(0));
01448     return;
01449   }
01450   case ARM::PICSTR:
01451   case ARM::PICSTRB:
01452   case ARM::PICSTRH:
01453   case ARM::PICLDR:
01454   case ARM::PICLDRB:
01455   case ARM::PICLDRH:
01456   case ARM::PICLDRSB:
01457   case ARM::PICLDRSH: {
01458     // This is a pseudo op for a label + instruction sequence, which looks like:
01459     // LPC0:
01460     //     OP r0, [pc, r0]
01461     // The LCP0 label is referenced by a constant pool entry in order to get
01462     // a PC-relative address at the ldr instruction.
01463 
01464     // Emit the label.
01465     OutStreamer->EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
01466                                        getFunctionNumber(),
01467                                        MI->getOperand(2).getImm(),
01468                                        OutContext));
01469 
01470     // Form and emit the load
01471     unsigned Opcode;
01472     switch (MI->getOpcode()) {
01473     default:
01474       llvm_unreachable("Unexpected opcode!");
01475     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
01476     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
01477     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
01478     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
01479     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
01480     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
01481     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
01482     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
01483     }
01484     EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
01485       .addReg(MI->getOperand(0).getReg())
01486       .addReg(ARM::PC)
01487       .addReg(MI->getOperand(1).getReg())
01488       .addImm(0)
01489       // Add predicate operands.
01490       .addImm(MI->getOperand(3).getImm())
01491       .addReg(MI->getOperand(4).getReg()));
01492 
01493     return;
01494   }
01495   case ARM::CONSTPOOL_ENTRY: {
01496     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
01497     /// in the function.  The first operand is the ID# for this instruction, the
01498     /// second is the index into the MachineConstantPool that this is, the third
01499     /// is the size in bytes of this constant pool entry.
01500     /// The required alignment is specified on the basic block holding this MI.
01501     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
01502     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
01503 
01504     // If this is the first entry of the pool, mark it.
01505     if (!InConstantPool) {
01506       OutStreamer->EmitDataRegion(MCDR_DataRegion);
01507       InConstantPool = true;
01508     }
01509 
01510     OutStreamer->EmitLabel(GetCPISymbol(LabelId));
01511 
01512     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
01513     if (MCPE.isMachineConstantPoolEntry())
01514       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
01515     else
01516       EmitGlobalConstant(MCPE.Val.ConstVal);
01517     return;
01518   }
01519   case ARM::JUMPTABLE_ADDRS:
01520     EmitJumpTableAddrs(MI);
01521     return;
01522   case ARM::JUMPTABLE_INSTS:
01523     EmitJumpTableInsts(MI);
01524     return;
01525   case ARM::JUMPTABLE_TBB:
01526   case ARM::JUMPTABLE_TBH:
01527     EmitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
01528     return;
01529   case ARM::t2BR_JT: {
01530     // Lower and emit the instruction itself, then the jump table following it.
01531     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
01532       .addReg(ARM::PC)
01533       .addReg(MI->getOperand(0).getReg())
01534       // Add predicate operands.
01535       .addImm(ARMCC::AL)
01536       .addReg(0));
01537     return;
01538   }
01539   case ARM::t2TBB_JT:
01540   case ARM::t2TBH_JT: {
01541     unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
01542     // Lower and emit the PC label, then the instruction itself.
01543     OutStreamer->EmitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
01544     EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
01545                                      .addReg(MI->getOperand(0).getReg())
01546                                      .addReg(MI->getOperand(1).getReg())
01547                                      // Add predicate operands.
01548                                      .addImm(ARMCC::AL)
01549                                      .addReg(0));
01550     return;
01551   }
01552   case ARM::tBR_JTr:
01553   case ARM::BR_JTr: {
01554     // Lower and emit the instruction itself, then the jump table following it.
01555     // mov pc, target
01556     MCInst TmpInst;
01557     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
01558       ARM::MOVr : ARM::tMOVr;
01559     TmpInst.setOpcode(Opc);
01560     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
01561     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
01562     // Add predicate operands.
01563     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
01564     TmpInst.addOperand(MCOperand::createReg(0));
01565     // Add 's' bit operand (always reg0 for this)
01566     if (Opc == ARM::MOVr)
01567       TmpInst.addOperand(MCOperand::createReg(0));
01568     EmitToStreamer(*OutStreamer, TmpInst);
01569     return;
01570   }
01571   case ARM::BR_JTm: {
01572     // Lower and emit the instruction itself, then the jump table following it.
01573     // ldr pc, target
01574     MCInst TmpInst;
01575     if (MI->getOperand(1).getReg() == 0) {
01576       // literal offset
01577       TmpInst.setOpcode(ARM::LDRi12);
01578       TmpInst.addOperand(MCOperand::createReg(ARM::PC));
01579       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
01580       TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
01581     } else {
01582       TmpInst.setOpcode(ARM::LDRrs);
01583       TmpInst.addOperand(MCOperand::createReg(ARM::PC));
01584       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
01585       TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
01586       TmpInst.addOperand(MCOperand::createImm(0));
01587     }
01588     // Add predicate operands.
01589     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
01590     TmpInst.addOperand(MCOperand::createReg(0));
01591     EmitToStreamer(*OutStreamer, TmpInst);
01592     return;
01593   }
01594   case ARM::BR_JTadd: {
01595     // Lower and emit the instruction itself, then the jump table following it.
01596     // add pc, target, idx
01597     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
01598       .addReg(ARM::PC)
01599       .addReg(MI->getOperand(0).getReg())
01600       .addReg(MI->getOperand(1).getReg())
01601       // Add predicate operands.
01602       .addImm(ARMCC::AL)
01603       .addReg(0)
01604       // Add 's' bit operand (always reg0 for this)
01605       .addReg(0));
01606     return;
01607   }
01608   case ARM::SPACE:
01609     OutStreamer->EmitZeros(MI->getOperand(1).getImm());
01610     return;
01611   case ARM::TRAP: {
01612     // Non-Darwin binutils don't yet support the "trap" mnemonic.
01613     // FIXME: Remove this special case when they do.
01614     if (!Subtarget->isTargetMachO()) {
01615       //.long 0xe7ffdefe @ trap
01616       uint32_t Val = 0xe7ffdefeUL;
01617       OutStreamer->AddComment("trap");
01618       OutStreamer->EmitIntValue(Val, 4);
01619       return;
01620     }
01621     break;
01622   }
01623   case ARM::TRAPNaCl: {
01624     //.long 0xe7fedef0 @ trap
01625     uint32_t Val = 0xe7fedef0UL;
01626     OutStreamer->AddComment("trap");
01627     OutStreamer->EmitIntValue(Val, 4);
01628     return;
01629   }
01630   case ARM::tTRAP: {
01631     // Non-Darwin binutils don't yet support the "trap" mnemonic.
01632     // FIXME: Remove this special case when they do.
01633     if (!Subtarget->isTargetMachO()) {
01634       //.short 57086 @ trap
01635       uint16_t Val = 0xdefe;
01636       OutStreamer->AddComment("trap");
01637       OutStreamer->EmitIntValue(Val, 2);
01638       return;
01639     }
01640     break;
01641   }
01642   case ARM::t2Int_eh_sjlj_setjmp:
01643   case ARM::t2Int_eh_sjlj_setjmp_nofp:
01644   case ARM::tInt_eh_sjlj_setjmp: {
01645     // Two incoming args: GPR:$src, GPR:$val
01646     // mov $val, pc
01647     // adds $val, #7
01648     // str $val, [$src, #4]
01649     // movs r0, #0
01650     // b 1f
01651     // movs r0, #1
01652     // 1:
01653     unsigned SrcReg = MI->getOperand(0).getReg();
01654     unsigned ValReg = MI->getOperand(1).getReg();
01655     MCSymbol *Label = GetARMSJLJEHLabel();
01656     OutStreamer->AddComment("eh_setjmp begin");
01657     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
01658       .addReg(ValReg)
01659       .addReg(ARM::PC)
01660       // Predicate.
01661       .addImm(ARMCC::AL)
01662       .addReg(0));
01663 
01664     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
01665       .addReg(ValReg)
01666       // 's' bit operand
01667       .addReg(ARM::CPSR)
01668       .addReg(ValReg)
01669       .addImm(7)
01670       // Predicate.
01671       .addImm(ARMCC::AL)
01672       .addReg(0));
01673 
01674     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
01675       .addReg(ValReg)
01676       .addReg(SrcReg)
01677       // The offset immediate is #4. The operand value is scaled by 4 for the
01678       // tSTR instruction.
01679       .addImm(1)
01680       // Predicate.
01681       .addImm(ARMCC::AL)
01682       .addReg(0));
01683 
01684     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
01685       .addReg(ARM::R0)
01686       .addReg(ARM::CPSR)
01687       .addImm(0)
01688       // Predicate.
01689       .addImm(ARMCC::AL)
01690       .addReg(0));
01691 
01692     const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
01693     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
01694       .addExpr(SymbolExpr)
01695       .addImm(ARMCC::AL)
01696       .addReg(0));
01697 
01698     OutStreamer->AddComment("eh_setjmp end");
01699     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
01700       .addReg(ARM::R0)
01701       .addReg(ARM::CPSR)
01702       .addImm(1)
01703       // Predicate.
01704       .addImm(ARMCC::AL)
01705       .addReg(0));
01706 
01707     OutStreamer->EmitLabel(Label);
01708     return;
01709   }
01710 
01711   case ARM::Int_eh_sjlj_setjmp_nofp:
01712   case ARM::Int_eh_sjlj_setjmp: {
01713     // Two incoming args: GPR:$src, GPR:$val
01714     // add $val, pc, #8
01715     // str $val, [$src, #+4]
01716     // mov r0, #0
01717     // add pc, pc, #0
01718     // mov r0, #1
01719     unsigned SrcReg = MI->getOperand(0).getReg();
01720     unsigned ValReg = MI->getOperand(1).getReg();
01721 
01722     OutStreamer->AddComment("eh_setjmp begin");
01723     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
01724       .addReg(ValReg)
01725       .addReg(ARM::PC)
01726       .addImm(8)
01727       // Predicate.
01728       .addImm(ARMCC::AL)
01729       .addReg(0)
01730       // 's' bit operand (always reg0 for this).
01731       .addReg(0));
01732 
01733     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
01734       .addReg(ValReg)
01735       .addReg(SrcReg)
01736       .addImm(4)
01737       // Predicate.
01738       .addImm(ARMCC::AL)
01739       .addReg(0));
01740 
01741     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
01742       .addReg(ARM::R0)
01743       .addImm(0)
01744       // Predicate.
01745       .addImm(ARMCC::AL)
01746       .addReg(0)
01747       // 's' bit operand (always reg0 for this).
01748       .addReg(0));
01749 
01750     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
01751       .addReg(ARM::PC)
01752       .addReg(ARM::PC)
01753       .addImm(0)
01754       // Predicate.
01755       .addImm(ARMCC::AL)
01756       .addReg(0)
01757       // 's' bit operand (always reg0 for this).
01758       .addReg(0));
01759 
01760     OutStreamer->AddComment("eh_setjmp end");
01761     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
01762       .addReg(ARM::R0)
01763       .addImm(1)
01764       // Predicate.
01765       .addImm(ARMCC::AL)
01766       .addReg(0)
01767       // 's' bit operand (always reg0 for this).
01768       .addReg(0));
01769     return;
01770   }
01771   case ARM::Int_eh_sjlj_longjmp: {
01772     // ldr sp, [$src, #8]
01773     // ldr $scratch, [$src, #4]
01774     // ldr r7, [$src]
01775     // bx $scratch
01776     unsigned SrcReg = MI->getOperand(0).getReg();
01777     unsigned ScratchReg = MI->getOperand(1).getReg();
01778     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
01779       .addReg(ARM::SP)
01780       .addReg(SrcReg)
01781       .addImm(8)
01782       // Predicate.
01783       .addImm(ARMCC::AL)
01784       .addReg(0));
01785 
01786     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
01787       .addReg(ScratchReg)
01788       .addReg(SrcReg)
01789       .addImm(4)
01790       // Predicate.
01791       .addImm(ARMCC::AL)
01792       .addReg(0));
01793 
01794     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
01795       .addReg(ARM::R7)
01796       .addReg(SrcReg)
01797       .addImm(0)
01798       // Predicate.
01799       .addImm(ARMCC::AL)
01800       .addReg(0));
01801 
01802     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
01803       .addReg(ScratchReg)
01804       // Predicate.
01805       .addImm(ARMCC::AL)
01806       .addReg(0));
01807     return;
01808   }
01809   case ARM::tInt_eh_sjlj_longjmp: {
01810     // ldr $scratch, [$src, #8]
01811     // mov sp, $scratch
01812     // ldr $scratch, [$src, #4]
01813     // ldr r7, [$src]
01814     // bx $scratch
01815     unsigned SrcReg = MI->getOperand(0).getReg();
01816     unsigned ScratchReg = MI->getOperand(1).getReg();
01817     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
01818       .addReg(ScratchReg)
01819       .addReg(SrcReg)
01820       // The offset immediate is #8. The operand value is scaled by 4 for the
01821       // tLDR instruction.
01822       .addImm(2)
01823       // Predicate.
01824       .addImm(ARMCC::AL)
01825       .addReg(0));
01826 
01827     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
01828       .addReg(ARM::SP)
01829       .addReg(ScratchReg)
01830       // Predicate.
01831       .addImm(ARMCC::AL)
01832       .addReg(0));
01833 
01834     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
01835       .addReg(ScratchReg)
01836       .addReg(SrcReg)
01837       .addImm(1)
01838       // Predicate.
01839       .addImm(ARMCC::AL)
01840       .addReg(0));
01841 
01842     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
01843       .addReg(ARM::R7)
01844       .addReg(SrcReg)
01845       .addImm(0)
01846       // Predicate.
01847       .addImm(ARMCC::AL)
01848       .addReg(0));
01849 
01850     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
01851       .addReg(ScratchReg)
01852       // Predicate.
01853       .addImm(ARMCC::AL)
01854       .addReg(0));
01855     return;
01856   }
01857   }
01858 
01859   MCInst TmpInst;
01860   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
01861 
01862   EmitToStreamer(*OutStreamer, TmpInst);
01863 }
01864 
01865 //===----------------------------------------------------------------------===//
01866 // Target Registry Stuff
01867 //===----------------------------------------------------------------------===//
01868 
01869 // Force static initialization.
01870 extern "C" void LLVMInitializeARMAsmPrinter() {
01871   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMLETarget);
01872   RegisterAsmPrinter<ARMAsmPrinter> Y(TheARMBETarget);
01873   RegisterAsmPrinter<ARMAsmPrinter> A(TheThumbLETarget);
01874   RegisterAsmPrinter<ARMAsmPrinter> B(TheThumbBETarget);
01875 }