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 (const Module *SourceModule = MMI->getModule()) {
744     // ABI_PCS_wchar_t to indicate wchar_t width
745     // FIXME: There is no way to emit value 0 (wchar_t prohibited).
746     if (auto WCharWidthValue = mdconst::extract_or_null<ConstantInt>(
747             SourceModule->getModuleFlag("wchar_size"))) {
748       int WCharWidth = WCharWidthValue->getZExtValue();
749       assert((WCharWidth == 2 || WCharWidth == 4) &&
750              "wchar_t width must be 2 or 4 bytes");
751       ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_wchar_t, WCharWidth);
752     }
753 
754     // ABI_enum_size to indicate enum width
755     // FIXME: There is no way to emit value 0 (enums prohibited) or value 3
756     //        (all enums contain a value needing 32 bits to encode).
757     if (auto EnumWidthValue = mdconst::extract_or_null<ConstantInt>(
758             SourceModule->getModuleFlag("min_enum_size"))) {
759       int EnumWidth = EnumWidthValue->getZExtValue();
760       assert((EnumWidth == 1 || EnumWidth == 4) &&
761              "Minimum enum width must be 1 or 4 bytes");
762       int EnumBuildAttr = EnumWidth == 1 ? 1 : 2;
763       ATS.emitAttribute(ARMBuildAttrs::ABI_enum_size, EnumBuildAttr);
764     }
765 
766     auto *PACValue = mdconst::extract_or_null<ConstantInt>(
767         SourceModule->getModuleFlag("sign-return-address"));
768     if (PACValue && PACValue->getZExtValue() == 1) {
769       // If "+pacbti" is used as an architecture extension,
770       // Tag_PAC_extension is emitted in
771       // ARMTargetStreamer::emitTargetAttributes().
772       if (!STI.hasPACBTI()) {
773         ATS.emitAttribute(ARMBuildAttrs::PAC_extension,
774                           ARMBuildAttrs::AllowPACInNOPSpace);
775       }
776       ATS.emitAttribute(ARMBuildAttrs::PACRET_use, ARMBuildAttrs::PACRETUsed);
777     }
778 
779     auto *BTIValue = mdconst::extract_or_null<ConstantInt>(
780         SourceModule->getModuleFlag("branch-target-enforcement"));
781     if (BTIValue && BTIValue->getZExtValue() == 1) {
782       // If "+pacbti" is used as an architecture extension,
783       // Tag_BTI_extension is emitted in
784       // ARMTargetStreamer::emitTargetAttributes().
785       if (!STI.hasPACBTI()) {
786         ATS.emitAttribute(ARMBuildAttrs::BTI_extension,
787                           ARMBuildAttrs::AllowBTIInNOPSpace);
788       }
789       ATS.emitAttribute(ARMBuildAttrs::BTI_use, ARMBuildAttrs::BTIUsed);
790     }
791   }
792 
793   // We currently do not support using R9 as the TLS pointer.
794   if (STI.isRWPI())
795     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
796                       ARMBuildAttrs::R9IsSB);
797   else if (STI.isR9Reserved())
798     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
799                       ARMBuildAttrs::R9Reserved);
800   else
801     ATS.emitAttribute(ARMBuildAttrs::ABI_PCS_R9_use,
802                       ARMBuildAttrs::R9IsGPR);
803 }
804 
805 //===----------------------------------------------------------------------===//
806 
807 static MCSymbol *getBFLabel(StringRef Prefix, unsigned FunctionNumber,
808                              unsigned LabelId, MCContext &Ctx) {
809 
810   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
811                        + "BF" + Twine(FunctionNumber) + "_" + Twine(LabelId));
812   return Label;
813 }
814 
815 static MCSymbol *getPICLabel(StringRef Prefix, unsigned FunctionNumber,
816                              unsigned LabelId, MCContext &Ctx) {
817 
818   MCSymbol *Label = Ctx.getOrCreateSymbol(Twine(Prefix)
819                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
820   return Label;
821 }
822 
823 static MCSymbolRefExpr::VariantKind
824 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
825   switch (Modifier) {
826   case ARMCP::no_modifier:
827     return MCSymbolRefExpr::VK_None;
828   case ARMCP::TLSGD:
829     return MCSymbolRefExpr::VK_TLSGD;
830   case ARMCP::TPOFF:
831     return MCSymbolRefExpr::VK_TPOFF;
832   case ARMCP::GOTTPOFF:
833     return MCSymbolRefExpr::VK_GOTTPOFF;
834   case ARMCP::SBREL:
835     return MCSymbolRefExpr::VK_ARM_SBREL;
836   case ARMCP::GOT_PREL:
837     return MCSymbolRefExpr::VK_ARM_GOT_PREL;
838   case ARMCP::SECREL:
839     return MCSymbolRefExpr::VK_SECREL;
840   }
841   llvm_unreachable("Invalid ARMCPModifier!");
842 }
843 
844 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
845                                         unsigned char TargetFlags) {
846   if (Subtarget->isTargetMachO()) {
847     bool IsIndirect =
848         (TargetFlags & ARMII::MO_NONLAZY) && Subtarget->isGVIndirectSymbol(GV);
849 
850     if (!IsIndirect)
851       return getSymbol(GV);
852 
853     // FIXME: Remove this when Darwin transition to @GOT like syntax.
854     MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
855     MachineModuleInfoMachO &MMIMachO =
856       MMI->getObjFileInfo<MachineModuleInfoMachO>();
857     MachineModuleInfoImpl::StubValueTy &StubSym =
858         GV->isThreadLocal() ? MMIMachO.getThreadLocalGVStubEntry(MCSym)
859                             : MMIMachO.getGVStubEntry(MCSym);
860 
861     if (!StubSym.getPointer())
862       StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV),
863                                                    !GV->hasInternalLinkage());
864     return MCSym;
865   } else if (Subtarget->isTargetCOFF()) {
866     assert(Subtarget->isTargetWindows() &&
867            "Windows is the only supported COFF target");
868 
869     bool IsIndirect =
870         (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB));
871     if (!IsIndirect)
872       return getSymbol(GV);
873 
874     SmallString<128> Name;
875     if (TargetFlags & ARMII::MO_DLLIMPORT)
876       Name = "__imp_";
877     else if (TargetFlags & ARMII::MO_COFFSTUB)
878       Name = ".refptr.";
879     getNameWithPrefix(Name, GV);
880 
881     MCSymbol *MCSym = OutContext.getOrCreateSymbol(Name);
882 
883     if (TargetFlags & ARMII::MO_COFFSTUB) {
884       MachineModuleInfoCOFF &MMICOFF =
885           MMI->getObjFileInfo<MachineModuleInfoCOFF>();
886       MachineModuleInfoImpl::StubValueTy &StubSym =
887           MMICOFF.getGVStubEntry(MCSym);
888 
889       if (!StubSym.getPointer())
890         StubSym = MachineModuleInfoImpl::StubValueTy(getSymbol(GV), true);
891     }
892 
893     return MCSym;
894   } else if (Subtarget->isTargetELF()) {
895     return getSymbol(GV);
896   }
897   llvm_unreachable("unexpected target");
898 }
899 
900 void ARMAsmPrinter::emitMachineConstantPoolValue(
901     MachineConstantPoolValue *MCPV) {
902   const DataLayout &DL = getDataLayout();
903   int Size = DL.getTypeAllocSize(MCPV->getType());
904 
905   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
906 
907   if (ACPV->isPromotedGlobal()) {
908     // This constant pool entry is actually a global whose storage has been
909     // promoted into the constant pool. This global may be referenced still
910     // by debug information, and due to the way AsmPrinter is set up, the debug
911     // info is immutable by the time we decide to promote globals to constant
912     // pools. Because of this, we need to ensure we emit a symbol for the global
913     // with private linkage (the default) so debug info can refer to it.
914     //
915     // However, if this global is promoted into several functions we must ensure
916     // we don't try and emit duplicate symbols!
917     auto *ACPC = cast<ARMConstantPoolConstant>(ACPV);
918     for (const auto *GV : ACPC->promotedGlobals()) {
919       if (!EmittedPromotedGlobalLabels.count(GV)) {
920         MCSymbol *GVSym = getSymbol(GV);
921         OutStreamer->emitLabel(GVSym);
922         EmittedPromotedGlobalLabels.insert(GV);
923       }
924     }
925     return emitGlobalConstant(DL, ACPC->getPromotedGlobalInit());
926   }
927 
928   MCSymbol *MCSym;
929   if (ACPV->isLSDA()) {
930     MCSym = getMBBExceptionSym(MF->front());
931   } else if (ACPV->isBlockAddress()) {
932     const BlockAddress *BA =
933       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
934     MCSym = GetBlockAddressSymbol(BA);
935   } else if (ACPV->isGlobalValue()) {
936     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
937 
938     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
939     // flag the global as MO_NONLAZY.
940     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
941     MCSym = GetARMGVSymbol(GV, TF);
942   } else if (ACPV->isMachineBasicBlock()) {
943     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
944     MCSym = MBB->getSymbol();
945   } else {
946     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
947     auto Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
948     MCSym = GetExternalSymbolSymbol(Sym);
949   }
950 
951   // Create an MCSymbol for the reference.
952   const MCExpr *Expr =
953     MCSymbolRefExpr::create(MCSym, getModifierVariantKind(ACPV->getModifier()),
954                             OutContext);
955 
956   if (ACPV->getPCAdjustment()) {
957     MCSymbol *PCLabel =
958         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
959                     ACPV->getLabelId(), OutContext);
960     const MCExpr *PCRelExpr = MCSymbolRefExpr::create(PCLabel, OutContext);
961     PCRelExpr =
962       MCBinaryExpr::createAdd(PCRelExpr,
963                               MCConstantExpr::create(ACPV->getPCAdjustment(),
964                                                      OutContext),
965                               OutContext);
966     if (ACPV->mustAddCurrentAddress()) {
967       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
968       // label, so just emit a local label end reference that instead.
969       MCSymbol *DotSym = OutContext.createTempSymbol();
970       OutStreamer->emitLabel(DotSym);
971       const MCExpr *DotExpr = MCSymbolRefExpr::create(DotSym, OutContext);
972       PCRelExpr = MCBinaryExpr::createSub(PCRelExpr, DotExpr, OutContext);
973     }
974     Expr = MCBinaryExpr::createSub(Expr, PCRelExpr, OutContext);
975   }
976   OutStreamer->emitValue(Expr, Size);
977 }
978 
979 void ARMAsmPrinter::emitJumpTableAddrs(const MachineInstr *MI) {
980   const MachineOperand &MO1 = MI->getOperand(1);
981   unsigned JTI = MO1.getIndex();
982 
983   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
984   // ARM mode tables.
985   emitAlignment(Align(4));
986 
987   // Emit a label for the jump table.
988   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
989   OutStreamer->emitLabel(JTISymbol);
990 
991   // Mark the jump table as data-in-code.
992   OutStreamer->emitDataRegion(MCDR_DataRegionJT32);
993 
994   // Emit each entry of the table.
995   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
996   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
997   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
998 
999   for (MachineBasicBlock *MBB : JTBBs) {
1000     // Construct an MCExpr for the entry. We want a value of the form:
1001     // (BasicBlockAddr - TableBeginAddr)
1002     //
1003     // For example, a table with entries jumping to basic blocks BB0 and BB1
1004     // would look like:
1005     // LJTI_0_0:
1006     //    .word (LBB0 - LJTI_0_0)
1007     //    .word (LBB1 - LJTI_0_0)
1008     const MCExpr *Expr = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
1009 
1010     if (isPositionIndependent() || Subtarget->isROPI())
1011       Expr = MCBinaryExpr::createSub(Expr, MCSymbolRefExpr::create(JTISymbol,
1012                                                                    OutContext),
1013                                      OutContext);
1014     // If we're generating a table of Thumb addresses in static relocation
1015     // model, we need to add one to keep interworking correctly.
1016     else if (AFI->isThumbFunction())
1017       Expr = MCBinaryExpr::createAdd(Expr, MCConstantExpr::create(1,OutContext),
1018                                      OutContext);
1019     OutStreamer->emitValue(Expr, 4);
1020   }
1021   // Mark the end of jump table data-in-code region.
1022   OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
1023 }
1024 
1025 void ARMAsmPrinter::emitJumpTableInsts(const MachineInstr *MI) {
1026   const MachineOperand &MO1 = MI->getOperand(1);
1027   unsigned JTI = MO1.getIndex();
1028 
1029   // Make sure the Thumb jump table is 4-byte aligned. This will be a nop for
1030   // ARM mode tables.
1031   emitAlignment(Align(4));
1032 
1033   // Emit a label for the jump table.
1034   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1035   OutStreamer->emitLabel(JTISymbol);
1036 
1037   // Emit each entry of the table.
1038   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1039   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1040   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1041 
1042   for (MachineBasicBlock *MBB : JTBBs) {
1043     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1044                                                           OutContext);
1045     // If this isn't a TBB or TBH, the entries are direct branch instructions.
1046     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2B)
1047         .addExpr(MBBSymbolExpr)
1048         .addImm(ARMCC::AL)
1049         .addReg(0));
1050   }
1051 }
1052 
1053 void ARMAsmPrinter::emitJumpTableTBInst(const MachineInstr *MI,
1054                                         unsigned OffsetWidth) {
1055   assert((OffsetWidth == 1 || OffsetWidth == 2) && "invalid tbb/tbh width");
1056   const MachineOperand &MO1 = MI->getOperand(1);
1057   unsigned JTI = MO1.getIndex();
1058 
1059   if (Subtarget->isThumb1Only())
1060     emitAlignment(Align(4));
1061 
1062   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel(JTI);
1063   OutStreamer->emitLabel(JTISymbol);
1064 
1065   // Emit each entry of the table.
1066   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1067   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1068   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1069 
1070   // Mark the jump table as data-in-code.
1071   OutStreamer->emitDataRegion(OffsetWidth == 1 ? MCDR_DataRegionJT8
1072                                                : MCDR_DataRegionJT16);
1073 
1074   for (auto MBB : JTBBs) {
1075     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::create(MBB->getSymbol(),
1076                                                           OutContext);
1077     // Otherwise it's an offset from the dispatch instruction. Construct an
1078     // MCExpr for the entry. We want a value of the form:
1079     // (BasicBlockAddr - TBBInstAddr + 4) / 2
1080     //
1081     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
1082     // would look like:
1083     // LJTI_0_0:
1084     //    .byte (LBB0 - (LCPI0_0 + 4)) / 2
1085     //    .byte (LBB1 - (LCPI0_0 + 4)) / 2
1086     // where LCPI0_0 is a label defined just before the TBB instruction using
1087     // this table.
1088     MCSymbol *TBInstPC = GetCPISymbol(MI->getOperand(0).getImm());
1089     const MCExpr *Expr = MCBinaryExpr::createAdd(
1090         MCSymbolRefExpr::create(TBInstPC, OutContext),
1091         MCConstantExpr::create(4, OutContext), OutContext);
1092     Expr = MCBinaryExpr::createSub(MBBSymbolExpr, Expr, OutContext);
1093     Expr = MCBinaryExpr::createDiv(Expr, MCConstantExpr::create(2, OutContext),
1094                                    OutContext);
1095     OutStreamer->emitValue(Expr, OffsetWidth);
1096   }
1097   // Mark the end of jump table data-in-code region. 32-bit offsets use
1098   // actual branch instructions here, so we don't mark those as a data-region
1099   // at all.
1100   OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
1101 
1102   // Make sure the next instruction is 2-byte aligned.
1103   emitAlignment(Align(2));
1104 }
1105 
1106 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
1107   assert(MI->getFlag(MachineInstr::FrameSetup) &&
1108       "Only instruction which are involved into frame setup code are allowed");
1109 
1110   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1111   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1112   const MachineFunction &MF = *MI->getParent()->getParent();
1113   const TargetRegisterInfo *TargetRegInfo =
1114     MF.getSubtarget().getRegisterInfo();
1115   const MachineRegisterInfo &MachineRegInfo = MF.getRegInfo();
1116 
1117   Register FramePtr = TargetRegInfo->getFrameRegister(MF);
1118   unsigned Opc = MI->getOpcode();
1119   unsigned SrcReg, DstReg;
1120 
1121   switch (Opc) {
1122   case ARM::tPUSH:
1123     // special case: tPUSH does not have src/dst regs.
1124     SrcReg = DstReg = ARM::SP;
1125     break;
1126   case ARM::tLDRpci:
1127   case ARM::t2MOVi16:
1128   case ARM::t2MOVTi16:
1129     // special cases:
1130     // 1) for Thumb1 code we sometimes materialize the constant via constpool
1131     //    load.
1132     // 2) for Thumb2 execute only code we materialize the constant via
1133     //    immediate constants in 2 separate instructions (MOVW/MOVT).
1134     SrcReg = ~0U;
1135     DstReg = MI->getOperand(0).getReg();
1136     break;
1137   default:
1138     SrcReg = MI->getOperand(1).getReg();
1139     DstReg = MI->getOperand(0).getReg();
1140     break;
1141   }
1142 
1143   // Try to figure out the unwinding opcode out of src / dst regs.
1144   if (MI->mayStore()) {
1145     // Register saves.
1146     assert(DstReg == ARM::SP &&
1147            "Only stack pointer as a destination reg is supported");
1148 
1149     SmallVector<unsigned, 4> RegList;
1150     // Skip src & dst reg, and pred ops.
1151     unsigned StartOp = 2 + 2;
1152     // Use all the operands.
1153     unsigned NumOffset = 0;
1154     // Amount of SP adjustment folded into a push, before the
1155     // registers are stored (pad at higher addresses).
1156     unsigned PadBefore = 0;
1157     // Amount of SP adjustment folded into a push, after the
1158     // registers are stored (pad at lower addresses).
1159     unsigned PadAfter = 0;
1160 
1161     switch (Opc) {
1162     default:
1163       MI->print(errs());
1164       llvm_unreachable("Unsupported opcode for unwinding information");
1165     case ARM::tPUSH:
1166       // Special case here: no src & dst reg, but two extra imp ops.
1167       StartOp = 2; NumOffset = 2;
1168       LLVM_FALLTHROUGH;
1169     case ARM::STMDB_UPD:
1170     case ARM::t2STMDB_UPD:
1171     case ARM::VSTMDDB_UPD:
1172       assert(SrcReg == ARM::SP &&
1173              "Only stack pointer as a source reg is supported");
1174       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1175            i != NumOps; ++i) {
1176         const MachineOperand &MO = MI->getOperand(i);
1177         // Actually, there should never be any impdef stuff here. Skip it
1178         // temporary to workaround PR11902.
1179         if (MO.isImplicit())
1180           continue;
1181         // Registers, pushed as a part of folding an SP update into the
1182         // push instruction are marked as undef and should not be
1183         // restored when unwinding, because the function can modify the
1184         // corresponding stack slots.
1185         if (MO.isUndef()) {
1186           assert(RegList.empty() &&
1187                  "Pad registers must come before restored ones");
1188           unsigned Width =
1189             TargetRegInfo->getRegSizeInBits(MO.getReg(), MachineRegInfo) / 8;
1190           PadAfter += Width;
1191           continue;
1192         }
1193         // Check for registers that are remapped (for a Thumb1 prologue that
1194         // saves high registers).
1195         Register Reg = MO.getReg();
1196         if (unsigned RemappedReg = AFI->EHPrologueRemappedRegs.lookup(Reg))
1197           Reg = RemappedReg;
1198         RegList.push_back(Reg);
1199       }
1200       break;
1201     case ARM::STR_PRE_IMM:
1202     case ARM::STR_PRE_REG:
1203     case ARM::t2STR_PRE:
1204       assert(MI->getOperand(2).getReg() == ARM::SP &&
1205              "Only stack pointer as a source reg is supported");
1206       if (unsigned RemappedReg = AFI->EHPrologueRemappedRegs.lookup(SrcReg))
1207         SrcReg = RemappedReg;
1208 
1209       RegList.push_back(SrcReg);
1210       break;
1211     case ARM::t2STRD_PRE:
1212       assert(MI->getOperand(3).getReg() == ARM::SP &&
1213              "Only stack pointer as a source reg is supported");
1214       SrcReg = MI->getOperand(1).getReg();
1215       if (unsigned RemappedReg = AFI->EHPrologueRemappedRegs.lookup(SrcReg))
1216         SrcReg = RemappedReg;
1217       RegList.push_back(SrcReg);
1218       SrcReg = MI->getOperand(2).getReg();
1219       if (unsigned RemappedReg = AFI->EHPrologueRemappedRegs.lookup(SrcReg))
1220         SrcReg = RemappedReg;
1221       RegList.push_back(SrcReg);
1222       PadBefore = -MI->getOperand(4).getImm() - 8;
1223       break;
1224     }
1225     if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1226       if (PadBefore)
1227         ATS.emitPad(PadBefore);
1228       ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1229       // Account for the SP adjustment, folded into the push.
1230       if (PadAfter)
1231         ATS.emitPad(PadAfter);
1232     }
1233   } else {
1234     // Changes of stack / frame pointer.
1235     if (SrcReg == ARM::SP) {
1236       int64_t Offset = 0;
1237       switch (Opc) {
1238       default:
1239         MI->print(errs());
1240         llvm_unreachable("Unsupported opcode for unwinding information");
1241       case ARM::MOVr:
1242       case ARM::tMOVr:
1243         Offset = 0;
1244         break;
1245       case ARM::ADDri:
1246       case ARM::t2ADDri:
1247       case ARM::t2ADDri12:
1248       case ARM::t2ADDspImm:
1249       case ARM::t2ADDspImm12:
1250         Offset = -MI->getOperand(2).getImm();
1251         break;
1252       case ARM::SUBri:
1253       case ARM::t2SUBri:
1254       case ARM::t2SUBri12:
1255       case ARM::t2SUBspImm:
1256       case ARM::t2SUBspImm12:
1257         Offset = MI->getOperand(2).getImm();
1258         break;
1259       case ARM::tSUBspi:
1260         Offset = MI->getOperand(2).getImm()*4;
1261         break;
1262       case ARM::tADDspi:
1263       case ARM::tADDrSPi:
1264         Offset = -MI->getOperand(2).getImm()*4;
1265         break;
1266       case ARM::tADDhirr:
1267         Offset =
1268             -AFI->EHPrologueOffsetInRegs.lookup(MI->getOperand(2).getReg());
1269         break;
1270       }
1271 
1272       if (MAI->getExceptionHandlingType() == ExceptionHandling::ARM) {
1273         if (DstReg == FramePtr && FramePtr != ARM::SP)
1274           // Set-up of the frame pointer. Positive values correspond to "add"
1275           // instruction.
1276           ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1277         else if (DstReg == ARM::SP) {
1278           // Change of SP by an offset. Positive values correspond to "sub"
1279           // instruction.
1280           ATS.emitPad(Offset);
1281         } else {
1282           // Move of SP to a register.  Positive values correspond to an "add"
1283           // instruction.
1284           ATS.emitMovSP(DstReg, -Offset);
1285         }
1286       }
1287     } else if (DstReg == ARM::SP) {
1288       MI->print(errs());
1289       llvm_unreachable("Unsupported opcode for unwinding information");
1290     } else {
1291       int64_t Offset = 0;
1292       switch (Opc) {
1293       case ARM::tMOVr:
1294         // If a Thumb1 function spills r8-r11, we copy the values to low
1295         // registers before pushing them. Record the copy so we can emit the
1296         // correct ".save" later.
1297         AFI->EHPrologueRemappedRegs[DstReg] = SrcReg;
1298         break;
1299       case ARM::tLDRpci: {
1300         // Grab the constpool index and check, whether it corresponds to
1301         // original or cloned constpool entry.
1302         unsigned CPI = MI->getOperand(1).getIndex();
1303         const MachineConstantPool *MCP = MF.getConstantPool();
1304         if (CPI >= MCP->getConstants().size())
1305           CPI = AFI->getOriginalCPIdx(CPI);
1306         assert(CPI != -1U && "Invalid constpool index");
1307 
1308         // Derive the actual offset.
1309         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1310         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1311         Offset = cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1312         AFI->EHPrologueOffsetInRegs[DstReg] = Offset;
1313         break;
1314       }
1315       case ARM::t2MOVi16:
1316         Offset = MI->getOperand(1).getImm();
1317         AFI->EHPrologueOffsetInRegs[DstReg] = Offset;
1318         break;
1319       case ARM::t2MOVTi16:
1320         Offset = MI->getOperand(2).getImm();
1321         AFI->EHPrologueOffsetInRegs[DstReg] |= (Offset << 16);
1322         break;
1323       case ARM::t2PAC:
1324       case ARM::t2PACBTI:
1325         AFI->EHPrologueRemappedRegs[ARM::R12] = ARM::RA_AUTH_CODE;
1326         break;
1327       default:
1328         MI->print(errs());
1329         llvm_unreachable("Unsupported opcode for unwinding information");
1330       }
1331     }
1332   }
1333 }
1334 
1335 // Simple pseudo-instructions have their lowering (with expansion to real
1336 // instructions) auto-generated.
1337 #include "ARMGenMCPseudoLowering.inc"
1338 
1339 void ARMAsmPrinter::emitInstruction(const MachineInstr *MI) {
1340   // TODOD FIXME: Enable feature predicate checks once all the test pass.
1341   // ARM_MC::verifyInstructionPredicates(MI->getOpcode(),
1342   //                                   getSubtargetInfo().getFeatureBits());
1343 
1344   const DataLayout &DL = getDataLayout();
1345   MCTargetStreamer &TS = *OutStreamer->getTargetStreamer();
1346   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1347 
1348   // If we just ended a constant pool, mark it as such.
1349   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1350     OutStreamer->emitDataRegion(MCDR_DataRegionEnd);
1351     InConstantPool = false;
1352   }
1353 
1354   // Emit unwinding stuff for frame-related instructions
1355   if (Subtarget->isTargetEHABICompatible() &&
1356        MI->getFlag(MachineInstr::FrameSetup))
1357     EmitUnwindingInstruction(MI);
1358 
1359   // Do any auto-generated pseudo lowerings.
1360   if (emitPseudoExpansionLowering(*OutStreamer, MI))
1361     return;
1362 
1363   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1364          "Pseudo flag setting opcode should be expanded early");
1365 
1366   // Check for manual lowerings.
1367   unsigned Opc = MI->getOpcode();
1368   switch (Opc) {
1369   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1370   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1371   case ARM::LEApcrel:
1372   case ARM::tLEApcrel:
1373   case ARM::t2LEApcrel: {
1374     // FIXME: Need to also handle globals and externals
1375     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1376     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1377                                                ARM::t2LEApcrel ? ARM::t2ADR
1378                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1379                      : ARM::ADR))
1380       .addReg(MI->getOperand(0).getReg())
1381       .addExpr(MCSymbolRefExpr::create(CPISymbol, OutContext))
1382       // Add predicate operands.
1383       .addImm(MI->getOperand(2).getImm())
1384       .addReg(MI->getOperand(3).getReg()));
1385     return;
1386   }
1387   case ARM::LEApcrelJT:
1388   case ARM::tLEApcrelJT:
1389   case ARM::t2LEApcrelJT: {
1390     MCSymbol *JTIPICSymbol =
1391       GetARMJTIPICJumpTableLabel(MI->getOperand(1).getIndex());
1392     EmitToStreamer(*OutStreamer, MCInstBuilder(MI->getOpcode() ==
1393                                                ARM::t2LEApcrelJT ? ARM::t2ADR
1394                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1395                      : ARM::ADR))
1396       .addReg(MI->getOperand(0).getReg())
1397       .addExpr(MCSymbolRefExpr::create(JTIPICSymbol, OutContext))
1398       // Add predicate operands.
1399       .addImm(MI->getOperand(2).getImm())
1400       .addReg(MI->getOperand(3).getReg()));
1401     return;
1402   }
1403   // Darwin call instructions are just normal call instructions with different
1404   // clobber semantics (they clobber R9).
1405   case ARM::BX_CALL: {
1406     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1407       .addReg(ARM::LR)
1408       .addReg(ARM::PC)
1409       // Add predicate operands.
1410       .addImm(ARMCC::AL)
1411       .addReg(0)
1412       // Add 's' bit operand (always reg0 for this)
1413       .addReg(0));
1414 
1415     assert(Subtarget->hasV4TOps());
1416     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
1417       .addReg(MI->getOperand(0).getReg()));
1418     return;
1419   }
1420   case ARM::tBX_CALL: {
1421     if (Subtarget->hasV5TOps())
1422       llvm_unreachable("Expected BLX to be selected for v5t+");
1423 
1424     // On ARM v4t, when doing a call from thumb mode, we need to ensure
1425     // that the saved lr has its LSB set correctly (the arch doesn't
1426     // have blx).
1427     // So here we generate a bl to a small jump pad that does bx rN.
1428     // The jump pads are emitted after the function body.
1429 
1430     Register TReg = MI->getOperand(0).getReg();
1431     MCSymbol *TRegSym = nullptr;
1432     for (std::pair<unsigned, MCSymbol *> &TIP : ThumbIndirectPads) {
1433       if (TIP.first == TReg) {
1434         TRegSym = TIP.second;
1435         break;
1436       }
1437     }
1438 
1439     if (!TRegSym) {
1440       TRegSym = OutContext.createTempSymbol();
1441       ThumbIndirectPads.push_back(std::make_pair(TReg, TRegSym));
1442     }
1443 
1444     // Create a link-saving branch to the Reg Indirect Jump Pad.
1445     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBL)
1446         // Predicate comes first here.
1447         .addImm(ARMCC::AL).addReg(0)
1448         .addExpr(MCSymbolRefExpr::create(TRegSym, OutContext)));
1449     return;
1450   }
1451   case ARM::BMOVPCRX_CALL: {
1452     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1453       .addReg(ARM::LR)
1454       .addReg(ARM::PC)
1455       // Add predicate operands.
1456       .addImm(ARMCC::AL)
1457       .addReg(0)
1458       // Add 's' bit operand (always reg0 for this)
1459       .addReg(0));
1460 
1461     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1462       .addReg(ARM::PC)
1463       .addReg(MI->getOperand(0).getReg())
1464       // Add predicate operands.
1465       .addImm(ARMCC::AL)
1466       .addReg(0)
1467       // Add 's' bit operand (always reg0 for this)
1468       .addReg(0));
1469     return;
1470   }
1471   case ARM::BMOVPCB_CALL: {
1472     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVr)
1473       .addReg(ARM::LR)
1474       .addReg(ARM::PC)
1475       // Add predicate operands.
1476       .addImm(ARMCC::AL)
1477       .addReg(0)
1478       // Add 's' bit operand (always reg0 for this)
1479       .addReg(0));
1480 
1481     const MachineOperand &Op = MI->getOperand(0);
1482     const GlobalValue *GV = Op.getGlobal();
1483     const unsigned TF = Op.getTargetFlags();
1484     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1485     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1486     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::Bcc)
1487       .addExpr(GVSymExpr)
1488       // Add predicate operands.
1489       .addImm(ARMCC::AL)
1490       .addReg(0));
1491     return;
1492   }
1493   case ARM::MOVi16_ga_pcrel:
1494   case ARM::t2MOVi16_ga_pcrel: {
1495     MCInst TmpInst;
1496     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1497     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1498 
1499     unsigned TF = MI->getOperand(1).getTargetFlags();
1500     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1501     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1502     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1503 
1504     MCSymbol *LabelSym =
1505         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1506                     MI->getOperand(2).getImm(), OutContext);
1507     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1508     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1509     const MCExpr *PCRelExpr =
1510       ARMMCExpr::createLower16(MCBinaryExpr::createSub(GVSymExpr,
1511                                       MCBinaryExpr::createAdd(LabelSymExpr,
1512                                       MCConstantExpr::create(PCAdj, OutContext),
1513                                       OutContext), OutContext), OutContext);
1514       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1515 
1516     // Add predicate operands.
1517     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1518     TmpInst.addOperand(MCOperand::createReg(0));
1519     // Add 's' bit operand (always reg0 for this)
1520     TmpInst.addOperand(MCOperand::createReg(0));
1521     EmitToStreamer(*OutStreamer, TmpInst);
1522     return;
1523   }
1524   case ARM::MOVTi16_ga_pcrel:
1525   case ARM::t2MOVTi16_ga_pcrel: {
1526     MCInst TmpInst;
1527     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1528                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1529     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1530     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1531 
1532     unsigned TF = MI->getOperand(2).getTargetFlags();
1533     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1534     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1535     const MCExpr *GVSymExpr = MCSymbolRefExpr::create(GVSym, OutContext);
1536 
1537     MCSymbol *LabelSym =
1538         getPICLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1539                     MI->getOperand(3).getImm(), OutContext);
1540     const MCExpr *LabelSymExpr= MCSymbolRefExpr::create(LabelSym, OutContext);
1541     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1542     const MCExpr *PCRelExpr =
1543         ARMMCExpr::createUpper16(MCBinaryExpr::createSub(GVSymExpr,
1544                                    MCBinaryExpr::createAdd(LabelSymExpr,
1545                                       MCConstantExpr::create(PCAdj, OutContext),
1546                                           OutContext), OutContext), OutContext);
1547       TmpInst.addOperand(MCOperand::createExpr(PCRelExpr));
1548     // Add predicate operands.
1549     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1550     TmpInst.addOperand(MCOperand::createReg(0));
1551     // Add 's' bit operand (always reg0 for this)
1552     TmpInst.addOperand(MCOperand::createReg(0));
1553     EmitToStreamer(*OutStreamer, TmpInst);
1554     return;
1555   }
1556   case ARM::t2BFi:
1557   case ARM::t2BFic:
1558   case ARM::t2BFLi:
1559   case ARM::t2BFr:
1560   case ARM::t2BFLr: {
1561     // This is a Branch Future instruction.
1562 
1563     const MCExpr *BranchLabel = MCSymbolRefExpr::create(
1564         getBFLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1565                    MI->getOperand(0).getIndex(), OutContext),
1566         OutContext);
1567 
1568     auto MCInst = MCInstBuilder(Opc).addExpr(BranchLabel);
1569     if (MI->getOperand(1).isReg()) {
1570       // For BFr/BFLr
1571       MCInst.addReg(MI->getOperand(1).getReg());
1572     } else {
1573       // For BFi/BFLi/BFic
1574       const MCExpr *BranchTarget;
1575       if (MI->getOperand(1).isMBB())
1576         BranchTarget = MCSymbolRefExpr::create(
1577             MI->getOperand(1).getMBB()->getSymbol(), OutContext);
1578       else if (MI->getOperand(1).isGlobal()) {
1579         const GlobalValue *GV = MI->getOperand(1).getGlobal();
1580         BranchTarget = MCSymbolRefExpr::create(
1581             GetARMGVSymbol(GV, MI->getOperand(1).getTargetFlags()), OutContext);
1582       } else if (MI->getOperand(1).isSymbol()) {
1583         BranchTarget = MCSymbolRefExpr::create(
1584             GetExternalSymbolSymbol(MI->getOperand(1).getSymbolName()),
1585             OutContext);
1586       } else
1587         llvm_unreachable("Unhandled operand kind in Branch Future instruction");
1588 
1589       MCInst.addExpr(BranchTarget);
1590     }
1591 
1592     if (Opc == ARM::t2BFic) {
1593       const MCExpr *ElseLabel = MCSymbolRefExpr::create(
1594           getBFLabel(DL.getPrivateGlobalPrefix(), getFunctionNumber(),
1595                      MI->getOperand(2).getIndex(), OutContext),
1596           OutContext);
1597       MCInst.addExpr(ElseLabel);
1598       MCInst.addImm(MI->getOperand(3).getImm());
1599     } else {
1600       MCInst.addImm(MI->getOperand(2).getImm())
1601           .addReg(MI->getOperand(3).getReg());
1602     }
1603 
1604     EmitToStreamer(*OutStreamer, MCInst);
1605     return;
1606   }
1607   case ARM::t2BF_LabelPseudo: {
1608     // This is a pseudo op for a label used by a branch future instruction
1609 
1610     // Emit the label.
1611     OutStreamer->emitLabel(getBFLabel(DL.getPrivateGlobalPrefix(),
1612                                        getFunctionNumber(),
1613                                        MI->getOperand(0).getIndex(), OutContext));
1614     return;
1615   }
1616   case ARM::tPICADD: {
1617     // This is a pseudo op for a label + instruction sequence, which looks like:
1618     // LPC0:
1619     //     add r0, pc
1620     // This adds the address of LPC0 to r0.
1621 
1622     // Emit the label.
1623     OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1624                                        getFunctionNumber(),
1625                                        MI->getOperand(2).getImm(), OutContext));
1626 
1627     // Form and emit the add.
1628     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1629       .addReg(MI->getOperand(0).getReg())
1630       .addReg(MI->getOperand(0).getReg())
1631       .addReg(ARM::PC)
1632       // Add predicate operands.
1633       .addImm(ARMCC::AL)
1634       .addReg(0));
1635     return;
1636   }
1637   case ARM::PICADD: {
1638     // This is a pseudo op for a label + instruction sequence, which looks like:
1639     // LPC0:
1640     //     add r0, pc, r0
1641     // This adds the address of LPC0 to r0.
1642 
1643     // Emit the label.
1644     OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1645                                        getFunctionNumber(),
1646                                        MI->getOperand(2).getImm(), OutContext));
1647 
1648     // Form and emit the add.
1649     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1650       .addReg(MI->getOperand(0).getReg())
1651       .addReg(ARM::PC)
1652       .addReg(MI->getOperand(1).getReg())
1653       // Add predicate operands.
1654       .addImm(MI->getOperand(3).getImm())
1655       .addReg(MI->getOperand(4).getReg())
1656       // Add 's' bit operand (always reg0 for this)
1657       .addReg(0));
1658     return;
1659   }
1660   case ARM::PICSTR:
1661   case ARM::PICSTRB:
1662   case ARM::PICSTRH:
1663   case ARM::PICLDR:
1664   case ARM::PICLDRB:
1665   case ARM::PICLDRH:
1666   case ARM::PICLDRSB:
1667   case ARM::PICLDRSH: {
1668     // This is a pseudo op for a label + instruction sequence, which looks like:
1669     // LPC0:
1670     //     OP r0, [pc, r0]
1671     // The LCP0 label is referenced by a constant pool entry in order to get
1672     // a PC-relative address at the ldr instruction.
1673 
1674     // Emit the label.
1675     OutStreamer->emitLabel(getPICLabel(DL.getPrivateGlobalPrefix(),
1676                                        getFunctionNumber(),
1677                                        MI->getOperand(2).getImm(), OutContext));
1678 
1679     // Form and emit the load
1680     unsigned Opcode;
1681     switch (MI->getOpcode()) {
1682     default:
1683       llvm_unreachable("Unexpected opcode!");
1684     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1685     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1686     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1687     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1688     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1689     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1690     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1691     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1692     }
1693     EmitToStreamer(*OutStreamer, MCInstBuilder(Opcode)
1694       .addReg(MI->getOperand(0).getReg())
1695       .addReg(ARM::PC)
1696       .addReg(MI->getOperand(1).getReg())
1697       .addImm(0)
1698       // Add predicate operands.
1699       .addImm(MI->getOperand(3).getImm())
1700       .addReg(MI->getOperand(4).getReg()));
1701 
1702     return;
1703   }
1704   case ARM::CONSTPOOL_ENTRY: {
1705     if (Subtarget->genExecuteOnly())
1706       llvm_unreachable("execute-only should not generate constant pools");
1707 
1708     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1709     /// in the function.  The first operand is the ID# for this instruction, the
1710     /// second is the index into the MachineConstantPool that this is, the third
1711     /// is the size in bytes of this constant pool entry.
1712     /// The required alignment is specified on the basic block holding this MI.
1713     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1714     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1715 
1716     // If this is the first entry of the pool, mark it.
1717     if (!InConstantPool) {
1718       OutStreamer->emitDataRegion(MCDR_DataRegion);
1719       InConstantPool = true;
1720     }
1721 
1722     OutStreamer->emitLabel(GetCPISymbol(LabelId));
1723 
1724     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1725     if (MCPE.isMachineConstantPoolEntry())
1726       emitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1727     else
1728       emitGlobalConstant(DL, MCPE.Val.ConstVal);
1729     return;
1730   }
1731   case ARM::JUMPTABLE_ADDRS:
1732     emitJumpTableAddrs(MI);
1733     return;
1734   case ARM::JUMPTABLE_INSTS:
1735     emitJumpTableInsts(MI);
1736     return;
1737   case ARM::JUMPTABLE_TBB:
1738   case ARM::JUMPTABLE_TBH:
1739     emitJumpTableTBInst(MI, MI->getOpcode() == ARM::JUMPTABLE_TBB ? 1 : 2);
1740     return;
1741   case ARM::t2BR_JT: {
1742     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1743       .addReg(ARM::PC)
1744       .addReg(MI->getOperand(0).getReg())
1745       // Add predicate operands.
1746       .addImm(ARMCC::AL)
1747       .addReg(0));
1748     return;
1749   }
1750   case ARM::t2TBB_JT:
1751   case ARM::t2TBH_JT: {
1752     unsigned Opc = MI->getOpcode() == ARM::t2TBB_JT ? ARM::t2TBB : ARM::t2TBH;
1753     // Lower and emit the PC label, then the instruction itself.
1754     OutStreamer->emitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1755     EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1756                                      .addReg(MI->getOperand(0).getReg())
1757                                      .addReg(MI->getOperand(1).getReg())
1758                                      // Add predicate operands.
1759                                      .addImm(ARMCC::AL)
1760                                      .addReg(0));
1761     return;
1762   }
1763   case ARM::tTBB_JT:
1764   case ARM::tTBH_JT: {
1765 
1766     bool Is8Bit = MI->getOpcode() == ARM::tTBB_JT;
1767     Register Base = MI->getOperand(0).getReg();
1768     Register Idx = MI->getOperand(1).getReg();
1769     assert(MI->getOperand(1).isKill() && "We need the index register as scratch!");
1770 
1771     // Multiply up idx if necessary.
1772     if (!Is8Bit)
1773       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1774                                        .addReg(Idx)
1775                                        .addReg(ARM::CPSR)
1776                                        .addReg(Idx)
1777                                        .addImm(1)
1778                                        // Add predicate operands.
1779                                        .addImm(ARMCC::AL)
1780                                        .addReg(0));
1781 
1782     if (Base == ARM::PC) {
1783       // TBB [base, idx] =
1784       //    ADDS idx, idx, base
1785       //    LDRB idx, [idx, #4] ; or LDRH if TBH
1786       //    LSLS idx, #1
1787       //    ADDS pc, pc, idx
1788 
1789       // When using PC as the base, it's important that there is no padding
1790       // between the last ADDS and the start of the jump table. The jump table
1791       // is 4-byte aligned, so we ensure we're 4 byte aligned here too.
1792       //
1793       // FIXME: Ideally we could vary the LDRB index based on the padding
1794       // between the sequence and jump table, however that relies on MCExprs
1795       // for load indexes which are currently not supported.
1796       OutStreamer->emitCodeAlignment(4, &getSubtargetInfo());
1797       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1798                                        .addReg(Idx)
1799                                        .addReg(Idx)
1800                                        .addReg(Base)
1801                                        // Add predicate operands.
1802                                        .addImm(ARMCC::AL)
1803                                        .addReg(0));
1804 
1805       unsigned Opc = Is8Bit ? ARM::tLDRBi : ARM::tLDRHi;
1806       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1807                                        .addReg(Idx)
1808                                        .addReg(Idx)
1809                                        .addImm(Is8Bit ? 4 : 2)
1810                                        // Add predicate operands.
1811                                        .addImm(ARMCC::AL)
1812                                        .addReg(0));
1813     } else {
1814       // TBB [base, idx] =
1815       //    LDRB idx, [base, idx] ; or LDRH if TBH
1816       //    LSLS idx, #1
1817       //    ADDS pc, pc, idx
1818 
1819       unsigned Opc = Is8Bit ? ARM::tLDRBr : ARM::tLDRHr;
1820       EmitToStreamer(*OutStreamer, MCInstBuilder(Opc)
1821                                        .addReg(Idx)
1822                                        .addReg(Base)
1823                                        .addReg(Idx)
1824                                        // Add predicate operands.
1825                                        .addImm(ARMCC::AL)
1826                                        .addReg(0));
1827     }
1828 
1829     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLSLri)
1830                                      .addReg(Idx)
1831                                      .addReg(ARM::CPSR)
1832                                      .addReg(Idx)
1833                                      .addImm(1)
1834                                      // Add predicate operands.
1835                                      .addImm(ARMCC::AL)
1836                                      .addReg(0));
1837 
1838     OutStreamer->emitLabel(GetCPISymbol(MI->getOperand(3).getImm()));
1839     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDhirr)
1840                                      .addReg(ARM::PC)
1841                                      .addReg(ARM::PC)
1842                                      .addReg(Idx)
1843                                      // Add predicate operands.
1844                                      .addImm(ARMCC::AL)
1845                                      .addReg(0));
1846     return;
1847   }
1848   case ARM::tBR_JTr:
1849   case ARM::BR_JTr: {
1850     // mov pc, target
1851     MCInst TmpInst;
1852     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1853       ARM::MOVr : ARM::tMOVr;
1854     TmpInst.setOpcode(Opc);
1855     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1856     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1857     // Add predicate operands.
1858     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1859     TmpInst.addOperand(MCOperand::createReg(0));
1860     // Add 's' bit operand (always reg0 for this)
1861     if (Opc == ARM::MOVr)
1862       TmpInst.addOperand(MCOperand::createReg(0));
1863     EmitToStreamer(*OutStreamer, TmpInst);
1864     return;
1865   }
1866   case ARM::BR_JTm_i12: {
1867     // ldr pc, target
1868     MCInst TmpInst;
1869     TmpInst.setOpcode(ARM::LDRi12);
1870     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1871     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1872     TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1873     // Add predicate operands.
1874     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1875     TmpInst.addOperand(MCOperand::createReg(0));
1876     EmitToStreamer(*OutStreamer, TmpInst);
1877     return;
1878   }
1879   case ARM::BR_JTm_rs: {
1880     // ldr pc, target
1881     MCInst TmpInst;
1882     TmpInst.setOpcode(ARM::LDRrs);
1883     TmpInst.addOperand(MCOperand::createReg(ARM::PC));
1884     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(0).getReg()));
1885     TmpInst.addOperand(MCOperand::createReg(MI->getOperand(1).getReg()));
1886     TmpInst.addOperand(MCOperand::createImm(MI->getOperand(2).getImm()));
1887     // Add predicate operands.
1888     TmpInst.addOperand(MCOperand::createImm(ARMCC::AL));
1889     TmpInst.addOperand(MCOperand::createReg(0));
1890     EmitToStreamer(*OutStreamer, TmpInst);
1891     return;
1892   }
1893   case ARM::BR_JTadd: {
1894     // add pc, target, idx
1895     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDrr)
1896       .addReg(ARM::PC)
1897       .addReg(MI->getOperand(0).getReg())
1898       .addReg(MI->getOperand(1).getReg())
1899       // Add predicate operands.
1900       .addImm(ARMCC::AL)
1901       .addReg(0)
1902       // Add 's' bit operand (always reg0 for this)
1903       .addReg(0));
1904     return;
1905   }
1906   case ARM::SPACE:
1907     OutStreamer->emitZeros(MI->getOperand(1).getImm());
1908     return;
1909   case ARM::TRAP: {
1910     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1911     // FIXME: Remove this special case when they do.
1912     if (!Subtarget->isTargetMachO()) {
1913       uint32_t Val = 0xe7ffdefeUL;
1914       OutStreamer->AddComment("trap");
1915       ATS.emitInst(Val);
1916       return;
1917     }
1918     break;
1919   }
1920   case ARM::TRAPNaCl: {
1921     uint32_t Val = 0xe7fedef0UL;
1922     OutStreamer->AddComment("trap");
1923     ATS.emitInst(Val);
1924     return;
1925   }
1926   case ARM::tTRAP: {
1927     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1928     // FIXME: Remove this special case when they do.
1929     if (!Subtarget->isTargetMachO()) {
1930       uint16_t Val = 0xdefe;
1931       OutStreamer->AddComment("trap");
1932       ATS.emitInst(Val, 'n');
1933       return;
1934     }
1935     break;
1936   }
1937   case ARM::t2Int_eh_sjlj_setjmp:
1938   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1939   case ARM::tInt_eh_sjlj_setjmp: {
1940     // Two incoming args: GPR:$src, GPR:$val
1941     // mov $val, pc
1942     // adds $val, #7
1943     // str $val, [$src, #4]
1944     // movs r0, #0
1945     // b LSJLJEH
1946     // movs r0, #1
1947     // LSJLJEH:
1948     Register SrcReg = MI->getOperand(0).getReg();
1949     Register ValReg = MI->getOperand(1).getReg();
1950     MCSymbol *Label = OutContext.createTempSymbol("SJLJEH");
1951     OutStreamer->AddComment("eh_setjmp begin");
1952     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
1953       .addReg(ValReg)
1954       .addReg(ARM::PC)
1955       // Predicate.
1956       .addImm(ARMCC::AL)
1957       .addReg(0));
1958 
1959     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tADDi3)
1960       .addReg(ValReg)
1961       // 's' bit operand
1962       .addReg(ARM::CPSR)
1963       .addReg(ValReg)
1964       .addImm(7)
1965       // Predicate.
1966       .addImm(ARMCC::AL)
1967       .addReg(0));
1968 
1969     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tSTRi)
1970       .addReg(ValReg)
1971       .addReg(SrcReg)
1972       // The offset immediate is #4. The operand value is scaled by 4 for the
1973       // tSTR instruction.
1974       .addImm(1)
1975       // Predicate.
1976       .addImm(ARMCC::AL)
1977       .addReg(0));
1978 
1979     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1980       .addReg(ARM::R0)
1981       .addReg(ARM::CPSR)
1982       .addImm(0)
1983       // Predicate.
1984       .addImm(ARMCC::AL)
1985       .addReg(0));
1986 
1987     const MCExpr *SymbolExpr = MCSymbolRefExpr::create(Label, OutContext);
1988     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tB)
1989       .addExpr(SymbolExpr)
1990       .addImm(ARMCC::AL)
1991       .addReg(0));
1992 
1993     OutStreamer->AddComment("eh_setjmp end");
1994     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVi8)
1995       .addReg(ARM::R0)
1996       .addReg(ARM::CPSR)
1997       .addImm(1)
1998       // Predicate.
1999       .addImm(ARMCC::AL)
2000       .addReg(0));
2001 
2002     OutStreamer->emitLabel(Label);
2003     return;
2004   }
2005 
2006   case ARM::Int_eh_sjlj_setjmp_nofp:
2007   case ARM::Int_eh_sjlj_setjmp: {
2008     // Two incoming args: GPR:$src, GPR:$val
2009     // add $val, pc, #8
2010     // str $val, [$src, #+4]
2011     // mov r0, #0
2012     // add pc, pc, #0
2013     // mov r0, #1
2014     Register SrcReg = MI->getOperand(0).getReg();
2015     Register ValReg = MI->getOperand(1).getReg();
2016 
2017     OutStreamer->AddComment("eh_setjmp begin");
2018     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
2019       .addReg(ValReg)
2020       .addReg(ARM::PC)
2021       .addImm(8)
2022       // Predicate.
2023       .addImm(ARMCC::AL)
2024       .addReg(0)
2025       // 's' bit operand (always reg0 for this).
2026       .addReg(0));
2027 
2028     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::STRi12)
2029       .addReg(ValReg)
2030       .addReg(SrcReg)
2031       .addImm(4)
2032       // Predicate.
2033       .addImm(ARMCC::AL)
2034       .addReg(0));
2035 
2036     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
2037       .addReg(ARM::R0)
2038       .addImm(0)
2039       // Predicate.
2040       .addImm(ARMCC::AL)
2041       .addReg(0)
2042       // 's' bit operand (always reg0 for this).
2043       .addReg(0));
2044 
2045     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::ADDri)
2046       .addReg(ARM::PC)
2047       .addReg(ARM::PC)
2048       .addImm(0)
2049       // Predicate.
2050       .addImm(ARMCC::AL)
2051       .addReg(0)
2052       // 's' bit operand (always reg0 for this).
2053       .addReg(0));
2054 
2055     OutStreamer->AddComment("eh_setjmp end");
2056     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::MOVi)
2057       .addReg(ARM::R0)
2058       .addImm(1)
2059       // Predicate.
2060       .addImm(ARMCC::AL)
2061       .addReg(0)
2062       // 's' bit operand (always reg0 for this).
2063       .addReg(0));
2064     return;
2065   }
2066   case ARM::Int_eh_sjlj_longjmp: {
2067     // ldr sp, [$src, #8]
2068     // ldr $scratch, [$src, #4]
2069     // ldr r7, [$src]
2070     // bx $scratch
2071     Register SrcReg = MI->getOperand(0).getReg();
2072     Register ScratchReg = MI->getOperand(1).getReg();
2073     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2074       .addReg(ARM::SP)
2075       .addReg(SrcReg)
2076       .addImm(8)
2077       // Predicate.
2078       .addImm(ARMCC::AL)
2079       .addReg(0));
2080 
2081     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2082       .addReg(ScratchReg)
2083       .addReg(SrcReg)
2084       .addImm(4)
2085       // Predicate.
2086       .addImm(ARMCC::AL)
2087       .addReg(0));
2088 
2089     const MachineFunction &MF = *MI->getParent()->getParent();
2090     const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>();
2091 
2092     if (STI.isTargetDarwin() || STI.isTargetWindows()) {
2093       // These platforms always use the same frame register
2094       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2095                                        .addReg(STI.getFramePointerReg())
2096                                        .addReg(SrcReg)
2097                                        .addImm(0)
2098                                        // Predicate.
2099                                        .addImm(ARMCC::AL)
2100                                        .addReg(0));
2101     } else {
2102       // If the calling code might use either R7 or R11 as
2103       // frame pointer register, restore it into both.
2104       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2105         .addReg(ARM::R7)
2106         .addReg(SrcReg)
2107         .addImm(0)
2108         // Predicate.
2109         .addImm(ARMCC::AL)
2110         .addReg(0));
2111       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::LDRi12)
2112         .addReg(ARM::R11)
2113         .addReg(SrcReg)
2114         .addImm(0)
2115         // Predicate.
2116         .addImm(ARMCC::AL)
2117         .addReg(0));
2118     }
2119 
2120     assert(Subtarget->hasV4TOps());
2121     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::BX)
2122       .addReg(ScratchReg)
2123       // Predicate.
2124       .addImm(ARMCC::AL)
2125       .addReg(0));
2126     return;
2127   }
2128   case ARM::tInt_eh_sjlj_longjmp: {
2129     // ldr $scratch, [$src, #8]
2130     // mov sp, $scratch
2131     // ldr $scratch, [$src, #4]
2132     // ldr r7, [$src]
2133     // bx $scratch
2134     Register SrcReg = MI->getOperand(0).getReg();
2135     Register ScratchReg = MI->getOperand(1).getReg();
2136 
2137     const MachineFunction &MF = *MI->getParent()->getParent();
2138     const ARMSubtarget &STI = MF.getSubtarget<ARMSubtarget>();
2139 
2140     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2141       .addReg(ScratchReg)
2142       .addReg(SrcReg)
2143       // The offset immediate is #8. The operand value is scaled by 4 for the
2144       // tLDR instruction.
2145       .addImm(2)
2146       // Predicate.
2147       .addImm(ARMCC::AL)
2148       .addReg(0));
2149 
2150     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tMOVr)
2151       .addReg(ARM::SP)
2152       .addReg(ScratchReg)
2153       // Predicate.
2154       .addImm(ARMCC::AL)
2155       .addReg(0));
2156 
2157     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2158       .addReg(ScratchReg)
2159       .addReg(SrcReg)
2160       .addImm(1)
2161       // Predicate.
2162       .addImm(ARMCC::AL)
2163       .addReg(0));
2164 
2165     if (STI.isTargetDarwin() || STI.isTargetWindows()) {
2166       // These platforms always use the same frame register
2167       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2168                                        .addReg(STI.getFramePointerReg())
2169                                        .addReg(SrcReg)
2170                                        .addImm(0)
2171                                        // Predicate.
2172                                        .addImm(ARMCC::AL)
2173                                        .addReg(0));
2174     } else {
2175       // If the calling code might use either R7 or R11 as
2176       // frame pointer register, restore it into both.
2177       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2178         .addReg(ARM::R7)
2179         .addReg(SrcReg)
2180         .addImm(0)
2181         // Predicate.
2182         .addImm(ARMCC::AL)
2183         .addReg(0));
2184       EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tLDRi)
2185         .addReg(ARM::R11)
2186         .addReg(SrcReg)
2187         .addImm(0)
2188         // Predicate.
2189         .addImm(ARMCC::AL)
2190         .addReg(0));
2191     }
2192 
2193     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::tBX)
2194       .addReg(ScratchReg)
2195       // Predicate.
2196       .addImm(ARMCC::AL)
2197       .addReg(0));
2198     return;
2199   }
2200   case ARM::tInt_WIN_eh_sjlj_longjmp: {
2201     // ldr.w r11, [$src, #0]
2202     // ldr.w  sp, [$src, #8]
2203     // ldr.w  pc, [$src, #4]
2204 
2205     Register SrcReg = MI->getOperand(0).getReg();
2206 
2207     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2208                                      .addReg(ARM::R11)
2209                                      .addReg(SrcReg)
2210                                      .addImm(0)
2211                                      // Predicate
2212                                      .addImm(ARMCC::AL)
2213                                      .addReg(0));
2214     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2215                                      .addReg(ARM::SP)
2216                                      .addReg(SrcReg)
2217                                      .addImm(8)
2218                                      // Predicate
2219                                      .addImm(ARMCC::AL)
2220                                      .addReg(0));
2221     EmitToStreamer(*OutStreamer, MCInstBuilder(ARM::t2LDRi12)
2222                                      .addReg(ARM::PC)
2223                                      .addReg(SrcReg)
2224                                      .addImm(4)
2225                                      // Predicate
2226                                      .addImm(ARMCC::AL)
2227                                      .addReg(0));
2228     return;
2229   }
2230   case ARM::PATCHABLE_FUNCTION_ENTER:
2231     LowerPATCHABLE_FUNCTION_ENTER(*MI);
2232     return;
2233   case ARM::PATCHABLE_FUNCTION_EXIT:
2234     LowerPATCHABLE_FUNCTION_EXIT(*MI);
2235     return;
2236   case ARM::PATCHABLE_TAIL_CALL:
2237     LowerPATCHABLE_TAIL_CALL(*MI);
2238     return;
2239   case ARM::SpeculationBarrierISBDSBEndBB: {
2240     // Print DSB SYS + ISB
2241     MCInst TmpInstDSB;
2242     TmpInstDSB.setOpcode(ARM::DSB);
2243     TmpInstDSB.addOperand(MCOperand::createImm(0xf));
2244     EmitToStreamer(*OutStreamer, TmpInstDSB);
2245     MCInst TmpInstISB;
2246     TmpInstISB.setOpcode(ARM::ISB);
2247     TmpInstISB.addOperand(MCOperand::createImm(0xf));
2248     EmitToStreamer(*OutStreamer, TmpInstISB);
2249     return;
2250   }
2251   case ARM::t2SpeculationBarrierISBDSBEndBB: {
2252     // Print DSB SYS + ISB
2253     MCInst TmpInstDSB;
2254     TmpInstDSB.setOpcode(ARM::t2DSB);
2255     TmpInstDSB.addOperand(MCOperand::createImm(0xf));
2256     TmpInstDSB.addOperand(MCOperand::createImm(ARMCC::AL));
2257     TmpInstDSB.addOperand(MCOperand::createReg(0));
2258     EmitToStreamer(*OutStreamer, TmpInstDSB);
2259     MCInst TmpInstISB;
2260     TmpInstISB.setOpcode(ARM::t2ISB);
2261     TmpInstISB.addOperand(MCOperand::createImm(0xf));
2262     TmpInstISB.addOperand(MCOperand::createImm(ARMCC::AL));
2263     TmpInstISB.addOperand(MCOperand::createReg(0));
2264     EmitToStreamer(*OutStreamer, TmpInstISB);
2265     return;
2266   }
2267   case ARM::SpeculationBarrierSBEndBB: {
2268     // Print SB
2269     MCInst TmpInstSB;
2270     TmpInstSB.setOpcode(ARM::SB);
2271     EmitToStreamer(*OutStreamer, TmpInstSB);
2272     return;
2273   }
2274   case ARM::t2SpeculationBarrierSBEndBB: {
2275     // Print SB
2276     MCInst TmpInstSB;
2277     TmpInstSB.setOpcode(ARM::t2SB);
2278     EmitToStreamer(*OutStreamer, TmpInstSB);
2279     return;
2280   }
2281 
2282   case ARM::SEH_StackAlloc:
2283     ATS.emitARMWinCFIAllocStack(MI->getOperand(0).getImm(),
2284                                 MI->getOperand(1).getImm());
2285     return;
2286 
2287   case ARM::SEH_SaveRegs:
2288   case ARM::SEH_SaveRegs_Ret:
2289     ATS.emitARMWinCFISaveRegMask(MI->getOperand(0).getImm(),
2290                                  MI->getOperand(1).getImm());
2291     return;
2292 
2293   case ARM::SEH_SaveSP:
2294     ATS.emitARMWinCFISaveSP(MI->getOperand(0).getImm());
2295     return;
2296 
2297   case ARM::SEH_SaveFRegs:
2298     ATS.emitARMWinCFISaveFRegs(MI->getOperand(0).getImm(),
2299                                MI->getOperand(1).getImm());
2300     return;
2301 
2302   case ARM::SEH_SaveLR:
2303     ATS.emitARMWinCFISaveLR(MI->getOperand(0).getImm());
2304     return;
2305 
2306   case ARM::SEH_Nop:
2307   case ARM::SEH_Nop_Ret:
2308     ATS.emitARMWinCFINop(MI->getOperand(0).getImm());
2309     return;
2310 
2311   case ARM::SEH_PrologEnd:
2312     ATS.emitARMWinCFIPrologEnd(/*Fragment=*/false);
2313     return;
2314 
2315   case ARM::SEH_EpilogStart:
2316     ATS.emitARMWinCFIEpilogStart(ARMCC::AL);
2317     return;
2318 
2319   case ARM::SEH_EpilogEnd:
2320     ATS.emitARMWinCFIEpilogEnd();
2321     return;
2322   }
2323 
2324   MCInst TmpInst;
2325   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
2326 
2327   EmitToStreamer(*OutStreamer, TmpInst);
2328 }
2329 
2330 //===----------------------------------------------------------------------===//
2331 // Target Registry Stuff
2332 //===----------------------------------------------------------------------===//
2333 
2334 // Force static initialization.
2335 extern "C" LLVM_EXTERNAL_VISIBILITY void LLVMInitializeARMAsmPrinter() {
2336   RegisterAsmPrinter<ARMAsmPrinter> X(getTheARMLETarget());
2337   RegisterAsmPrinter<ARMAsmPrinter> Y(getTheARMBETarget());
2338   RegisterAsmPrinter<ARMAsmPrinter> A(getTheThumbLETarget());
2339   RegisterAsmPrinter<ARMAsmPrinter> B(getTheThumbBETarget());
2340 }
2341