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