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