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