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