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