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