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