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