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