For ARM/Darwin, add a dwarf entry indicating whether a function is arm or thumb
[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 "ARM.h"
17 #include "ARMBuildAttrs.h"
18 #include "ARMAddressingModes.h"
19 #include "ARMConstantPoolValue.h"
20 #include "AsmPrinter/ARMInstPrinter.h"
21 #include "ARMMachineFunctionInfo.h"
22 #include "ARMMCInstLower.h"
23 #include "ARMTargetMachine.h"
24 #include "llvm/Analysis/DebugInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Module.h"
27 #include "llvm/Type.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/CodeGen/AsmPrinter.h"
30 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCExpr.h"
37 #include "llvm/MC/MCInst.h"
38 #include "llvm/MC/MCSectionMachO.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Target/Mangler.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Target/TargetRegistry.h"
46 #include "llvm/ADT/SmallPtrSet.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/StringExtras.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include <cctype>
53 using namespace llvm;
54
55 static cl::opt<bool>
56 EnableMCInst("enable-arm-mcinst-printer", cl::Hidden,
57             cl::desc("enable experimental asmprinter gunk in the arm backend"));
58
59 namespace llvm {
60   namespace ARM {
61     enum DW_ISA {
62       DW_ISA_ARM_thumb = 1,
63       DW_ISA_ARM_arm = 2
64     };
65   }
66 }
67
68 namespace {
69   class ARMAsmPrinter : public AsmPrinter {
70
71     /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
72     /// make the right decision when printing asm code for different targets.
73     const ARMSubtarget *Subtarget;
74
75     /// AFI - Keep a pointer to ARMFunctionInfo for the current
76     /// MachineFunction.
77     ARMFunctionInfo *AFI;
78
79     /// MCP - Keep a pointer to constantpool entries of the current
80     /// MachineFunction.
81     const MachineConstantPool *MCP;
82
83   public:
84     explicit ARMAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
85       : AsmPrinter(TM, Streamer), AFI(NULL), MCP(NULL) {
86       Subtarget = &TM.getSubtarget<ARMSubtarget>();
87     }
88
89     virtual const char *getPassName() const {
90       return "ARM Assembly Printer";
91     }
92     
93     void printInstructionThroughMCStreamer(const MachineInstr *MI);
94     
95
96     void printOperand(const MachineInstr *MI, int OpNum, raw_ostream &O,
97                       const char *Modifier = 0);
98     void printSOImmOperand(const MachineInstr *MI, int OpNum, raw_ostream &O);
99     void printSOImm2PartOperand(const MachineInstr *MI, int OpNum,
100                                 raw_ostream &O);
101     void printSORegOperand(const MachineInstr *MI, int OpNum,
102                            raw_ostream &O);
103     void printAddrMode2Operand(const MachineInstr *MI, int OpNum,
104                                raw_ostream &O);
105     void printAddrMode2OffsetOperand(const MachineInstr *MI, int OpNum,
106                                      raw_ostream &O);
107     void printAddrMode3Operand(const MachineInstr *MI, int OpNum,
108                                raw_ostream &O);
109     void printAddrMode3OffsetOperand(const MachineInstr *MI, int OpNum,
110                                      raw_ostream &O);
111     void printAddrMode4Operand(const MachineInstr *MI, int OpNum,raw_ostream &O,
112                                const char *Modifier = 0);
113     void printAddrMode5Operand(const MachineInstr *MI, int OpNum,raw_ostream &O,
114                                const char *Modifier = 0);
115     void printAddrMode6Operand(const MachineInstr *MI, int OpNum,
116                                raw_ostream &O);
117     void printAddrMode6OffsetOperand(const MachineInstr *MI, int OpNum,
118                                      raw_ostream &O);
119     void printAddrModePCOperand(const MachineInstr *MI, int OpNum,
120                                 raw_ostream &O,
121                                 const char *Modifier = 0);
122     void printBitfieldInvMaskImmOperand (const MachineInstr *MI, int OpNum,
123                                          raw_ostream &O);
124
125     void printThumbS4ImmOperand(const MachineInstr *MI, int OpNum,
126                                 raw_ostream &O);
127     void printThumbITMask(const MachineInstr *MI, int OpNum, raw_ostream &O);
128     void printThumbAddrModeRROperand(const MachineInstr *MI, int OpNum,
129                                      raw_ostream &O);
130     void printThumbAddrModeRI5Operand(const MachineInstr *MI, int OpNum,
131                                       raw_ostream &O,
132                                       unsigned Scale);
133     void printThumbAddrModeS1Operand(const MachineInstr *MI, int OpNum,
134                                      raw_ostream &O);
135     void printThumbAddrModeS2Operand(const MachineInstr *MI, int OpNum,
136                                      raw_ostream &O);
137     void printThumbAddrModeS4Operand(const MachineInstr *MI, int OpNum,
138                                      raw_ostream &O);
139     void printThumbAddrModeSPOperand(const MachineInstr *MI, int OpNum,
140                                      raw_ostream &O);
141
142     void printT2SOOperand(const MachineInstr *MI, int OpNum, raw_ostream &O);
143     void printT2AddrModeImm12Operand(const MachineInstr *MI, int OpNum,
144                                      raw_ostream &O);
145     void printT2AddrModeImm8Operand(const MachineInstr *MI, int OpNum,
146                                     raw_ostream &O);
147     void printT2AddrModeImm8s4Operand(const MachineInstr *MI, int OpNum,
148                                       raw_ostream &O);
149     void printT2AddrModeImm8OffsetOperand(const MachineInstr *MI, int OpNum,
150                                           raw_ostream &O);
151     void printT2AddrModeImm8s4OffsetOperand(const MachineInstr *MI, int OpNum,
152                                             raw_ostream &O) {}
153     void printT2AddrModeSoRegOperand(const MachineInstr *MI, int OpNum,
154                                      raw_ostream &O);
155
156     void printCPSOptionOperand(const MachineInstr *MI, int OpNum,
157                                raw_ostream &O) {}
158     void printMSRMaskOperand(const MachineInstr *MI, int OpNum,
159                              raw_ostream &O) {}
160     void printNegZeroOperand(const MachineInstr *MI, int OpNum,
161                              raw_ostream &O) {}
162     void printPredicateOperand(const MachineInstr *MI, int OpNum,
163                                raw_ostream &O);
164     void printMandatoryPredicateOperand(const MachineInstr *MI, int OpNum,
165                                         raw_ostream &O);
166     void printSBitModifierOperand(const MachineInstr *MI, int OpNum,
167                                   raw_ostream &O);
168     void printPCLabel(const MachineInstr *MI, int OpNum,
169                       raw_ostream &O);
170     void printRegisterList(const MachineInstr *MI, int OpNum,
171                            raw_ostream &O);
172     void printCPInstOperand(const MachineInstr *MI, int OpNum,
173                             raw_ostream &O,
174                             const char *Modifier);
175     void printJTBlockOperand(const MachineInstr *MI, int OpNum,
176                              raw_ostream &O);
177     void printJT2BlockOperand(const MachineInstr *MI, int OpNum,
178                               raw_ostream &O);
179     void printTBAddrMode(const MachineInstr *MI, int OpNum,
180                          raw_ostream &O);
181     void printNoHashImmediate(const MachineInstr *MI, int OpNum,
182                               raw_ostream &O);
183     void printVFPf32ImmOperand(const MachineInstr *MI, int OpNum,
184                                raw_ostream &O);
185     void printVFPf64ImmOperand(const MachineInstr *MI, int OpNum,
186                                raw_ostream &O);
187     void printNEONModImmOperand(const MachineInstr *MI, int OpNum,
188                                 raw_ostream &O);
189
190     virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
191                                  unsigned AsmVariant, const char *ExtraCode,
192                                  raw_ostream &O);
193     virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
194                                        unsigned AsmVariant,
195                                        const char *ExtraCode, raw_ostream &O);
196
197     void printInstruction(const MachineInstr *MI, raw_ostream &O); // autogen
198     static const char *getRegisterName(unsigned RegNo);
199
200     virtual void EmitInstruction(const MachineInstr *MI);
201     bool runOnMachineFunction(MachineFunction &F);
202     
203     virtual void EmitConstantPool() {} // we emit constant pools customly!
204     virtual void EmitFunctionEntryLabel();
205     void EmitStartOfAsmFile(Module &M);
206     void EmitEndOfAsmFile(Module &M);
207
208     virtual unsigned getISAEncoding() {
209       // ARM/Darwin adds ISA to the DWARF info for each function.
210       if (!Subtarget->isTargetDarwin())
211         return 0;
212       return Subtarget->isThumb() ?
213         llvm::ARM::DW_ISA_ARM_thumb : llvm::ARM::DW_ISA_ARM_arm;
214     }
215
216     MCSymbol *GetARMSetPICJumpTableLabel2(unsigned uid, unsigned uid2,
217                                           const MachineBasicBlock *MBB) const;
218     MCSymbol *GetARMJTIPICJumpTableLabel2(unsigned uid, unsigned uid2) const;
219
220     /// EmitMachineConstantPoolValue - Print a machine constantpool value to
221     /// the .s file.
222     virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
223       SmallString<128> Str;
224       raw_svector_ostream OS(Str);
225       EmitMachineConstantPoolValue(MCPV, OS);
226       OutStreamer.EmitRawText(OS.str());
227     }
228     
229     void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV,
230                                       raw_ostream &O) {
231       switch (TM.getTargetData()->getTypeAllocSize(MCPV->getType())) {
232       case 1: O << MAI->getData8bitsDirective(0); break;
233       case 2: O << MAI->getData16bitsDirective(0); break;
234       case 4: O << MAI->getData32bitsDirective(0); break;
235       default: assert(0 && "Unknown CPV size");
236       }
237
238       ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
239
240       if (ACPV->isLSDA()) {
241         O << MAI->getPrivateGlobalPrefix() << "_LSDA_" << getFunctionNumber();
242       } else if (ACPV->isBlockAddress()) {
243         O << *GetBlockAddressSymbol(ACPV->getBlockAddress());
244       } else if (ACPV->isGlobalValue()) {
245         const GlobalValue *GV = ACPV->getGV();
246         bool isIndirect = Subtarget->isTargetDarwin() &&
247           Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel());
248         if (!isIndirect)
249           O << *Mang->getSymbol(GV);
250         else {
251           // FIXME: Remove this when Darwin transition to @GOT like syntax.
252           MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
253           O << *Sym;
254           
255           MachineModuleInfoMachO &MMIMachO =
256             MMI->getObjFileInfo<MachineModuleInfoMachO>();
257           MachineModuleInfoImpl::StubValueTy &StubSym =
258             GV->hasHiddenVisibility() ? MMIMachO.getHiddenGVStubEntry(Sym) :
259                                         MMIMachO.getGVStubEntry(Sym);
260           if (StubSym.getPointer() == 0)
261             StubSym = MachineModuleInfoImpl::
262               StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
263         }
264       } else {
265         assert(ACPV->isExtSymbol() && "unrecognized constant pool value");
266         O << *GetExternalSymbolSymbol(ACPV->getSymbol());
267       }
268
269       if (ACPV->hasModifier()) O << "(" << ACPV->getModifier() << ")";
270       if (ACPV->getPCAdjustment() != 0) {
271         O << "-(" << MAI->getPrivateGlobalPrefix() << "PC"
272           << getFunctionNumber() << "_"  << ACPV->getLabelId()
273           << "+" << (unsigned)ACPV->getPCAdjustment();
274          if (ACPV->mustAddCurrentAddress())
275            O << "-.";
276          O << ')';
277       }
278     }
279   };
280 } // end of anonymous namespace
281
282 #include "ARMGenAsmWriter.inc"
283
284 void ARMAsmPrinter::EmitFunctionEntryLabel() {
285   if (AFI->isThumbFunction()) {
286     OutStreamer.EmitRawText(StringRef("\t.code\t16"));
287     if (!Subtarget->isTargetDarwin())
288       OutStreamer.EmitRawText(StringRef("\t.thumb_func"));
289     else {
290       // This needs to emit to a temporary string to get properly quoted
291       // MCSymbols when they have spaces in them.
292       SmallString<128> Tmp;
293       raw_svector_ostream OS(Tmp);
294       OS << "\t.thumb_func\t" << *CurrentFnSym;
295       OutStreamer.EmitRawText(OS.str());
296     }
297   }
298   
299   OutStreamer.EmitLabel(CurrentFnSym);
300 }
301
302 /// runOnMachineFunction - This uses the printInstruction()
303 /// method to print assembly for each instruction.
304 ///
305 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
306   AFI = MF.getInfo<ARMFunctionInfo>();
307   MCP = MF.getConstantPool();
308
309   return AsmPrinter::runOnMachineFunction(MF);
310 }
311
312 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
313                                  raw_ostream &O, const char *Modifier) {
314   const MachineOperand &MO = MI->getOperand(OpNum);
315   unsigned TF = MO.getTargetFlags();
316
317   switch (MO.getType()) {
318   default:
319     assert(0 && "<unknown operand type>");
320   case MachineOperand::MO_Register: {
321     unsigned Reg = MO.getReg();
322     assert(TargetRegisterInfo::isPhysicalRegister(Reg));
323     if (Modifier && strcmp(Modifier, "dregpair") == 0) {
324       unsigned DRegLo = TM.getRegisterInfo()->getSubReg(Reg, ARM::dsub_0);
325       unsigned DRegHi = TM.getRegisterInfo()->getSubReg(Reg, ARM::dsub_1);
326       O << '{'
327         << getRegisterName(DRegLo) << ", " << getRegisterName(DRegHi)
328         << '}';
329     } else if (Modifier && strcmp(Modifier, "lane") == 0) {
330       unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(Reg);
331       unsigned DReg =
332         TM.getRegisterInfo()->getMatchingSuperReg(Reg,
333           RegNum & 1 ? ARM::ssub_1 : ARM::ssub_0, &ARM::DPR_VFP2RegClass);
334       O << getRegisterName(DReg) << '[' << (RegNum & 1) << ']';
335     } else {
336       assert(!MO.getSubReg() && "Subregs should be eliminated!");
337       O << getRegisterName(Reg);
338     }
339     break;
340   }
341   case MachineOperand::MO_Immediate: {
342     int64_t Imm = MO.getImm();
343     O << '#';
344     if ((Modifier && strcmp(Modifier, "lo16") == 0) ||
345         (TF & ARMII::MO_LO16))
346       O << ":lower16:";
347     else if ((Modifier && strcmp(Modifier, "hi16") == 0) ||
348              (TF & ARMII::MO_HI16))
349       O << ":upper16:";
350     O << Imm;
351     break;
352   }
353   case MachineOperand::MO_MachineBasicBlock:
354     O << *MO.getMBB()->getSymbol();
355     return;
356   case MachineOperand::MO_GlobalAddress: {
357     bool isCallOp = Modifier && !strcmp(Modifier, "call");
358     const GlobalValue *GV = MO.getGlobal();
359
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
370     if (isCallOp && Subtarget->isTargetELF() &&
371         TM.getRelocationModel() == Reloc::PIC_)
372       O << "(PLT)";
373     break;
374   }
375   case MachineOperand::MO_ExternalSymbol: {
376     bool isCallOp = Modifier && !strcmp(Modifier, "call");
377     O << *GetExternalSymbolSymbol(MO.getSymbolName());
378     
379     if (isCallOp && Subtarget->isTargetELF() &&
380         TM.getRelocationModel() == Reloc::PIC_)
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 static void printSOImm(raw_ostream &O, int64_t V, bool VerboseAsm,
394                        const MCAsmInfo *MAI) {
395   // Break it up into two parts that make up a shifter immediate.
396   V = ARM_AM::getSOImmVal(V);
397   assert(V != -1 && "Not a valid so_imm value!");
398
399   unsigned Imm = ARM_AM::getSOImmValImm(V);
400   unsigned Rot = ARM_AM::getSOImmValRot(V);
401
402   // Print low-level immediate formation info, per
403   // A5.1.3: "Data-processing operands - Immediate".
404   if (Rot) {
405     O << "#" << Imm << ", " << Rot;
406     // Pretty printed version.
407     if (VerboseAsm) {
408       O << "\t" << MAI->getCommentString() << ' ';
409       O << (int)ARM_AM::rotr32(Imm, Rot);
410     }
411   } else {
412     O << "#" << Imm;
413   }
414 }
415
416 /// printSOImmOperand - SOImm is 4-bit rotate amount in bits 8-11 with 8-bit
417 /// immediate in bits 0-7.
418 void ARMAsmPrinter::printSOImmOperand(const MachineInstr *MI, int OpNum,
419                                       raw_ostream &O) {
420   const MachineOperand &MO = MI->getOperand(OpNum);
421   assert(MO.isImm() && "Not a valid so_imm value!");
422   printSOImm(O, MO.getImm(), isVerbose(), MAI);
423 }
424
425 /// printSOImm2PartOperand - SOImm is broken into two pieces using a 'mov'
426 /// followed by an 'orr' to materialize.
427 void ARMAsmPrinter::printSOImm2PartOperand(const MachineInstr *MI, int OpNum,
428                                            raw_ostream &O) {
429   const MachineOperand &MO = MI->getOperand(OpNum);
430   assert(MO.isImm() && "Not a valid so_imm value!");
431   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO.getImm());
432   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO.getImm());
433   printSOImm(O, V1, isVerbose(), MAI);
434   O << "\n\torr";
435   printPredicateOperand(MI, 2, O);
436   O << "\t";
437   printOperand(MI, 0, O);
438   O << ", ";
439   printOperand(MI, 0, O);
440   O << ", ";
441   printSOImm(O, V2, isVerbose(), MAI);
442 }
443
444 // so_reg is a 4-operand unit corresponding to register forms of the A5.1
445 // "Addressing Mode 1 - Data-processing operands" forms.  This includes:
446 //    REG 0   0           - e.g. R5
447 //    REG REG 0,SH_OPC    - e.g. R5, ROR R3
448 //    REG 0   IMM,SH_OPC  - e.g. R5, LSL #3
449 void ARMAsmPrinter::printSORegOperand(const MachineInstr *MI, int Op,
450                                       raw_ostream &O) {
451   const MachineOperand &MO1 = MI->getOperand(Op);
452   const MachineOperand &MO2 = MI->getOperand(Op+1);
453   const MachineOperand &MO3 = MI->getOperand(Op+2);
454
455   O << getRegisterName(MO1.getReg());
456
457   // Print the shift opc.
458   O << ", "
459     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO3.getImm()))
460     << " ";
461
462   if (MO2.getReg()) {
463     O << getRegisterName(MO2.getReg());
464     assert(ARM_AM::getSORegOffset(MO3.getImm()) == 0);
465   } else {
466     O << "#" << ARM_AM::getSORegOffset(MO3.getImm());
467   }
468 }
469
470 void ARMAsmPrinter::printAddrMode2Operand(const MachineInstr *MI, int Op,
471                                           raw_ostream &O) {
472   const MachineOperand &MO1 = MI->getOperand(Op);
473   const MachineOperand &MO2 = MI->getOperand(Op+1);
474   const MachineOperand &MO3 = MI->getOperand(Op+2);
475
476   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
477     printOperand(MI, Op, O);
478     return;
479   }
480
481   O << "[" << getRegisterName(MO1.getReg());
482
483   if (!MO2.getReg()) {
484     if (ARM_AM::getAM2Offset(MO3.getImm())) // Don't print +0.
485       O << ", #"
486         << ARM_AM::getAddrOpcStr(ARM_AM::getAM2Op(MO3.getImm()))
487         << ARM_AM::getAM2Offset(MO3.getImm());
488     O << "]";
489     return;
490   }
491
492   O << ", "
493     << ARM_AM::getAddrOpcStr(ARM_AM::getAM2Op(MO3.getImm()))
494     << getRegisterName(MO2.getReg());
495
496   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm()))
497     O << ", "
498       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO3.getImm()))
499       << " #" << ShImm;
500   O << "]";
501 }
502
503 void ARMAsmPrinter::printAddrMode2OffsetOperand(const MachineInstr *MI, int Op,
504                                                 raw_ostream &O) {
505   const MachineOperand &MO1 = MI->getOperand(Op);
506   const MachineOperand &MO2 = MI->getOperand(Op+1);
507
508   if (!MO1.getReg()) {
509     unsigned ImmOffs = ARM_AM::getAM2Offset(MO2.getImm());
510     O << "#"
511       << ARM_AM::getAddrOpcStr(ARM_AM::getAM2Op(MO2.getImm()))
512       << ImmOffs;
513     return;
514   }
515
516   O << ARM_AM::getAddrOpcStr(ARM_AM::getAM2Op(MO2.getImm()))
517     << getRegisterName(MO1.getReg());
518
519   if (unsigned ShImm = ARM_AM::getAM2Offset(MO2.getImm()))
520     O << ", "
521       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO2.getImm()))
522       << " #" << ShImm;
523 }
524
525 void ARMAsmPrinter::printAddrMode3Operand(const MachineInstr *MI, int Op,
526                                           raw_ostream &O) {
527   const MachineOperand &MO1 = MI->getOperand(Op);
528   const MachineOperand &MO2 = MI->getOperand(Op+1);
529   const MachineOperand &MO3 = MI->getOperand(Op+2);
530
531   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
532   O << "[" << getRegisterName(MO1.getReg());
533
534   if (MO2.getReg()) {
535     O << ", "
536       << (char)ARM_AM::getAM3Op(MO3.getImm())
537       << getRegisterName(MO2.getReg())
538       << "]";
539     return;
540   }
541
542   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm()))
543     O << ", #"
544       << ARM_AM::getAddrOpcStr(ARM_AM::getAM3Op(MO3.getImm()))
545       << ImmOffs;
546   O << "]";
547 }
548
549 void ARMAsmPrinter::printAddrMode3OffsetOperand(const MachineInstr *MI, int Op,
550                                                 raw_ostream &O){
551   const MachineOperand &MO1 = MI->getOperand(Op);
552   const MachineOperand &MO2 = MI->getOperand(Op+1);
553
554   if (MO1.getReg()) {
555     O << (char)ARM_AM::getAM3Op(MO2.getImm())
556       << getRegisterName(MO1.getReg());
557     return;
558   }
559
560   unsigned ImmOffs = ARM_AM::getAM3Offset(MO2.getImm());
561   O << "#"
562     << ARM_AM::getAddrOpcStr(ARM_AM::getAM3Op(MO2.getImm()))
563     << ImmOffs;
564 }
565
566 void ARMAsmPrinter::printAddrMode4Operand(const MachineInstr *MI, int Op,
567                                           raw_ostream &O,
568                                           const char *Modifier) {
569   const MachineOperand &MO2 = MI->getOperand(Op+1);
570   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
571   if (Modifier && strcmp(Modifier, "submode") == 0) {
572     O << ARM_AM::getAMSubModeStr(Mode);
573   } else if (Modifier && strcmp(Modifier, "wide") == 0) {
574     ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
575     if (Mode == ARM_AM::ia)
576       O << ".w";
577   } else {
578     printOperand(MI, Op, O);
579   }
580 }
581
582 void ARMAsmPrinter::printAddrMode5Operand(const MachineInstr *MI, int Op,
583                                           raw_ostream &O,
584                                           const char *Modifier) {
585   const MachineOperand &MO1 = MI->getOperand(Op);
586   const MachineOperand &MO2 = MI->getOperand(Op+1);
587
588   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
589     printOperand(MI, Op, O);
590     return;
591   }
592
593   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
594
595   if (Modifier && strcmp(Modifier, "submode") == 0) {
596     ARM_AM::AMSubMode Mode = ARM_AM::getAM5SubMode(MO2.getImm());
597     O << ARM_AM::getAMSubModeStr(Mode);
598     return;
599   } else if (Modifier && strcmp(Modifier, "base") == 0) {
600     // Used for FSTM{D|S} and LSTM{D|S} operations.
601     O << getRegisterName(MO1.getReg());
602     return;
603   }
604
605   O << "[" << getRegisterName(MO1.getReg());
606
607   if (unsigned ImmOffs = ARM_AM::getAM5Offset(MO2.getImm())) {
608     O << ", #"
609       << ARM_AM::getAddrOpcStr(ARM_AM::getAM5Op(MO2.getImm()))
610       << ImmOffs*4;
611   }
612   O << "]";
613 }
614
615 void ARMAsmPrinter::printAddrMode6Operand(const MachineInstr *MI, int Op,
616                                           raw_ostream &O) {
617   const MachineOperand &MO1 = MI->getOperand(Op);
618   const MachineOperand &MO2 = MI->getOperand(Op+1);
619
620   O << "[" << getRegisterName(MO1.getReg());
621   if (MO2.getImm()) {
622     // FIXME: Both darwin as and GNU as violate ARM docs here.
623     O << ", :" << (MO2.getImm() << 3);
624   }
625   O << "]";
626 }
627
628 void ARMAsmPrinter::printAddrMode6OffsetOperand(const MachineInstr *MI, int Op,
629                                                 raw_ostream &O){
630   const MachineOperand &MO = MI->getOperand(Op);
631   if (MO.getReg() == 0)
632     O << "!";
633   else
634     O << ", " << getRegisterName(MO.getReg());
635 }
636
637 void ARMAsmPrinter::printAddrModePCOperand(const MachineInstr *MI, int Op,
638                                            raw_ostream &O,
639                                            const char *Modifier) {
640   if (Modifier && strcmp(Modifier, "label") == 0) {
641     printPCLabel(MI, Op+1, O);
642     return;
643   }
644
645   const MachineOperand &MO1 = MI->getOperand(Op);
646   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
647   O << "[pc, " << getRegisterName(MO1.getReg()) << "]";
648 }
649
650 void
651 ARMAsmPrinter::printBitfieldInvMaskImmOperand(const MachineInstr *MI, int Op,
652                                               raw_ostream &O) {
653   const MachineOperand &MO = MI->getOperand(Op);
654   uint32_t v = ~MO.getImm();
655   int32_t lsb = CountTrailingZeros_32(v);
656   int32_t width = (32 - CountLeadingZeros_32 (v)) - lsb;
657   assert(MO.isImm() && "Not a valid bf_inv_mask_imm value!");
658   O << "#" << lsb << ", #" << width;
659 }
660
661 //===--------------------------------------------------------------------===//
662
663 void ARMAsmPrinter::printThumbS4ImmOperand(const MachineInstr *MI, int Op,
664                                            raw_ostream &O) {
665   O << "#" <<  MI->getOperand(Op).getImm() * 4;
666 }
667
668 void
669 ARMAsmPrinter::printThumbITMask(const MachineInstr *MI, int Op,
670                                 raw_ostream &O) {
671   // (3 - the number of trailing zeros) is the number of then / else.
672   unsigned Mask = MI->getOperand(Op).getImm();
673   unsigned CondBit0 = Mask >> 4 & 1;
674   unsigned NumTZ = CountTrailingZeros_32(Mask);
675   assert(NumTZ <= 3 && "Invalid IT mask!");
676   for (unsigned Pos = 3, e = NumTZ; Pos > e; --Pos) {
677     bool T = ((Mask >> Pos) & 1) == CondBit0;
678     if (T)
679       O << 't';
680     else
681       O << 'e';
682   }
683 }
684
685 void
686 ARMAsmPrinter::printThumbAddrModeRROperand(const MachineInstr *MI, int Op,
687                                            raw_ostream &O) {
688   const MachineOperand &MO1 = MI->getOperand(Op);
689   const MachineOperand &MO2 = MI->getOperand(Op+1);
690   O << "[" << getRegisterName(MO1.getReg());
691   O << ", " << getRegisterName(MO2.getReg()) << "]";
692 }
693
694 void
695 ARMAsmPrinter::printThumbAddrModeRI5Operand(const MachineInstr *MI, int Op,
696                                             raw_ostream &O,
697                                             unsigned Scale) {
698   const MachineOperand &MO1 = MI->getOperand(Op);
699   const MachineOperand &MO2 = MI->getOperand(Op+1);
700   const MachineOperand &MO3 = MI->getOperand(Op+2);
701
702   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
703     printOperand(MI, Op, O);
704     return;
705   }
706
707   O << "[" << getRegisterName(MO1.getReg());
708   if (MO3.getReg())
709     O << ", " << getRegisterName(MO3.getReg());
710   else if (unsigned ImmOffs = MO2.getImm())
711     O << ", #" << ImmOffs * Scale;
712   O << "]";
713 }
714
715 void
716 ARMAsmPrinter::printThumbAddrModeS1Operand(const MachineInstr *MI, int Op,
717                                            raw_ostream &O) {
718   printThumbAddrModeRI5Operand(MI, Op, O, 1);
719 }
720 void
721 ARMAsmPrinter::printThumbAddrModeS2Operand(const MachineInstr *MI, int Op,
722                                            raw_ostream &O) {
723   printThumbAddrModeRI5Operand(MI, Op, O, 2);
724 }
725 void
726 ARMAsmPrinter::printThumbAddrModeS4Operand(const MachineInstr *MI, int Op,
727                                            raw_ostream &O) {
728   printThumbAddrModeRI5Operand(MI, Op, O, 4);
729 }
730
731 void ARMAsmPrinter::printThumbAddrModeSPOperand(const MachineInstr *MI,int Op,
732                                                 raw_ostream &O) {
733   const MachineOperand &MO1 = MI->getOperand(Op);
734   const MachineOperand &MO2 = MI->getOperand(Op+1);
735   O << "[" << getRegisterName(MO1.getReg());
736   if (unsigned ImmOffs = MO2.getImm())
737     O << ", #" << ImmOffs*4;
738   O << "]";
739 }
740
741 //===--------------------------------------------------------------------===//
742
743 // Constant shifts t2_so_reg is a 2-operand unit corresponding to the Thumb2
744 // register with shift forms.
745 // REG 0   0           - e.g. R5
746 // REG IMM, SH_OPC     - e.g. R5, LSL #3
747 void ARMAsmPrinter::printT2SOOperand(const MachineInstr *MI, int OpNum,
748                                      raw_ostream &O) {
749   const MachineOperand &MO1 = MI->getOperand(OpNum);
750   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
751
752   unsigned Reg = MO1.getReg();
753   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
754   O << getRegisterName(Reg);
755
756   // Print the shift opc.
757   O << ", "
758     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO2.getImm()))
759     << " ";
760
761   assert(MO2.isImm() && "Not a valid t2_so_reg value!");
762   O << "#" << ARM_AM::getSORegOffset(MO2.getImm());
763 }
764
765 void ARMAsmPrinter::printT2AddrModeImm12Operand(const MachineInstr *MI,
766                                                 int OpNum,
767                                                 raw_ostream &O) {
768   const MachineOperand &MO1 = MI->getOperand(OpNum);
769   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
770
771   O << "[" << getRegisterName(MO1.getReg());
772
773   unsigned OffImm = MO2.getImm();
774   if (OffImm)  // Don't print +0.
775     O << ", #" << OffImm;
776   O << "]";
777 }
778
779 void ARMAsmPrinter::printT2AddrModeImm8Operand(const MachineInstr *MI,
780                                                int OpNum,
781                                                raw_ostream &O) {
782   const MachineOperand &MO1 = MI->getOperand(OpNum);
783   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
784
785   O << "[" << getRegisterName(MO1.getReg());
786
787   int32_t OffImm = (int32_t)MO2.getImm();
788   // Don't print +0.
789   if (OffImm < 0)
790     O << ", #-" << -OffImm;
791   else if (OffImm > 0)
792     O << ", #" << OffImm;
793   O << "]";
794 }
795
796 void ARMAsmPrinter::printT2AddrModeImm8s4Operand(const MachineInstr *MI,
797                                                  int OpNum,
798                                                  raw_ostream &O) {
799   const MachineOperand &MO1 = MI->getOperand(OpNum);
800   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
801
802   O << "[" << getRegisterName(MO1.getReg());
803
804   int32_t OffImm = (int32_t)MO2.getImm() / 4;
805   // Don't print +0.
806   if (OffImm < 0)
807     O << ", #-" << -OffImm * 4;
808   else if (OffImm > 0)
809     O << ", #" << OffImm * 4;
810   O << "]";
811 }
812
813 void ARMAsmPrinter::printT2AddrModeImm8OffsetOperand(const MachineInstr *MI,
814                                                      int OpNum,
815                                                      raw_ostream &O) {
816   const MachineOperand &MO1 = MI->getOperand(OpNum);
817   int32_t OffImm = (int32_t)MO1.getImm();
818   // Don't print +0.
819   if (OffImm < 0)
820     O << "#-" << -OffImm;
821   else if (OffImm > 0)
822     O << "#" << OffImm;
823 }
824
825 void ARMAsmPrinter::printT2AddrModeSoRegOperand(const MachineInstr *MI,
826                                                 int OpNum,
827                                                 raw_ostream &O) {
828   const MachineOperand &MO1 = MI->getOperand(OpNum);
829   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
830   const MachineOperand &MO3 = MI->getOperand(OpNum+2);
831
832   O << "[" << getRegisterName(MO1.getReg());
833
834   assert(MO2.getReg() && "Invalid so_reg load / store address!");
835   O << ", " << getRegisterName(MO2.getReg());
836
837   unsigned ShAmt = MO3.getImm();
838   if (ShAmt) {
839     assert(ShAmt <= 3 && "Not a valid Thumb2 addressing mode!");
840     O << ", lsl #" << ShAmt;
841   }
842   O << "]";
843 }
844
845
846 //===--------------------------------------------------------------------===//
847
848 void ARMAsmPrinter::printPredicateOperand(const MachineInstr *MI, int OpNum,
849                                           raw_ostream &O) {
850   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(OpNum).getImm();
851   if (CC != ARMCC::AL)
852     O << ARMCondCodeToString(CC);
853 }
854
855 void ARMAsmPrinter::printMandatoryPredicateOperand(const MachineInstr *MI,
856                                                    int OpNum,
857                                                    raw_ostream &O) {
858   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(OpNum).getImm();
859   O << ARMCondCodeToString(CC);
860 }
861
862 void ARMAsmPrinter::printSBitModifierOperand(const MachineInstr *MI, int OpNum,
863                                              raw_ostream &O){
864   unsigned Reg = MI->getOperand(OpNum).getReg();
865   if (Reg) {
866     assert(Reg == ARM::CPSR && "Expect ARM CPSR register!");
867     O << 's';
868   }
869 }
870
871 void ARMAsmPrinter::printPCLabel(const MachineInstr *MI, int OpNum,
872                                  raw_ostream &O) {
873   int Id = (int)MI->getOperand(OpNum).getImm();
874   O << MAI->getPrivateGlobalPrefix()
875     << "PC" << getFunctionNumber() << "_" << Id;
876 }
877
878 void ARMAsmPrinter::printRegisterList(const MachineInstr *MI, int OpNum,
879                                       raw_ostream &O) {
880   O << "{";
881   for (unsigned i = OpNum, e = MI->getNumOperands(); i != e; ++i) {
882     if (MI->getOperand(i).isImplicit())
883       continue;
884     if ((int)i != OpNum) O << ", ";
885     printOperand(MI, i, O);
886   }
887   O << "}";
888 }
889
890 void ARMAsmPrinter::printCPInstOperand(const MachineInstr *MI, int OpNum,
891                                        raw_ostream &O, const char *Modifier) {
892   assert(Modifier && "This operand only works with a modifier!");
893   // There are two aspects to a CONSTANTPOOL_ENTRY operand, the label and the
894   // data itself.
895   if (!strcmp(Modifier, "label")) {
896     unsigned ID = MI->getOperand(OpNum).getImm();
897     OutStreamer.EmitLabel(GetCPISymbol(ID));
898   } else {
899     assert(!strcmp(Modifier, "cpentry") && "Unknown modifier for CPE");
900     unsigned CPI = MI->getOperand(OpNum).getIndex();
901
902     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
903
904     if (MCPE.isMachineConstantPoolEntry()) {
905       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
906     } else {
907       EmitGlobalConstant(MCPE.Val.ConstVal);
908     }
909   }
910 }
911
912 MCSymbol *ARMAsmPrinter::
913 GetARMSetPICJumpTableLabel2(unsigned uid, unsigned uid2,
914                             const MachineBasicBlock *MBB) const {
915   SmallString<60> Name;
916   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix()
917     << getFunctionNumber() << '_' << uid << '_' << uid2
918     << "_set_" << MBB->getNumber();
919   return OutContext.GetOrCreateSymbol(Name.str());
920 }
921
922 MCSymbol *ARMAsmPrinter::
923 GetARMJTIPICJumpTableLabel2(unsigned uid, unsigned uid2) const {
924   SmallString<60> Name;
925   raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "JTI"
926     << getFunctionNumber() << '_' << uid << '_' << uid2;
927   return OutContext.GetOrCreateSymbol(Name.str());
928 }
929
930 void ARMAsmPrinter::printJTBlockOperand(const MachineInstr *MI, int OpNum,
931                                         raw_ostream &O) {
932   assert(!Subtarget->isThumb2() && "Thumb2 should use double-jump jumptables!");
933
934   const MachineOperand &MO1 = MI->getOperand(OpNum);
935   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
936   
937   unsigned JTI = MO1.getIndex();
938   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
939   // Can't use EmitLabel until instprinter happens, label comes out in the wrong
940   // order.
941   O << *JTISymbol << ":\n";
942
943   const char *JTEntryDirective = MAI->getData32bitsDirective();
944
945   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
946   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
947   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
948   bool UseSet= MAI->hasSetDirective() && TM.getRelocationModel() == Reloc::PIC_;
949   SmallPtrSet<MachineBasicBlock*, 8> JTSets;
950   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
951     MachineBasicBlock *MBB = JTBBs[i];
952     bool isNew = JTSets.insert(MBB);
953
954     if (UseSet && isNew) {
955       O << "\t.set\t"
956         << *GetARMSetPICJumpTableLabel2(JTI, MO2.getImm(), MBB) << ','
957         << *MBB->getSymbol() << '-' << *JTISymbol << '\n';
958     }
959
960     O << JTEntryDirective << ' ';
961     if (UseSet)
962       O << *GetARMSetPICJumpTableLabel2(JTI, MO2.getImm(), MBB);
963     else if (TM.getRelocationModel() == Reloc::PIC_)
964       O << *MBB->getSymbol() << '-' << *JTISymbol;
965     else
966       O << *MBB->getSymbol();
967
968     if (i != e-1)
969       O << '\n';
970   }
971 }
972
973 void ARMAsmPrinter::printJT2BlockOperand(const MachineInstr *MI, int OpNum,
974                                          raw_ostream &O) {
975   const MachineOperand &MO1 = MI->getOperand(OpNum);
976   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
977   unsigned JTI = MO1.getIndex();
978   
979   MCSymbol *JTISymbol = GetARMJTIPICJumpTableLabel2(JTI, MO2.getImm());
980   
981   // Can't use EmitLabel until instprinter happens, label comes out in the wrong
982   // order.
983   O << *JTISymbol << ":\n";
984
985   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
986   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
987   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
988   bool ByteOffset = false, HalfWordOffset = false;
989   if (MI->getOpcode() == ARM::t2TBB)
990     ByteOffset = true;
991   else if (MI->getOpcode() == ARM::t2TBH)
992     HalfWordOffset = true;
993
994   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
995     MachineBasicBlock *MBB = JTBBs[i];
996     if (ByteOffset)
997       O << MAI->getData8bitsDirective();
998     else if (HalfWordOffset)
999       O << MAI->getData16bitsDirective();
1000     
1001     if (ByteOffset || HalfWordOffset)
1002       O << '(' << *MBB->getSymbol() << "-" << *JTISymbol << ")/2";
1003     else
1004       O << "\tb.w " << *MBB->getSymbol();
1005
1006     if (i != e-1)
1007       O << '\n';
1008   }
1009 }
1010
1011 void ARMAsmPrinter::printTBAddrMode(const MachineInstr *MI, int OpNum,
1012                                     raw_ostream &O) {
1013   O << "[pc, " << getRegisterName(MI->getOperand(OpNum).getReg());
1014   if (MI->getOpcode() == ARM::t2TBH)
1015     O << ", lsl #1";
1016   O << ']';
1017 }
1018
1019 void ARMAsmPrinter::printNoHashImmediate(const MachineInstr *MI, int OpNum,
1020                                          raw_ostream &O) {
1021   O << MI->getOperand(OpNum).getImm();
1022 }
1023
1024 void ARMAsmPrinter::printVFPf32ImmOperand(const MachineInstr *MI, int OpNum,
1025                                           raw_ostream &O) {
1026   const ConstantFP *FP = MI->getOperand(OpNum).getFPImm();
1027   O << '#' << FP->getValueAPF().convertToFloat();
1028   if (isVerbose()) {
1029     O << "\t\t" << MAI->getCommentString() << ' ';
1030     WriteAsOperand(O, FP, /*PrintType=*/false);
1031   }
1032 }
1033
1034 void ARMAsmPrinter::printVFPf64ImmOperand(const MachineInstr *MI, int OpNum,
1035                                           raw_ostream &O) {
1036   const ConstantFP *FP = MI->getOperand(OpNum).getFPImm();
1037   O << '#' << FP->getValueAPF().convertToDouble();
1038   if (isVerbose()) {
1039     O << "\t\t" << MAI->getCommentString() << ' ';
1040     WriteAsOperand(O, FP, /*PrintType=*/false);
1041   }
1042 }
1043
1044 void ARMAsmPrinter::printNEONModImmOperand(const MachineInstr *MI, int OpNum,
1045                                            raw_ostream &O) {
1046   unsigned EncodedImm = MI->getOperand(OpNum).getImm();
1047   unsigned EltBits;
1048   uint64_t Val = ARM_AM::decodeNEONModImm(EncodedImm, EltBits);
1049   O << "#0x" << utohexstr(Val);
1050 }
1051
1052 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
1053                                     unsigned AsmVariant, const char *ExtraCode,
1054                                     raw_ostream &O) {
1055   // Does this asm operand have a single letter operand modifier?
1056   if (ExtraCode && ExtraCode[0]) {
1057     if (ExtraCode[1] != 0) return true; // Unknown modifier.
1058
1059     switch (ExtraCode[0]) {
1060     default: return true;  // Unknown modifier.
1061     case 'a': // Print as a memory address.
1062       if (MI->getOperand(OpNum).isReg()) {
1063         O << "[" << getRegisterName(MI->getOperand(OpNum).getReg()) << "]";
1064         return false;
1065       }
1066       // Fallthrough
1067     case 'c': // Don't print "#" before an immediate operand.
1068       if (!MI->getOperand(OpNum).isImm())
1069         return true;
1070       printNoHashImmediate(MI, OpNum, O);
1071       return false;
1072     case 'P': // Print a VFP double precision register.
1073     case 'q': // Print a NEON quad precision register.
1074       printOperand(MI, OpNum, O);
1075       return false;
1076     case 'Q':
1077     case 'R':
1078     case 'H':
1079       report_fatal_error("llvm does not support 'Q', 'R', and 'H' modifiers!");
1080       return true;
1081     }
1082   }
1083
1084   printOperand(MI, OpNum, O);
1085   return false;
1086 }
1087
1088 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1089                                           unsigned OpNum, unsigned AsmVariant,
1090                                           const char *ExtraCode,
1091                                           raw_ostream &O) {
1092   if (ExtraCode && ExtraCode[0])
1093     return true; // Unknown modifier.
1094
1095   const MachineOperand &MO = MI->getOperand(OpNum);
1096   assert(MO.isReg() && "unexpected inline asm memory operand");
1097   O << "[" << getRegisterName(MO.getReg()) << "]";
1098   return false;
1099 }
1100
1101 void ARMAsmPrinter::EmitInstruction(const MachineInstr *MI) {
1102   if (EnableMCInst) {
1103     printInstructionThroughMCStreamer(MI);
1104     return;
1105   }
1106   
1107   if (MI->getOpcode() == ARM::CONSTPOOL_ENTRY)
1108     EmitAlignment(2);
1109   
1110   SmallString<128> Str;
1111   raw_svector_ostream OS(Str);
1112   if (MI->getOpcode() == ARM::DBG_VALUE) {
1113     unsigned NOps = MI->getNumOperands();
1114     assert(NOps==4);
1115     OS << '\t' << MAI->getCommentString() << "DEBUG_VALUE: ";
1116     // cast away const; DIetc do not take const operands for some reason.
1117     DIVariable V(const_cast<MDNode *>(MI->getOperand(NOps-1).getMetadata()));
1118     OS << V.getName();
1119     OS << " <- ";
1120     // Frame address.  Currently handles register +- offset only.
1121     assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm());
1122     OS << '['; printOperand(MI, 0, OS); OS << '+'; printOperand(MI, 1, OS);
1123     OS << ']';
1124     OS << "+";
1125     printOperand(MI, NOps-2, OS);
1126     OutStreamer.EmitRawText(OS.str());
1127     return;
1128   }
1129
1130   printInstruction(MI, OS);
1131   OutStreamer.EmitRawText(OS.str());
1132   
1133   // Make sure the instruction that follows TBB is 2-byte aligned.
1134   // FIXME: Constant island pass should insert an "ALIGN" instruction instead.
1135   if (MI->getOpcode() == ARM::t2TBB)
1136     EmitAlignment(1);
1137 }
1138
1139 void ARMAsmPrinter::EmitStartOfAsmFile(Module &M) {
1140   if (Subtarget->isTargetDarwin()) {
1141     Reloc::Model RelocM = TM.getRelocationModel();
1142     if (RelocM == Reloc::PIC_ || RelocM == Reloc::DynamicNoPIC) {
1143       // Declare all the text sections up front (before the DWARF sections
1144       // emitted by AsmPrinter::doInitialization) so the assembler will keep
1145       // them together at the beginning of the object file.  This helps
1146       // avoid out-of-range branches that are due a fundamental limitation of
1147       // the way symbol offsets are encoded with the current Darwin ARM
1148       // relocations.
1149       const TargetLoweringObjectFileMachO &TLOFMacho = 
1150         static_cast<const TargetLoweringObjectFileMachO &>(
1151           getObjFileLowering());
1152       OutStreamer.SwitchSection(TLOFMacho.getTextSection());
1153       OutStreamer.SwitchSection(TLOFMacho.getTextCoalSection());
1154       OutStreamer.SwitchSection(TLOFMacho.getConstTextCoalSection());
1155       if (RelocM == Reloc::DynamicNoPIC) {
1156         const MCSection *sect =
1157           OutContext.getMachOSection("__TEXT", "__symbol_stub4",
1158                                      MCSectionMachO::S_SYMBOL_STUBS,
1159                                      12, SectionKind::getText());
1160         OutStreamer.SwitchSection(sect);
1161       } else {
1162         const MCSection *sect =
1163           OutContext.getMachOSection("__TEXT", "__picsymbolstub4",
1164                                      MCSectionMachO::S_SYMBOL_STUBS,
1165                                      16, SectionKind::getText());
1166         OutStreamer.SwitchSection(sect);
1167       }
1168     }
1169   }
1170
1171   // Use unified assembler syntax.
1172   OutStreamer.EmitRawText(StringRef("\t.syntax unified"));
1173
1174   // Emit ARM Build Attributes
1175   if (Subtarget->isTargetELF()) {
1176     // CPU Type
1177     std::string CPUString = Subtarget->getCPUString();
1178     if (CPUString != "generic")
1179       OutStreamer.EmitRawText("\t.cpu " + Twine(CPUString));
1180
1181     // FIXME: Emit FPU type
1182     if (Subtarget->hasVFP2())
1183       OutStreamer.EmitRawText("\t.eabi_attribute " +
1184                               Twine(ARMBuildAttrs::VFP_arch) + ", 2");
1185
1186     // Signal various FP modes.
1187     if (!UnsafeFPMath) {
1188       OutStreamer.EmitRawText("\t.eabi_attribute " +
1189                               Twine(ARMBuildAttrs::ABI_FP_denormal) + ", 1");
1190       OutStreamer.EmitRawText("\t.eabi_attribute " +
1191                               Twine(ARMBuildAttrs::ABI_FP_exceptions) + ", 1");
1192     }
1193     
1194     if (NoInfsFPMath && NoNaNsFPMath)
1195       OutStreamer.EmitRawText("\t.eabi_attribute " +
1196                               Twine(ARMBuildAttrs::ABI_FP_number_model)+ ", 1");
1197     else
1198       OutStreamer.EmitRawText("\t.eabi_attribute " +
1199                               Twine(ARMBuildAttrs::ABI_FP_number_model)+ ", 3");
1200
1201     // 8-bytes alignment stuff.
1202     OutStreamer.EmitRawText("\t.eabi_attribute " +
1203                             Twine(ARMBuildAttrs::ABI_align8_needed) + ", 1");
1204     OutStreamer.EmitRawText("\t.eabi_attribute " +
1205                             Twine(ARMBuildAttrs::ABI_align8_preserved) + ", 1");
1206
1207     // Hard float.  Use both S and D registers and conform to AAPCS-VFP.
1208     if (Subtarget->isAAPCS_ABI() && FloatABIType == FloatABI::Hard) {
1209       OutStreamer.EmitRawText("\t.eabi_attribute " +
1210                               Twine(ARMBuildAttrs::ABI_HardFP_use) + ", 3");
1211       OutStreamer.EmitRawText("\t.eabi_attribute " +
1212                               Twine(ARMBuildAttrs::ABI_VFP_args) + ", 1");
1213     }
1214     // FIXME: Should we signal R9 usage?
1215   }
1216 }
1217
1218
1219 void ARMAsmPrinter::EmitEndOfAsmFile(Module &M) {
1220   if (Subtarget->isTargetDarwin()) {
1221     // All darwin targets use mach-o.
1222     const TargetLoweringObjectFileMachO &TLOFMacho =
1223       static_cast<const TargetLoweringObjectFileMachO &>(getObjFileLowering());
1224     MachineModuleInfoMachO &MMIMacho =
1225       MMI->getObjFileInfo<MachineModuleInfoMachO>();
1226
1227     // Output non-lazy-pointers for external and common global variables.
1228     MachineModuleInfoMachO::SymbolListTy Stubs = MMIMacho.GetGVStubList();
1229
1230     if (!Stubs.empty()) {
1231       // Switch with ".non_lazy_symbol_pointer" directive.
1232       OutStreamer.SwitchSection(TLOFMacho.getNonLazySymbolPointerSection());
1233       EmitAlignment(2);
1234       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1235         // L_foo$stub:
1236         OutStreamer.EmitLabel(Stubs[i].first);
1237         //   .indirect_symbol _foo
1238         MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
1239         OutStreamer.EmitSymbolAttribute(MCSym.getPointer(),MCSA_IndirectSymbol);
1240
1241         if (MCSym.getInt())
1242           // External to current translation unit.
1243           OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
1244         else
1245           // Internal to current translation unit.
1246           //
1247           // When we place the LSDA into the TEXT section, the type info pointers
1248           // need to be indirect and pc-rel. We accomplish this by using NLPs.
1249           // However, sometimes the types are local to the file. So we need to
1250           // fill in the value for the NLP in those cases.
1251           OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
1252                                                         OutContext),
1253                                 4/*size*/, 0/*addrspace*/);
1254       }
1255
1256       Stubs.clear();
1257       OutStreamer.AddBlankLine();
1258     }
1259
1260     Stubs = MMIMacho.GetHiddenGVStubList();
1261     if (!Stubs.empty()) {
1262       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
1263       EmitAlignment(2);
1264       for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
1265         // L_foo$stub:
1266         OutStreamer.EmitLabel(Stubs[i].first);
1267         //   .long _foo
1268         OutStreamer.EmitValue(MCSymbolRefExpr::
1269                               Create(Stubs[i].second.getPointer(),
1270                                      OutContext),
1271                               4/*size*/, 0/*addrspace*/);
1272       }
1273
1274       Stubs.clear();
1275       OutStreamer.AddBlankLine();
1276     }
1277
1278     // Funny Darwin hack: This flag tells the linker that no global symbols
1279     // contain code that falls through to other global symbols (e.g. the obvious
1280     // implementation of multiple entry points).  If this doesn't occur, the
1281     // linker can safely perform dead code stripping.  Since LLVM never
1282     // generates code that does this, it is always safe to set.
1283     OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
1284   }
1285 }
1286
1287 //===----------------------------------------------------------------------===//
1288
1289 void ARMAsmPrinter::printInstructionThroughMCStreamer(const MachineInstr *MI) {
1290   ARMMCInstLower MCInstLowering(OutContext, *Mang, *this);
1291   switch (MI->getOpcode()) {
1292   case ARM::t2MOVi32imm:
1293     assert(0 && "Should be lowered by thumb2it pass");
1294   default: break;
1295   case ARM::PICADD: { // FIXME: Remove asm string from td file.
1296     // This is a pseudo op for a label + instruction sequence, which looks like:
1297     // LPC0:
1298     //     add r0, pc, r0
1299     // This adds the address of LPC0 to r0.
1300     
1301     // Emit the label.
1302     // FIXME: MOVE TO SHARED PLACE.
1303     unsigned Id = (unsigned)MI->getOperand(2).getImm();
1304     const char *Prefix = MAI->getPrivateGlobalPrefix();
1305     MCSymbol *Label =OutContext.GetOrCreateSymbol(Twine(Prefix)
1306                          + "PC" + Twine(getFunctionNumber()) + "_" + Twine(Id));
1307     OutStreamer.EmitLabel(Label);
1308     
1309     
1310     // Form and emit tha dd.
1311     MCInst AddInst;
1312     AddInst.setOpcode(ARM::ADDrr);
1313     AddInst.addOperand(MCOperand::CreateReg(MI->getOperand(0).getReg()));
1314     AddInst.addOperand(MCOperand::CreateReg(ARM::PC));
1315     AddInst.addOperand(MCOperand::CreateReg(MI->getOperand(1).getReg()));
1316     OutStreamer.EmitInstruction(AddInst);
1317     return;
1318   }
1319   case ARM::CONSTPOOL_ENTRY: { // FIXME: Remove asm string from td file.
1320     /// CONSTPOOL_ENTRY - This instruction represents a floating constant pool
1321     /// in the function.  The first operand is the ID# for this instruction, the
1322     /// second is the index into the MachineConstantPool that this is, the third
1323     /// is the size in bytes of this constant pool entry.
1324     unsigned LabelId = (unsigned)MI->getOperand(0).getImm();
1325     unsigned CPIdx   = (unsigned)MI->getOperand(1).getIndex();
1326
1327     EmitAlignment(2);
1328     OutStreamer.EmitLabel(GetCPISymbol(LabelId));
1329
1330     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPIdx];
1331     if (MCPE.isMachineConstantPoolEntry())
1332       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
1333     else
1334       EmitGlobalConstant(MCPE.Val.ConstVal);
1335     
1336     return;
1337   }
1338   case ARM::MOVi2pieces: { // FIXME: Remove asmstring from td file.
1339     // This is a hack that lowers as a two instruction sequence.
1340     unsigned DstReg = MI->getOperand(0).getReg();
1341     unsigned ImmVal = (unsigned)MI->getOperand(1).getImm();
1342
1343     unsigned SOImmValV1 = ARM_AM::getSOImmTwoPartFirst(ImmVal);
1344     unsigned SOImmValV2 = ARM_AM::getSOImmTwoPartSecond(ImmVal);
1345     
1346     {
1347       MCInst TmpInst;
1348       TmpInst.setOpcode(ARM::MOVi);
1349       TmpInst.addOperand(MCOperand::CreateReg(DstReg));
1350       TmpInst.addOperand(MCOperand::CreateImm(SOImmValV1));
1351       
1352       // Predicate.
1353       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1354       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(3).getReg()));
1355
1356       TmpInst.addOperand(MCOperand::CreateReg(0));          // cc_out
1357       OutStreamer.EmitInstruction(TmpInst);
1358     }
1359
1360     {
1361       MCInst TmpInst;
1362       TmpInst.setOpcode(ARM::ORRri);
1363       TmpInst.addOperand(MCOperand::CreateReg(DstReg));     // dstreg
1364       TmpInst.addOperand(MCOperand::CreateReg(DstReg));     // inreg
1365       TmpInst.addOperand(MCOperand::CreateImm(SOImmValV2)); // so_imm
1366       // Predicate.
1367       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1368       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(3).getReg()));
1369       
1370       TmpInst.addOperand(MCOperand::CreateReg(0));          // cc_out
1371       OutStreamer.EmitInstruction(TmpInst);
1372     }
1373     return; 
1374   }
1375   case ARM::MOVi32imm: { // FIXME: Remove asmstring from td file.
1376     // This is a hack that lowers as a two instruction sequence.
1377     unsigned DstReg = MI->getOperand(0).getReg();
1378     const MachineOperand &MO = MI->getOperand(1);
1379     MCOperand V1, V2;
1380     if (MO.isImm()) {
1381       unsigned ImmVal = (unsigned)MI->getOperand(1).getImm();
1382       V1 = MCOperand::CreateImm(ImmVal & 65535);
1383       V2 = MCOperand::CreateImm(ImmVal >> 16);
1384     } else if (MO.isGlobal()) {
1385       MCSymbol *Symbol = MCInstLowering.GetGlobalAddressSymbol(MO);
1386       const MCSymbolRefExpr *SymRef1 =
1387         MCSymbolRefExpr::Create(Symbol,
1388                                 MCSymbolRefExpr::VK_ARM_LO16, OutContext);
1389       const MCSymbolRefExpr *SymRef2 =
1390         MCSymbolRefExpr::Create(Symbol,
1391                                 MCSymbolRefExpr::VK_ARM_HI16, OutContext);
1392       V1 = MCOperand::CreateExpr(SymRef1);
1393       V2 = MCOperand::CreateExpr(SymRef2);
1394     } else {
1395       MI->dump();
1396       llvm_unreachable("cannot handle this operand");
1397     }
1398
1399     {
1400       MCInst TmpInst;
1401       TmpInst.setOpcode(ARM::MOVi16);
1402       TmpInst.addOperand(MCOperand::CreateReg(DstReg));         // dstreg
1403       TmpInst.addOperand(V1); // lower16(imm)
1404       
1405       // Predicate.
1406       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1407       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(3).getReg()));
1408       
1409       OutStreamer.EmitInstruction(TmpInst);
1410     }
1411     
1412     {
1413       MCInst TmpInst;
1414       TmpInst.setOpcode(ARM::MOVTi16);
1415       TmpInst.addOperand(MCOperand::CreateReg(DstReg));         // dstreg
1416       TmpInst.addOperand(MCOperand::CreateReg(DstReg));         // srcreg
1417       TmpInst.addOperand(V2);   // upper16(imm)
1418       
1419       // Predicate.
1420       TmpInst.addOperand(MCOperand::CreateImm(MI->getOperand(2).getImm()));
1421       TmpInst.addOperand(MCOperand::CreateReg(MI->getOperand(3).getReg()));
1422       
1423       OutStreamer.EmitInstruction(TmpInst);
1424     }
1425     
1426     return;
1427   }
1428   }
1429       
1430   MCInst TmpInst;
1431   MCInstLowering.Lower(MI, TmpInst);
1432   OutStreamer.EmitInstruction(TmpInst);
1433 }
1434
1435 //===----------------------------------------------------------------------===//
1436 // Target Registry Stuff
1437 //===----------------------------------------------------------------------===//
1438
1439 static MCInstPrinter *createARMMCInstPrinter(const Target &T,
1440                                              unsigned SyntaxVariant,
1441                                              const MCAsmInfo &MAI) {
1442   if (SyntaxVariant == 0)
1443     return new ARMInstPrinter(MAI, false);
1444   return 0;
1445 }
1446
1447 // Force static initialization.
1448 extern "C" void LLVMInitializeARMAsmPrinter() {
1449   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMTarget);
1450   RegisterAsmPrinter<ARMAsmPrinter> Y(TheThumbTarget);
1451
1452   TargetRegistry::RegisterMCInstPrinter(TheARMTarget, createARMMCInstPrinter);
1453   TargetRegistry::RegisterMCInstPrinter(TheThumbTarget, createARMMCInstPrinter);
1454 }
1455