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