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