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