Move emitInlineAsmEnd to the AsmPrinter interface.
[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 static bool isThumb(const MCSubtargetInfo& STI) {
442   return (STI.getFeatureBits() & ARM::ModeThumb) != 0;
443 }
444
445 void ARMAsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
446                                      MCSubtargetInfo *EndInfo) const {
447   // If either end mode is unknown (EndInfo == NULL) or different than
448   // the start mode, then restore the start mode.
449   const bool WasThumb = isThumb(StartInfo);
450   if (EndInfo == NULL || WasThumb != isThumb(*EndInfo)) {
451     OutStreamer.EmitAssemblerFlag(WasThumb ? MCAF_Code16 : MCAF_Code32);
452     if (EndInfo)
453       EndInfo->ToggleFeature(ARM::ModeThumb);
454   }
455 }
456
457 void ARMAsmPrinter::EmitStartOfAsmFile(Module &M) {
458   if (Subtarget->isTargetMachO()) {
459     Reloc::Model RelocM = TM.getRelocationModel();
460     if (RelocM == Reloc::PIC_ || RelocM == Reloc::DynamicNoPIC) {
461       // Declare all the text sections up front (before the DWARF sections
462       // emitted by AsmPrinter::doInitialization) so the assembler will keep
463       // them together at the beginning of the object file.  This helps
464       // avoid out-of-range branches that are due a fundamental limitation of
465       // the way symbol offsets are encoded with the current Darwin ARM
466       // relocations.
467       const TargetLoweringObjectFileMachO &TLOFMacho =
468         static_cast<const TargetLoweringObjectFileMachO &>(
469           getObjFileLowering());
470
471       // Collect the set of sections our functions will go into.
472       SetVector<const MCSection *, SmallVector<const MCSection *, 8>,
473         SmallPtrSet<const MCSection *, 8> > TextSections;
474       // Default text section comes first.
475       TextSections.insert(TLOFMacho.getTextSection());
476       // Now any user defined text sections from function attributes.
477       for (Module::iterator F = M.begin(), e = M.end(); F != e; ++F)
478         if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage())
479           TextSections.insert(TLOFMacho.SectionForGlobal(F, Mang, TM));
480       // Now the coalescable sections.
481       TextSections.insert(TLOFMacho.getTextCoalSection());
482       TextSections.insert(TLOFMacho.getConstTextCoalSection());
483
484       // Emit the sections in the .s file header to fix the order.
485       for (unsigned i = 0, e = TextSections.size(); i != e; ++i)
486         OutStreamer.SwitchSection(TextSections[i]);
487
488       if (RelocM == Reloc::DynamicNoPIC) {
489         const MCSection *sect =
490           OutContext.getMachOSection("__TEXT", "__symbol_stub4",
491                                      MCSectionMachO::S_SYMBOL_STUBS,
492                                      12, SectionKind::getText());
493         OutStreamer.SwitchSection(sect);
494       } else {
495         const MCSection *sect =
496           OutContext.getMachOSection("__TEXT", "__picsymbolstub4",
497                                      MCSectionMachO::S_SYMBOL_STUBS,
498                                      16, SectionKind::getText());
499         OutStreamer.SwitchSection(sect);
500       }
501       const MCSection *StaticInitSect =
502         OutContext.getMachOSection("__TEXT", "__StaticInit",
503                                    MCSectionMachO::S_REGULAR |
504                                    MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
505                                    SectionKind::getText());
506       OutStreamer.SwitchSection(StaticInitSect);
507     }
508
509     // Compiling with debug info should not affect the code
510     // generation.  Ensure the cstring section comes before the
511     // optional __DWARF secion. Otherwise, PC-relative loads would
512     // have to use different instruction sequences at "-g" in order to
513     // reach global data in the same object file.
514     OutStreamer.SwitchSection(getObjFileLowering().getCStringSection());
515   }
516
517   // Use unified assembler syntax.
518   OutStreamer.EmitAssemblerFlag(MCAF_SyntaxUnified);
519
520   // Emit ARM Build Attributes
521   if (Subtarget->isTargetELF())
522     emitAttributes();
523 }
524
525
526 void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
527   if (Subtarget->isTargetMachO()) {
528     // All darwin targets use mach-o.
529     const TargetLoweringObjectFileMachO &TLOFMacho =
530       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
531     MachineModuleInfoMachO &MMIMacho =
532       MMI->getObjFileInfo<MachineModuleInfoMachO>();
533
534     // Output non-lazy-pointers for external and common global variables.
535     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
536
537     if (!Stubs.empty()) {
538       // Switch with ".non_lazy_symbol_pointer" directive.
539       OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
540       EmitAlignment(2);
541       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
542         // L_foo$stub:
543         OutStreamer.EmitLabel(Stubs[i].first);
544         //   .indirect_symbol _foo
545         MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
546         OutStreamer.EmitSymbolAttribute(MCSym.getPointer(),MCSA_IndirectSymbol);
547
548         if (MCSym.getInt())
549           // External to current translation unit.
550           OutStreamer.EmitIntValue(0, 4/*size*/);
551         else
552           // Internal to current translation unit.
553           //
554           // When we place the LSDA into the TEXT section, the type info
555           // pointers need to be indirect and pc-rel. We accomplish this by
556           // using NLPs; however, sometimes the types are local to the file.
557           // We need to fill in the value for the NLP in those cases.
558           OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
559                                                         OutContext),
560                                 4/*size*/);
561       }
562
563       Stubs.clear();
564       OutStreamer.AddBlankLine();
565     }
566
567     Stubs = MMIMacho.GetHiddenGVStubList();
568     if (!Stubs.empty()) {
569       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
570       EmitAlignment(2);
571       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
572         // L_foo$stub:
573         OutStreamer.EmitLabel(Stubs[i].first);
574         //   .long _foo
575         OutStreamer.EmitValue(MCSymbolRefExpr::
576                               Create(Stubs[i].second.getPointer(),
577                                      OutContext),
578                               4/*size*/);
579       }
580
581       Stubs.clear();
582       OutStreamer.AddBlankLine();
583     }
584
585     // Funny Darwin hack: This flag tells the linker that no global symbols
586     // contain code that falls through to other global symbols (e.g. the obvious
587     // implementation of multiple entry points).  If this doesn't occur, the
588     // linker can safely perform dead code stripping.  Since LLVM never
589     // generates code that does this, it is always safe to set.
590     OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
591   }
592 }
593
594 //===----------------------------------------------------------------------===//
595 // Helper routines for EmitStartOfAsmFile() and EmitEndOfAsmFile()
596 // FIXME:
597 // The following seem like one-off assembler flags, but they actually need
598 // to appear in the .ARM.attributes section in ELF.
599 // Instead of subclassing the MCELFStreamer, we do the work here.
600
601 static ARMBuildAttrs::CPUArch getArchForCPU(StringRef CPU,
602                                             const ARMSubtarget *Subtarget) {
603   if (CPU == "xscale")
604     return ARMBuildAttrs::v5TEJ;
605
606   if (Subtarget->hasV8Ops())
607     return ARMBuildAttrs::v8;
608   else if (Subtarget->hasV7Ops()) {
609     if (Subtarget->isMClass() && Subtarget->hasThumb2DSP())
610       return ARMBuildAttrs::v7E_M;
611     return ARMBuildAttrs::v7;
612   } else if (Subtarget->hasV6T2Ops())
613     return ARMBuildAttrs::v6T2;
614   else if (Subtarget->hasV6MOps())
615     return ARMBuildAttrs::v6S_M;
616   else if (Subtarget->hasV6Ops())
617     return ARMBuildAttrs::v6;
618   else if (Subtarget->hasV5TEOps())
619     return ARMBuildAttrs::v5TE;
620   else if (Subtarget->hasV5TOps())
621     return ARMBuildAttrs::v5T;
622   else if (Subtarget->hasV4TOps())
623     return ARMBuildAttrs::v4T;
624   else
625     return ARMBuildAttrs::v4;
626 }
627
628 void ARMAsmPrinter::emitAttributes() {
629   MCTargetStreamer &TS = *OutStreamer.getTargetStreamer();
630   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
631
632   ATS.switchVendor("aeabi");
633
634   std::string CPUString = Subtarget->getCPUString();
635
636   // FIXME: remove krait check when GNU tools support krait cpu
637   if (CPUString != "generic" && CPUString != "krait")
638     ATS.emitTextAttribute(ARMBuildAttrs::CPU_name, CPUString);
639
640   ATS.emitAttribute(ARMBuildAttrs::CPU_arch,
641                     getArchForCPU(CPUString, Subtarget));
642
643   // Tag_CPU_arch_profile must have the default value of 0 when "Architecture
644   // profile is not applicable (e.g. pre v7, or cross-profile code)". 
645   if (Subtarget->hasV7Ops()) {
646     if (Subtarget->isAClass()) {
647       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
648                         ARMBuildAttrs::ApplicationProfile);
649     } else if (Subtarget->isRClass()) {
650       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
651                         ARMBuildAttrs::RealTimeProfile);
652     } else if (Subtarget->isMClass()) {
653       ATS.emitAttribute(ARMBuildAttrs::CPU_arch_profile,
654                         ARMBuildAttrs::MicroControllerProfile);
655     }
656   }
657
658   ATS.emitAttribute(ARMBuildAttrs::ARM_ISA_use, Subtarget->hasARMOps() ?
659                       ARMBuildAttrs::Allowed : ARMBuildAttrs::Not_Allowed);
660   if (Subtarget->isThumb1Only()) {
661     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
662                       ARMBuildAttrs::Allowed);
663   } else if (Subtarget->hasThumb2()) {
664     ATS.emitAttribute(ARMBuildAttrs::THUMB_ISA_use,
665                       ARMBuildAttrs::AllowThumb32);
666   }
667
668   if (Subtarget->hasNEON()) {
669     /* NEON is not exactly a VFP architecture, but GAS emit one of
670      * neon/neon-fp-armv8/neon-vfpv4/vfpv3/vfpv2 for .fpu parameters */
671     if (Subtarget->hasFPARMv8()) {
672       if (Subtarget->hasCrypto())
673         ATS.emitFPU(ARM::CRYPTO_NEON_FP_ARMV8);
674       else
675         ATS.emitFPU(ARM::NEON_FP_ARMV8);
676     }
677     else if (Subtarget->hasVFP4())
678       ATS.emitFPU(ARM::NEON_VFPV4);
679     else
680       ATS.emitFPU(ARM::NEON);
681     // Emit Tag_Advanced_SIMD_arch for ARMv8 architecture
682     if (Subtarget->hasV8Ops())
683       ATS.emitAttribute(ARMBuildAttrs::Advanced_SIMD_arch,
684                         ARMBuildAttrs::AllowNeonARMv8);
685   } else {
686     if (Subtarget->hasFPARMv8())
687       ATS.emitFPU(ARM::FP_ARMV8);
688     else if (Subtarget->hasVFP4())
689       ATS.emitFPU(Subtarget->hasD16() ? ARM::VFPV4_D16 : ARM::VFPV4);
690     else if (Subtarget->hasVFP3())
691       ATS.emitFPU(Subtarget->hasD16() ? ARM::VFPV3_D16 : ARM::VFPV3);
692     else if (Subtarget->hasVFP2())
693       ATS.emitFPU(ARM::VFPV2);
694   }
695
696   // Signal various FP modes.
697   if (!TM.Options.UnsafeFPMath) {
698     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_denormal, ARMBuildAttrs::Allowed);
699     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_exceptions,
700                       ARMBuildAttrs::Allowed);
701   }
702
703   if (TM.Options.NoInfsFPMath && TM.Options.NoNaNsFPMath)
704     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
705                       ARMBuildAttrs::Allowed);
706   else
707     ATS.emitAttribute(ARMBuildAttrs::ABI_FP_number_model,
708                       ARMBuildAttrs::AllowIEE754);
709
710   // FIXME: add more flags to ARMBuildAttributes.h
711   // 8-bytes alignment stuff.
712   ATS.emitAttribute(ARMBuildAttrs::ABI_align_needed, 1);
713   ATS.emitAttribute(ARMBuildAttrs::ABI_align_preserved, 1);
714
715   // ABI_HardFP_use attribute to indicate single precision FP.
716   if (Subtarget->isFPOnlySP())
717     ATS.emitAttribute(ARMBuildAttrs::ABI_HardFP_use,
718                       ARMBuildAttrs::HardFPSinglePrecision);
719
720   // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
721   if (Subtarget->isAAPCS_ABI() && TM.Options.FloatABIType == FloatABI::Hard)
722     ATS.emitAttribute(ARMBuildAttrs::ABI_VFP_args, ARMBuildAttrs::HardFPAAPCS);
723
724   // FIXME: Should we signal R9 usage?
725
726   if (Subtarget->hasFP16())
727       ATS.emitAttribute(ARMBuildAttrs::FP_HP_extension, ARMBuildAttrs::AllowHPFP);
728
729   if (Subtarget->hasMPExtension())
730       ATS.emitAttribute(ARMBuildAttrs::MPextension_use, ARMBuildAttrs::AllowMP);
731
732   // Hardware divide in ARM mode is part of base arch, starting from ARMv8.
733   // If only Thumb hwdiv is present, it must also be in base arch (ARMv7-R/M).
734   // It is not possible to produce DisallowDIV: if hwdiv is present in the base
735   // arch, supplying -hwdiv downgrades the effective arch, via ClearImpliedBits.
736   // AllowDIVExt is only emitted if hwdiv isn't available in the base arch;
737   // otherwise, the default value (AllowDIVIfExists) applies.
738   if (Subtarget->hasDivideInARMMode() && !Subtarget->hasV8Ops())
739       ATS.emitAttribute(ARMBuildAttrs::DIV_use, ARMBuildAttrs::AllowDIVExt);
740
741   if (Subtarget->hasTrustZone() && Subtarget->hasVirtualization())
742       ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
743                         ARMBuildAttrs::AllowTZVirtualization);
744   else if (Subtarget->hasTrustZone())
745       ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
746                         ARMBuildAttrs::AllowTZ);
747   else if (Subtarget->hasVirtualization())
748       ATS.emitAttribute(ARMBuildAttrs::Virtualization_use,
749                         ARMBuildAttrs::AllowVirtualization);
750
751   ATS.finishAttributeSection();
752 }
753
754 void ARMAsmPrinter::emitARMAttributeSection() {
755   // <format-version>
756   // [ <section-length> "vendor-name"
757   // [ <file-tag> <size> <attribute>*
758   //   | <section-tag> <size> <section-number>* 0 <attribute>*
759   //   | <symbol-tag> <size> <symbol-number>* 0 <attribute>*
760   //   ]+
761   // ]*
762
763   if (OutStreamer.hasRawTextSupport())
764     return;
765
766   const ARMElfTargetObjectFile &TLOFELF =
767     static_cast<const ARMElfTargetObjectFile &>
768     (getObjFileLowering());
769
770   OutStreamer.SwitchSection(TLOFELF.getAttributesSection());
771
772   // Format version
773   OutStreamer.EmitIntValue(0x41, 1);
774 }
775
776 //===----------------------------------------------------------------------===//
777
778 static MCSymbol *getPICLabel(const char *Prefix, unsigned FunctionNumber,
779                              unsigned LabelId, MCContext &Ctx) {
780
781   MCSymbol *Label = Ctx.GetOrCreateSymbol(Twine(Prefix)
782                        + "PC" + Twine(FunctionNumber) + "_" + Twine(LabelId));
783   return Label;
784 }
785
786 static MCSymbolRefExpr::VariantKind
787 getModifierVariantKind(ARMCP::ARMCPModifier Modifier) {
788   switch (Modifier) {
789   case ARMCP::no_modifier: return MCSymbolRefExpr::VK_None;
790   case ARMCP::TLSGD:       return MCSymbolRefExpr::VK_TLSGD;
791   case ARMCP::TPOFF:       return MCSymbolRefExpr::VK_TPOFF;
792   case ARMCP::GOTTPOFF:    return MCSymbolRefExpr::VK_GOTTPOFF;
793   case ARMCP::GOT:         return MCSymbolRefExpr::VK_GOT;
794   case ARMCP::GOTOFF:      return MCSymbolRefExpr::VK_GOTOFF;
795   }
796   llvm_unreachable("Invalid ARMCPModifier!");
797 }
798
799 MCSymbol *ARMAsmPrinter::GetARMGVSymbol(const GlobalValue *GV,
800                                         unsigned char TargetFlags) {
801   bool isIndirect = Subtarget->isTargetMachO() &&
802     (TargetFlags & ARMII::MO_NONLAZY) &&
803     Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
804   if (!isIndirect)
805     return getSymbol(GV);
806
807   // FIXME: Remove this when Darwin transition to @GOT like syntax.
808   MCSymbol *MCSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
809   MachineModuleInfoMachO &MMIMachO =
810     MMI->getObjFileInfo<MachineModuleInfoMachO>();
811   MachineModuleInfoImpl::StubValueTy &StubSym =
812     GV->hasHiddenVisibility() ? MMIMachO.getHiddenGVStubEntry(MCSym) :
813     MMIMachO.getGVStubEntry(MCSym);
814   if (StubSym.getPointer() == 0)
815     StubSym = MachineModuleInfoImpl::
816       StubValueTy(getSymbol(GV), !GV->hasInternalLinkage());
817   return MCSym;
818 }
819
820 void ARMAsmPrinter::
821 EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
822   const DataLayout *DL = TM.getDataLayout();
823   int Size = TM.getDataLayout()->getTypeAllocSize(MCPV->getType());
824
825   ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
826
827   MCSymbol *MCSym;
828   if (ACPV->isLSDA()) {
829     SmallString<128> Str;
830     raw_svector_ostream OS(Str);
831     OS << DL->getPrivateGlobalPrefix() << "_LSDA_" << getFunctionNumber();
832     MCSym = OutContext.GetOrCreateSymbol(OS.str());
833   } else if (ACPV->isBlockAddress()) {
834     const BlockAddress *BA =
835       cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress();
836     MCSym = GetBlockAddressSymbol(BA);
837   } else if (ACPV->isGlobalValue()) {
838     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
839
840     // On Darwin, const-pool entries may get the "FOO$non_lazy_ptr" mangling, so
841     // flag the global as MO_NONLAZY.
842     unsigned char TF = Subtarget->isTargetMachO() ? ARMII::MO_NONLAZY : 0;
843     MCSym = GetARMGVSymbol(GV, TF);
844   } else if (ACPV->isMachineBasicBlock()) {
845     const MachineBasicBlock *MBB = cast<ARMConstantPoolMBB>(ACPV)->getMBB();
846     MCSym = MBB->getSymbol();
847   } else {
848     assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
849     const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
850     MCSym = GetExternalSymbolSymbol(Sym);
851   }
852
853   // Create an MCSymbol for the reference.
854   const MCExpr *Expr =
855     MCSymbolRefExpr::Create(MCSym, getModifierVariantKind(ACPV->getModifier()),
856                             OutContext);
857
858   if (ACPV->getPCAdjustment()) {
859     MCSymbol *PCLabel = getPICLabel(DL->getPrivateGlobalPrefix(),
860                                     getFunctionNumber(),
861                                     ACPV->getLabelId(),
862                                     OutContext);
863     const MCExpr *PCRelExpr = MCSymbolRefExpr::Create(PCLabel, OutContext);
864     PCRelExpr =
865       MCBinaryExpr::CreateAdd(PCRelExpr,
866                               MCConstantExpr::Create(ACPV->getPCAdjustment(),
867                                                      OutContext),
868                               OutContext);
869     if (ACPV->mustAddCurrentAddress()) {
870       // We want "(<expr> - .)", but MC doesn't have a concept of the '.'
871       // label, so just emit a local label end reference that instead.
872       MCSymbol *DotSym = OutContext.CreateTempSymbol();
873       OutStreamer.EmitLabel(DotSym);
874       const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
875       PCRelExpr = MCBinaryExpr::CreateSub(PCRelExpr, DotExpr, OutContext);
876     }
877     Expr = MCBinaryExpr::CreateSub(Expr, PCRelExpr, OutContext);
878   }
879   OutStreamer.EmitValue(Expr, Size);
880 }
881
882 void ARMAsmPrinter::EmitJumpTable(const MachineInstr *MI) {
883   unsigned Opcode = MI->getOpcode();
884   int OpNum = 1;
885   if (Opcode == ARM::BR_JTadd)
886     OpNum = 2;
887   else if (Opcode == ARM::BR_JTm)
888     OpNum = 3;
889
890   const MachineOperand &MO1 = MI->getOperand(OpNum);
891   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
892   unsigned JTI = MO1.getIndex();
893
894   // Emit a label for the jump table.
895   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
896   OutStreamer.EmitLabel(JTISymbol);
897
898   // Mark the jump table as data-in-code.
899   OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
900
901   // Emit each entry of the table.
902   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
903   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
904   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
905
906   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
907     MachineBasicBlock *MBB = JTBBs[i];
908     // Construct an MCExpr for the entry. We want a value of the form:
909     // (BasicBlockAddr - TableBeginAddr)
910     //
911     // For example, a table with entries jumping to basic blocks BB0 and BB1
912     // would look like:
913     // LJTI_0_0:
914     //    .word (LBB0 - LJTI_0_0)
915     //    .word (LBB1 - LJTI_0_0)
916     const MCExpr *Expr = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
917
918     if (TM.getRelocationModel() == Reloc::PIC_)
919       Expr = MCBinaryExpr::CreateSub(Expr, MCSymbolRefExpr::Create(JTISymbol,
920                                                                    OutContext),
921                                      OutContext);
922     // If we're generating a table of Thumb addresses in static relocation
923     // model, we need to add one to keep interworking correctly.
924     else if (AFI->isThumbFunction())
925       Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(1,OutContext),
926                                      OutContext);
927     OutStreamer.EmitValue(Expr, 4);
928   }
929   // Mark the end of jump table data-in-code region.
930   OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
931 }
932
933 void ARMAsmPrinter::EmitJump2Table(const MachineInstr *MI) {
934   unsigned Opcode = MI->getOpcode();
935   int OpNum = (Opcode == ARM::t2BR_JT) ? 2 : 1;
936   const MachineOperand &MO1 = MI->getOperand(OpNum);
937   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
938   unsigned JTI = MO1.getIndex();
939
940   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
941   OutStreamer.EmitLabel(JTISymbol);
942
943   // Emit each entry of the table.
944   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
945   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
946   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
947   unsigned OffsetWidth = 4;
948   if (MI->getOpcode() == ARM::t2TBB_JT) {
949     OffsetWidth = 1;
950     // Mark the jump table as data-in-code.
951     OutStreamer.EmitDataRegion(MCDR_DataRegionJT8);
952   } else if (MI->getOpcode() == ARM::t2TBH_JT) {
953     OffsetWidth = 2;
954     // Mark the jump table as data-in-code.
955     OutStreamer.EmitDataRegion(MCDR_DataRegionJT16);
956   }
957
958   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
959     MachineBasicBlock *MBB = JTBBs[i];
960     const MCExpr *MBBSymbolExpr = MCSymbolRefExpr::Create(MBB->getSymbol(),
961                                                       OutContext);
962     // If this isn't a TBB or TBH, the entries are direct branch instructions.
963     if (OffsetWidth == 4) {
964       OutStreamer.EmitInstruction(MCInstBuilder(ARM::t2B)
965         .addExpr(MBBSymbolExpr)
966         .addImm(ARMCC::AL)
967         .addReg(0));
968       continue;
969     }
970     // Otherwise it's an offset from the dispatch instruction. Construct an
971     // MCExpr for the entry. We want a value of the form:
972     // (BasicBlockAddr - TableBeginAddr) / 2
973     //
974     // For example, a TBB table with entries jumping to basic blocks BB0 and BB1
975     // would look like:
976     // LJTI_0_0:
977     //    .byte (LBB0 - LJTI_0_0) / 2
978     //    .byte (LBB1 - LJTI_0_0) / 2
979     const MCExpr *Expr =
980       MCBinaryExpr::CreateSub(MBBSymbolExpr,
981                               MCSymbolRefExpr::Create(JTISymbol, OutContext),
982                               OutContext);
983     Expr = MCBinaryExpr::CreateDiv(Expr, MCConstantExpr::Create(2, OutContext),
984                                    OutContext);
985     OutStreamer.EmitValue(Expr, OffsetWidth);
986   }
987   // Mark the end of jump table data-in-code region. 32-bit offsets use
988   // actual branch instructions here, so we don't mark those as a data-region
989   // at all.
990   if (OffsetWidth != 4)
991     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
992 }
993
994 void ARMAsmPrinter::EmitUnwindingInstruction(const MachineInstr *MI) {
995   assert(MI->getFlag(MachineInstr::FrameSetup) &&
996       "Only instruction which are involved into frame setup code are allowed");
997
998   MCTargetStreamer &TS = *OutStreamer.getTargetStreamer();
999   ARMTargetStreamer &ATS = static_cast<ARMTargetStreamer &>(TS);
1000   const MachineFunction &MF = *MI->getParent()->getParent();
1001   const TargetRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
1002   const ARMFunctionInfo &AFI = *MF.getInfo<ARMFunctionInfo>();
1003
1004   unsigned FramePtr = RegInfo->getFrameRegister(MF);
1005   unsigned Opc = MI->getOpcode();
1006   unsigned SrcReg, DstReg;
1007
1008   if (Opc == ARM::tPUSH || Opc == ARM::tLDRpci) {
1009     // Two special cases:
1010     // 1) tPUSH does not have src/dst regs.
1011     // 2) for Thumb1 code we sometimes materialize the constant via constpool
1012     // load. Yes, this is pretty fragile, but for now I don't see better
1013     // way... :(
1014     SrcReg = DstReg = ARM::SP;
1015   } else {
1016     SrcReg = MI->getOperand(1).getReg();
1017     DstReg = MI->getOperand(0).getReg();
1018   }
1019
1020   // Try to figure out the unwinding opcode out of src / dst regs.
1021   if (MI->mayStore()) {
1022     // Register saves.
1023     assert(DstReg == ARM::SP &&
1024            "Only stack pointer as a destination reg is supported");
1025
1026     SmallVector<unsigned, 4> RegList;
1027     // Skip src & dst reg, and pred ops.
1028     unsigned StartOp = 2 + 2;
1029     // Use all the operands.
1030     unsigned NumOffset = 0;
1031
1032     switch (Opc) {
1033     default:
1034       MI->dump();
1035       llvm_unreachable("Unsupported opcode for unwinding information");
1036     case ARM::tPUSH:
1037       // Special case here: no src & dst reg, but two extra imp ops.
1038       StartOp = 2; NumOffset = 2;
1039     case ARM::STMDB_UPD:
1040     case ARM::t2STMDB_UPD:
1041     case ARM::VSTMDDB_UPD:
1042       assert(SrcReg == ARM::SP &&
1043              "Only stack pointer as a source reg is supported");
1044       for (unsigned i = StartOp, NumOps = MI->getNumOperands() - NumOffset;
1045            i != NumOps; ++i) {
1046         const MachineOperand &MO = MI->getOperand(i);
1047         // Actually, there should never be any impdef stuff here. Skip it
1048         // temporary to workaround PR11902.
1049         if (MO.isImplicit())
1050           continue;
1051         RegList.push_back(MO.getReg());
1052       }
1053       break;
1054     case ARM::STR_PRE_IMM:
1055     case ARM::STR_PRE_REG:
1056     case ARM::t2STR_PRE:
1057       assert(MI->getOperand(2).getReg() == ARM::SP &&
1058              "Only stack pointer as a source reg is supported");
1059       RegList.push_back(SrcReg);
1060       break;
1061     }
1062     ATS.emitRegSave(RegList, Opc == ARM::VSTMDDB_UPD);
1063   } else {
1064     // Changes of stack / frame pointer.
1065     if (SrcReg == ARM::SP) {
1066       int64_t Offset = 0;
1067       switch (Opc) {
1068       default:
1069         MI->dump();
1070         llvm_unreachable("Unsupported opcode for unwinding information");
1071       case ARM::MOVr:
1072       case ARM::tMOVr:
1073         Offset = 0;
1074         break;
1075       case ARM::ADDri:
1076         Offset = -MI->getOperand(2).getImm();
1077         break;
1078       case ARM::SUBri:
1079       case ARM::t2SUBri:
1080         Offset = MI->getOperand(2).getImm();
1081         break;
1082       case ARM::tSUBspi:
1083         Offset = MI->getOperand(2).getImm()*4;
1084         break;
1085       case ARM::tADDspi:
1086       case ARM::tADDrSPi:
1087         Offset = -MI->getOperand(2).getImm()*4;
1088         break;
1089       case ARM::tLDRpci: {
1090         // Grab the constpool index and check, whether it corresponds to
1091         // original or cloned constpool entry.
1092         unsigned CPI = MI->getOperand(1).getIndex();
1093         const MachineConstantPool *MCP = MF.getConstantPool();
1094         if (CPI >= MCP->getConstants().size())
1095           CPI = AFI.getOriginalCPIdx(CPI);
1096         assert(CPI != -1U && "Invalid constpool index");
1097
1098         // Derive the actual offset.
1099         const MachineConstantPoolEntry &CPE = MCP->getConstants()[CPI];
1100         assert(!CPE.isMachineConstantPoolEntry() && "Invalid constpool entry");
1101         // FIXME: Check for user, it should be "add" instruction!
1102         Offset = -cast<ConstantInt>(CPE.Val.ConstVal)->getSExtValue();
1103         break;
1104       }
1105       }
1106
1107       if (DstReg == FramePtr && FramePtr != ARM::SP)
1108         // Set-up of the frame pointer. Positive values correspond to "add"
1109         // instruction.
1110         ATS.emitSetFP(FramePtr, ARM::SP, -Offset);
1111       else if (DstReg == ARM::SP) {
1112         // Change of SP by an offset. Positive values correspond to "sub"
1113         // instruction.
1114         ATS.emitPad(Offset);
1115       } else {
1116         MI->dump();
1117         llvm_unreachable("Unsupported opcode for unwinding information");
1118       }
1119     } else if (DstReg == ARM::SP) {
1120       // FIXME: .movsp goes here
1121       MI->dump();
1122       llvm_unreachable("Unsupported opcode for unwinding information");
1123     }
1124     else {
1125       MI->dump();
1126       llvm_unreachable("Unsupported opcode for unwinding information");
1127     }
1128   }
1129 }
1130
1131 extern cl::opt<bool> EnableARMEHABI;
1132
1133 // Simple pseudo-instructions have their lowering (with expansion to real
1134 // instructions) auto-generated.
1135 #include "ARMGenMCPseudoLowering.inc"
1136
1137 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1138   const DataLayout *DL = TM.getDataLayout();
1139
1140   // If we just ended a constant pool, mark it as such.
1141   if (InConstantPool && MI->getOpcode() != ARM::CONSTPOOL_ENTRY) {
1142     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
1143     InConstantPool = false;
1144   }
1145
1146   // Emit unwinding stuff for frame-related instructions
1147   if (EnableARMEHABI && MI->getFlag(MachineInstr::FrameSetup))
1148     EmitUnwindingInstruction(MI);
1149
1150   // Do any auto-generated pseudo lowerings.
1151   if (emitPseudoExpansionLowering(OutStreamer, MI))
1152     return;
1153
1154   assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
1155          "Pseudo flag setting opcode should be expanded early");
1156
1157   // Check for manual lowerings.
1158   unsigned Opc = MI->getOpcode();
1159   switch (Opc) {
1160   case ARM::t2MOVi32imm: llvm_unreachable("Should be lowered by thumb2it pass");
1161   case ARM::DBG_VALUE: llvm_unreachable("Should be handled by generic printing");
1162   case ARM::LEApcrel:
1163   case ARM::tLEApcrel:
1164   case ARM::t2LEApcrel: {
1165     // FIXME: Need to also handle globals and externals
1166     MCSymbol *CPISymbol = GetCPISymbol(MI->getOperand(1).getIndex());
1167     OutStreamer.EmitInstruction(MCInstBuilder(MI->getOpcode() ==
1168                                               ARM::t2LEApcrel ? ARM::t2ADR
1169                   : (MI->getOpcode() == ARM::tLEApcrel ? ARM::tADR
1170                      : ARM::ADR))
1171       .addReg(MI->getOperand(0).getReg())
1172       .addExpr(MCSymbolRefExpr::Create(CPISymbol, OutContext))
1173       // Add predicate operands.
1174       .addImm(MI->getOperand(2).getImm())
1175       .addReg(MI->getOperand(3).getReg()));
1176     return;
1177   }
1178   case ARM::LEApcrelJT:
1179   case ARM::tLEApcrelJT:
1180   case ARM::t2LEApcrelJT: {
1181     MCSymbol *JTIPICSymbol =
1182       GetARMJTIPICJumpTableLabel2(MI->getOperand(1).getIndex(),
1183                                   MI->getOperand(2).getImm());
1184     OutStreamer.EmitInstruction(MCInstBuilder(MI->getOpcode() ==
1185                                               ARM::t2LEApcrelJT ? ARM::t2ADR
1186                   : (MI->getOpcode() == ARM::tLEApcrelJT ? ARM::tADR
1187                      : ARM::ADR))
1188       .addReg(MI->getOperand(0).getReg())
1189       .addExpr(MCSymbolRefExpr::Create(JTIPICSymbol, OutContext))
1190       // Add predicate operands.
1191       .addImm(MI->getOperand(3).getImm())
1192       .addReg(MI->getOperand(4).getReg()));
1193     return;
1194   }
1195   // Darwin call instructions are just normal call instructions with different
1196   // clobber semantics (they clobber R9).
1197   case ARM::BX_CALL: {
1198     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVr)
1199       .addReg(ARM::LR)
1200       .addReg(ARM::PC)
1201       // Add predicate operands.
1202       .addImm(ARMCC::AL)
1203       .addReg(0)
1204       // Add 's' bit operand (always reg0 for this)
1205       .addReg(0));
1206
1207     OutStreamer.EmitInstruction(MCInstBuilder(ARM::BX)
1208       .addReg(MI->getOperand(0).getReg()));
1209     return;
1210   }
1211   case ARM::tBX_CALL: {
1212     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVr)
1213       .addReg(ARM::LR)
1214       .addReg(ARM::PC)
1215       // Add predicate operands.
1216       .addImm(ARMCC::AL)
1217       .addReg(0));
1218
1219     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tBX)
1220       .addReg(MI->getOperand(0).getReg())
1221       // Add predicate operands.
1222       .addImm(ARMCC::AL)
1223       .addReg(0));
1224     return;
1225   }
1226   case ARM::BMOVPCRX_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     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVr)
1237       .addReg(ARM::PC)
1238       .addReg(MI->getOperand(0).getReg())
1239       // Add predicate operands.
1240       .addImm(ARMCC::AL)
1241       .addReg(0)
1242       // Add 's' bit operand (always reg0 for this)
1243       .addReg(0));
1244     return;
1245   }
1246   case ARM::BMOVPCB_CALL: {
1247     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVr)
1248       .addReg(ARM::LR)
1249       .addReg(ARM::PC)
1250       // Add predicate operands.
1251       .addImm(ARMCC::AL)
1252       .addReg(0)
1253       // Add 's' bit operand (always reg0 for this)
1254       .addReg(0));
1255
1256     const GlobalValue *GV = MI->getOperand(0).getGlobal();
1257     MCSymbol *GVSym = getSymbol(GV);
1258     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1259     OutStreamer.EmitInstruction(MCInstBuilder(ARM::Bcc)
1260       .addExpr(GVSymExpr)
1261       // Add predicate operands.
1262       .addImm(ARMCC::AL)
1263       .addReg(0));
1264     return;
1265   }
1266   case ARM::MOVi16_ga_pcrel:
1267   case ARM::t2MOVi16_ga_pcrel: {
1268     MCInst TmpInst;
1269     TmpInst.setOpcode(Opc == ARM::MOVi16_ga_pcrel? ARM::MOVi16 : ARM::t2MOVi16);
1270     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1271
1272     unsigned TF = MI->getOperand(1).getTargetFlags();
1273     const GlobalValue *GV = MI->getOperand(1).getGlobal();
1274     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1275     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1276
1277     MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
1278                                      getFunctionNumber(),
1279                                      MI->getOperand(2).getImm(), OutContext);
1280     const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
1281     unsigned PCAdj = (Opc == ARM::MOVi16_ga_pcrel) ? 8 : 4;
1282     const MCExpr *PCRelExpr =
1283       ARMMCExpr::CreateLower16(MCBinaryExpr::CreateSub(GVSymExpr,
1284                                       MCBinaryExpr::CreateAdd(LabelSymExpr,
1285                                       MCConstantExpr::Create(PCAdj, OutContext),
1286                                       OutContext), OutContext), OutContext);
1287       TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
1288
1289     // Add predicate operands.
1290     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1291     TmpInst.addOperand(MCOperand::CreateReg(0));
1292     // Add 's' bit operand (always reg0 for this)
1293     TmpInst.addOperand(MCOperand::CreateReg(0));
1294     OutStreamer.EmitInstruction(TmpInst);
1295     return;
1296   }
1297   case ARM::MOVTi16_ga_pcrel:
1298   case ARM::t2MOVTi16_ga_pcrel: {
1299     MCInst TmpInst;
1300     TmpInst.setOpcode(Opc == ARM::MOVTi16_ga_pcrel
1301                       ? ARM::MOVTi16 : ARM::t2MOVTi16);
1302     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1303     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1304
1305     unsigned TF = MI->getOperand(2).getTargetFlags();
1306     const GlobalValue *GV = MI->getOperand(2).getGlobal();
1307     MCSymbol *GVSym = GetARMGVSymbol(GV, TF);
1308     const MCExpr *GVSymExpr = MCSymbolRefExpr::Create(GVSym, OutContext);
1309
1310     MCSymbol *LabelSym = getPICLabel(DL->getPrivateGlobalPrefix(),
1311                                      getFunctionNumber(),
1312                                      MI->getOperand(3).getImm(), OutContext);
1313     const MCExpr *LabelSymExpr= MCSymbolRefExpr::Create(LabelSym, OutContext);
1314     unsigned PCAdj = (Opc == ARM::MOVTi16_ga_pcrel) ? 8 : 4;
1315     const MCExpr *PCRelExpr =
1316         ARMMCExpr::CreateUpper16(MCBinaryExpr::CreateSub(GVSymExpr,
1317                                    MCBinaryExpr::CreateAdd(LabelSymExpr,
1318                                       MCConstantExpr::Create(PCAdj, OutContext),
1319                                           OutContext), OutContext), OutContext);
1320       TmpInst.addOperand(MCOperand::CreateExpr(PCRelExpr));
1321     // Add predicate operands.
1322     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1323     TmpInst.addOperand(MCOperand::CreateReg(0));
1324     // Add 's' bit operand (always reg0 for this)
1325     TmpInst.addOperand(MCOperand::CreateReg(0));
1326     OutStreamer.EmitInstruction(TmpInst);
1327     return;
1328   }
1329   case ARM::tPICADD: {
1330     // This is a pseudo op for a label + instruction sequence, which looks like:
1331     // LPC0:
1332     //     add r0, pc
1333     // This adds the address of LPC0 to r0.
1334
1335     // Emit the label.
1336     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1337                           getFunctionNumber(), MI->getOperand(2).getImm(),
1338                           OutContext));
1339
1340     // Form and emit the add.
1341     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tADDhirr)
1342       .addReg(MI->getOperand(0).getReg())
1343       .addReg(MI->getOperand(0).getReg())
1344       .addReg(ARM::PC)
1345       // Add predicate operands.
1346       .addImm(ARMCC::AL)
1347       .addReg(0));
1348     return;
1349   }
1350   case ARM::PICADD: {
1351     // This is a pseudo op for a label + instruction sequence, which looks like:
1352     // LPC0:
1353     //     add r0, pc, r0
1354     // This adds the address of LPC0 to r0.
1355
1356     // Emit the label.
1357     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1358                           getFunctionNumber(), MI->getOperand(2).getImm(),
1359                           OutContext));
1360
1361     // Form and emit the add.
1362     OutStreamer.EmitInstruction(MCInstBuilder(ARM::ADDrr)
1363       .addReg(MI->getOperand(0).getReg())
1364       .addReg(ARM::PC)
1365       .addReg(MI->getOperand(1).getReg())
1366       // Add predicate operands.
1367       .addImm(MI->getOperand(3).getImm())
1368       .addReg(MI->getOperand(4).getReg())
1369       // Add 's' bit operand (always reg0 for this)
1370       .addReg(0));
1371     return;
1372   }
1373   case ARM::PICSTR:
1374   case ARM::PICSTRB:
1375   case ARM::PICSTRH:
1376   case ARM::PICLDR:
1377   case ARM::PICLDRB:
1378   case ARM::PICLDRH:
1379   case ARM::PICLDRSB:
1380   case ARM::PICLDRSH: {
1381     // This is a pseudo op for a label + instruction sequence, which looks like:
1382     // LPC0:
1383     //     OP r0, [pc, r0]
1384     // The LCP0 label is referenced by a constant pool entry in order to get
1385     // a PC-relative address at the ldr instruction.
1386
1387     // Emit the label.
1388     OutStreamer.EmitLabel(getPICLabel(DL->getPrivateGlobalPrefix(),
1389                           getFunctionNumber(), MI->getOperand(2).getImm(),
1390                           OutContext));
1391
1392     // Form and emit the load
1393     unsigned Opcode;
1394     switch (MI->getOpcode()) {
1395     default:
1396       llvm_unreachable("Unexpected opcode!");
1397     case ARM::PICSTR:   Opcode = ARM::STRrs; break;
1398     case ARM::PICSTRB:  Opcode = ARM::STRBrs; break;
1399     case ARM::PICSTRH:  Opcode = ARM::STRH; break;
1400     case ARM::PICLDR:   Opcode = ARM::LDRrs; break;
1401     case ARM::PICLDRB:  Opcode = ARM::LDRBrs; break;
1402     case ARM::PICLDRH:  Opcode = ARM::LDRH; break;
1403     case ARM::PICLDRSB: Opcode = ARM::LDRSB; break;
1404     case ARM::PICLDRSH: Opcode = ARM::LDRSH; break;
1405     }
1406     OutStreamer.EmitInstruction(MCInstBuilder(Opcode)
1407       .addReg(MI->getOperand(0).getReg())
1408       .addReg(ARM::PC)
1409       .addReg(MI->getOperand(1).getReg())
1410       .addImm(0)
1411       // Add predicate operands.
1412       .addImm(MI->getOperand(3).getImm())
1413       .addReg(MI->getOperand(4).getReg()));
1414
1415     return;
1416   }
1417   case ARM::CONSTPOOL_ENTRY: {
1418     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1419     /// in the function.  The first operand is the ID# for this instruction, the
1420     /// second is the index into the MachineConstantPool that this is, the third
1421     /// is the size in bytes of this constant pool entry.
1422     /// The required alignment is specified on the basic block holding this MI.
1423     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1424     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1425
1426     // If this is the first entry of the pool, mark it.
1427     if (!InConstantPool) {
1428       OutStreamer.EmitDataRegion(MCDR_DataRegion);
1429       InConstantPool = true;
1430     }
1431
1432     OutStreamer.EmitLabel(GetCPISymbol(LabelId));
1433
1434     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1435     if (MCPE.isMachineConstantPoolEntry())
1436       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1437     else
1438       EmitGlobalConstant(MCPE.Val.ConstVal);
1439     return;
1440   }
1441   case ARM::t2BR_JT: {
1442     // Lower and emit the instruction itself, then the jump table following it.
1443     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVr)
1444       .addReg(ARM::PC)
1445       .addReg(MI->getOperand(0).getReg())
1446       // Add predicate operands.
1447       .addImm(ARMCC::AL)
1448       .addReg(0));
1449
1450     // Output the data for the jump table itself
1451     EmitJump2Table(MI);
1452     return;
1453   }
1454   case ARM::t2TBB_JT: {
1455     // Lower and emit the instruction itself, then the jump table following it.
1456     OutStreamer.EmitInstruction(MCInstBuilder(ARM::t2TBB)
1457       .addReg(ARM::PC)
1458       .addReg(MI->getOperand(0).getReg())
1459       // Add predicate operands.
1460       .addImm(ARMCC::AL)
1461       .addReg(0));
1462
1463     // Output the data for the jump table itself
1464     EmitJump2Table(MI);
1465     // Make sure the next instruction is 2-byte aligned.
1466     EmitAlignment(1);
1467     return;
1468   }
1469   case ARM::t2TBH_JT: {
1470     // Lower and emit the instruction itself, then the jump table following it.
1471     OutStreamer.EmitInstruction(MCInstBuilder(ARM::t2TBH)
1472       .addReg(ARM::PC)
1473       .addReg(MI->getOperand(0).getReg())
1474       // Add predicate operands.
1475       .addImm(ARMCC::AL)
1476       .addReg(0));
1477
1478     // Output the data for the jump table itself
1479     EmitJump2Table(MI);
1480     return;
1481   }
1482   case ARM::tBR_JTr:
1483   case ARM::BR_JTr: {
1484     // Lower and emit the instruction itself, then the jump table following it.
1485     // mov pc, target
1486     MCInst TmpInst;
1487     unsigned Opc = MI->getOpcode() == ARM::BR_JTr ?
1488       ARM::MOVr : ARM::tMOVr;
1489     TmpInst.setOpcode(Opc);
1490     TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1491     TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1492     // Add predicate operands.
1493     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1494     TmpInst.addOperand(MCOperand::CreateReg(0));
1495     // Add 's' bit operand (always reg0 for this)
1496     if (Opc == ARM::MOVr)
1497       TmpInst.addOperand(MCOperand::CreateReg(0));
1498     OutStreamer.EmitInstruction(TmpInst);
1499
1500     // Make sure the Thumb jump table is 4-byte aligned.
1501     if (Opc == ARM::tMOVr)
1502       EmitAlignment(2);
1503
1504     // Output the data for the jump table itself
1505     EmitJumpTable(MI);
1506     return;
1507   }
1508   case ARM::BR_JTm: {
1509     // Lower and emit the instruction itself, then the jump table following it.
1510     // ldr pc, target
1511     MCInst TmpInst;
1512     if (MI->getOperand(1).getReg() == 0) {
1513       // literal offset
1514       TmpInst.setOpcode(ARM::LDRi12);
1515       TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1516       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1517       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1518     } else {
1519       TmpInst.setOpcode(ARM::LDRrs);
1520       TmpInst.addOperand(MCOperand::CreateReg(ARM::PC));
1521       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1522       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1523       TmpInst.addOperand(MCOperand::CreateImm(0));
1524     }
1525     // Add predicate operands.
1526     TmpInst.addOperand(MCOperand::CreateImm(ARMCC::AL));
1527     TmpInst.addOperand(MCOperand::CreateReg(0));
1528     OutStreamer.EmitInstruction(TmpInst);
1529
1530     // Output the data for the jump table itself
1531     EmitJumpTable(MI);
1532     return;
1533   }
1534   case ARM::BR_JTadd: {
1535     // Lower and emit the instruction itself, then the jump table following it.
1536     // add pc, target, idx
1537     OutStreamer.EmitInstruction(MCInstBuilder(ARM::ADDrr)
1538       .addReg(ARM::PC)
1539       .addReg(MI->getOperand(0).getReg())
1540       .addReg(MI->getOperand(1).getReg())
1541       // Add predicate operands.
1542       .addImm(ARMCC::AL)
1543       .addReg(0)
1544       // Add 's' bit operand (always reg0 for this)
1545       .addReg(0));
1546
1547     // Output the data for the jump table itself
1548     EmitJumpTable(MI);
1549     return;
1550   }
1551   case ARM::TRAP: {
1552     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1553     // FIXME: Remove this special case when they do.
1554     if (!Subtarget->isTargetMachO()) {
1555       //.long 0xe7ffdefe @ trap
1556       uint32_t Val = 0xe7ffdefeUL;
1557       OutStreamer.AddComment("trap");
1558       OutStreamer.EmitIntValue(Val, 4);
1559       return;
1560     }
1561     break;
1562   }
1563   case ARM::TRAPNaCl: {
1564     //.long 0xe7fedef0 @ trap
1565     uint32_t Val = 0xe7fedef0UL;
1566     OutStreamer.AddComment("trap");
1567     OutStreamer.EmitIntValue(Val, 4);
1568     return;
1569   }
1570   case ARM::tTRAP: {
1571     // Non-Darwin binutils don't yet support the "trap" mnemonic.
1572     // FIXME: Remove this special case when they do.
1573     if (!Subtarget->isTargetMachO()) {
1574       //.short 57086 @ trap
1575       uint16_t Val = 0xdefe;
1576       OutStreamer.AddComment("trap");
1577       OutStreamer.EmitIntValue(Val, 2);
1578       return;
1579     }
1580     break;
1581   }
1582   case ARM::t2Int_eh_sjlj_setjmp:
1583   case ARM::t2Int_eh_sjlj_setjmp_nofp:
1584   case ARM::tInt_eh_sjlj_setjmp: {
1585     // Two incoming args: GPR:$src, GPR:$val
1586     // mov $val, pc
1587     // adds $val, #7
1588     // str $val, [$src, #4]
1589     // movs r0, #0
1590     // b 1f
1591     // movs r0, #1
1592     // 1:
1593     unsigned SrcReg = MI->getOperand(0).getReg();
1594     unsigned ValReg = MI->getOperand(1).getReg();
1595     MCSymbol *Label = GetARMSJLJEHLabel();
1596     OutStreamer.AddComment("eh_setjmp begin");
1597     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVr)
1598       .addReg(ValReg)
1599       .addReg(ARM::PC)
1600       // Predicate.
1601       .addImm(ARMCC::AL)
1602       .addReg(0));
1603
1604     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tADDi3)
1605       .addReg(ValReg)
1606       // 's' bit operand
1607       .addReg(ARM::CPSR)
1608       .addReg(ValReg)
1609       .addImm(7)
1610       // Predicate.
1611       .addImm(ARMCC::AL)
1612       .addReg(0));
1613
1614     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tSTRi)
1615       .addReg(ValReg)
1616       .addReg(SrcReg)
1617       // The offset immediate is #4. The operand value is scaled by 4 for the
1618       // tSTR instruction.
1619       .addImm(1)
1620       // Predicate.
1621       .addImm(ARMCC::AL)
1622       .addReg(0));
1623
1624     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVi8)
1625       .addReg(ARM::R0)
1626       .addReg(ARM::CPSR)
1627       .addImm(0)
1628       // Predicate.
1629       .addImm(ARMCC::AL)
1630       .addReg(0));
1631
1632     const MCExpr *SymbolExpr = MCSymbolRefExpr::Create(Label, OutContext);
1633     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tB)
1634       .addExpr(SymbolExpr)
1635       .addImm(ARMCC::AL)
1636       .addReg(0));
1637
1638     OutStreamer.AddComment("eh_setjmp end");
1639     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVi8)
1640       .addReg(ARM::R0)
1641       .addReg(ARM::CPSR)
1642       .addImm(1)
1643       // Predicate.
1644       .addImm(ARMCC::AL)
1645       .addReg(0));
1646
1647     OutStreamer.EmitLabel(Label);
1648     return;
1649   }
1650
1651   case ARM::Int_eh_sjlj_setjmp_nofp:
1652   case ARM::Int_eh_sjlj_setjmp: {
1653     // Two incoming args: GPR:$src, GPR:$val
1654     // add $val, pc, #8
1655     // str $val, [$src, #+4]
1656     // mov r0, #0
1657     // add pc, pc, #0
1658     // mov r0, #1
1659     unsigned SrcReg = MI->getOperand(0).getReg();
1660     unsigned ValReg = MI->getOperand(1).getReg();
1661
1662     OutStreamer.AddComment("eh_setjmp begin");
1663     OutStreamer.EmitInstruction(MCInstBuilder(ARM::ADDri)
1664       .addReg(ValReg)
1665       .addReg(ARM::PC)
1666       .addImm(8)
1667       // Predicate.
1668       .addImm(ARMCC::AL)
1669       .addReg(0)
1670       // 's' bit operand (always reg0 for this).
1671       .addReg(0));
1672
1673     OutStreamer.EmitInstruction(MCInstBuilder(ARM::STRi12)
1674       .addReg(ValReg)
1675       .addReg(SrcReg)
1676       .addImm(4)
1677       // Predicate.
1678       .addImm(ARMCC::AL)
1679       .addReg(0));
1680
1681     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVi)
1682       .addReg(ARM::R0)
1683       .addImm(0)
1684       // Predicate.
1685       .addImm(ARMCC::AL)
1686       .addReg(0)
1687       // 's' bit operand (always reg0 for this).
1688       .addReg(0));
1689
1690     OutStreamer.EmitInstruction(MCInstBuilder(ARM::ADDri)
1691       .addReg(ARM::PC)
1692       .addReg(ARM::PC)
1693       .addImm(0)
1694       // Predicate.
1695       .addImm(ARMCC::AL)
1696       .addReg(0)
1697       // 's' bit operand (always reg0 for this).
1698       .addReg(0));
1699
1700     OutStreamer.AddComment("eh_setjmp end");
1701     OutStreamer.EmitInstruction(MCInstBuilder(ARM::MOVi)
1702       .addReg(ARM::R0)
1703       .addImm(1)
1704       // Predicate.
1705       .addImm(ARMCC::AL)
1706       .addReg(0)
1707       // 's' bit operand (always reg0 for this).
1708       .addReg(0));
1709     return;
1710   }
1711   case ARM::Int_eh_sjlj_longjmp: {
1712     // ldr sp, [$src, #8]
1713     // ldr $scratch, [$src, #4]
1714     // ldr r7, [$src]
1715     // bx $scratch
1716     unsigned SrcReg = MI->getOperand(0).getReg();
1717     unsigned ScratchReg = MI->getOperand(1).getReg();
1718     OutStreamer.EmitInstruction(MCInstBuilder(ARM::LDRi12)
1719       .addReg(ARM::SP)
1720       .addReg(SrcReg)
1721       .addImm(8)
1722       // Predicate.
1723       .addImm(ARMCC::AL)
1724       .addReg(0));
1725
1726     OutStreamer.EmitInstruction(MCInstBuilder(ARM::LDRi12)
1727       .addReg(ScratchReg)
1728       .addReg(SrcReg)
1729       .addImm(4)
1730       // Predicate.
1731       .addImm(ARMCC::AL)
1732       .addReg(0));
1733
1734     OutStreamer.EmitInstruction(MCInstBuilder(ARM::LDRi12)
1735       .addReg(ARM::R7)
1736       .addReg(SrcReg)
1737       .addImm(0)
1738       // Predicate.
1739       .addImm(ARMCC::AL)
1740       .addReg(0));
1741
1742     OutStreamer.EmitInstruction(MCInstBuilder(ARM::BX)
1743       .addReg(ScratchReg)
1744       // Predicate.
1745       .addImm(ARMCC::AL)
1746       .addReg(0));
1747     return;
1748   }
1749   case ARM::tInt_eh_sjlj_longjmp: {
1750     // ldr $scratch, [$src, #8]
1751     // mov sp, $scratch
1752     // ldr $scratch, [$src, #4]
1753     // ldr r7, [$src]
1754     // bx $scratch
1755     unsigned SrcReg = MI->getOperand(0).getReg();
1756     unsigned ScratchReg = MI->getOperand(1).getReg();
1757     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tLDRi)
1758       .addReg(ScratchReg)
1759       .addReg(SrcReg)
1760       // The offset immediate is #8. The operand value is scaled by 4 for the
1761       // tLDR instruction.
1762       .addImm(2)
1763       // Predicate.
1764       .addImm(ARMCC::AL)
1765       .addReg(0));
1766
1767     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tMOVr)
1768       .addReg(ARM::SP)
1769       .addReg(ScratchReg)
1770       // Predicate.
1771       .addImm(ARMCC::AL)
1772       .addReg(0));
1773
1774     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tLDRi)
1775       .addReg(ScratchReg)
1776       .addReg(SrcReg)
1777       .addImm(1)
1778       // Predicate.
1779       .addImm(ARMCC::AL)
1780       .addReg(0));
1781
1782     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tLDRi)
1783       .addReg(ARM::R7)
1784       .addReg(SrcReg)
1785       .addImm(0)
1786       // Predicate.
1787       .addImm(ARMCC::AL)
1788       .addReg(0));
1789
1790     OutStreamer.EmitInstruction(MCInstBuilder(ARM::tBX)
1791       .addReg(ScratchReg)
1792       // Predicate.
1793       .addImm(ARMCC::AL)
1794       .addReg(0));
1795     return;
1796   }
1797   }
1798
1799   MCInst TmpInst;
1800   LowerARMMachineInstrToMCInst(MI, TmpInst, *this);
1801
1802   OutStreamer.EmitInstruction(TmpInst);
1803 }
1804
1805 //===----------------------------------------------------------------------===//
1806 // Target Registry Stuff
1807 //===----------------------------------------------------------------------===//
1808
1809 // Force static initialization.
1810 extern "C" void LLVMInitializeARMAsmPrinter() {
1811   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMTarget);
1812   RegisterAsmPrinter<ARMAsmPrinter> Y(TheThumbTarget);
1813 }