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