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