ARMAsmPrinter.cpp revision dce4a407a24b04eebc6a376f8e62b41aaa7b071f
1//===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains a printer that converts from our internal representation
11// of machine-dependent LLVM code to GAS-format ARM assembly language.
12//
13//===----------------------------------------------------------------------===//
14
15#include "ARMAsmPrinter.h"
16#include "ARM.h"
17#include "ARMConstantPoolValue.h"
18#include "ARMFPUName.h"
19#include "ARMMachineFunctionInfo.h"
20#include "ARMTargetMachine.h"
21#include "ARMTargetObjectFile.h"
22#include "InstPrinter/ARMInstPrinter.h"
23#include "MCTargetDesc/ARMAddressingModes.h"
24#include "MCTargetDesc/ARMMCExpr.h"
25#include "llvm/ADT/SetVector.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
28#include "llvm/CodeGen/MachineJumpTableInfo.h"
29#include "llvm/CodeGen/MachineModuleInfoImpls.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/DebugInfo.h"
33#include "llvm/IR/Mangler.h"
34#include "llvm/IR/Module.h"
35#include "llvm/IR/Type.h"
36#include "llvm/MC/MCAsmInfo.h"
37#include "llvm/MC/MCAssembler.h"
38#include "llvm/MC/MCContext.h"
39#include "llvm/MC/MCELFStreamer.h"
40#include "llvm/MC/MCInst.h"
41#include "llvm/MC/MCInstBuilder.h"
42#include "llvm/MC/MCObjectStreamer.h"
43#include "llvm/MC/MCSectionMachO.h"
44#include "llvm/MC/MCStreamer.h"
45#include "llvm/MC/MCSymbol.h"
46#include "llvm/Support/ARMBuildAttributes.h"
47#include "llvm/Support/COFF.h"
48#include "llvm/Support/CommandLine.h"
49#include "llvm/Support/Debug.h"
50#include "llvm/Support/ELF.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/TargetRegistry.h"
53#include "llvm/Support/raw_ostream.h"
54#include "llvm/Target/TargetMachine.h"
55#include <cctype>
56using namespace llvm;
57
58#define DEBUG_TYPE "asm-printer"
59
60void ARMAsmPrinter::EmitFunctionBodyEnd() {
61  // Make sure to terminate any constant pools that were at the end
62  // of the function.
63  if (!InConstantPool)
64    return;
65  InConstantPool = false;
66  OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
67}
68
69void ARMAsmPrinter::EmitFunctionEntryLabel() {
70  if (AFI->isThumbFunction()) {
71    OutStreamer.EmitAssemblerFlag(MCAF_Code16);
72    OutStreamer.EmitThumbFunc(CurrentFnSym);
73  }
74
75  OutStreamer.EmitLabel(CurrentFnSym);
76}
77
78void ARMAsmPrinter::EmitXXStructor(const Constant *CV) {
79  uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
80  assert(Size && "C++ constructor pointer had zero size!");
81
82  const GlobalValue *GV = dyn_cast<GlobalValue>(CV->stripPointerCasts());
83  assert(GV && "C++ constructor pointer was not a GlobalValue!");
84
85  const MCExpr *E = MCSymbolRefExpr::Create(getSymbol(GV),
86                                            (Subtarget->isTargetELF()
87                                             ? MCSymbolRefExpr::VK_ARM_TARGET1
88                                             : MCSymbolRefExpr::VK_None),
89                                            OutContext);
90
91  OutStreamer.EmitValue(E, Size);
92}
93
94/// runOnMachineFunction - This uses the EmitInstruction()
95/// method to print assembly for each instruction.
96///
97bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
98  AFI = MF.getInfo<ARMFunctionInfo>();
99  MCP = MF.getConstantPool();
100
101  SetupMachineFunction(MF);
102
103  if (Subtarget->isTargetCOFF()) {
104    bool Internal = MF.getFunction()->hasInternalLinkage();
105    COFF::SymbolStorageClass Scl = Internal ? COFF::IMAGE_SYM_CLASS_STATIC
106                                            : COFF::IMAGE_SYM_CLASS_EXTERNAL;
107    int Type = COFF::IMAGE_SYM_DTYPE_FUNCTION << COFF::SCT_COMPLEX_TYPE_SHIFT;
108
109    OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
110    OutStreamer.EmitCOFFSymbolStorageClass(Scl);
111    OutStreamer.EmitCOFFSymbolType(Type);
112    OutStreamer.EndCOFFSymbolDef();
113  }
114
115  // Have common code print out the function header with linkage info etc.
116  EmitFunctionHeader();
117
118  // Emit the rest of the function body.
119  EmitFunctionBody();
120
121  // We didn't modify anything.
122  return false;
123}
124
125void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
126                                 raw_ostream &O, const char *Modifier) {
127  const MachineOperand &MO = MI->getOperand(OpNum);
128  unsigned TF = MO.getTargetFlags();
129
130  switch (MO.getType()) {
131  default: llvm_unreachable("<unknown operand type>");
132  case MachineOperand::MO_Register: {
133    unsigned Reg = MO.getReg();
134    assert(TargetRegisterInfo::isPhysicalRegister(Reg));
135    assert(!MO.getSubReg() && "Subregs should be eliminated!");
136    if(ARM::GPRPairRegClass.contains(Reg)) {
137      const MachineFunction &MF = *MI->getParent()->getParent();
138      const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
139      Reg = TRI->getSubReg(Reg, ARM::gsub_0);
140    }
141    O << ARMInstPrinter::getRegisterName(Reg);
142    break;
143  }
144  case MachineOperand::MO_Immediate: {
145    int64_t Imm = MO.getImm();
146    O << '#';
147    if ((Modifier && strcmp(Modifier, "lo16") == 0) ||
148        (TF == ARMII::MO_LO16))
149      O << ":lower16:";
150    else if ((Modifier && strcmp(Modifier, "hi16") == 0) ||
151             (TF == ARMII::MO_HI16))
152      O << ":upper16:";
153    O << Imm;
154    break;
155  }
156  case MachineOperand::MO_MachineBasicBlock:
157    O << *MO.getMBB()->getSymbol();
158    return;
159  case MachineOperand::MO_GlobalAddress: {
160    const GlobalValue *GV = MO.getGlobal();
161    if ((Modifier && strcmp(Modifier, "lo16") == 0) ||
162        (TF & ARMII::MO_LO16))
163      O << ":lower16:";
164    else if ((Modifier && strcmp(Modifier, "hi16") == 0) ||
165             (TF & ARMII::MO_HI16))
166      O << ":upper16:";
167    O << *getSymbol(GV);
168
169    printOffset(MO.getOffset(), O);
170    if (TF == ARMII::MO_PLT)
171      O << "(PLT)";
172    break;
173  }
174  case MachineOperand::MO_ConstantPoolIndex:
175    O << *GetCPISymbol(MO.getIndex());
176    break;
177  }
178}
179
180//===--------------------------------------------------------------------===//
181
182MCSymbol *ARMAsmPrinter::
183GetARMJTIPICJumpTableLabel2(unsigned uid, unsigned uid2) const {
184  const DataLayout *DL = TM.getDataLayout();
185  SmallString<60> Name;
186  raw_svector_ostream(Name) << DL->getPrivateGlobalPrefix() << "JTI"
187    << getFunctionNumber() << '_' << uid << '_' << uid2;
188  return OutContext.GetOrCreateSymbol(Name.str());
189}
190
191
192MCSymbol *ARMAsmPrinter::GetARMSJLJEHLabel() const {
193  const DataLayout *DL = TM.getDataLayout();
194  SmallString<60> Name;
195  raw_svector_ostream(Name) << DL->getPrivateGlobalPrefix() << "SJLJEH"
196    << getFunctionNumber();
197  return OutContext.GetOrCreateSymbol(Name.str());
198}
199
200bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
201                                    unsigned AsmVariant, const char *ExtraCode,
202                                    raw_ostream &O) {
203  // Does this asm operand have a single letter operand modifier?
204  if (ExtraCode && ExtraCode[0]) {
205    if (ExtraCode[1] != 0) return true; // Unknown modifier.
206
207    switch (ExtraCode[0]) {
208    default:
209      // See if this is a generic print operand
210      return AsmPrinter::PrintAsmOperand(MI, OpNum, AsmVariant, ExtraCode, O);
211    case 'a': // Print as a memory address.
212      if (MI->getOperand(OpNum).isReg()) {
213        O << "["
214          << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg())
215          << "]";
216        return false;
217      }
218      // Fallthrough
219    case 'c': // Don't print "#" before an immediate operand.
220      if (!MI->getOperand(OpNum).isImm())
221        return true;
222      O << MI->getOperand(OpNum).getImm();
223      return false;
224    case 'P': // Print a VFP double precision register.
225    case 'q': // Print a NEON quad precision register.
226      printOperand(MI, OpNum, O);
227      return false;
228    case 'y': // Print a VFP single precision register as indexed double.
229      if (MI->getOperand(OpNum).isReg()) {
230        unsigned Reg = MI->getOperand(OpNum).getReg();
231        const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
232        // Find the 'd' register that has this 's' register as a sub-register,
233        // and determine the lane number.
234        for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
235          if (!ARM::DPRRegClass.contains(*SR))
236            continue;
237          bool Lane0 = TRI->getSubReg(*SR, ARM::ssub_0) == Reg;
238          O << ARMInstPrinter::getRegisterName(*SR) << (Lane0 ? "[0]" : "[1]");
239          return false;
240        }
241      }
242      return true;
243    case 'B': // Bitwise inverse of integer or symbol without a preceding #.
244      if (!MI->getOperand(OpNum).isImm())
245        return true;
246      O << ~(MI->getOperand(OpNum).getImm());
247      return false;
248    case 'L': // The low 16 bits of an immediate constant.
249      if (!MI->getOperand(OpNum).isImm())
250        return true;
251      O << (MI->getOperand(OpNum).getImm() & 0xffff);
252      return false;
253    case 'M': { // A register range suitable for LDM/STM.
254      if (!MI->getOperand(OpNum).isReg())
255        return true;
256      const MachineOperand &MO = MI->getOperand(OpNum);
257      unsigned RegBegin = MO.getReg();
258      // This takes advantage of the 2 operand-ness of ldm/stm and that we've
259      // already got the operands in registers that are operands to the
260      // inline asm statement.
261      O << "{";
262      if (ARM::GPRPairRegClass.contains(RegBegin)) {
263        const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
264        unsigned Reg0 = TRI->getSubReg(RegBegin, ARM::gsub_0);
265        O << ARMInstPrinter::getRegisterName(Reg0) << ", ";
266        RegBegin = TRI->getSubReg(RegBegin, ARM::gsub_1);
267      }
268      O << ARMInstPrinter::getRegisterName(RegBegin);
269
270      // FIXME: The register allocator not only may not have given us the
271      // registers in sequence, but may not be in ascending registers. This
272      // will require changes in the register allocator that'll need to be
273      // propagated down here if the operands change.
274      unsigned RegOps = OpNum + 1;
275      while (MI->getOperand(RegOps).isReg()) {
276        O << ", "
277          << ARMInstPrinter::getRegisterName(MI->getOperand(RegOps).getReg());
278        RegOps++;
279      }
280
281      O << "}";
282
283      return false;
284    }
285    case 'R': // The most significant register of a pair.
286    case 'Q': { // The least significant register of a pair.
287      if (OpNum == 0)
288        return true;
289      const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
290      if (!FlagsOP.isImm())
291        return true;
292      unsigned Flags = FlagsOP.getImm();
293
294      // This operand may not be the one that actually provides the register. If
295      // it's tied to a previous one then we should refer instead to that one
296      // for registers and their classes.
297      unsigned TiedIdx;
298      if (InlineAsm::isUseOperandTiedToDef(Flags, TiedIdx)) {
299        for (OpNum = InlineAsm::MIOp_FirstOperand; TiedIdx; --TiedIdx) {
300          unsigned OpFlags = MI->getOperand(OpNum).getImm();
301          OpNum += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
302        }
303        Flags = MI->getOperand(OpNum).getImm();
304
305        // Later code expects OpNum to be pointing at the register rather than
306        // the flags.
307        OpNum += 1;
308      }
309
310      unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
311      unsigned RC;
312      InlineAsm::hasRegClassConstraint(Flags, RC);
313      if (RC == ARM::GPRPairRegClassID) {
314        if (NumVals != 1)
315          return true;
316        const MachineOperand &MO = MI->getOperand(OpNum);
317        if (!MO.isReg())
318          return true;
319        const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
320        unsigned Reg = TRI->getSubReg(MO.getReg(), ExtraCode[0] == 'Q' ?
321            ARM::gsub_0 : ARM::gsub_1);
322        O << ARMInstPrinter::getRegisterName(Reg);
323        return false;
324      }
325      if (NumVals != 2)
326        return true;
327      unsigned RegOp = ExtraCode[0] == 'Q' ? OpNum : OpNum + 1;
328      if (RegOp >= MI->getNumOperands())
329        return true;
330      const MachineOperand &MO = MI->getOperand(RegOp);
331      if (!MO.isReg())
332        return true;
333      unsigned Reg = MO.getReg();
334      O << ARMInstPrinter::getRegisterName(Reg);
335      return false;
336    }
337
338    case 'e': // The low doubleword register of a NEON quad register.
339    case 'f': { // The high doubleword register of a NEON quad register.
340      if (!MI->getOperand(OpNum).isReg())
341        return true;
342      unsigned Reg = MI->getOperand(OpNum).getReg();
343      if (!ARM::QPRRegClass.contains(Reg))
344        return true;
345      const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
346      unsigned SubReg = TRI->getSubReg(Reg, ExtraCode[0] == 'e' ?
347                                       ARM::dsub_0 : ARM::dsub_1);
348      O << ARMInstPrinter::getRegisterName(SubReg);
349      return false;
350    }
351
352    // This modifier is not yet supported.
353    case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
354      return true;
355    case 'H': { // The highest-numbered register of a pair.
356      const MachineOperand &MO = MI->getOperand(OpNum);
357      if (!MO.isReg())
358        return true;
359      const MachineFunction &MF = *MI->getParent()->getParent();
360      const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
361      unsigned Reg = MO.getReg();
362      if(!ARM::GPRPairRegClass.contains(Reg))
363        return false;
364      Reg = TRI->getSubReg(Reg, ARM::gsub_1);
365      O << ARMInstPrinter::getRegisterName(Reg);
366      return false;
367    }
368    }
369  }
370
371  printOperand(MI, OpNum, O);
372  return false;
373}
374
375bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
376                                          unsigned OpNum, unsigned AsmVariant,
377                                          const char *ExtraCode,
378                                          raw_ostream &O) {
379  // Does this asm operand have a single letter operand modifier?
380  if (ExtraCode && ExtraCode[0]) {
381    if (ExtraCode[1] != 0) return true; // Unknown modifier.
382
383    switch (ExtraCode[0]) {
384      case 'A': // A memory operand for a VLD1/VST1 instruction.
385      default: return true;  // Unknown modifier.
386      case 'm': // The base register of a memory operand.
387        if (!MI->getOperand(OpNum).isReg())
388          return true;
389        O << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg());
390        return false;
391    }
392  }
393
394  const MachineOperand &MO = MI->getOperand(OpNum);
395  assert(MO.isReg() && "unexpected inline asm memory operand");
396  O << "[" << ARMInstPrinter::getRegisterName(MO.getReg()) << "]";
397  return false;
398}
399
400static bool isThumb(const MCSubtargetInfo& STI) {
401  return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
402}
403
404void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
405                                     const MCSubtargetInfo *EndInfo) const {
406  // If either end mode is unknown (EndInfo == NULL) or different than
407  // the start mode, then restore the start mode.
408  const bool WasThumb = isThumb(StartInfo);
409  if (!EndInfo || WasThumb != isThumb(*EndInfo)) {
410    OutStreamer.EmitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
411  }
412}
413
414void ARMAsmPrinter::EmitStartOfAsmFile(Module &M) {
415  if (Subtarget->isTargetMachO()) {
416    Reloc::Model RelocM = TM.getRelocationModel();
417    if (RelocM == Reloc::PIC_ || RelocM == Reloc::DynamicNoPIC) {
418      // Declare all the text sections up front (before the DWARF sections
419      // emitted by AsmPrinter::doInitialization) so the assembler will keep
420      // them together at the beginning of the object file.  This helps
421      // avoid out-of-range branches that are due a fundamental limitation of
422      // the way symbol offsets are encoded with the current Darwin ARM
423      // relocations.
424      const TargetLoweringObjectFileMachO &TLOFMacho =
425        static_cast<const TargetLoweringObjectFileMachO &>(
426          getObjFileLowering());
427
428      // Collect the set of sections our functions will go into.
429      SetVector<const MCSection *, SmallVector<const MCSection *, 8>,
430        SmallPtrSet<const MCSection *, 8> > TextSections;
431      // Default text section comes first.
432      TextSections.insert(TLOFMacho.getTextSection());
433      // Now any user defined text sections from function attributes.
434      for (Module::iterator F = M.begin(), e = M.end(); F != e; ++F)
435        if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage())
436          TextSections.insert(TLOFMacho.SectionForGlobal(F, *Mang, TM));
437      // Now the coalescable sections.
438      TextSections.insert(TLOFMacho.getTextCoalSection());
439      TextSections.insert(TLOFMacho.getConstTextCoalSection());
440
441      // Emit the sections in the .s file header to fix the order.
442      for (unsigned i = 0, e = TextSections.size(); i != e; ++i)
443        OutStreamer.SwitchSection(TextSections[i]);
444
445      if (RelocM == Reloc::DynamicNoPIC) {
446        const MCSection *sect =
447          OutContext.getMachOSection("__TEXT", "__symbol_stub4",
448                                     MachO::S_SYMBOL_STUBS,
449                                     12, SectionKind::getText());
450        OutStreamer.SwitchSection(sect);
451      } else {
452        const MCSection *sect =
453          OutContext.getMachOSection("__TEXT", "__picsymbolstub4",
454                                     MachO::S_SYMBOL_STUBS,
455                                     16, SectionKind::getText());
456        OutStreamer.SwitchSection(sect);
457      }
458      const MCSection *StaticInitSect =
459        OutContext.getMachOSection("__TEXT", "__StaticInit",
460                                   MachO::S_REGULAR |
461                                   MachO::S_ATTR_PURE_INSTRUCTIONS,
462                                   SectionKind::getText());
463      OutStreamer.SwitchSection(StaticInitSect);
464    }
465
466    // Compiling with debug info should not affect the code
467    // generation.  Ensure the cstring section comes before the
468    // optional __DWARF secion. Otherwise, PC-relative loads would
469    // have to use different instruction sequences at "-g" in order to
470    // reach global data in the same object file.
471    OutStreamer.SwitchSection(getObjFileLowering().getCStringSection());
472  }
473
474  // Use unified assembler syntax.
475  OutStreamer.EmitAssemblerFlag(MCAF_SyntaxUnified);
476
477  // Emit ARM Build Attributes
478  if (Subtarget->isTargetELF())
479    emitAttributes();
480}
481
482static void
483emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
484                         MachineModuleInfoImpl::StubValueTy &MCSym) {
485  // L_foo$stub:
486  OutStreamer.EmitLabel(StubLabel);
487  //   .indirect_symbol _foo
488  OutStreamer.EmitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
489
490  if (MCSym.getInt())
491    // External to current translation unit.
492    OutStreamer.EmitIntValue(0, 4/*size*/);
493  else
494    // Internal to current translation unit.
495    //
496    // When we place the LSDA into the TEXT section, the type info
497    // pointers need to be indirect and pc-rel. We accomplish this by
498    // using NLPs; however, sometimes the types are local to the file.
499    // We need to fill in the value for the NLP in those cases.
500    OutStreamer.EmitValue(
501        MCSymbolRefExpr::Create(MCSym.getPointer(), OutStreamer.getContext()),
502        4 /*size*/);
503}
504
505
506void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
507  if (Subtarget->isTargetMachO()) {
508    // All darwin targets use mach-o.
509    const TargetLoweringObjectFileMachO &TLOFMacho =
510      static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
511    MachineModuleInfoMachO &MMIMacho =
512      MMI->getObjFileInfo<MachineModuleInfoMachO>();
513
514    // Output non-lazy-pointers for external and common global variables.
515    MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
516
517    if (!Stubs.empty()) {
518      // Switch with ".non_lazy_symbol_pointer" directive.
519      OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
520      EmitAlignment(2);
521
522      for (auto &Stub : Stubs)
523        emitNonLazySymbolPointer(OutStreamer, Stub.first, Stub.second);
524
525      Stubs.clear();
526      OutStreamer.AddBlankLine();
527    }
528
529    Stubs = MMIMacho.GetHiddenGVStubList();
530    if (!Stubs.empty()) {
531      OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
532      EmitAlignment(2);
533
534      for (auto &Stub : Stubs)
535        emitNonLazySymbolPointer(OutStreamer, Stub.first, Stub.second);
536
537      Stubs.clear();
538      OutStreamer.AddBlankLine();
539    }
540
541    // Funny Darwin hack: This flag tells the linker that no global symbols
542    // contain code that falls through to other global symbols (e.g. the obvious
543    // implementation of multiple entry points).  If this doesn't occur, the
544    // linker can safely perform dead code stripping.  Since LLVM never
545    // generates code that does this, it is always safe to set.
546    OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
547  }
548
549  // Emit a .data.rel section containing any stubs that were created.
550  if (Subtarget->isTargetELF()) {
551    const TargetLoweringObjectFileELF &TLOFELF =
552      static_cast<const TargetLoweringObjectFileELF &>(getObjFileLowering());
553
554    MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
555
556    // Output stubs for external and common global variables.
557    MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
558    if (!Stubs.empty()) {
559      OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
560      const DataLayout *TD = TM.getDataLayout();
561
562      for (auto &stub: Stubs) {
563        OutStreamer.EmitLabel(stub.first);
564        OutStreamer.EmitSymbolValue(stub.second.getPointer(),
565                                    TD->getPointerSize(0));
566      }
567      Stubs.clear();
568    }
569  }
570}
571
572//===----------------------------------------------------------------------===//
573// Helper routines for EmitStartOfAsmFile() and EmitEndOfAsmFile()
574// FIXME:
575// The following seem like one-off assembler flags, but they actually need
576// to appear in the .ARM.attributes section in ELF.
577// Instead of subclassing the MCELFStreamer, we do the work here.
578
579static ARMBuildAttrs::CPUArch getArchForCPU(StringRef CPU,
580                                            const ARMSubtarget *Subtarget) {
581  if (CPU == "xscale")
582    return ARMBuildAttrs::v5TEJ;
583
584  if (Subtarget->hasV8Ops())
585    return ARMBuildAttrs::v8;
586  else if (Subtarget->hasV7Ops()) {
587    if (Subtarget->isMClass() && Subtarget->hasThumb2DSP())
588      return ARMBuildAttrs::v7E_M;
589    return ARMBuildAttrs::v7;
590  } else if (Subtarget->hasV6T2Ops())
591    return ARMBuildAttrs::v6T2;
592  else if (Subtarget->hasV6MOps())
593    return ARMBuildAttrs::v6S_M;
594  else if (Subtarget->hasV6Ops())
595    return ARMBuildAttrs::v6;
596  else if (Subtarget->hasV5TEOps())
597    return ARMBuildAttrs::v5TE;
598  else if (Subtarget->hasV5TOps())
599    return ARMBuildAttrs::v5T;
600  else if (Subtarget->hasV4TOps())
601    return ARMBuildAttrs::v4T;
602  else
603    return ARMBuildAttrs::v4;
604}
605
606void ARMAsmPrinter::emitAttributes() {
607  MCTargetStreamer &TS = *OutStreamer.getTargetStreamer();
608  ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
609
610  ATS.switchVendor("aeabi");
611
612  std::string CPUString = Subtarget->getCPUString();
613
614  // FIXME: remove krait check when GNU tools support krait cpu
615  if (CPUString != "generic" && CPUString != "krait")
616    ATS.emitTextAttribute(ARMBuildAttrs::CPU_name, CPUString);
617
618  ATS.emitAttribute(ARMBuildAttrs::CPU_arch,
619                    getArchForCPU(CPUString, Subtarget));
620
621  // Tag_CPU_arch_profile must have the default value of 0 when "Architecture
622  // profile is not applicable (e.g. pre v7, or cross-profile code)".
623  if (Subtarget->hasV7Ops()) {
624    if (Subtarget->isAClass()) {
625      ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
626                        ARMBuildAttrs::ApplicationProfile);
627    } else if (Subtarget->isRClass()) {
628      ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
629                        ARMBuildAttrs::RealTimeProfile);
630    } else if (Subtarget->isMClass()) {
631      ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
632                        ARMBuildAttrs::MicroControllerProfile);
633    }
634  }
635
636  ATS.emitAttribute(ARMBuildAttrs::ARM_ISA_use, Subtarget->hasARMOps() ?
637                      ARMBuildAttrs::Allowed : ARMBuildAttrs::Not_Allowed);
638  if (Subtarget->isThumb1Only()) {
639    ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
640                      ARMBuildAttrs::Allowed);
641  } else if (Subtarget->hasThumb2()) {
642    ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
643                      ARMBuildAttrs::AllowThumb32);
644  }
645
646  if (Subtarget->hasNEON()) {
647    /* NEON is not exactly a VFP architecture, but GAS emit one of
648     * neon/neon-fp-armv8/neon-vfpv4/vfpv3/vfpv2 for .fpu parameters */
649    if (Subtarget->hasFPARMv8()) {
650      if (Subtarget->hasCrypto())
651        ATS.emitFPU(ARM::CRYPTO_NEON_FP_ARMV8);
652      else
653        ATS.emitFPU(ARM::NEON_FP_ARMV8);
654    }
655    else if (Subtarget->hasVFP4())
656      ATS.emitFPU(ARM::NEON_VFPV4);
657    else
658      ATS.emitFPU(ARM::NEON);
659    // Emit Tag_Advanced_SIMD_arch for ARMv8 architecture
660    if (Subtarget->hasV8Ops())
661      ATS.emitAttribute(ARMBuildAttrs::Advanced_SIMD_arch,
662                        ARMBuildAttrs::AllowNeonARMv8);
663  } else {
664    if (Subtarget->hasFPARMv8())
665      ATS.emitFPU(ARM::FP_ARMV8);
666    else if (Subtarget->hasVFP4())
667      ATS.emitFPU(Subtarget->hasD16() ? ARM::VFPV4_D16 : ARM::VFPV4);
668    else if (Subtarget->hasVFP3())
669      ATS.emitFPU(Subtarget->hasD16() ? ARM::VFPV3_D16 : ARM::VFPV3);
670    else if (Subtarget->hasVFP2())
671      ATS.emitFPU(ARM::VFPV2);
672  }
673
674  if (TM.getRelocationModel() == Reloc::PIC_) {
675    // PIC specific attributes.
676    ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
677                      ARMBuildAttrs::AddressRWPCRel);
678    ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
679                      ARMBuildAttrs::AddressROPCRel);
680    ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
681                      ARMBuildAttrs::AddressGOT);
682  } else {
683    // Allow direct addressing of imported data for all other relocation models.
684    ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
685                      ARMBuildAttrs::AddressDirect);
686  }
687
688  // Signal various FP modes.
689  if (!TM.Options.UnsafeFPMath) {
690    ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal, ARMBuildAttrs::Allowed);
691    ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
692                      ARMBuildAttrs::Allowed);
693  }
694
695  if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
696    ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
697                      ARMBuildAttrs::Allowed);
698  else
699    ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
700                      ARMBuildAttrs::AllowIEE754);
701
702  // FIXME: add more flags to ARMBuildAttributes.h
703  // 8-bytes alignment stuff.
704  ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
705  ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
706
707  // ABI_HardFP_use attribute to indicate single precision FP.
708  if (Subtarget->isFPOnlySP())
709    ATS.emitAttribute(ARMBuildAttrs::ABI_HardFP_use,
710                      ARMBuildAttrs::HardFPSinglePrecision);
711
712  // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
713  if (Subtarget->isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
714    ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
715
716  // FIXME: Should we signal R9 usage?
717
718  if (Subtarget->hasFP16())
719      ATS.emitAttribute(ARMBuildAttrs::FP_HP_extension, ARMBuildAttrs::AllowHPFP);
720
721  if (Subtarget->hasMPExtension())
722      ATS.emitAttribute(ARMBuildAttrs::MPextension_use, ARMBuildAttrs::AllowMP);
723
724  // Hardware divide in ARM mode is part of base arch, starting from ARMv8.
725  // If only Thumb hwdiv is present, it must also be in base arch (ARMv7-R/M).
726  // It is not possible to produce DisallowDIV: if hwdiv is present in the base
727  // arch, supplying -hwdiv downgrades the effective arch, via ClearImpliedBits.
728  // AllowDIVExt is only emitted if hwdiv isn't available in the base arch;
729  // otherwise, the default value (AllowDIVIfExists) applies.
730  if (Subtarget->hasDivideInARMMode() && !Subtarget->hasV8Ops())
731      ATS.emitAttribute(ARMBuildAttrs::DIV_use, ARMBuildAttrs::AllowDIVExt);
732
733  if (Subtarget->hasTrustZone() && Subtarget->hasVirtualization())
734      ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
735                        ARMBuildAttrs::AllowTZVirtualization);
736  else if (Subtarget->hasTrustZone())
737      ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
738                        ARMBuildAttrs::AllowTZ);
739  else if (Subtarget->hasVirtualization())
740      ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
741                        ARMBuildAttrs::AllowVirtualization);
742
743  ATS.finishAttributeSection();
744}
745
746//===----------------------------------------------------------------------===//
747
748static MCSymbol *getPICLabel(const char *Prefix, unsigned FunctionNumber,
749                             unsigned LabelId, MCContext &Ctx) {
750
751  MCSymbol *Label = Ctx.GetOrCreateSymbol(Twine(Prefix)
752                       + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
753  return Label;
754}
755
756static MCSymbolRefExpr::VariantKind
757getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
758  switch (Modifier) {
759  case ARMCP::no_modifier: return MCSymbolRefExpr::VK_None;
760  case ARMCP::TLSGD:       return MCSymbolRefExpr::VK_TLSGD;
761  case ARMCP::TPOFF:       return MCSymbolRefExpr::VK_TPOFF;
762  case ARMCP::GOTTPOFF:    return MCSymbolRefExpr::VK_GOTTPOFF;
763  case ARMCP::GOT:         return MCSymbolRefExpr::VK_GOT;
764  case ARMCP::GOTOFF:      return MCSymbolRefExpr::VK_GOTOFF;
765  }
766  llvm_unreachable("Invalid ARMCPModifier!");
767}
768
769MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
770                                        unsigned char TargetFlags) {
771  bool isIndirect = Subtarget->isTargetMachO() &&
772    (TargetFlags & ARMII::MO_NONLAZY) &&
773    Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
774  if (!isIndirect)
775    return getSymbol(GV);
776
777  // FIXME: Remove this when Darwin transition to @GOT like syntax.
778  MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
779  MachineModuleInfoMachO &MMIMachO =
780    MMI->getObjFileInfo<MachineModuleInfoMachO>();
781  MachineModuleInfoImpl::StubValueTy &StubSym =
782    GV->hasHiddenVisibility() ? MMIMachO.getHiddenGVStubEntry(MCSym) :
783    MMIMachO.getGVStubEntry(MCSym);
784  if (!StubSym.getPointer())
785    StubSym = MachineModuleInfoImpl::
786      StubValueTy(getSymbol(GV), !GV->hasInternalLinkage());
787  return MCSym;
788}
789
790void ARMAsmPrinter::
791EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
792  const DataLayout *DL = TM.getDataLayout();
793  int Size = TM.getDataLayout()->getTypeAllocSize(MCPV->getType());
794
795  ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
796
797  MCSymbol *MCSym;
798  if (ACPV->isLSDA()) {
799    SmallString<128> Str;
800    raw_svector_ostream OS(Str);
801    OS << DL->getPrivateGlobalPrefix() << "_LSDA_" << getFunctionNumber();
802    MCSym = OutContext.GetOrCreateSymbol(OS.str());
803  } else if (ACPV->isBlockAddress()) {
804    const BlockAddress *BA =
805      cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
806    MCSym = GetBlockAddressSymbol(BA);
807  } else if (ACPV->isGlobalValue()) {
808    const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
809
810    // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
811    // flag the global as MO_NONLAZY.
812    unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
813    MCSym = GetARMGVSymbol(GV, TF);
814  } else if (ACPV->isMachineBasicBlock()) {
815    const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
816    MCSym = MBB->getSymbol();
817  } else {
818    assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
819    const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
820    MCSym = GetExternalSymbolSymbol(Sym);
821  }
822
823  // Create an MCSymbol for the reference.
824  const MCExpr *Expr =
825    MCSymbolRefExpr::Create(MCSym, getModifierVariantKind(ACPV->getModifier()),
826                            OutContext);
827
828  if (ACPV->getPCAdjustment()) {
829    MCSymbol *PCLabel = getPICLabel(DL->getPrivateGlobalPrefix(),
830                                    getFunctionNumber(),
831                                    ACPV->getLabelId(),
832                                    OutContext);
833    const MCExpr *PCRelExpr = MCSymbolRefExpr::Create(PCLabel, OutContext);
834    PCRelExpr =
835      MCBinaryExpr::CreateAdd(PCRelExpr,
836                              MCConstantExpr::Create(ACPV->getPCAdjustment(),
837                                                     OutContext),
838                              OutContext);
839    if (ACPV->mustAddCurrentAddress()) {
840      // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
841      // label, so just emit a local label end reference that instead.
842      MCSymbol *DotSym = OutContext.CreateTempSymbol();
843      OutStreamer.EmitLabel(DotSym);
844      const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
845      PCRelExpr = MCBinaryExpr::CreateSub(PCRelExpr, DotExpr, OutContext);
846    }
847    Expr = MCBinaryExpr::CreateSub(Expr, PCRelExpr, OutContext);
848  }
849  OutStreamer.EmitValue(Expr, Size);
850}
851
852void ARMAsmPrinter::EmitJumpTable(const MachineInstr *MI) {
853  unsigned Opcode = MI->getOpcode();
854  int OpNum = 1;
855  if (Opcode == ARM::BR_JTadd)
856    OpNum = 2;
857  else if (Opcode == ARM::BR_JTm)
858    OpNum = 3;
859
860  const MachineOperand &MO1 = MI->getOperand(OpNum);
861  const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
862  unsigned JTI = MO1.getIndex();
863
864  // Emit a label for the jump table.
865  MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
866  OutStreamer.EmitLabel(JTISymbol);
867
868  // Mark the jump table as data-in-code.
869  OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
870
871  // Emit each entry of the table.
872  const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
873  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
874  const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
875
876  for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
877    MachineBasicBlock *MBB = JTBBs[i];
878    // Construct an MCExpr for the entry. We want a value of the form:
879    // (BasicBlockAddr - TableBeginAddr)
880    //
881    // For example, a table with entries jumping to basic blocks BB0 and BB1
882    // would look like:
883    // LJTI_0_0:
884    //    .word (LBB0 - LJTI_0_0)
885    //    .word (LBB1 - LJTI_0_0)
886    const MCExpr *Expr = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
887
888    if (TM.getRelocationModel() == Reloc::PIC_)
889      Expr = MCBinaryExpr::CreateSub(Expr, MCSymbolRefExpr::Create(JTISymbol,
890                                                                   OutContext),
891                                     OutContext);
892    // If we're generating a table of Thumb addresses in static relocation
893    // model, we need to add one to keep interworking correctly.
894    else if (AFI->isThumbFunction())
895      Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(1,OutContext),
896                                     OutContext);
897    OutStreamer.EmitValue(Expr, 4);
898  }
899  // Mark the end of jump table data-in-code region.
900  OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
901}
902
903void ARMAsmPrinter::EmitJump2Table(const MachineInstr *MI) {
904  unsigned Opcode = MI->getOpcode();
905  int OpNum = (Opcode == ARM::t2BR_JT) ? 2 : 1;
906  const MachineOperand &MO1 = MI->getOperand(OpNum);
907  const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
908  unsigned JTI = MO1.getIndex();
909
910  MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
911  OutStreamer.EmitLabel(JTISymbol);
912
913  // Emit each entry of the table.
914  const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
915  const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
916  const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
917  unsigned OffsetWidth = 4;
918  if (MI->getOpcode() == ARM::t2TBB_JT) {
919    OffsetWidth = 1;
920    // Mark the jump table as data-in-code.
921    OutStreamer.EmitDataRegion(MCDR_DataRegionJT8);
922  } else if (MI->getOpcode() == ARM::t2TBH_JT) {
923    OffsetWidth = 2;
924    // Mark the jump table as data-in-code.
925    OutStreamer.EmitDataRegion(MCDR_DataRegionJT16);
926  }
927
928  for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
929    MachineBasicBlock *MBB = JTBBs[i];
930    const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::Create(MBB->getSymbol(),
931                                                      OutContext);
932    // If this isn't a TBB or TBH, the entries are direct branch instructions.
933    if (OffsetWidth == 4) {
934      EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2B)
935        .addExpr(MBBSymbolExpr)
936        .addImm(ARMCC::AL)
937        .addReg(0));
938      continue;
939    }
940    // Otherwise it's an offset from the dispatch instruction. Construct an
941    // MCExpr for the entry. We want a value of the form:
942    // (BasicBlockAddr - TableBeginAddr) / 2
943    //
944    // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
945    // would look like:
946    // LJTI_0_0:
947    //    .byte (LBB0 - LJTI_0_0) / 2
948    //    .byte (LBB1 - LJTI_0_0) / 2
949    const MCExpr *Expr =
950      MCBinaryExpr::CreateSub(MBBSymbolExpr,
951                              MCSymbolRefExpr::Create(JTISymbol, OutContext),
952                              OutContext);
953    Expr = MCBinaryExpr::CreateDiv(Expr, MCConstantExpr::Create(2, OutContext),
954                                   OutContext);
955    OutStreamer.EmitValue(Expr, OffsetWidth);
956  }
957  // Mark the end of jump table data-in-code region. 32-bit offsets use
958  // actual branch instructions here, so we don't mark those as a data-region
959  // at all.
960  if (OffsetWidth != 4)
961    OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
962}
963
964void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
965  assert(MI->getFlag(MachineInstr::FrameSetup) &&
966      "Only instruction which are involved into frame setup code are allowed");
967
968  MCTargetStreamer &TS = *OutStreamer.getTargetStreamer();
969  ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
970  const MachineFunction &MF = *MI->getParent()->getParent();
971  const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
972  const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
973
974  unsigned FramePtr = RegInfo->getFrameRegister(MF);
975  unsigned Opc = MI->getOpcode();
976  unsigned SrcReg, DstReg;
977
978  if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
979    // Two special cases:
980    // 1) tPUSH does not have src/dst regs.
981    // 2) for Thumb1 code we sometimes materialize the constant via constpool
982    // load. Yes, this is pretty fragile, but for now I don't see better
983    // way... :(
984    SrcReg = DstReg = ARM::SP;
985  } else {
986    SrcReg = MI->getOperand(1).getReg();
987    DstReg = MI->getOperand(0).getReg();
988  }
989
990  // Try to figure out the unwinding opcode out of src / dst regs.
991  if (MI->mayStore()) {
992    // Register saves.
993    assert(DstReg == ARM::SP &&
994           "Only stack pointer as a destination reg is supported");
995
996    SmallVector<unsigned, 4> RegList;
997    // Skip src & dst reg, and pred ops.
998    unsigned StartOp = 2 + 2;
999    // Use all the operands.
1000    unsigned NumOffset = 0;
1001
1002    switch (Opc) {
1003    default:
1004      MI->dump();
1005      llvm_unreachable("Unsupported opcode for unwinding information");
1006    case ARM::tPUSH:
1007      // Special case here: no src & dst reg, but two extra imp ops.
1008      StartOp = 2; NumOffset = 2;
1009    case ARM::STMDB_UPD:
1010    case ARM::t2STMDB_UPD:
1011    case ARM::VSTMDDB_UPD:
1012      assert(SrcReg == ARM::SP &&
1013             "Only stack pointer as a source reg is supported");
1014      for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1015           i != NumOps; ++i) {
1016        const MachineOperand &MO = MI->getOperand(i);
1017        // Actually, there should never be any impdef stuff here. Skip it
1018        // temporary to workaround PR11902.
1019        if (MO.isImplicit())
1020          continue;
1021        RegList.push_back(MO.getReg());
1022      }
1023      break;
1024    case ARM::STR_PRE_IMM:
1025    case ARM::STR_PRE_REG:
1026    case ARM::t2STR_PRE:
1027      assert(MI->getOperand(2).getReg() == ARM::SP &&
1028             "Only stack pointer as a source reg is supported");
1029      RegList.push_back(SrcReg);
1030      break;
1031    }
1032    if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM)
1033      ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1034  } else {
1035    // Changes of stack / frame pointer.
1036    if (SrcReg == ARM::SP) {
1037      int64_t Offset = 0;
1038      switch (Opc) {
1039      default:
1040        MI->dump();
1041        llvm_unreachable("Unsupported opcode for unwinding information");
1042      case ARM::MOVr:
1043      case ARM::tMOVr:
1044        Offset = 0;
1045        break;
1046      case ARM::ADDri:
1047        Offset = -MI->getOperand(2).getImm();
1048        break;
1049      case ARM::SUBri:
1050      case ARM::t2SUBri:
1051        Offset = MI->getOperand(2).getImm();
1052        break;
1053      case ARM::tSUBspi:
1054        Offset = MI->getOperand(2).getImm()*4;
1055        break;
1056      case ARM::tADDspi:
1057      case ARM::tADDrSPi:
1058        Offset = -MI->getOperand(2).getImm()*4;
1059        break;
1060      case ARM::tLDRpci: {
1061        // Grab the constpool index and check, whether it corresponds to
1062        // original or cloned constpool entry.
1063        unsigned CPI = MI->getOperand(1).getIndex();
1064        const MachineConstantPool *MCP = MF.getConstantPool();
1065        if (CPI >= MCP->getConstants().size())
1066          CPI = AFI.getOriginalCPIdx(CPI);
1067        assert(CPI != -1U && "Invalid constpool index");
1068
1069        // Derive the actual offset.
1070        const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1071        assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1072        // FIXME: Check for user, it should be "add" instruction!
1073        Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1074        break;
1075      }
1076      }
1077
1078      if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1079        if (DstReg == FramePtr && FramePtr != ARM::SP)
1080          // Set-up of the frame pointer. Positive values correspond to "add"
1081          // instruction.
1082          ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1083        else if (DstReg == ARM::SP) {
1084          // Change of SP by an offset. Positive values correspond to "sub"
1085          // instruction.
1086          ATS.emitPad(Offset);
1087        } else {
1088          // Move of SP to a register.  Positive values correspond to an "add"
1089          // instruction.
1090          ATS.emitMovSP(DstReg, -Offset);
1091        }
1092      }
1093    } else if (DstReg == ARM::SP) {
1094      MI->dump();
1095      llvm_unreachable("Unsupported opcode for unwinding information");
1096    }
1097    else {
1098      MI->dump();
1099      llvm_unreachable("Unsupported opcode for unwinding information");
1100    }
1101  }
1102}
1103
1104// Simple pseudo-instructions have their lowering (with expansion to real
1105// instructions) auto-generated.
1106#include "ARMGenMCPseudoLowering.inc"
1107
1108void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1109  const DataLayout *DL = TM.getDataLayout();
1110
1111  // If we just ended a constant pool, mark it as such.
1112  if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1113    OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1114    InConstantPool = false;
1115  }
1116
1117  // Emit unwinding stuff for frame-related instructions
1118  if (Subtarget->isTargetEHABICompatible() &&
1119       MI->getFlag(MachineInstr::FrameSetup))
1120    EmitUnwindingInstruction(MI);
1121
1122  // Do any auto-generated pseudo lowerings.
1123  if (emitPseudoExpansionLowering(OutStreamer, MI))
1124    return;
1125
1126  assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1127         "Pseudo flag setting opcode should be expanded early");
1128
1129  // Check for manual lowerings.
1130  unsigned Opc = MI->getOpcode();
1131  switch (Opc) {
1132  case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1133  case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1134  case ARM::LEApcrel:
1135  case ARM::tLEApcrel:
1136  case ARM::t2LEApcrel: {
1137    // FIXME: Need to also handle globals and externals
1138    MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1139    EmitToStreamer(OutStreamer, MCInstBuilder(MI->getOpcode() ==
1140                                              ARM::t2LEApcrel ? ARM::t2ADR
1141                  : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1142                     : ARM::ADR))
1143      .addReg(MI->getOperand(0).getReg())
1144      .addExpr(MCSymbolRefExpr::Create(CPISymbol, OutContext))
1145      // Add predicate operands.
1146      .addImm(MI->getOperand(2).getImm())
1147      .addReg(MI->getOperand(3).getReg()));
1148    return;
1149  }
1150  case ARM::LEApcrelJT:
1151  case ARM::tLEApcrelJT:
1152  case ARM::t2LEApcrelJT: {
1153    MCSymbol *JTIPICSymbol =
1154      GetARMJTIPICJumpTableLabel2(MI->getOperand(1).getIndex(),
1155                                  MI->getOperand(2).getImm());
1156    EmitToStreamer(OutStreamer, MCInstBuilder(MI->getOpcode() ==
1157                                              ARM::t2LEApcrelJT ? ARM::t2ADR
1158                  : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1159                     : ARM::ADR))
1160      .addReg(MI->getOperand(0).getReg())
1161      .addExpr(MCSymbolRefExpr::Create(JTIPICSymbol, OutContext))
1162      // Add predicate operands.
1163      .addImm(MI->getOperand(3).getImm())
1164      .addReg(MI->getOperand(4).getReg()));
1165    return;
1166  }
1167  // Darwin call instructions are just normal call instructions with different
1168  // clobber semantics (they clobber R9).
1169  case ARM::BX_CALL: {
1170    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1171      .addReg(ARM::LR)
1172      .addReg(ARM::PC)
1173      // Add predicate operands.
1174      .addImm(ARMCC::AL)
1175      .addReg(0)
1176      // Add 's' bit operand (always reg0 for this)
1177      .addReg(0));
1178
1179    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::BX)
1180      .addReg(MI->getOperand(0).getReg()));
1181    return;
1182  }
1183  case ARM::tBX_CALL: {
1184    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1185      .addReg(ARM::LR)
1186      .addReg(ARM::PC)
1187      // Add predicate operands.
1188      .addImm(ARMCC::AL)
1189      .addReg(0));
1190
1191    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tBX)
1192      .addReg(MI->getOperand(0).getReg())
1193      // Add predicate operands.
1194      .addImm(ARMCC::AL)
1195      .addReg(0));
1196    return;
1197  }
1198  case ARM::BMOVPCRX_CALL: {
1199    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1200      .addReg(ARM::LR)
1201      .addReg(ARM::PC)
1202      // Add predicate operands.
1203      .addImm(ARMCC::AL)
1204      .addReg(0)
1205      // Add 's' bit operand (always reg0 for this)
1206      .addReg(0));
1207
1208    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1209      .addReg(ARM::PC)
1210      .addReg(MI->getOperand(0).getReg())
1211      // Add predicate operands.
1212      .addImm(ARMCC::AL)
1213      .addReg(0)
1214      // Add 's' bit operand (always reg0 for this)
1215      .addReg(0));
1216    return;
1217  }
1218  case ARM::BMOVPCB_CALL: {
1219    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVr)
1220      .addReg(ARM::LR)
1221      .addReg(ARM::PC)
1222      // Add predicate operands.
1223      .addImm(ARMCC::AL)
1224      .addReg(0)
1225      // Add 's' bit operand (always reg0 for this)
1226      .addReg(0));
1227
1228    const GlobalValue *GV = MI->getOperand(0).getGlobal();
1229    MCSymbol *GVSym = getSymbol(GV);
1230    const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1231    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::Bcc)
1232      .addExpr(GVSymExpr)
1233      // Add predicate operands.
1234      .addImm(ARMCC::AL)
1235      .addReg(0));
1236    return;
1237  }
1238  case ARM::MOVi16_ga_pcrel:
1239  case ARM::t2MOVi16_ga_pcrel: {
1240    MCInst TmpInst;
1241    TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1242    TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1243
1244    unsigned TF = MI->getOperand(1).getTargetFlags();
1245    const GlobalValue *GV = MI->getOperand(1).getGlobal();
1246    MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1247    const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1248
1249    MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
1250                                     getFunctionNumber(),
1251                                     MI->getOperand(2).getImm(), OutContext);
1252    const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
1253    unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1254    const MCExpr *PCRelExpr =
1255      ARMMCExpr::CreateLower16(MCBinaryExpr::CreateSub(GVSymExpr,
1256                                      MCBinaryExpr::CreateAdd(LabelSymExpr,
1257                                      MCConstantExpr::Create(PCAdj, OutContext),
1258                                      OutContext), OutContext), OutContext);
1259      TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
1260
1261    // Add predicate operands.
1262    TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1263    TmpInst.addOperand(MCOperand::CreateReg(0));
1264    // Add 's' bit operand (always reg0 for this)
1265    TmpInst.addOperand(MCOperand::CreateReg(0));
1266    EmitToStreamer(OutStreamer, TmpInst);
1267    return;
1268  }
1269  case ARM::MOVTi16_ga_pcrel:
1270  case ARM::t2MOVTi16_ga_pcrel: {
1271    MCInst TmpInst;
1272    TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1273                      ? ARM::MOVTi16 : ARM::t2MOVTi16);
1274    TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1275    TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1276
1277    unsigned TF = MI->getOperand(2).getTargetFlags();
1278    const GlobalValue *GV = MI->getOperand(2).getGlobal();
1279    MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1280    const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1281
1282    MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
1283                                     getFunctionNumber(),
1284                                     MI->getOperand(3).getImm(), OutContext);
1285    const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
1286    unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1287    const MCExpr *PCRelExpr =
1288        ARMMCExpr::CreateUpper16(MCBinaryExpr::CreateSub(GVSymExpr,
1289                                   MCBinaryExpr::CreateAdd(LabelSymExpr,
1290                                      MCConstantExpr::Create(PCAdj, OutContext),
1291                                          OutContext), OutContext), OutContext);
1292      TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
1293    // Add predicate operands.
1294    TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1295    TmpInst.addOperand(MCOperand::CreateReg(0));
1296    // Add 's' bit operand (always reg0 for this)
1297    TmpInst.addOperand(MCOperand::CreateReg(0));
1298    EmitToStreamer(OutStreamer, TmpInst);
1299    return;
1300  }
1301  case ARM::tPICADD: {
1302    // This is a pseudo op for a label + instruction sequence, which looks like:
1303    // LPC0:
1304    //     add r0, pc
1305    // This adds the address of LPC0 to r0.
1306
1307    // Emit the label.
1308    OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1309                          getFunctionNumber(), MI->getOperand(2).getImm(),
1310                          OutContext));
1311
1312    // Form and emit the add.
1313    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tADDhirr)
1314      .addReg(MI->getOperand(0).getReg())
1315      .addReg(MI->getOperand(0).getReg())
1316      .addReg(ARM::PC)
1317      // Add predicate operands.
1318      .addImm(ARMCC::AL)
1319      .addReg(0));
1320    return;
1321  }
1322  case ARM::PICADD: {
1323    // This is a pseudo op for a label + instruction sequence, which looks like:
1324    // LPC0:
1325    //     add r0, pc, r0
1326    // This adds the address of LPC0 to r0.
1327
1328    // Emit the label.
1329    OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1330                          getFunctionNumber(), MI->getOperand(2).getImm(),
1331                          OutContext));
1332
1333    // Form and emit the add.
1334    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDrr)
1335      .addReg(MI->getOperand(0).getReg())
1336      .addReg(ARM::PC)
1337      .addReg(MI->getOperand(1).getReg())
1338      // Add predicate operands.
1339      .addImm(MI->getOperand(3).getImm())
1340      .addReg(MI->getOperand(4).getReg())
1341      // Add 's' bit operand (always reg0 for this)
1342      .addReg(0));
1343    return;
1344  }
1345  case ARM::PICSTR:
1346  case ARM::PICSTRB:
1347  case ARM::PICSTRH:
1348  case ARM::PICLDR:
1349  case ARM::PICLDRB:
1350  case ARM::PICLDRH:
1351  case ARM::PICLDRSB:
1352  case ARM::PICLDRSH: {
1353    // This is a pseudo op for a label + instruction sequence, which looks like:
1354    // LPC0:
1355    //     OP r0, [pc, r0]
1356    // The LCP0 label is referenced by a constant pool entry in order to get
1357    // a PC-relative address at the ldr instruction.
1358
1359    // Emit the label.
1360    OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1361                          getFunctionNumber(), MI->getOperand(2).getImm(),
1362                          OutContext));
1363
1364    // Form and emit the load
1365    unsigned Opcode;
1366    switch (MI->getOpcode()) {
1367    default:
1368      llvm_unreachable("Unexpected opcode!");
1369    case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1370    case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1371    case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1372    case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1373    case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1374    case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1375    case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1376    case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1377    }
1378    EmitToStreamer(OutStreamer, MCInstBuilder(Opcode)
1379      .addReg(MI->getOperand(0).getReg())
1380      .addReg(ARM::PC)
1381      .addReg(MI->getOperand(1).getReg())
1382      .addImm(0)
1383      // Add predicate operands.
1384      .addImm(MI->getOperand(3).getImm())
1385      .addReg(MI->getOperand(4).getReg()));
1386
1387    return;
1388  }
1389  case ARM::CONSTPOOL_ENTRY: {
1390    /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1391    /// in the function.  The first operand is the ID# for this instruction, the
1392    /// second is the index into the MachineConstantPool that this is, the third
1393    /// is the size in bytes of this constant pool entry.
1394    /// The required alignment is specified on the basic block holding this MI.
1395    unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1396    unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1397
1398    // If this is the first entry of the pool, mark it.
1399    if (!InConstantPool) {
1400      OutStreamer.EmitDataRegion(MCDR_DataRegion);
1401      InConstantPool = true;
1402    }
1403
1404    OutStreamer.EmitLabel(GetCPISymbol(LabelId));
1405
1406    const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1407    if (MCPE.isMachineConstantPoolEntry())
1408      EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1409    else
1410      EmitGlobalConstant(MCPE.Val.ConstVal);
1411    return;
1412  }
1413  case ARM::t2BR_JT: {
1414    // Lower and emit the instruction itself, then the jump table following it.
1415    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1416      .addReg(ARM::PC)
1417      .addReg(MI->getOperand(0).getReg())
1418      // Add predicate operands.
1419      .addImm(ARMCC::AL)
1420      .addReg(0));
1421
1422    // Output the data for the jump table itself
1423    EmitJump2Table(MI);
1424    return;
1425  }
1426  case ARM::t2TBB_JT: {
1427    // Lower and emit the instruction itself, then the jump table following it.
1428    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2TBB)
1429      .addReg(ARM::PC)
1430      .addReg(MI->getOperand(0).getReg())
1431      // Add predicate operands.
1432      .addImm(ARMCC::AL)
1433      .addReg(0));
1434
1435    // Output the data for the jump table itself
1436    EmitJump2Table(MI);
1437    // Make sure the next instruction is 2-byte aligned.
1438    EmitAlignment(1);
1439    return;
1440  }
1441  case ARM::t2TBH_JT: {
1442    // Lower and emit the instruction itself, then the jump table following it.
1443    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::t2TBH)
1444      .addReg(ARM::PC)
1445      .addReg(MI->getOperand(0).getReg())
1446      // Add predicate operands.
1447      .addImm(ARMCC::AL)
1448      .addReg(0));
1449
1450    // Output the data for the jump table itself
1451    EmitJump2Table(MI);
1452    return;
1453  }
1454  case ARM::tBR_JTr:
1455  case ARM::BR_JTr: {
1456    // Lower and emit the instruction itself, then the jump table following it.
1457    // mov pc, target
1458    MCInst TmpInst;
1459    unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1460      ARM::MOVr : ARM::tMOVr;
1461    TmpInst.setOpcode(Opc);
1462    TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1463    TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1464    // Add predicate operands.
1465    TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1466    TmpInst.addOperand(MCOperand::CreateReg(0));
1467    // Add 's' bit operand (always reg0 for this)
1468    if (Opc == ARM::MOVr)
1469      TmpInst.addOperand(MCOperand::CreateReg(0));
1470    EmitToStreamer(OutStreamer, TmpInst);
1471
1472    // Make sure the Thumb jump table is 4-byte aligned.
1473    if (Opc == ARM::tMOVr)
1474      EmitAlignment(2);
1475
1476    // Output the data for the jump table itself
1477    EmitJumpTable(MI);
1478    return;
1479  }
1480  case ARM::BR_JTm: {
1481    // Lower and emit the instruction itself, then the jump table following it.
1482    // ldr pc, target
1483    MCInst TmpInst;
1484    if (MI->getOperand(1).getReg() == 0) {
1485      // literal offset
1486      TmpInst.setOpcode(ARM::LDRi12);
1487      TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1488      TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1489      TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1490    } else {
1491      TmpInst.setOpcode(ARM::LDRrs);
1492      TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1493      TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1494      TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1495      TmpInst.addOperand(MCOperand::CreateImm(0));
1496    }
1497    // Add predicate operands.
1498    TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1499    TmpInst.addOperand(MCOperand::CreateReg(0));
1500    EmitToStreamer(OutStreamer, TmpInst);
1501
1502    // Output the data for the jump table itself
1503    EmitJumpTable(MI);
1504    return;
1505  }
1506  case ARM::BR_JTadd: {
1507    // Lower and emit the instruction itself, then the jump table following it.
1508    // add pc, target, idx
1509    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDrr)
1510      .addReg(ARM::PC)
1511      .addReg(MI->getOperand(0).getReg())
1512      .addReg(MI->getOperand(1).getReg())
1513      // Add predicate operands.
1514      .addImm(ARMCC::AL)
1515      .addReg(0)
1516      // Add 's' bit operand (always reg0 for this)
1517      .addReg(0));
1518
1519    // Output the data for the jump table itself
1520    EmitJumpTable(MI);
1521    return;
1522  }
1523  case ARM::TRAP: {
1524    // Non-Darwin binutils don't yet support the "trap" mnemonic.
1525    // FIXME: Remove this special case when they do.
1526    if (!Subtarget->isTargetMachO()) {
1527      //.long 0xe7ffdefe @ trap
1528      uint32_t Val = 0xe7ffdefeUL;
1529      OutStreamer.AddComment("trap");
1530      OutStreamer.EmitIntValue(Val, 4);
1531      return;
1532    }
1533    break;
1534  }
1535  case ARM::TRAPNaCl: {
1536    //.long 0xe7fedef0 @ trap
1537    uint32_t Val = 0xe7fedef0UL;
1538    OutStreamer.AddComment("trap");
1539    OutStreamer.EmitIntValue(Val, 4);
1540    return;
1541  }
1542  case ARM::tTRAP: {
1543    // Non-Darwin binutils don't yet support the "trap" mnemonic.
1544    // FIXME: Remove this special case when they do.
1545    if (!Subtarget->isTargetMachO()) {
1546      //.short 57086 @ trap
1547      uint16_t Val = 0xdefe;
1548      OutStreamer.AddComment("trap");
1549      OutStreamer.EmitIntValue(Val, 2);
1550      return;
1551    }
1552    break;
1553  }
1554  case ARM::t2Int_eh_sjlj_setjmp:
1555  case ARM::t2Int_eh_sjlj_setjmp_nofp:
1556  case ARM::tInt_eh_sjlj_setjmp: {
1557    // Two incoming args: GPR:$src, GPR:$val
1558    // mov $val, pc
1559    // adds $val, #7
1560    // str $val, [$src, #4]
1561    // movs r0, #0
1562    // b 1f
1563    // movs r0, #1
1564    // 1:
1565    unsigned SrcReg = MI->getOperand(0).getReg();
1566    unsigned ValReg = MI->getOperand(1).getReg();
1567    MCSymbol *Label = GetARMSJLJEHLabel();
1568    OutStreamer.AddComment("eh_setjmp begin");
1569    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1570      .addReg(ValReg)
1571      .addReg(ARM::PC)
1572      // Predicate.
1573      .addImm(ARMCC::AL)
1574      .addReg(0));
1575
1576    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tADDi3)
1577      .addReg(ValReg)
1578      // 's' bit operand
1579      .addReg(ARM::CPSR)
1580      .addReg(ValReg)
1581      .addImm(7)
1582      // Predicate.
1583      .addImm(ARMCC::AL)
1584      .addReg(0));
1585
1586    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tSTRi)
1587      .addReg(ValReg)
1588      .addReg(SrcReg)
1589      // The offset immediate is #4. The operand value is scaled by 4 for the
1590      // tSTR instruction.
1591      .addImm(1)
1592      // Predicate.
1593      .addImm(ARMCC::AL)
1594      .addReg(0));
1595
1596    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVi8)
1597      .addReg(ARM::R0)
1598      .addReg(ARM::CPSR)
1599      .addImm(0)
1600      // Predicate.
1601      .addImm(ARMCC::AL)
1602      .addReg(0));
1603
1604    const MCExpr *SymbolExpr = MCSymbolRefExpr::Create(Label, OutContext);
1605    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tB)
1606      .addExpr(SymbolExpr)
1607      .addImm(ARMCC::AL)
1608      .addReg(0));
1609
1610    OutStreamer.AddComment("eh_setjmp end");
1611    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVi8)
1612      .addReg(ARM::R0)
1613      .addReg(ARM::CPSR)
1614      .addImm(1)
1615      // Predicate.
1616      .addImm(ARMCC::AL)
1617      .addReg(0));
1618
1619    OutStreamer.EmitLabel(Label);
1620    return;
1621  }
1622
1623  case ARM::Int_eh_sjlj_setjmp_nofp:
1624  case ARM::Int_eh_sjlj_setjmp: {
1625    // Two incoming args: GPR:$src, GPR:$val
1626    // add $val, pc, #8
1627    // str $val, [$src, #+4]
1628    // mov r0, #0
1629    // add pc, pc, #0
1630    // mov r0, #1
1631    unsigned SrcReg = MI->getOperand(0).getReg();
1632    unsigned ValReg = MI->getOperand(1).getReg();
1633
1634    OutStreamer.AddComment("eh_setjmp begin");
1635    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDri)
1636      .addReg(ValReg)
1637      .addReg(ARM::PC)
1638      .addImm(8)
1639      // Predicate.
1640      .addImm(ARMCC::AL)
1641      .addReg(0)
1642      // 's' bit operand (always reg0 for this).
1643      .addReg(0));
1644
1645    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::STRi12)
1646      .addReg(ValReg)
1647      .addReg(SrcReg)
1648      .addImm(4)
1649      // Predicate.
1650      .addImm(ARMCC::AL)
1651      .addReg(0));
1652
1653    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVi)
1654      .addReg(ARM::R0)
1655      .addImm(0)
1656      // Predicate.
1657      .addImm(ARMCC::AL)
1658      .addReg(0)
1659      // 's' bit operand (always reg0 for this).
1660      .addReg(0));
1661
1662    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::ADDri)
1663      .addReg(ARM::PC)
1664      .addReg(ARM::PC)
1665      .addImm(0)
1666      // Predicate.
1667      .addImm(ARMCC::AL)
1668      .addReg(0)
1669      // 's' bit operand (always reg0 for this).
1670      .addReg(0));
1671
1672    OutStreamer.AddComment("eh_setjmp end");
1673    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::MOVi)
1674      .addReg(ARM::R0)
1675      .addImm(1)
1676      // Predicate.
1677      .addImm(ARMCC::AL)
1678      .addReg(0)
1679      // 's' bit operand (always reg0 for this).
1680      .addReg(0));
1681    return;
1682  }
1683  case ARM::Int_eh_sjlj_longjmp: {
1684    // ldr sp, [$src, #8]
1685    // ldr $scratch, [$src, #4]
1686    // ldr r7, [$src]
1687    // bx $scratch
1688    unsigned SrcReg = MI->getOperand(0).getReg();
1689    unsigned ScratchReg = MI->getOperand(1).getReg();
1690    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
1691      .addReg(ARM::SP)
1692      .addReg(SrcReg)
1693      .addImm(8)
1694      // Predicate.
1695      .addImm(ARMCC::AL)
1696      .addReg(0));
1697
1698    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
1699      .addReg(ScratchReg)
1700      .addReg(SrcReg)
1701      .addImm(4)
1702      // Predicate.
1703      .addImm(ARMCC::AL)
1704      .addReg(0));
1705
1706    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::LDRi12)
1707      .addReg(ARM::R7)
1708      .addReg(SrcReg)
1709      .addImm(0)
1710      // Predicate.
1711      .addImm(ARMCC::AL)
1712      .addReg(0));
1713
1714    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::BX)
1715      .addReg(ScratchReg)
1716      // Predicate.
1717      .addImm(ARMCC::AL)
1718      .addReg(0));
1719    return;
1720  }
1721  case ARM::tInt_eh_sjlj_longjmp: {
1722    // ldr $scratch, [$src, #8]
1723    // mov sp, $scratch
1724    // ldr $scratch, [$src, #4]
1725    // ldr r7, [$src]
1726    // bx $scratch
1727    unsigned SrcReg = MI->getOperand(0).getReg();
1728    unsigned ScratchReg = MI->getOperand(1).getReg();
1729    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
1730      .addReg(ScratchReg)
1731      .addReg(SrcReg)
1732      // The offset immediate is #8. The operand value is scaled by 4 for the
1733      // tLDR instruction.
1734      .addImm(2)
1735      // Predicate.
1736      .addImm(ARMCC::AL)
1737      .addReg(0));
1738
1739    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tMOVr)
1740      .addReg(ARM::SP)
1741      .addReg(ScratchReg)
1742      // Predicate.
1743      .addImm(ARMCC::AL)
1744      .addReg(0));
1745
1746    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
1747      .addReg(ScratchReg)
1748      .addReg(SrcReg)
1749      .addImm(1)
1750      // Predicate.
1751      .addImm(ARMCC::AL)
1752      .addReg(0));
1753
1754    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tLDRi)
1755      .addReg(ARM::R7)
1756      .addReg(SrcReg)
1757      .addImm(0)
1758      // Predicate.
1759      .addImm(ARMCC::AL)
1760      .addReg(0));
1761
1762    EmitToStreamer(OutStreamer, MCInstBuilder(ARM::tBX)
1763      .addReg(ScratchReg)
1764      // Predicate.
1765      .addImm(ARMCC::AL)
1766      .addReg(0));
1767    return;
1768  }
1769  }
1770
1771  MCInst TmpInst;
1772  LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
1773
1774  EmitToStreamer(OutStreamer, TmpInst);
1775}
1776
1777//===----------------------------------------------------------------------===//
1778// Target Registry Stuff
1779//===----------------------------------------------------------------------===//
1780
1781// Force static initialization.
1782extern "C" void LLVMInitializeARMAsmPrinter() {
1783  RegisterAsmPrinter<ARMAsmPrinter> X(TheARMLETarget);
1784  RegisterAsmPrinter<ARMAsmPrinter> Y(TheARMBETarget);
1785  RegisterAsmPrinter<ARMAsmPrinter> A(TheThumbLETarget);
1786  RegisterAsmPrinter<ARMAsmPrinter> B(TheThumbBETarget);
1787}
1788