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