1 //===-- ARMAsmPrinter.cpp - Print machine code to an ARM .s file ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains a printer that converts from our internal representation
10 // of machine-dependent LLVM code to GAS-format ARM assembly language.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMAsmPrinter.h"
15 #include "ARM.h"
16 #include "ARMConstantPoolValue.h"
17 #include "ARMMachineFunctionInfo.h"
18 #include "ARMTargetMachine.h"
19 #include "ARMTargetObjectFile.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "MCTargetDesc/ARMInstPrinter.h"
22 #include "MCTargetDesc/ARMMCExpr.h"
23 #include "TargetInfo/ARMTargetInfo.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/BinaryFormat/COFF.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/Mangler.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCAssembler.h"
37 #include "llvm/MC/MCContext.h"
38 #include "llvm/MC/MCELFStreamer.h"
39 #include "llvm/MC/MCInst.h"
40 #include "llvm/MC/MCInstBuilder.h"
41 #include "llvm/MC/MCObjectStreamer.h"
42 #include "llvm/MC/MCStreamer.h"
43 #include "llvm/MC/MCSymbol.h"
44 #include "llvm/Support/ARMBuildAttributes.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/TargetParser.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetMachine.h"
51 using namespace llvm;
52 
53 #define DEBUG_TYPE "asm-printer"
54 
55 ARMAsmPrinter::ARMAsmPrinter(TargetMachine &TM,
56                              std::unique_ptr<MCStreamer> Streamer)
57     : AsmPrinter(TM, std::move(Streamer)), Subtarget(nullptr), AFI(nullptr),
58       MCP(nullptr), InConstantPool(false), OptimizationGoals(-1) {}
59 
60 void 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 
69 void ARMAsmPrinter::emitFunctionEntryLabel() {
70   if (AFI->isThumbFunction()) {
71     OutStreamer->emitAssemblerFlag(MCAF_Code16);
72     OutStreamer->emitThumbFunc(CurrentFnSym);
73   } else {
74     OutStreamer->emitAssemblerFlag(MCAF_Code32);
75   }
76   OutStreamer->emitLabel(CurrentFnSym);
77 }
78 
79 void ARMAsmPrinter::emitXXStructor(const DataLayout &DL, const Constant *CV) {
80   uint64_t Size = getDataLayout().getTypeAllocSize(CV->getType());
81   assert(Size && "C++ constructor pointer had zero size!");
82 
83   const GlobalValue *GV = dyn_cast<GlobalValue>(CV->stripPointerCasts());
84   assert(GV && "C++ constructor pointer was not a GlobalValue!");
85 
86   const MCExpr *E = MCSymbolRefExpr::create(GetARMGVSymbol(GV,
87                                                            ARMII::MO_NO_FLAG),
88                                             (Subtarget->isTargetELF()
89                                              ? MCSymbolRefExpr::VK_ARM_TARGET1
90                                              : MCSymbolRefExpr::VK_None),
91                                             OutContext);
92 
93   OutStreamer->emitValue(E, Size);
94 }
95 
96 void ARMAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
97   if (PromotedGlobals.count(GV))
98     // The global was promoted into a constant pool. It should not be emitted.
99     return;
100   AsmPrinter::emitGlobalVariable(GV);
101 }
102 
103 /// runOnMachineFunction - This uses the emitInstruction()
104 /// method to print assembly for each instruction.
105 ///
106 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
107   AFI = MF.getInfo<ARMFunctionInfo>();
108   MCP = MF.getConstantPool();
109   Subtarget = &MF.getSubtarget<ARMSubtarget>();
110 
111   SetupMachineFunction(MF);
112   const Function &F = MF.getFunction();
113   const TargetMachine& TM = MF.getTarget();
114 
115   // Collect all globals that had their storage promoted to a constant pool.
116   // Functions are emitted before variables, so this accumulates promoted
117   // globals from all functions in PromotedGlobals.
118   for (auto *GV : AFI->getGlobalsPromotedToConstantPool())
119     PromotedGlobals.insert(GV);
120 
121   // Calculate this function's optimization goal.
122   unsigned OptimizationGoal;
123   if (F.hasOptNone())
124     // For best debugging illusion, speed and small size sacrificed
125     OptimizationGoal = 6;
126   else if (F.hasMinSize())
127     // Aggressively for small size, speed and debug illusion sacrificed
128     OptimizationGoal = 4;
129   else if (F.hasOptSize())
130     // For small size, but speed and debugging illusion preserved
131     OptimizationGoal = 3;
132   else if (TM.getOptLevel() == CodeGenOpt::Aggressive)
133     // Aggressively for speed, small size and debug illusion sacrificed
134     OptimizationGoal = 2;
135   else if (TM.getOptLevel() > CodeGenOpt::None)
136     // For speed, but small size and good debug illusion preserved
137     OptimizationGoal = 1;
138   else // TM.getOptLevel() == CodeGenOpt::None
139     // For good debugging, but speed and small size preserved
140     OptimizationGoal = 5;
141 
142   // Combine a new optimization goal with existing ones.
143   if (OptimizationGoals == -1) // uninitialized goals
144     OptimizationGoals = OptimizationGoal;
145   else if (OptimizationGoals != (int)OptimizationGoal) // conflicting goals
146     OptimizationGoals = 0;
147 
148   if (Subtarget->isTargetCOFF()) {
149     bool Internal = F.hasInternalLinkage();
150     COFF::SymbolStorageClass Scl = Internal ? COFF::IMAGE_SYM_CLASS_STATIC
151                                             : COFF::IMAGE_SYM_CLASS_EXTERNAL;
152     int Type = COFF::IMAGE_SYM_DTYPE_FUNCTION << COFF::SCT_COMPLEX_TYPE_SHIFT;
153 
154     OutStreamer->BeginCOFFSymbolDef(CurrentFnSym);
155     OutStreamer->EmitCOFFSymbolStorageClass(Scl);
156     OutStreamer->EmitCOFFSymbolType(Type);
157     OutStreamer->EndCOFFSymbolDef();
158   }
159 
160   // Emit the rest of the function body.
161   emitFunctionBody();
162 
163   // Emit the XRay table for this function.
164   emitXRayTable();
165 
166   // If we need V4T thumb mode Register Indirect Jump pads, emit them.
167   // These are created per function, rather than per TU, since it's
168   // relatively easy to exceed the thumb branch range within a TU.
169   if (! ThumbIndirectPads.empty()) {
170     OutStreamer->emitAssemblerFlag(MCAF_Code16);
171     emitAlignment(Align(2));
172     for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
173       OutStreamer->emitLabel(TIP.second);
174       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
175         .addReg(TIP.first)
176         // Add predicate operands.
177         .addImm(ARMCC::AL)
178         .addReg(0));
179     }
180     ThumbIndirectPads.clear();
181   }
182 
183   // We didn't modify anything.
184   return false;
185 }
186 
187 void ARMAsmPrinter::PrintSymbolOperand(const MachineOperand &MO,
188                                        raw_ostream &O) {
189   assert(MO.isGlobal() && "caller should check MO.isGlobal");
190   unsigned TF = MO.getTargetFlags();
191   if (TF & ARMII::MO_LO16)
192     O << ":lower16:";
193   else if (TF & ARMII::MO_HI16)
194     O << ":upper16:";
195   GetARMGVSymbol(MO.getGlobal(), TF)->print(O, MAI);
196   printOffset(MO.getOffset(), O);
197 }
198 
199 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
200                                  raw_ostream &O) {
201   const MachineOperand &MO = MI->getOperand(OpNum);
202 
203   switch (MO.getType()) {
204   default: llvm_unreachable("<unknown operand type>");
205   case MachineOperand::MO_Register: {
206     Register Reg = MO.getReg();
207     assert(Register::isPhysicalRegister(Reg));
208     assert(!MO.getSubReg() && "Subregs should be eliminated!");
209     if(ARM::GPRPairRegClass.contains(Reg)) {
210       const MachineFunction &MF = *MI->getParent()->getParent();
211       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
212       Reg = TRI->getSubReg(Reg, ARM::gsub_0);
213     }
214     O << ARMInstPrinter::getRegisterName(Reg);
215     break;
216   }
217   case MachineOperand::MO_Immediate: {
218     O << '#';
219     unsigned TF = MO.getTargetFlags();
220     if (TF == ARMII::MO_LO16)
221       O << ":lower16:";
222     else if (TF == ARMII::MO_HI16)
223       O << ":upper16:";
224     O << MO.getImm();
225     break;
226   }
227   case MachineOperand::MO_MachineBasicBlock:
228     MO.getMBB()->getSymbol()->print(O, MAI);
229     return;
230   case MachineOperand::MO_GlobalAddress: {
231     PrintSymbolOperand(MO, O);
232     break;
233   }
234   case MachineOperand::MO_ConstantPoolIndex:
235     if (Subtarget->genExecuteOnly())
236       llvm_unreachable("execute-only should not generate constant pools");
237     GetCPISymbol(MO.getIndex())->print(O, MAI);
238     break;
239   }
240 }
241 
242 MCSymbol *ARMAsmPrinter::GetCPISymbol(unsigned CPID) const {
243   // The AsmPrinter::GetCPISymbol superclass method tries to use CPID as
244   // indexes in MachineConstantPool, which isn't in sync with indexes used here.
245   const DataLayout &DL = getDataLayout();
246   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
247                                       "CPI" + Twine(getFunctionNumber()) + "_" +
248                                       Twine(CPID));
249 }
250 
251 //===--------------------------------------------------------------------===//
252 
253 MCSymbol *ARMAsmPrinter::
254 GetARMJTIPICJumpTableLabel(unsigned uid) const {
255   const DataLayout &DL = getDataLayout();
256   SmallString<60> Name;
257   raw_svector_ostream(Name) << DL.getPrivateGlobalPrefix() << "JTI"
258                             << getFunctionNumber() << '_' << uid;
259   return OutContext.getOrCreateSymbol(Name);
260 }
261 
262 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
263                                     const char *ExtraCode, raw_ostream &O) {
264   // Does this asm operand have a single letter operand modifier?
265   if (ExtraCode && ExtraCode[0]) {
266     if (ExtraCode[1] != 0) return true; // Unknown modifier.
267 
268     switch (ExtraCode[0]) {
269     default:
270       // See if this is a generic print operand
271       return AsmPrinter::PrintAsmOperand(MI, OpNum, ExtraCode, O);
272     case 'P': // Print a VFP double precision register.
273     case 'q': // Print a NEON quad precision register.
274       printOperand(MI, OpNum, O);
275       return false;
276     case 'y': // Print a VFP single precision register as indexed double.
277       if (MI->getOperand(OpNum).isReg()) {
278         Register Reg = MI->getOperand(OpNum).getReg();
279         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
280         // Find the 'd' register that has this 's' register as a sub-register,
281         // and determine the lane number.
282         for (MCSuperRegIterator SR(Reg, TRI); SR.isValid(); ++SR) {
283           if (!ARM::DPRRegClass.contains(*SR))
284             continue;
285           bool Lane0 = TRI->getSubReg(*SR, ARM::ssub_0) == Reg;
286           O << ARMInstPrinter::getRegisterName(*SR) << (Lane0 ? "[0]" : "[1]");
287           return false;
288         }
289       }
290       return true;
291     case 'B': // Bitwise inverse of integer or symbol without a preceding #.
292       if (!MI->getOperand(OpNum).isImm())
293         return true;
294       O << ~(MI->getOperand(OpNum).getImm());
295       return false;
296     case 'L': // The low 16 bits of an immediate constant.
297       if (!MI->getOperand(OpNum).isImm())
298         return true;
299       O << (MI->getOperand(OpNum).getImm() & 0xffff);
300       return false;
301     case 'M': { // A register range suitable for LDM/STM.
302       if (!MI->getOperand(OpNum).isReg())
303         return true;
304       const MachineOperand &MO = MI->getOperand(OpNum);
305       Register RegBegin = MO.getReg();
306       // This takes advantage of the 2 operand-ness of ldm/stm and that we've
307       // already got the operands in registers that are operands to the
308       // inline asm statement.
309       O << "{";
310       if (ARM::GPRPairRegClass.contains(RegBegin)) {
311         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
312         Register Reg0 = TRI->getSubReg(RegBegin, ARM::gsub_0);
313         O << ARMInstPrinter::getRegisterName(Reg0) << ", ";
314         RegBegin = TRI->getSubReg(RegBegin, ARM::gsub_1);
315       }
316       O << ARMInstPrinter::getRegisterName(RegBegin);
317 
318       // FIXME: The register allocator not only may not have given us the
319       // registers in sequence, but may not be in ascending registers. This
320       // will require changes in the register allocator that'll need to be
321       // propagated down here if the operands change.
322       unsigned RegOps = OpNum + 1;
323       while (MI->getOperand(RegOps).isReg()) {
324         O << ", "
325           << ARMInstPrinter::getRegisterName(MI->getOperand(RegOps).getReg());
326         RegOps++;
327       }
328 
329       O << "}";
330 
331       return false;
332     }
333     case 'R': // The most significant register of a pair.
334     case 'Q': { // The least significant register of a pair.
335       if (OpNum == 0)
336         return true;
337       const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
338       if (!FlagsOP.isImm())
339         return true;
340       unsigned Flags = FlagsOP.getImm();
341 
342       // This operand may not be the one that actually provides the register. If
343       // it's tied to a previous one then we should refer instead to that one
344       // for registers and their classes.
345       unsigned TiedIdx;
346       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedIdx)) {
347         for (OpNum = InlineAsm::MIOp_FirstOperand; TiedIdx; --TiedIdx) {
348           unsigned OpFlags = MI->getOperand(OpNum).getImm();
349           OpNum += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
350         }
351         Flags = MI->getOperand(OpNum).getImm();
352 
353         // Later code expects OpNum to be pointing at the register rather than
354         // the flags.
355         OpNum += 1;
356       }
357 
358       unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
359       unsigned RC;
360       bool FirstHalf;
361       const ARMBaseTargetMachine &ATM =
362         static_cast<const ARMBaseTargetMachine &>(TM);
363 
364       // 'Q' should correspond to the low order register and 'R' to the high
365       // order register.  Whether this corresponds to the upper or lower half
366       // depends on the endianess mode.
367       if (ExtraCode[0] == 'Q')
368         FirstHalf = ATM.isLittleEndian();
369       else
370         // ExtraCode[0] == 'R'.
371         FirstHalf = !ATM.isLittleEndian();
372       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
373       if (InlineAsm::hasRegClassConstraint(Flags, RC) &&
374           ARM::GPRPairRegClass.hasSubClassEq(TRI->getRegClass(RC))) {
375         if (NumVals != 1)
376           return true;
377         const MachineOperand &MO = MI->getOperand(OpNum);
378         if (!MO.isReg())
379           return true;
380         const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
381         Register Reg =
382             TRI->getSubReg(MO.getReg(), FirstHalf ? ARM::gsub_0 : ARM::gsub_1);
383         O << ARMInstPrinter::getRegisterName(Reg);
384         return false;
385       }
386       if (NumVals != 2)
387         return true;
388       unsigned RegOp = FirstHalf ? OpNum : OpNum + 1;
389       if (RegOp >= MI->getNumOperands())
390         return true;
391       const MachineOperand &MO = MI->getOperand(RegOp);
392       if (!MO.isReg())
393         return true;
394       Register Reg = MO.getReg();
395       O << ARMInstPrinter::getRegisterName(Reg);
396       return false;
397     }
398 
399     case 'e': // The low doubleword register of a NEON quad register.
400     case 'f': { // The high doubleword register of a NEON quad register.
401       if (!MI->getOperand(OpNum).isReg())
402         return true;
403       Register Reg = MI->getOperand(OpNum).getReg();
404       if (!ARM::QPRRegClass.contains(Reg))
405         return true;
406       const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
407       Register SubReg =
408           TRI->getSubReg(Reg, ExtraCode[0] == 'e' ? ARM::dsub_0 : ARM::dsub_1);
409       O << ARMInstPrinter::getRegisterName(SubReg);
410       return false;
411     }
412 
413     // This modifier is not yet supported.
414     case 'h': // A range of VFP/NEON registers suitable for VLD1/VST1.
415       return true;
416     case 'H': { // The highest-numbered register of a pair.
417       const MachineOperand &MO = MI->getOperand(OpNum);
418       if (!MO.isReg())
419         return true;
420       const MachineFunction &MF = *MI->getParent()->getParent();
421       const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
422       Register Reg = MO.getReg();
423       if(!ARM::GPRPairRegClass.contains(Reg))
424         return false;
425       Reg = TRI->getSubReg(Reg, ARM::gsub_1);
426       O << ARMInstPrinter::getRegisterName(Reg);
427       return false;
428     }
429     }
430   }
431 
432   printOperand(MI, OpNum, O);
433   return false;
434 }
435 
436 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
437                                           unsigned OpNum, const char *ExtraCode,
438                                           raw_ostream &O) {
439   // Does this asm operand have a single letter operand modifier?
440   if (ExtraCode && ExtraCode[0]) {
441     if (ExtraCode[1] != 0) return true; // Unknown modifier.
442 
443     switch (ExtraCode[0]) {
444       case 'A': // A memory operand for a VLD1/VST1 instruction.
445       default: return true;  // Unknown modifier.
446       case 'm': // The base register of a memory operand.
447         if (!MI->getOperand(OpNum).isReg())
448           return true;
449         O << ARMInstPrinter::getRegisterName(MI->getOperand(OpNum).getReg());
450         return false;
451     }
452   }
453 
454   const MachineOperand &MO = MI->getOperand(OpNum);
455   assert(MO.isReg() && "unexpected inline asm memory operand");
456   O << "[" << ARMInstPrinter::getRegisterName(MO.getReg()) << "]";
457   return false;
458 }
459 
460 static bool isThumb(const MCSubtargetInfo& STI) {
461   return STI.getFeatureBits()[ARM::ModeThumb];
462 }
463 
464 void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
465                                      const MCSubtargetInfo *EndInfo) const {
466   // If either end mode is unknown (EndInfo == NULL) or different than
467   // the start mode, then restore the start mode.
468   const bool WasThumb = isThumb(StartInfo);
469   if (!EndInfo || WasThumb != isThumb(*EndInfo)) {
470     OutStreamer->emitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
471   }
472 }
473 
474 void ARMAsmPrinter::emitStartOfAsmFile(Module &M) {
475   const Triple &TT = TM.getTargetTriple();
476   // Use unified assembler syntax.
477   OutStreamer->emitAssemblerFlag(MCAF_SyntaxUnified);
478 
479   // Emit ARM Build Attributes
480   if (TT.isOSBinFormatELF())
481     emitAttributes();
482 
483   // Use the triple's architecture and subarchitecture to determine
484   // if we're thumb for the purposes of the top level code16 assembler
485   // flag.
486   if (!M.getModuleInlineAsm().empty() && TT.isThumb())
487     OutStreamer->emitAssemblerFlag(MCAF_Code16);
488 }
489 
490 static void
491 emitNonLazySymbolPointer(MCStreamer &OutStreamer, MCSymbol *StubLabel,
492                          MachineModuleInfoImpl::StubValueTy &MCSym) {
493   // L_foo$stub:
494   OutStreamer.emitLabel(StubLabel);
495   //   .indirect_symbol _foo
496   OutStreamer.emitSymbolAttribute(MCSym.getPointer(), MCSA_IndirectSymbol);
497 
498   if (MCSym.getInt())
499     // External to current translation unit.
500     OutStreamer.emitIntValue(0, 4/*size*/);
501   else
502     // Internal to current translation unit.
503     //
504     // When we place the LSDA into the TEXT section, the type info
505     // pointers need to be indirect and pc-rel. We accomplish this by
506     // using NLPs; however, sometimes the types are local to the file.
507     // We need to fill in the value for the NLP in those cases.
508     OutStreamer.emitValue(
509         MCSymbolRefExpr::create(MCSym.getPointer(), OutStreamer.getContext()),
510         4 /*size*/);
511 }
512 
513 
514 void ARMAsmPrinter::emitEndOfAsmFile(Module &M) {
515   const Triple &TT = TM.getTargetTriple();
516   if (TT.isOSBinFormatMachO()) {
517     // All darwin targets use mach-o.
518     const TargetLoweringObjectFileMachO &TLOFMacho =
519       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
520     MachineModuleInfoMachO &MMIMacho =
521       MMI->getObjFileInfo<MachineModuleInfoMachO>();
522 
523     // Output non-lazy-pointers for external and common global variables.
524     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
525 
526     if (!Stubs.empty()) {
527       // Switch with ".non_lazy_symbol_pointer" directive.
528       OutStreamer->SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
529       emitAlignment(Align(4));
530 
531       for (auto &Stub : Stubs)
532         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
533 
534       Stubs.clear();
535       OutStreamer->AddBlankLine();
536     }
537 
538     Stubs = MMIMacho.GetThreadLocalGVStubList();
539     if (!Stubs.empty()) {
540       // Switch with ".non_lazy_symbol_pointer" directive.
541       OutStreamer->SwitchSection(TLOFMacho.getThreadLocalPointerSection());
542       emitAlignment(Align(4));
543 
544       for (auto &Stub : Stubs)
545         emitNonLazySymbolPointer(*OutStreamer, Stub.first, Stub.second);
546 
547       Stubs.clear();
548       OutStreamer->AddBlankLine();
549     }
550 
551     // Funny Darwin hack: This flag tells the linker that no global symbols
552     // contain code that falls through to other global symbols (e.g. the obvious
553     // implementation of multiple entry points).  If this doesn't occur, the
554     // linker can safely perform dead code stripping.  Since LLVM never
555     // generates code that does this, it is always safe to set.
556     OutStreamer->emitAssemblerFlag(MCAF_SubsectionsViaSymbols);
557   }
558 
559   // The last attribute to be emitted is ABI_optimization_goals
560   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
561   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
562 
563   if (OptimizationGoals > 0 &&
564       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
565        Subtarget->isTargetMuslAEABI()))
566     ATS.emitAttribute(ARMBuildAttrs::ABI_optimization_goals, OptimizationGoals);
567   OptimizationGoals = -1;
568 
569   ATS.finishAttributeSection();
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 
579  // Returns true if all functions have the same function attribute value.
580  // It also returns true when the module has no functions.
581 static bool checkFunctionsAttributeConsistency(const Module &M, StringRef Attr,
582                                                StringRef Value) {
583    return !any_of(M, [&](const Function &F) {
584        return F.getFnAttribute(Attr).getValueAsString() != Value;
585    });
586 }
587 // Returns true if all functions have the same denormal mode.
588 // It also returns true when the module has no functions.
589 static bool checkDenormalAttributeConsistency(const Module &M,
590                                               StringRef Attr,
591                                               DenormalMode Value) {
592   return !any_of(M, [&](const Function &F) {
593     StringRef AttrVal = F.getFnAttribute(Attr).getValueAsString();
594     return parseDenormalFPAttribute(AttrVal) != Value;
595   });
596 }
597 
598 void ARMAsmPrinter::emitAttributes() {
599   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
600   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
601 
602   ATS.emitTextAttribute(ARMBuildAttrs::conformance, "2.09");
603 
604   ATS.switchVendor("aeabi");
605 
606   // Compute ARM ELF Attributes based on the default subtarget that
607   // we'd have constructed. The existing ARM behavior isn't LTO clean
608   // anyhow.
609   // FIXME: For ifunc related functions we could iterate over and look
610   // for a feature string that doesn't match the default one.
611   const Triple &TT = TM.getTargetTriple();
612   StringRef CPU = TM.getTargetCPU();
613   StringRef FS = TM.getTargetFeatureString();
614   std::string ArchFS = ARM_MC::ParseARMTriple(TT, CPU);
615   if (!FS.empty()) {
616     if (!ArchFS.empty())
617       ArchFS = (Twine(ArchFS) + "," + FS).str();
618     else
619       ArchFS = std::string(FS);
620   }
621   const ARMBaseTargetMachine &ATM =
622       static_cast<const ARMBaseTargetMachine &>(TM);
623   const ARMSubtarget STI(TT, std::string(CPU), ArchFS, ATM,
624                          ATM.isLittleEndian());
625 
626   // Emit build attributes for the available hardware.
627   ATS.emitTargetAttributes(STI);
628 
629   // RW data addressing.
630   if (isPositionIndependent()) {
631     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
632                       ARMBuildAttrs::AddressRWPCRel);
633   } else if (STI.isRWPI()) {
634     // RWPI specific attributes.
635     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RW_data,
636                       ARMBuildAttrs::AddressRWSBRel);
637   }
638 
639   // RO data addressing.
640   if (isPositionIndependent() || STI.isROPI()) {
641     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_RO_data,
642                       ARMBuildAttrs::AddressROPCRel);
643   }
644 
645   // GOT use.
646   if (isPositionIndependent()) {
647     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
648                       ARMBuildAttrs::AddressGOT);
649   } else {
650     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_GOT_use,
651                       ARMBuildAttrs::AddressDirect);
652   }
653 
654   // Set FP Denormals.
655   if (checkDenormalAttributeConsistency(*MMI->getModule(),
656                                         "denormal-fp-math",
657                                         DenormalMode::getPreserveSign()) ||
658       TM.Options.FPDenormalMode == FPDenormal::PreserveSign)
659     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
660                       ARMBuildAttrs::PreserveFPSign);
661   else if (checkDenormalAttributeConsistency(*MMI->getModule(),
662                                              "denormal-fp-math",
663                                              DenormalMode::getPositiveZero()) ||
664            TM.Options.FPDenormalMode == FPDenormal::PositiveZero)
665     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
666                       ARMBuildAttrs::PositiveZero);
667   else if (!TM.Options.UnsafeFPMath)
668     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
669                       ARMBuildAttrs::IEEEDenormals);
670   else {
671     if (!STI.hasVFP2Base()) {
672       // When the target doesn't have an FPU (by design or
673       // intention), the assumptions made on the software support
674       // mirror that of the equivalent hardware support *if it
675       // existed*. For v7 and better we indicate that denormals are
676       // flushed preserving sign, and for V6 we indicate that
677       // denormals are flushed to positive zero.
678       if (STI.hasV7Ops())
679         ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
680                           ARMBuildAttrs::PreserveFPSign);
681     } else if (STI.hasVFP3Base()) {
682       // In VFPv4, VFPv4U, VFPv3, or VFPv3U, it is preserved. That is,
683       // the sign bit of the zero matches the sign bit of the input or
684       // result that is being flushed to zero.
685       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal,
686                         ARMBuildAttrs::PreserveFPSign);
687     }
688     // For VFPv2 implementations it is implementation defined as
689     // to whether denormals are flushed to positive zero or to
690     // whatever the sign of zero is (ARM v7AR ARM 2.7.5). Historically
691     // LLVM has chosen to flush this to positive zero (most likely for
692     // GCC compatibility), so that's the chosen value here (the
693     // absence of its emission implies zero).
694   }
695 
696   // Set FP exceptions and rounding
697   if (checkFunctionsAttributeConsistency(*MMI->getModule(),
698                                          "no-trapping-math", "true") ||
699       TM.Options.NoTrappingFPMath)
700     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
701                       ARMBuildAttrs::Not_Allowed);
702   else if (!TM.Options.UnsafeFPMath) {
703     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions, ARMBuildAttrs::Allowed);
704 
705     // If the user has permitted this code to choose the IEEE 754
706     // rounding at run-time, emit the rounding attribute.
707     if (TM.Options.HonorSignDependentRoundingFPMathOption)
708       ATS.emitAttribute(ARMBuildAttrs::ABI_FP_rounding, ARMBuildAttrs::Allowed);
709   }
710 
711   // TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath is the
712   // equivalent of GCC's -ffinite-math-only flag.
713   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
714     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
715                       ARMBuildAttrs::Allowed);
716   else
717     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
718                       ARMBuildAttrs::AllowIEEE754);
719 
720   // FIXME: add more flags to ARMBuildAttributes.h
721   // 8-bytes alignment stuff.
722   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
723   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
724 
725   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
726   if (STI.isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
727     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
728 
729   // FIXME: To support emitting this build attribute as GCC does, the
730   // -mfp16-format option and associated plumbing must be
731   // supported. For now the __fp16 type is exposed by default, so this
732   // attribute should be emitted with value 1.
733   ATS.emitAttribute(ARMBuildAttrs::ABI_FP_16bit_format,
734                     ARMBuildAttrs::FP16FormatIEEE);
735 
736   if (MMI) {
737     if (const Module *SourceModule = MMI->getModule()) {
738       // ABI_PCS_wchar_t to indicate wchar_t width
739       // FIXME: There is no way to emit value 0 (wchar_t prohibited).
740       if (auto WCharWidthValue = mdconst::extract_or_null<ConstantInt>(
741               SourceModule->getModuleFlag("wchar_size"))) {
742         int WCharWidth = WCharWidthValue->getZExtValue();
743         assert((WCharWidth == 2 || WCharWidth == 4) &&
744                "wchar_t width must be 2 or 4 bytes");
745         ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
746       }
747 
748       // ABI_enum_size to indicate enum width
749       // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
750       //        (all enums contain a value needing 32 bits to encode).
751       if (auto EnumWidthValue = mdconst::extract_or_null<ConstantInt>(
752               SourceModule->getModuleFlag("min_enum_size"))) {
753         int EnumWidth = EnumWidthValue->getZExtValue();
754         assert((EnumWidth == 1 || EnumWidth == 4) &&
755                "Minimum enum width must be 1 or 4 bytes");
756         int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
757         ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
758       }
759     }
760   }
761 
762   // We currently do not support using R9 as the TLS pointer.
763   if (STI.isRWPI())
764     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
765                       ARMBuildAttrs::R9IsSB);
766   else if (STI.isR9Reserved())
767     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
768                       ARMBuildAttrs::R9Reserved);
769   else
770     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
771                       ARMBuildAttrs::R9IsGPR);
772 }
773 
774 //===----------------------------------------------------------------------===//
775 
776 static MCSymbol *getBFLabel(StringRef Prefix, unsigned FunctionNumber,
777                              unsigned LabelId, MCContext &Ctx) {
778 
779   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
780                        + "BF" + Twine(FunctionNumber) + "_" + Twine(LabelId));
781   return Label;
782 }
783 
784 static MCSymbol *getPICLabel(StringRef Prefix, unsigned FunctionNumber,
785                              unsigned LabelId, MCContext &Ctx) {
786 
787   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
788                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
789   return Label;
790 }
791 
792 static MCSymbolRefExpr::VariantKind
793 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
794   switch (Modifier) {
795   case ARMCP::no_modifier:
796     return MCSymbolRefExpr::VK_None;
797   case ARMCP::TLSGD:
798     return MCSymbolRefExpr::VK_TLSGD;
799   case ARMCP::TPOFF:
800     return MCSymbolRefExpr::VK_TPOFF;
801   case ARMCP::GOTTPOFF:
802     return MCSymbolRefExpr::VK_GOTTPOFF;
803   case ARMCP::SBREL:
804     return MCSymbolRefExpr::VK_ARM_SBREL;
805   case ARMCP::GOT_PREL:
806     return MCSymbolRefExpr::VK_ARM_GOT_PREL;
807   case ARMCP::SECREL:
808     return MCSymbolRefExpr::VK_SECREL;
809   }
810   llvm_unreachable("Invalid ARMCPModifier!");
811 }
812 
813 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
814                                         unsigned char TargetFlags) {
815   if (Subtarget->isTargetMachO()) {
816     bool IsIndirect =
817         (TargetFlags & ARMII::MO_NONLAZY) && Subtarget->isGVIndirectSymbol(GV);
818 
819     if (!IsIndirect)
820       return getSymbol(GV);
821 
822     // FIXME: Remove this when Darwin transition to @GOT like syntax.
823     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
824     MachineModuleInfoMachO &MMIMachO =
825       MMI->getObjFileInfo<MachineModuleInfoMachO>();
826     MachineModuleInfoImpl::StubValueTy &StubSym =
827         GV->isThreadLocal() ? MMIMachO.getThreadLocalGVStubEntry(MCSym)
828                             : MMIMachO.getGVStubEntry(MCSym);
829 
830     if (!StubSym.getPointer())
831       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
832                                                    !GV->hasInternalLinkage());
833     return MCSym;
834   } else if (Subtarget->isTargetCOFF()) {
835     assert(Subtarget->isTargetWindows() &&
836            "Windows is the only supported COFF target");
837 
838     bool IsIndirect =
839         (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB));
840     if (!IsIndirect)
841       return getSymbol(GV);
842 
843     SmallString<128> Name;
844     if (TargetFlags & ARMII::MO_DLLIMPORT)
845       Name = "__imp_";
846     else if (TargetFlags & ARMII::MO_COFFSTUB)
847       Name = ".refptr.";
848     getNameWithPrefix(Name, GV);
849 
850     MCSymbol *MCSym = OutContext.getOrCreateSymbol(Name);
851 
852     if (TargetFlags & ARMII::MO_COFFSTUB) {
853       MachineModuleInfoCOFF &MMICOFF =
854           MMI->getObjFileInfo<MachineModuleInfoCOFF>();
855       MachineModuleInfoImpl::StubValueTy &StubSym =
856           MMICOFF.getGVStubEntry(MCSym);
857 
858       if (!StubSym.getPointer())
859         StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV), true);
860     }
861 
862     return MCSym;
863   } else if (Subtarget->isTargetELF()) {
864     return getSymbol(GV);
865   }
866   llvm_unreachable("unexpected target");
867 }
868 
869 void ARMAsmPrinter::emitMachineConstantPoolValue(
870     MachineConstantPoolValue *MCPV) {
871   const DataLayout &DL = getDataLayout();
872   int Size = DL.getTypeAllocSize(MCPV->getType());
873 
874   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
875 
876   if (ACPV->isPromotedGlobal()) {
877     // This constant pool entry is actually a global whose storage has been
878     // promoted into the constant pool. This global may be referenced still
879     // by debug information, and due to the way AsmPrinter is set up, the debug
880     // info is immutable by the time we decide to promote globals to constant
881     // pools. Because of this, we need to ensure we emit a symbol for the global
882     // with private linkage (the default) so debug info can refer to it.
883     //
884     // However, if this global is promoted into several functions we must ensure
885     // we don't try and emit duplicate symbols!
886     auto *ACPC = cast<ARMConstantPoolConstant>(ACPV);
887     for (const auto *GV : ACPC->promotedGlobals()) {
888       if (!EmittedPromotedGlobalLabels.count(GV)) {
889         MCSymbol *GVSym = getSymbol(GV);
890         OutStreamer->emitLabel(GVSym);
891         EmittedPromotedGlobalLabels.insert(GV);
892       }
893     }
894     return emitGlobalConstant(DL, ACPC->getPromotedGlobalInit());
895   }
896 
897   MCSymbol *MCSym;
898   if (ACPV->isLSDA()) {
899     MCSym = getCurExceptionSym();
900   } else if (ACPV->isBlockAddress()) {
901     const BlockAddress *BA =
902       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
903     MCSym = GetBlockAddressSymbol(BA);
904   } else if (ACPV->isGlobalValue()) {
905     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
906 
907     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
908     // flag the global as MO_NONLAZY.
909     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
910     MCSym = GetARMGVSymbol(GV, TF);
911   } else if (ACPV->isMachineBasicBlock()) {
912     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
913     MCSym = MBB->getSymbol();
914   } else {
915     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
916     auto Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
917     MCSym = GetExternalSymbolSymbol(Sym);
918   }
919 
920   // Create an MCSymbol for the reference.
921   const MCExpr *Expr =
922     MCSymbolRefExpr::create(MCSym, getModifierVariantKind(ACPV->getModifier()),
923                             OutContext);
924 
925   if (ACPV->getPCAdjustment()) {
926     MCSymbol *PCLabel =
927         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
928                     ACPV->getLabelId(), OutContext);
929     const MCExpr *PCRelExpr = MCSymbolRefExpr::create(PCLabel, OutContext);
930     PCRelExpr =
931       MCBinaryExpr::createAdd(PCRelExpr,
932                               MCConstantExpr::create(ACPV->getPCAdjustment(),
933                                                      OutContext),
934                               OutContext);
935     if (ACPV->mustAddCurrentAddress()) {
936       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
937       // label, so just emit a local label end reference that instead.
938       MCSymbol *DotSym = OutContext.createTempSymbol();
939       OutStreamer->emitLabel(DotSym);
940       const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
941       PCRelExpr = MCBinaryExpr::createSub(PCRelExpr, DotExpr, OutContext);
942     }
943     Expr = MCBinaryExpr::createSub(Expr, PCRelExpr, OutContext);
944   }
945   OutStreamer->emitValue(Expr, Size);
946 }
947 
948 void ARMAsmPrinter::emitJumpTableAddrs(const MachineInstr *MI) {
949   const MachineOperand &MO1 = MI->getOperand(1);
950   unsigned JTI = MO1.getIndex();
951 
952   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
953   // ARM mode tables.
954   emitAlignment(Align(4));
955 
956   // Emit a label for the jump table.
957   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
958   OutStreamer->emitLabel(JTISymbol);
959 
960   // Mark the jump table as data-in-code.
961   OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
962 
963   // Emit each entry of the table.
964   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
965   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
966   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
967 
968   for (MachineBasicBlock *MBB : JTBBs) {
969     // Construct an MCExpr for the entry. We want a value of the form:
970     // (BasicBlockAddr - TableBeginAddr)
971     //
972     // For example, a table with entries jumping to basic blocks BB0 and BB1
973     // would look like:
974     // LJTI_0_0:
975     //    .word (LBB0 - LJTI_0_0)
976     //    .word (LBB1 - LJTI_0_0)
977     const MCExpr *Expr = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
978 
979     if (isPositionIndependent() || Subtarget->isROPI())
980       Expr = MCBinaryExpr::createSub(Expr, MCSymbolRefExpr::create(JTISymbol,
981                                                                    OutContext),
982                                      OutContext);
983     // If we're generating a table of Thumb addresses in static relocation
984     // model, we need to add one to keep interworking correctly.
985     else if (AFI->isThumbFunction())
986       Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(1,OutContext),
987                                      OutContext);
988     OutStreamer->emitValue(Expr, 4);
989   }
990   // Mark the end of jump table data-in-code region.
991   OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
992 }
993 
994 void ARMAsmPrinter::emitJumpTableInsts(const MachineInstr *MI) {
995   const MachineOperand &MO1 = MI->getOperand(1);
996   unsigned JTI = MO1.getIndex();
997 
998   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
999   // ARM mode tables.
1000   emitAlignment(Align(4));
1001 
1002   // Emit a label for the jump table.
1003   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1004   OutStreamer->emitLabel(JTISymbol);
1005 
1006   // Emit each entry of the table.
1007   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1008   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1009   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1010 
1011   for (MachineBasicBlock *MBB : JTBBs) {
1012     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1013                                                           OutContext);
1014     // If this isn't a TBB or TBH, the entries are direct branch instructions.
1015     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2B)
1016         .addExpr(MBBSymbolExpr)
1017         .addImm(ARMCC::AL)
1018         .addReg(0));
1019   }
1020 }
1021 
1022 void ARMAsmPrinter::emitJumpTableTBInst(const MachineInstr *MI,
1023                                         unsigned OffsetWidth) {
1024   assert((OffsetWidth == 1 || OffsetWidth == 2) && "invalid tbb/tbh width");
1025   const MachineOperand &MO1 = MI->getOperand(1);
1026   unsigned JTI = MO1.getIndex();
1027 
1028   if (Subtarget->isThumb1Only())
1029     emitAlignment(Align(4));
1030 
1031   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1032   OutStreamer->emitLabel(JTISymbol);
1033 
1034   // Emit each entry of the table.
1035   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1036   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1037   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1038 
1039   // Mark the jump table as data-in-code.
1040   OutStreamer->emitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
1041                                                : MCDR_DataRegionJT16);
1042 
1043   for (auto MBB : JTBBs) {
1044     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1045                                                           OutContext);
1046     // Otherwise it's an offset from the dispatch instruction. Construct an
1047     // MCExpr for the entry. We want a value of the form:
1048     // (BasicBlockAddr - TBBInstAddr + 4) / 2
1049     //
1050     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1051     // would look like:
1052     // LJTI_0_0:
1053     //    .byte (LBB0 - (LCPI0_0 + 4)) / 2
1054     //    .byte (LBB1 - (LCPI0_0 + 4)) / 2
1055     // where LCPI0_0 is a label defined just before the TBB instruction using
1056     // this table.
1057     MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
1058     const MCExpr *Expr = MCBinaryExpr::createAdd(
1059         MCSymbolRefExpr::create(TBInstPC, OutContext),
1060         MCConstantExpr::create(4, OutContext), OutContext);
1061     Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
1062     Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
1063                                    OutContext);
1064     OutStreamer->emitValue(Expr, OffsetWidth);
1065   }
1066   // Mark the end of jump table data-in-code region. 32-bit offsets use
1067   // actual branch instructions here, so we don't mark those as a data-region
1068   // at all.
1069   OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
1070 
1071   // Make sure the next instruction is 2-byte aligned.
1072   emitAlignment(Align(2));
1073 }
1074 
1075 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1076   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1077       "Only instruction which are involved into frame setup code are allowed");
1078 
1079   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1080   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1081   const MachineFunction &MF = *MI->getParent()->getParent();
1082   const TargetRegisterInfo *TargetRegInfo =
1083     MF.getSubtarget().getRegisterInfo();
1084   const MachineRegisterInfo &MachineRegInfo = MF.getRegInfo();
1085 
1086   Register FramePtr = TargetRegInfo->getFrameRegister(MF);
1087   unsigned Opc = MI->getOpcode();
1088   unsigned SrcReg, DstReg;
1089 
1090   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1091     // Two special cases:
1092     // 1) tPUSH does not have src/dst regs.
1093     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1094     // load. Yes, this is pretty fragile, but for now I don't see better
1095     // way... :(
1096     SrcReg = DstReg = ARM::SP;
1097   } else {
1098     SrcReg = MI->getOperand(1).getReg();
1099     DstReg = MI->getOperand(0).getReg();
1100   }
1101 
1102   // Try to figure out the unwinding opcode out of src / dst regs.
1103   if (MI->mayStore()) {
1104     // Register saves.
1105     assert(DstReg == ARM::SP &&
1106            "Only stack pointer as a destination reg is supported");
1107 
1108     SmallVector<unsigned, 4> RegList;
1109     // Skip src & dst reg, and pred ops.
1110     unsigned StartOp = 2 + 2;
1111     // Use all the operands.
1112     unsigned NumOffset = 0;
1113     // Amount of SP adjustment folded into a push.
1114     unsigned Pad = 0;
1115 
1116     switch (Opc) {
1117     default:
1118       MI->print(errs());
1119       llvm_unreachable("Unsupported opcode for unwinding information");
1120     case ARM::tPUSH:
1121       // Special case here: no src & dst reg, but two extra imp ops.
1122       StartOp = 2; NumOffset = 2;
1123       LLVM_FALLTHROUGH;
1124     case ARM::STMDB_UPD:
1125     case ARM::t2STMDB_UPD:
1126     case ARM::VSTMDDB_UPD:
1127       assert(SrcReg == ARM::SP &&
1128              "Only stack pointer as a source reg is supported");
1129       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1130            i != NumOps; ++i) {
1131         const MachineOperand &MO = MI->getOperand(i);
1132         // Actually, there should never be any impdef stuff here. Skip it
1133         // temporary to workaround PR11902.
1134         if (MO.isImplicit())
1135           continue;
1136         // Registers, pushed as a part of folding an SP update into the
1137         // push instruction are marked as undef and should not be
1138         // restored when unwinding, because the function can modify the
1139         // corresponding stack slots.
1140         if (MO.isUndef()) {
1141           assert(RegList.empty() &&
1142                  "Pad registers must come before restored ones");
1143           unsigned Width =
1144             TargetRegInfo->getRegSizeInBits(MO.getReg(), MachineRegInfo) / 8;
1145           Pad += Width;
1146           continue;
1147         }
1148         // Check for registers that are remapped (for a Thumb1 prologue that
1149         // saves high registers).
1150         Register Reg = MO.getReg();
1151         if (unsigned RemappedReg = AFI->EHPrologueRemappedRegs.lookup(Reg))
1152           Reg = RemappedReg;
1153         RegList.push_back(Reg);
1154       }
1155       break;
1156     case ARM::STR_PRE_IMM:
1157     case ARM::STR_PRE_REG:
1158     case ARM::t2STR_PRE:
1159       assert(MI->getOperand(2).getReg() == ARM::SP &&
1160              "Only stack pointer as a source reg is supported");
1161       RegList.push_back(SrcReg);
1162       break;
1163     }
1164     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1165       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1166       // Account for the SP adjustment, folded into the push.
1167       if (Pad)
1168         ATS.emitPad(Pad);
1169     }
1170   } else {
1171     // Changes of stack / frame pointer.
1172     if (SrcReg == ARM::SP) {
1173       int64_t Offset = 0;
1174       switch (Opc) {
1175       default:
1176         MI->print(errs());
1177         llvm_unreachable("Unsupported opcode for unwinding information");
1178       case ARM::MOVr:
1179       case ARM::tMOVr:
1180         Offset = 0;
1181         break;
1182       case ARM::ADDri:
1183       case ARM::t2ADDri:
1184       case ARM::t2ADDri12:
1185       case ARM::t2ADDspImm:
1186       case ARM::t2ADDspImm12:
1187         Offset = -MI->getOperand(2).getImm();
1188         break;
1189       case ARM::SUBri:
1190       case ARM::t2SUBri:
1191       case ARM::t2SUBri12:
1192       case ARM::t2SUBspImm:
1193       case ARM::t2SUBspImm12:
1194         Offset = MI->getOperand(2).getImm();
1195         break;
1196       case ARM::tSUBspi:
1197         Offset = MI->getOperand(2).getImm()*4;
1198         break;
1199       case ARM::tADDspi:
1200       case ARM::tADDrSPi:
1201         Offset = -MI->getOperand(2).getImm()*4;
1202         break;
1203       case ARM::tLDRpci: {
1204         // Grab the constpool index and check, whether it corresponds to
1205         // original or cloned constpool entry.
1206         unsigned CPI = MI->getOperand(1).getIndex();
1207         const MachineConstantPool *MCP = MF.getConstantPool();
1208         if (CPI >= MCP->getConstants().size())
1209           CPI = AFI->getOriginalCPIdx(CPI);
1210         assert(CPI != -1U && "Invalid constpool index");
1211 
1212         // Derive the actual offset.
1213         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1214         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1215         // FIXME: Check for user, it should be "add" instruction!
1216         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1217         break;
1218       }
1219       }
1220 
1221       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1222         if (DstReg == FramePtr && FramePtr != ARM::SP)
1223           // Set-up of the frame pointer. Positive values correspond to "add"
1224           // instruction.
1225           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1226         else if (DstReg == ARM::SP) {
1227           // Change of SP by an offset. Positive values correspond to "sub"
1228           // instruction.
1229           ATS.emitPad(Offset);
1230         } else {
1231           // Move of SP to a register.  Positive values correspond to an "add"
1232           // instruction.
1233           ATS.emitMovSP(DstReg, -Offset);
1234         }
1235       }
1236     } else if (DstReg == ARM::SP) {
1237       MI->print(errs());
1238       llvm_unreachable("Unsupported opcode for unwinding information");
1239     } else if (Opc == ARM::tMOVr) {
1240       // If a Thumb1 function spills r8-r11, we copy the values to low
1241       // registers before pushing them. Record the copy so we can emit the
1242       // correct ".save" later.
1243       AFI->EHPrologueRemappedRegs[DstReg] = SrcReg;
1244     } else {
1245       MI->print(errs());
1246       llvm_unreachable("Unsupported opcode for unwinding information");
1247     }
1248   }
1249 }
1250 
1251 // Simple pseudo-instructions have their lowering (with expansion to real
1252 // instructions) auto-generated.
1253 #include "ARMGenMCPseudoLowering.inc"
1254 
1255 void ARMAsmPrinter::emitInstruction(const MachineInstr *MI) {
1256   const DataLayout &DL = getDataLayout();
1257   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1258   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1259 
1260   const MachineFunction &MF = *MI->getParent()->getParent();
1261   const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>();
1262   unsigned FramePtr = STI.useR7AsFramePointer() ? ARM::R7 : ARM::R11;
1263 
1264   // If we just ended a constant pool, mark it as such.
1265   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1266     OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
1267     InConstantPool = false;
1268   }
1269 
1270   // Emit unwinding stuff for frame-related instructions
1271   if (Subtarget->isTargetEHABICompatible() &&
1272        MI->getFlag(MachineInstr::FrameSetup))
1273     EmitUnwindingInstruction(MI);
1274 
1275   // Do any auto-generated pseudo lowerings.
1276   if (emitPseudoExpansionLowering(*OutStreamer, MI))
1277     return;
1278 
1279   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1280          "Pseudo flag setting opcode should be expanded early");
1281 
1282   // Check for manual lowerings.
1283   unsigned Opc = MI->getOpcode();
1284   switch (Opc) {
1285   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1286   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1287   case ARM::LEApcrel:
1288   case ARM::tLEApcrel:
1289   case ARM::t2LEApcrel: {
1290     // FIXME: Need to also handle globals and externals
1291     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1292     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1293                                                ARM::t2LEApcrel ? ARM::t2ADR
1294                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1295                      : ARM::ADR))
1296       .addReg(MI->getOperand(0).getReg())
1297       .addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
1298       // Add predicate operands.
1299       .addImm(MI->getOperand(2).getImm())
1300       .addReg(MI->getOperand(3).getReg()));
1301     return;
1302   }
1303   case ARM::LEApcrelJT:
1304   case ARM::tLEApcrelJT:
1305   case ARM::t2LEApcrelJT: {
1306     MCSymbol *JTIPICSymbol =
1307       GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
1308     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1309                                                ARM::t2LEApcrelJT ? ARM::t2ADR
1310                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1311                      : ARM::ADR))
1312       .addReg(MI->getOperand(0).getReg())
1313       .addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
1314       // Add predicate operands.
1315       .addImm(MI->getOperand(2).getImm())
1316       .addReg(MI->getOperand(3).getReg()));
1317     return;
1318   }
1319   // Darwin call instructions are just normal call instructions with different
1320   // clobber semantics (they clobber R9).
1321   case ARM::BX_CALL: {
1322     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1323       .addReg(ARM::LR)
1324       .addReg(ARM::PC)
1325       // Add predicate operands.
1326       .addImm(ARMCC::AL)
1327       .addReg(0)
1328       // Add 's' bit operand (always reg0 for this)
1329       .addReg(0));
1330 
1331     assert(Subtarget->hasV4TOps());
1332     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1333       .addReg(MI->getOperand(0).getReg()));
1334     return;
1335   }
1336   case ARM::tBX_CALL: {
1337     if (Subtarget->hasV5TOps())
1338       llvm_unreachable("Expected BLX to be selected for v5t+");
1339 
1340     // On ARM v4t, when doing a call from thumb mode, we need to ensure
1341     // that the saved lr has its LSB set correctly (the arch doesn't
1342     // have blx).
1343     // So here we generate a bl to a small jump pad that does bx rN.
1344     // The jump pads are emitted after the function body.
1345 
1346     Register TReg = MI->getOperand(0).getReg();
1347     MCSymbol *TRegSym = nullptr;
1348     for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
1349       if (TIP.first == TReg) {
1350         TRegSym = TIP.second;
1351         break;
1352       }
1353     }
1354 
1355     if (!TRegSym) {
1356       TRegSym = OutContext.createTempSymbol();
1357       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
1358     }
1359 
1360     // Create a link-saving branch to the Reg Indirect Jump Pad.
1361     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
1362         // Predicate comes first here.
1363         .addImm(ARMCC::AL).addReg(0)
1364         .addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
1365     return;
1366   }
1367   case ARM::BMOVPCRX_CALL: {
1368     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1369       .addReg(ARM::LR)
1370       .addReg(ARM::PC)
1371       // Add predicate operands.
1372       .addImm(ARMCC::AL)
1373       .addReg(0)
1374       // Add 's' bit operand (always reg0 for this)
1375       .addReg(0));
1376 
1377     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1378       .addReg(ARM::PC)
1379       .addReg(MI->getOperand(0).getReg())
1380       // Add predicate operands.
1381       .addImm(ARMCC::AL)
1382       .addReg(0)
1383       // Add 's' bit operand (always reg0 for this)
1384       .addReg(0));
1385     return;
1386   }
1387   case ARM::BMOVPCB_CALL: {
1388     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1389       .addReg(ARM::LR)
1390       .addReg(ARM::PC)
1391       // Add predicate operands.
1392       .addImm(ARMCC::AL)
1393       .addReg(0)
1394       // Add 's' bit operand (always reg0 for this)
1395       .addReg(0));
1396 
1397     const MachineOperand &Op = MI->getOperand(0);
1398     const GlobalValue *GV = Op.getGlobal();
1399     const unsigned TF = Op.getTargetFlags();
1400     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1401     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1402     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
1403       .addExpr(GVSymExpr)
1404       // Add predicate operands.
1405       .addImm(ARMCC::AL)
1406       .addReg(0));
1407     return;
1408   }
1409   case ARM::MOVi16_ga_pcrel:
1410   case ARM::t2MOVi16_ga_pcrel: {
1411     MCInst TmpInst;
1412     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1413     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1414 
1415     unsigned TF = MI->getOperand(1).getTargetFlags();
1416     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1417     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1418     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1419 
1420     MCSymbol *LabelSym =
1421         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1422                     MI->getOperand(2).getImm(), OutContext);
1423     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1424     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1425     const MCExpr *PCRelExpr =
1426       ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
1427                                       MCBinaryExpr::createAdd(LabelSymExpr,
1428                                       MCConstantExpr::create(PCAdj, OutContext),
1429                                       OutContext), OutContext), OutContext);
1430       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1431 
1432     // Add predicate operands.
1433     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1434     TmpInst.addOperand(MCOperand::createReg(0));
1435     // Add 's' bit operand (always reg0 for this)
1436     TmpInst.addOperand(MCOperand::createReg(0));
1437     EmitToStreamer(*OutStreamer, TmpInst);
1438     return;
1439   }
1440   case ARM::MOVTi16_ga_pcrel:
1441   case ARM::t2MOVTi16_ga_pcrel: {
1442     MCInst TmpInst;
1443     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1444                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1445     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1446     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1447 
1448     unsigned TF = MI->getOperand(2).getTargetFlags();
1449     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1450     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1451     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1452 
1453     MCSymbol *LabelSym =
1454         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1455                     MI->getOperand(3).getImm(), OutContext);
1456     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1457     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1458     const MCExpr *PCRelExpr =
1459         ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
1460                                    MCBinaryExpr::createAdd(LabelSymExpr,
1461                                       MCConstantExpr::create(PCAdj, OutContext),
1462                                           OutContext), OutContext), OutContext);
1463       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
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     TmpInst.addOperand(MCOperand::createReg(0));
1469     EmitToStreamer(*OutStreamer, TmpInst);
1470     return;
1471   }
1472   case ARM::t2BFi:
1473   case ARM::t2BFic:
1474   case ARM::t2BFLi:
1475   case ARM::t2BFr:
1476   case ARM::t2BFLr: {
1477     // This is a Branch Future instruction.
1478 
1479     const MCExpr *BranchLabel = MCSymbolRefExpr::create(
1480         getBFLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1481                    MI->getOperand(0).getIndex(), OutContext),
1482         OutContext);
1483 
1484     auto MCInst = MCInstBuilder(Opc).addExpr(BranchLabel);
1485     if (MI->getOperand(1).isReg()) {
1486       // For BFr/BFLr
1487       MCInst.addReg(MI->getOperand(1).getReg());
1488     } else {
1489       // For BFi/BFLi/BFic
1490       const MCExpr *BranchTarget;
1491       if (MI->getOperand(1).isMBB())
1492         BranchTarget = MCSymbolRefExpr::create(
1493             MI->getOperand(1).getMBB()->getSymbol(), OutContext);
1494       else if (MI->getOperand(1).isGlobal()) {
1495         const GlobalValue *GV = MI->getOperand(1).getGlobal();
1496         BranchTarget = MCSymbolRefExpr::create(
1497             GetARMGVSymbol(GV, MI->getOperand(1).getTargetFlags()), OutContext);
1498       } else if (MI->getOperand(1).isSymbol()) {
1499         BranchTarget = MCSymbolRefExpr::create(
1500             GetExternalSymbolSymbol(MI->getOperand(1).getSymbolName()),
1501             OutContext);
1502       } else
1503         llvm_unreachable("Unhandled operand kind in Branch Future instruction");
1504 
1505       MCInst.addExpr(BranchTarget);
1506     }
1507 
1508       if (Opc == ARM::t2BFic) {
1509         const MCExpr *ElseLabel = MCSymbolRefExpr::create(
1510             getBFLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1511                        MI->getOperand(2).getIndex(), OutContext),
1512             OutContext);
1513         MCInst.addExpr(ElseLabel);
1514         MCInst.addImm(MI->getOperand(3).getImm());
1515       } else {
1516         MCInst.addImm(MI->getOperand(2).getImm())
1517             .addReg(MI->getOperand(3).getReg());
1518       }
1519 
1520     EmitToStreamer(*OutStreamer, MCInst);
1521     return;
1522   }
1523   case ARM::t2BF_LabelPseudo: {
1524     // This is a pseudo op for a label used by a branch future instruction
1525 
1526     // Emit the label.
1527     OutStreamer->emitLabel(getBFLabel(DL.getPrivateGlobalPrefix(),
1528                                        getFunctionNumber(),
1529                                        MI->getOperand(0).getIndex(), OutContext));
1530     return;
1531   }
1532   case ARM::tPICADD: {
1533     // This is a pseudo op for a label + instruction sequence, which looks like:
1534     // LPC0:
1535     //     add r0, pc
1536     // This adds the address of LPC0 to r0.
1537 
1538     // Emit the label.
1539     OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1540                                        getFunctionNumber(),
1541                                        MI->getOperand(2).getImm(), OutContext));
1542 
1543     // Form and emit the add.
1544     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1545       .addReg(MI->getOperand(0).getReg())
1546       .addReg(MI->getOperand(0).getReg())
1547       .addReg(ARM::PC)
1548       // Add predicate operands.
1549       .addImm(ARMCC::AL)
1550       .addReg(0));
1551     return;
1552   }
1553   case ARM::PICADD: {
1554     // This is a pseudo op for a label + instruction sequence, which looks like:
1555     // LPC0:
1556     //     add r0, pc, r0
1557     // This adds the address of LPC0 to r0.
1558 
1559     // Emit the label.
1560     OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1561                                        getFunctionNumber(),
1562                                        MI->getOperand(2).getImm(), OutContext));
1563 
1564     // Form and emit the add.
1565     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1566       .addReg(MI->getOperand(0).getReg())
1567       .addReg(ARM::PC)
1568       .addReg(MI->getOperand(1).getReg())
1569       // Add predicate operands.
1570       .addImm(MI->getOperand(3).getImm())
1571       .addReg(MI->getOperand(4).getReg())
1572       // Add 's' bit operand (always reg0 for this)
1573       .addReg(0));
1574     return;
1575   }
1576   case ARM::PICSTR:
1577   case ARM::PICSTRB:
1578   case ARM::PICSTRH:
1579   case ARM::PICLDR:
1580   case ARM::PICLDRB:
1581   case ARM::PICLDRH:
1582   case ARM::PICLDRSB:
1583   case ARM::PICLDRSH: {
1584     // This is a pseudo op for a label + instruction sequence, which looks like:
1585     // LPC0:
1586     //     OP r0, [pc, r0]
1587     // The LCP0 label is referenced by a constant pool entry in order to get
1588     // a PC-relative address at the ldr instruction.
1589 
1590     // Emit the label.
1591     OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1592                                        getFunctionNumber(),
1593                                        MI->getOperand(2).getImm(), OutContext));
1594 
1595     // Form and emit the load
1596     unsigned Opcode;
1597     switch (MI->getOpcode()) {
1598     default:
1599       llvm_unreachable("Unexpected opcode!");
1600     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1601     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1602     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1603     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1604     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1605     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1606     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1607     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1608     }
1609     EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
1610       .addReg(MI->getOperand(0).getReg())
1611       .addReg(ARM::PC)
1612       .addReg(MI->getOperand(1).getReg())
1613       .addImm(0)
1614       // Add predicate operands.
1615       .addImm(MI->getOperand(3).getImm())
1616       .addReg(MI->getOperand(4).getReg()));
1617 
1618     return;
1619   }
1620   case ARM::CONSTPOOL_ENTRY: {
1621     if (Subtarget->genExecuteOnly())
1622       llvm_unreachable("execute-only should not generate constant pools");
1623 
1624     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1625     /// in the function.  The first operand is the ID# for this instruction, the
1626     /// second is the index into the MachineConstantPool that this is, the third
1627     /// is the size in bytes of this constant pool entry.
1628     /// The required alignment is specified on the basic block holding this MI.
1629     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1630     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1631 
1632     // If this is the first entry of the pool, mark it.
1633     if (!InConstantPool) {
1634       OutStreamer->emitDataRegion(MCDR_DataRegion);
1635       InConstantPool = true;
1636     }
1637 
1638     OutStreamer->emitLabel(GetCPISymbol(LabelId));
1639 
1640     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1641     if (MCPE.isMachineConstantPoolEntry())
1642       emitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1643     else
1644       emitGlobalConstant(DL, MCPE.Val.ConstVal);
1645     return;
1646   }
1647   case ARM::JUMPTABLE_ADDRS:
1648     emitJumpTableAddrs(MI);
1649     return;
1650   case ARM::JUMPTABLE_INSTS:
1651     emitJumpTableInsts(MI);
1652     return;
1653   case ARM::JUMPTABLE_TBB:
1654   case ARM::JUMPTABLE_TBH:
1655     emitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
1656     return;
1657   case ARM::t2BR_JT: {
1658     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1659       .addReg(ARM::PC)
1660       .addReg(MI->getOperand(0).getReg())
1661       // Add predicate operands.
1662       .addImm(ARMCC::AL)
1663       .addReg(0));
1664     return;
1665   }
1666   case ARM::t2TBB_JT:
1667   case ARM::t2TBH_JT: {
1668     unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
1669     // Lower and emit the PC label, then the instruction itself.
1670     OutStreamer->emitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1671     EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1672                                      .addReg(MI->getOperand(0).getReg())
1673                                      .addReg(MI->getOperand(1).getReg())
1674                                      // Add predicate operands.
1675                                      .addImm(ARMCC::AL)
1676                                      .addReg(0));
1677     return;
1678   }
1679   case ARM::tTBB_JT:
1680   case ARM::tTBH_JT: {
1681 
1682     bool Is8Bit = MI->getOpcode() == ARM::tTBB_JT;
1683     Register Base = MI->getOperand(0).getReg();
1684     Register Idx = MI->getOperand(1).getReg();
1685     assert(MI->getOperand(1).isKill() && "We need the index register as scratch!");
1686 
1687     // Multiply up idx if necessary.
1688     if (!Is8Bit)
1689       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1690                                        .addReg(Idx)
1691                                        .addReg(ARM::CPSR)
1692                                        .addReg(Idx)
1693                                        .addImm(1)
1694                                        // Add predicate operands.
1695                                        .addImm(ARMCC::AL)
1696                                        .addReg(0));
1697 
1698     if (Base == ARM::PC) {
1699       // TBB [base, idx] =
1700       //    ADDS idx, idx, base
1701       //    LDRB idx, [idx, #4] ; or LDRH if TBH
1702       //    LSLS idx, #1
1703       //    ADDS pc, pc, idx
1704 
1705       // When using PC as the base, it's important that there is no padding
1706       // between the last ADDS and the start of the jump table. The jump table
1707       // is 4-byte aligned, so we ensure we're 4 byte aligned here too.
1708       //
1709       // FIXME: Ideally we could vary the LDRB index based on the padding
1710       // between the sequence and jump table, however that relies on MCExprs
1711       // for load indexes which are currently not supported.
1712       OutStreamer->emitCodeAlignment(4);
1713       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1714                                        .addReg(Idx)
1715                                        .addReg(Idx)
1716                                        .addReg(Base)
1717                                        // Add predicate operands.
1718                                        .addImm(ARMCC::AL)
1719                                        .addReg(0));
1720 
1721       unsigned Opc = Is8Bit ? ARM::tLDRBi : ARM::tLDRHi;
1722       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1723                                        .addReg(Idx)
1724                                        .addReg(Idx)
1725                                        .addImm(Is8Bit ? 4 : 2)
1726                                        // Add predicate operands.
1727                                        .addImm(ARMCC::AL)
1728                                        .addReg(0));
1729     } else {
1730       // TBB [base, idx] =
1731       //    LDRB idx, [base, idx] ; or LDRH if TBH
1732       //    LSLS idx, #1
1733       //    ADDS pc, pc, idx
1734 
1735       unsigned Opc = Is8Bit ? ARM::tLDRBr : ARM::tLDRHr;
1736       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1737                                        .addReg(Idx)
1738                                        .addReg(Base)
1739                                        .addReg(Idx)
1740                                        // Add predicate operands.
1741                                        .addImm(ARMCC::AL)
1742                                        .addReg(0));
1743     }
1744 
1745     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1746                                      .addReg(Idx)
1747                                      .addReg(ARM::CPSR)
1748                                      .addReg(Idx)
1749                                      .addImm(1)
1750                                      // Add predicate operands.
1751                                      .addImm(ARMCC::AL)
1752                                      .addReg(0));
1753 
1754     OutStreamer->emitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1755     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1756                                      .addReg(ARM::PC)
1757                                      .addReg(ARM::PC)
1758                                      .addReg(Idx)
1759                                      // Add predicate operands.
1760                                      .addImm(ARMCC::AL)
1761                                      .addReg(0));
1762     return;
1763   }
1764   case ARM::tBR_JTr:
1765   case ARM::BR_JTr: {
1766     // mov pc, target
1767     MCInst TmpInst;
1768     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1769       ARM::MOVr : ARM::tMOVr;
1770     TmpInst.setOpcode(Opc);
1771     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1772     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1773     // Add predicate operands.
1774     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1775     TmpInst.addOperand(MCOperand::createReg(0));
1776     // Add 's' bit operand (always reg0 for this)
1777     if (Opc == ARM::MOVr)
1778       TmpInst.addOperand(MCOperand::createReg(0));
1779     EmitToStreamer(*OutStreamer, TmpInst);
1780     return;
1781   }
1782   case ARM::BR_JTm_i12: {
1783     // ldr pc, target
1784     MCInst TmpInst;
1785     TmpInst.setOpcode(ARM::LDRi12);
1786     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1787     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1788     TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1789     // Add predicate operands.
1790     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1791     TmpInst.addOperand(MCOperand::createReg(0));
1792     EmitToStreamer(*OutStreamer, TmpInst);
1793     return;
1794   }
1795   case ARM::BR_JTm_rs: {
1796     // ldr pc, target
1797     MCInst TmpInst;
1798     TmpInst.setOpcode(ARM::LDRrs);
1799     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1800     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1801     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1802     TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1803     // Add predicate operands.
1804     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1805     TmpInst.addOperand(MCOperand::createReg(0));
1806     EmitToStreamer(*OutStreamer, TmpInst);
1807     return;
1808   }
1809   case ARM::BR_JTadd: {
1810     // add pc, target, idx
1811     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1812       .addReg(ARM::PC)
1813       .addReg(MI->getOperand(0).getReg())
1814       .addReg(MI->getOperand(1).getReg())
1815       // Add predicate operands.
1816       .addImm(ARMCC::AL)
1817       .addReg(0)
1818       // Add 's' bit operand (always reg0 for this)
1819       .addReg(0));
1820     return;
1821   }
1822   case ARM::SPACE:
1823     OutStreamer->emitZeros(MI->getOperand(1).getImm());
1824     return;
1825   case ARM::TRAP: {
1826     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1827     // FIXME: Remove this special case when they do.
1828     if (!Subtarget->isTargetMachO()) {
1829       uint32_t Val = 0xe7ffdefeUL;
1830       OutStreamer->AddComment("trap");
1831       ATS.emitInst(Val);
1832       return;
1833     }
1834     break;
1835   }
1836   case ARM::TRAPNaCl: {
1837     uint32_t Val = 0xe7fedef0UL;
1838     OutStreamer->AddComment("trap");
1839     ATS.emitInst(Val);
1840     return;
1841   }
1842   case ARM::tTRAP: {
1843     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1844     // FIXME: Remove this special case when they do.
1845     if (!Subtarget->isTargetMachO()) {
1846       uint16_t Val = 0xdefe;
1847       OutStreamer->AddComment("trap");
1848       ATS.emitInst(Val, 'n');
1849       return;
1850     }
1851     break;
1852   }
1853   case ARM::t2Int_eh_sjlj_setjmp:
1854   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1855   case ARM::tInt_eh_sjlj_setjmp: {
1856     // Two incoming args: GPR:$src, GPR:$val
1857     // mov $val, pc
1858     // adds $val, #7
1859     // str $val, [$src, #4]
1860     // movs r0, #0
1861     // b LSJLJEH
1862     // movs r0, #1
1863     // LSJLJEH:
1864     Register SrcReg = MI->getOperand(0).getReg();
1865     Register ValReg = MI->getOperand(1).getReg();
1866     MCSymbol *Label = OutContext.createTempSymbol("SJLJEH", false, true);
1867     OutStreamer->AddComment("eh_setjmp begin");
1868     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1869       .addReg(ValReg)
1870       .addReg(ARM::PC)
1871       // Predicate.
1872       .addImm(ARMCC::AL)
1873       .addReg(0));
1874 
1875     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
1876       .addReg(ValReg)
1877       // 's' bit operand
1878       .addReg(ARM::CPSR)
1879       .addReg(ValReg)
1880       .addImm(7)
1881       // Predicate.
1882       .addImm(ARMCC::AL)
1883       .addReg(0));
1884 
1885     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
1886       .addReg(ValReg)
1887       .addReg(SrcReg)
1888       // The offset immediate is #4. The operand value is scaled by 4 for the
1889       // tSTR instruction.
1890       .addImm(1)
1891       // Predicate.
1892       .addImm(ARMCC::AL)
1893       .addReg(0));
1894 
1895     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1896       .addReg(ARM::R0)
1897       .addReg(ARM::CPSR)
1898       .addImm(0)
1899       // Predicate.
1900       .addImm(ARMCC::AL)
1901       .addReg(0));
1902 
1903     const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
1904     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
1905       .addExpr(SymbolExpr)
1906       .addImm(ARMCC::AL)
1907       .addReg(0));
1908 
1909     OutStreamer->AddComment("eh_setjmp end");
1910     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1911       .addReg(ARM::R0)
1912       .addReg(ARM::CPSR)
1913       .addImm(1)
1914       // Predicate.
1915       .addImm(ARMCC::AL)
1916       .addReg(0));
1917 
1918     OutStreamer->emitLabel(Label);
1919     return;
1920   }
1921 
1922   case ARM::Int_eh_sjlj_setjmp_nofp:
1923   case ARM::Int_eh_sjlj_setjmp: {
1924     // Two incoming args: GPR:$src, GPR:$val
1925     // add $val, pc, #8
1926     // str $val, [$src, #+4]
1927     // mov r0, #0
1928     // add pc, pc, #0
1929     // mov r0, #1
1930     Register SrcReg = MI->getOperand(0).getReg();
1931     Register ValReg = MI->getOperand(1).getReg();
1932 
1933     OutStreamer->AddComment("eh_setjmp begin");
1934     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1935       .addReg(ValReg)
1936       .addReg(ARM::PC)
1937       .addImm(8)
1938       // Predicate.
1939       .addImm(ARMCC::AL)
1940       .addReg(0)
1941       // 's' bit operand (always reg0 for this).
1942       .addReg(0));
1943 
1944     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
1945       .addReg(ValReg)
1946       .addReg(SrcReg)
1947       .addImm(4)
1948       // Predicate.
1949       .addImm(ARMCC::AL)
1950       .addReg(0));
1951 
1952     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1953       .addReg(ARM::R0)
1954       .addImm(0)
1955       // Predicate.
1956       .addImm(ARMCC::AL)
1957       .addReg(0)
1958       // 's' bit operand (always reg0 for this).
1959       .addReg(0));
1960 
1961     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
1962       .addReg(ARM::PC)
1963       .addReg(ARM::PC)
1964       .addImm(0)
1965       // Predicate.
1966       .addImm(ARMCC::AL)
1967       .addReg(0)
1968       // 's' bit operand (always reg0 for this).
1969       .addReg(0));
1970 
1971     OutStreamer->AddComment("eh_setjmp end");
1972     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
1973       .addReg(ARM::R0)
1974       .addImm(1)
1975       // Predicate.
1976       .addImm(ARMCC::AL)
1977       .addReg(0)
1978       // 's' bit operand (always reg0 for this).
1979       .addReg(0));
1980     return;
1981   }
1982   case ARM::Int_eh_sjlj_longjmp: {
1983     // ldr sp, [$src, #8]
1984     // ldr $scratch, [$src, #4]
1985     // ldr r7, [$src]
1986     // bx $scratch
1987     Register SrcReg = MI->getOperand(0).getReg();
1988     Register ScratchReg = MI->getOperand(1).getReg();
1989     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1990       .addReg(ARM::SP)
1991       .addReg(SrcReg)
1992       .addImm(8)
1993       // Predicate.
1994       .addImm(ARMCC::AL)
1995       .addReg(0));
1996 
1997     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
1998       .addReg(ScratchReg)
1999       .addReg(SrcReg)
2000       .addImm(4)
2001       // Predicate.
2002       .addImm(ARMCC::AL)
2003       .addReg(0));
2004 
2005     if (STI.isTargetDarwin() || STI.isTargetWindows()) {
2006       // These platforms always use the same frame register
2007       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2008         .addReg(FramePtr)
2009         .addReg(SrcReg)
2010         .addImm(0)
2011         // Predicate.
2012         .addImm(ARMCC::AL)
2013         .addReg(0));
2014     } else {
2015       // If the calling code might use either R7 or R11 as
2016       // frame pointer register, restore it into both.
2017       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2018         .addReg(ARM::R7)
2019         .addReg(SrcReg)
2020         .addImm(0)
2021         // Predicate.
2022         .addImm(ARMCC::AL)
2023         .addReg(0));
2024       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2025         .addReg(ARM::R11)
2026         .addReg(SrcReg)
2027         .addImm(0)
2028         // Predicate.
2029         .addImm(ARMCC::AL)
2030         .addReg(0));
2031     }
2032 
2033     assert(Subtarget->hasV4TOps());
2034     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
2035       .addReg(ScratchReg)
2036       // Predicate.
2037       .addImm(ARMCC::AL)
2038       .addReg(0));
2039     return;
2040   }
2041   case ARM::tInt_eh_sjlj_longjmp: {
2042     // ldr $scratch, [$src, #8]
2043     // mov sp, $scratch
2044     // ldr $scratch, [$src, #4]
2045     // ldr r7, [$src]
2046     // bx $scratch
2047     Register SrcReg = MI->getOperand(0).getReg();
2048     Register ScratchReg = MI->getOperand(1).getReg();
2049 
2050     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2051       .addReg(ScratchReg)
2052       .addReg(SrcReg)
2053       // The offset immediate is #8. The operand value is scaled by 4 for the
2054       // tLDR instruction.
2055       .addImm(2)
2056       // Predicate.
2057       .addImm(ARMCC::AL)
2058       .addReg(0));
2059 
2060     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
2061       .addReg(ARM::SP)
2062       .addReg(ScratchReg)
2063       // Predicate.
2064       .addImm(ARMCC::AL)
2065       .addReg(0));
2066 
2067     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2068       .addReg(ScratchReg)
2069       .addReg(SrcReg)
2070       .addImm(1)
2071       // Predicate.
2072       .addImm(ARMCC::AL)
2073       .addReg(0));
2074 
2075     if (STI.isTargetDarwin() || STI.isTargetWindows()) {
2076       // These platforms always use the same frame register
2077       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2078         .addReg(FramePtr)
2079         .addReg(SrcReg)
2080         .addImm(0)
2081         // Predicate.
2082         .addImm(ARMCC::AL)
2083         .addReg(0));
2084     } else {
2085       // If the calling code might use either R7 or R11 as
2086       // frame pointer register, restore it into both.
2087       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2088         .addReg(ARM::R7)
2089         .addReg(SrcReg)
2090         .addImm(0)
2091         // Predicate.
2092         .addImm(ARMCC::AL)
2093         .addReg(0));
2094       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2095         .addReg(ARM::R11)
2096         .addReg(SrcReg)
2097         .addImm(0)
2098         // Predicate.
2099         .addImm(ARMCC::AL)
2100         .addReg(0));
2101     }
2102 
2103     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
2104       .addReg(ScratchReg)
2105       // Predicate.
2106       .addImm(ARMCC::AL)
2107       .addReg(0));
2108     return;
2109   }
2110   case ARM::tInt_WIN_eh_sjlj_longjmp: {
2111     // ldr.w r11, [$src, #0]
2112     // ldr.w  sp, [$src, #8]
2113     // ldr.w  pc, [$src, #4]
2114 
2115     Register SrcReg = MI->getOperand(0).getReg();
2116 
2117     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2118                                      .addReg(ARM::R11)
2119                                      .addReg(SrcReg)
2120                                      .addImm(0)
2121                                      // Predicate
2122                                      .addImm(ARMCC::AL)
2123                                      .addReg(0));
2124     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2125                                      .addReg(ARM::SP)
2126                                      .addReg(SrcReg)
2127                                      .addImm(8)
2128                                      // Predicate
2129                                      .addImm(ARMCC::AL)
2130                                      .addReg(0));
2131     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2132                                      .addReg(ARM::PC)
2133                                      .addReg(SrcReg)
2134                                      .addImm(4)
2135                                      // Predicate
2136                                      .addImm(ARMCC::AL)
2137                                      .addReg(0));
2138     return;
2139   }
2140   case ARM::PATCHABLE_FUNCTION_ENTER:
2141     LowerPATCHABLE_FUNCTION_ENTER(*MI);
2142     return;
2143   case ARM::PATCHABLE_FUNCTION_EXIT:
2144     LowerPATCHABLE_FUNCTION_EXIT(*MI);
2145     return;
2146   case ARM::PATCHABLE_TAIL_CALL:
2147     LowerPATCHABLE_TAIL_CALL(*MI);
2148     return;
2149   }
2150 
2151   MCInst TmpInst;
2152   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
2153 
2154   EmitToStreamer(*OutStreamer, TmpInst);
2155 }
2156 
2157 //===----------------------------------------------------------------------===//
2158 // Target Registry Stuff
2159 //===----------------------------------------------------------------------===//
2160 
2161 // Force static initialization.
2162 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMAsmPrinter() {
2163   RegisterAsmPrinter<ARMAsmPrinter> X(getTheARMLETarget());
2164   RegisterAsmPrinter<ARMAsmPrinter> Y(getTheARMBETarget());
2165   RegisterAsmPrinter<ARMAsmPrinter> A(getTheThumbLETarget());
2166   RegisterAsmPrinter<ARMAsmPrinter> B(getTheThumbBETarget());
2167 }
2168