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