d908cf43631368eeff47252dfb126802e3ed4b2f
[oota-llvm.git] / lib / Target / ARM / AsmPrinter / ARMAsmPrinter.cpp
1 //===-- ARMAsmPrinter.cpp - ARM LLVM assembly writer ----------------------===//
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 "ARMTargetMachine.h"
19 #include "ARMAddressingModes.h"
20 #include "ARMConstantPoolValue.h"
21 #include "ARMMachineFunctionInfo.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Module.h"
24 #include "llvm/CodeGen/AsmPrinter.h"
25 #include "llvm/CodeGen/DwarfWriter.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringSet.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/Mangler.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <cctype>
41 using namespace llvm;
42
43 STATISTIC(EmittedInsts, "Number of machine instrs printed");
44
45 namespace {
46   class VISIBILITY_HIDDEN ARMAsmPrinter : public AsmPrinter {
47     DwarfWriter *DW;
48     MachineModuleInfo *MMI;
49
50     /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
51     /// make the right decision when printing asm code for different targets.
52     const ARMSubtarget *Subtarget;
53
54     /// AFI - Keep a pointer to ARMFunctionInfo for the current
55     /// MachineFunction.
56     ARMFunctionInfo *AFI;
57
58     /// MCP - Keep a pointer to constantpool entries of the current
59     /// MachineFunction.
60     const MachineConstantPool *MCP;
61
62     /// We name each basic block in a Function with a unique number, so
63     /// that we can consistently refer to them later. This is cleared
64     /// at the beginning of each call to runOnMachineFunction().
65     ///
66     typedef std::map<const Value *, unsigned> ValueMapTy;
67     ValueMapTy NumberForBB;
68
69     /// GVNonLazyPtrs - Keeps the set of GlobalValues that require
70     /// non-lazy-pointers for indirect access.
71     StringSet<> GVNonLazyPtrs;
72
73     /// HiddenGVNonLazyPtrs - Keeps the set of GlobalValues with hidden
74     /// visibility that require non-lazy-pointers for indirect access.
75     StringSet<> HiddenGVNonLazyPtrs;
76
77     /// FnStubs - Keeps the set of external function GlobalAddresses that the
78     /// asm printer should generate stubs for.
79     StringSet<> FnStubs;
80
81     /// True if asm printer is printing a series of CONSTPOOL_ENTRY.
82     bool InCPMode;
83   public:
84     explicit ARMAsmPrinter(raw_ostream &O, TargetMachine &TM,
85                            const TargetAsmInfo *T, CodeGenOpt::Level OL,
86                            bool V)
87       : AsmPrinter(O, TM, T, OL, V), DW(0), MMI(NULL), AFI(NULL), MCP(NULL),
88         InCPMode(false) {
89       Subtarget = &TM.getSubtarget<ARMSubtarget>();
90     }
91
92     virtual const char *getPassName() const {
93       return "ARM Assembly Printer";
94     }
95
96     void printOperand(const MachineInstr *MI, int opNum,
97                       const char *Modifier = 0);
98     void printSOImmOperand(const MachineInstr *MI, int opNum);
99     void printSOImm2PartOperand(const MachineInstr *MI, int opNum);
100     void printSORegOperand(const MachineInstr *MI, int opNum);
101     void printAddrMode2Operand(const MachineInstr *MI, int OpNo);
102     void printAddrMode2OffsetOperand(const MachineInstr *MI, int OpNo);
103     void printAddrMode3Operand(const MachineInstr *MI, int OpNo);
104     void printAddrMode3OffsetOperand(const MachineInstr *MI, int OpNo);
105     void printAddrMode4Operand(const MachineInstr *MI, int OpNo,
106                                const char *Modifier = 0);
107     void printAddrMode5Operand(const MachineInstr *MI, int OpNo,
108                                const char *Modifier = 0);
109     void printAddrModePCOperand(const MachineInstr *MI, int OpNo,
110                                 const char *Modifier = 0);
111     void printThumbAddrModeRROperand(const MachineInstr *MI, int OpNo);
112     void printThumbAddrModeRI5Operand(const MachineInstr *MI, int OpNo,
113                                       unsigned Scale);
114     void printThumbAddrModeS1Operand(const MachineInstr *MI, int OpNo);
115     void printThumbAddrModeS2Operand(const MachineInstr *MI, int OpNo);
116     void printThumbAddrModeS4Operand(const MachineInstr *MI, int OpNo);
117     void printThumbAddrModeSPOperand(const MachineInstr *MI, int OpNo);
118     void printPredicateOperand(const MachineInstr *MI, int opNum);
119     void printSBitModifierOperand(const MachineInstr *MI, int opNum);
120     void printPCLabel(const MachineInstr *MI, int opNum);
121     void printRegisterList(const MachineInstr *MI, int opNum);
122     void printCPInstOperand(const MachineInstr *MI, int opNum,
123                             const char *Modifier);
124     void printJTBlockOperand(const MachineInstr *MI, int opNum);
125
126     virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
127                                  unsigned AsmVariant, const char *ExtraCode);
128     virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
129                                        unsigned AsmVariant,
130                                        const char *ExtraCode);
131
132     void printModuleLevelGV(const GlobalVariable* GVar);
133     bool printInstruction(const MachineInstr *MI);  // autogenerated.
134     void printMachineInstruction(const MachineInstr *MI);
135     bool runOnMachineFunction(MachineFunction &F);
136     bool doInitialization(Module &M);
137     bool doFinalization(Module &M);
138
139     /// EmitMachineConstantPoolValue - Print a machine constantpool value to
140     /// the .s file.
141     virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
142       printDataDirective(MCPV->getType());
143
144       ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
145       GlobalValue *GV = ACPV->getGV();
146       std::string Name = GV ? Mang->getValueName(GV) : TAI->getGlobalPrefix();
147       if (!GV)
148         Name += ACPV->getSymbol();
149       if (ACPV->isNonLazyPointer()) {
150         if (GV->hasHiddenVisibility())
151           HiddenGVNonLazyPtrs.insert(Name);
152         else
153           GVNonLazyPtrs.insert(Name);
154         printSuffixedName(Name, "$non_lazy_ptr");
155       } else if (ACPV->isStub()) {
156         FnStubs.insert(Name);
157         printSuffixedName(Name, "$stub");
158       } else
159         O << Name;
160       if (ACPV->hasModifier()) O << "(" << ACPV->getModifier() << ")";
161       if (ACPV->getPCAdjustment() != 0) {
162         O << "-(" << TAI->getPrivateGlobalPrefix() << "PC"
163           << utostr(ACPV->getLabelId())
164           << "+" << (unsigned)ACPV->getPCAdjustment();
165          if (ACPV->mustAddCurrentAddress())
166            O << "-.";
167          O << ")";
168       }
169       O << "\n";
170
171       // If the constant pool value is a extern weak symbol, remember to emit
172       // the weak reference.
173       if (GV && GV->hasExternalWeakLinkage())
174         ExtWeakSymbols.insert(GV);
175     }
176     
177     void getAnalysisUsage(AnalysisUsage &AU) const {
178       AsmPrinter::getAnalysisUsage(AU);
179       AU.setPreservesAll();
180       AU.addRequired<MachineModuleInfo>();
181       AU.addRequired<DwarfWriter>();
182     }
183   };
184 } // end of anonymous namespace
185
186 #include "ARMGenAsmWriter.inc"
187
188 /// runOnMachineFunction - This uses the printInstruction()
189 /// method to print assembly for each instruction.
190 ///
191 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
192   this->MF = &MF;
193
194   AFI = MF.getInfo<ARMFunctionInfo>();
195   MCP = MF.getConstantPool();
196
197   SetupMachineFunction(MF);
198   O << "\n";
199
200   // NOTE: we don't print out constant pools here, they are handled as
201   // instructions.
202
203   O << "\n";
204   // Print out labels for the function.
205   const Function *F = MF.getFunction();
206   switch (F->getLinkage()) {
207   default: assert(0 && "Unknown linkage type!");
208   case Function::PrivateLinkage:
209   case Function::InternalLinkage:
210     SwitchToTextSection("\t.text", F);
211     break;
212   case Function::ExternalLinkage:
213     SwitchToTextSection("\t.text", F);
214     O << "\t.globl\t" << CurrentFnName << "\n";
215     break;
216   case Function::WeakAnyLinkage:
217   case Function::WeakODRLinkage:
218   case Function::LinkOnceAnyLinkage:
219   case Function::LinkOnceODRLinkage:
220     if (Subtarget->isTargetDarwin()) {
221       SwitchToTextSection(
222                 ".section __TEXT,__textcoal_nt,coalesced,pure_instructions", F);
223       O << "\t.globl\t" << CurrentFnName << "\n";
224       O << "\t.weak_definition\t" << CurrentFnName << "\n";
225     } else {
226       O << TAI->getWeakRefDirective() << CurrentFnName << "\n";
227     }
228     break;
229   }
230
231   printVisibility(CurrentFnName, F->getVisibility());
232
233   if (AFI->isThumbFunction()) {
234     EmitAlignment(1, F, AFI->getAlign());
235     O << "\t.code\t16\n";
236     O << "\t.thumb_func";
237     if (Subtarget->isTargetDarwin())
238       O << "\t" << CurrentFnName;
239     O << "\n";
240     InCPMode = false;
241   } else
242     EmitAlignment(2, F);
243
244   O << CurrentFnName << ":\n";
245   // Emit pre-function debug information.
246   DW->BeginFunction(&MF);
247
248   if (Subtarget->isTargetDarwin()) {
249     // If the function is empty, then we need to emit *something*. Otherwise,
250     // the function's label might be associated with something that it wasn't
251     // meant to be associated with. We emit a noop in this situation.
252     MachineFunction::iterator I = MF.begin();
253
254     if (++I == MF.end() && MF.front().empty())
255       O << "\tnop\n";
256   }
257
258   // Print out code for the function.
259   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
260        I != E; ++I) {
261     // Print a label for the basic block.
262     if (I != MF.begin()) {
263       printBasicBlockLabel(I, true, true, VerboseAsm);
264       O << '\n';
265     }
266     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
267          II != E; ++II) {
268       // Print the assembly for the instruction.
269       printMachineInstruction(II);
270     }
271   }
272
273   if (TAI->hasDotTypeDotSizeDirective())
274     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
275
276   // Emit post-function debug information.
277   DW->EndFunction(&MF);
278
279   O.flush();
280
281   return false;
282 }
283
284 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
285                                  const char *Modifier) {
286   const MachineOperand &MO = MI->getOperand(opNum);
287   switch (MO.getType()) {
288   case MachineOperand::MO_Register:
289     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
290       O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
291     else
292       assert(0 && "not implemented");
293     break;
294   case MachineOperand::MO_Immediate: {
295     if (!Modifier || strcmp(Modifier, "no_hash") != 0)
296       O << "#";
297
298     O << MO.getImm();
299     break;
300   }
301   case MachineOperand::MO_MachineBasicBlock:
302     printBasicBlockLabel(MO.getMBB());
303     return;
304   case MachineOperand::MO_GlobalAddress: {
305     bool isCallOp = Modifier && !strcmp(Modifier, "call");
306     GlobalValue *GV = MO.getGlobal();
307     std::string Name = Mang->getValueName(GV);
308     bool isExt = (GV->isDeclaration() || GV->hasWeakLinkage() ||
309                   GV->hasLinkOnceLinkage());
310     if (isExt && isCallOp && Subtarget->isTargetDarwin() &&
311         TM.getRelocationModel() != Reloc::Static) {
312       printSuffixedName(Name, "$stub");
313       FnStubs.insert(Name);
314     } else
315       O << Name;
316
317     printOffset(MO.getOffset());
318
319     if (isCallOp && Subtarget->isTargetELF() &&
320         TM.getRelocationModel() == Reloc::PIC_)
321       O << "(PLT)";
322     if (GV->hasExternalWeakLinkage())
323       ExtWeakSymbols.insert(GV);
324     break;
325   }
326   case MachineOperand::MO_ExternalSymbol: {
327     bool isCallOp = Modifier && !strcmp(Modifier, "call");
328     std::string Name(TAI->getGlobalPrefix());
329     Name += MO.getSymbolName();
330     if (isCallOp && Subtarget->isTargetDarwin() &&
331         TM.getRelocationModel() != Reloc::Static) {
332       printSuffixedName(Name, "$stub");
333       FnStubs.insert(Name);
334     } else
335       O << Name;
336     if (isCallOp && Subtarget->isTargetELF() &&
337         TM.getRelocationModel() == Reloc::PIC_)
338       O << "(PLT)";
339     break;
340   }
341   case MachineOperand::MO_ConstantPoolIndex:
342     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
343       << '_' << MO.getIndex();
344     break;
345   case MachineOperand::MO_JumpTableIndex:
346     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
347       << '_' << MO.getIndex();
348     break;
349   default:
350     O << "<unknown operand type>"; abort (); break;
351   }
352 }
353
354 static void printSOImm(raw_ostream &O, int64_t V, bool VerboseAsm,
355                        const TargetAsmInfo *TAI) {
356   assert(V < (1 << 12) && "Not a valid so_imm value!");
357   unsigned Imm = ARM_AM::getSOImmValImm(V);
358   unsigned Rot = ARM_AM::getSOImmValRot(V);
359
360   // Print low-level immediate formation info, per
361   // A5.1.3: "Data-processing operands - Immediate".
362   if (Rot) {
363     O << "#" << Imm << ", " << Rot;
364     // Pretty printed version.
365     if (VerboseAsm)
366       O << ' ' << TAI->getCommentString()
367         << ' ' << (int)ARM_AM::rotr32(Imm, Rot);
368   } else {
369     O << "#" << Imm;
370   }
371 }
372
373 /// printSOImmOperand - SOImm is 4-bit rotate amount in bits 8-11 with 8-bit
374 /// immediate in bits 0-7.
375 void ARMAsmPrinter::printSOImmOperand(const MachineInstr *MI, int OpNum) {
376   const MachineOperand &MO = MI->getOperand(OpNum);
377   assert(MO.isImm() && "Not a valid so_imm value!");
378   printSOImm(O, MO.getImm(), VerboseAsm, TAI);
379 }
380
381 /// printSOImm2PartOperand - SOImm is broken into two pieces using a 'mov'
382 /// followed by an 'orr' to materialize.
383 void ARMAsmPrinter::printSOImm2PartOperand(const MachineInstr *MI, int OpNum) {
384   const MachineOperand &MO = MI->getOperand(OpNum);
385   assert(MO.isImm() && "Not a valid so_imm value!");
386   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO.getImm());
387   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO.getImm());
388   printSOImm(O, ARM_AM::getSOImmVal(V1), VerboseAsm, TAI);
389   O << "\n\torr";
390   printPredicateOperand(MI, 2);
391   O << " ";
392   printOperand(MI, 0); 
393   O << ", ";
394   printOperand(MI, 0); 
395   O << ", ";
396   printSOImm(O, ARM_AM::getSOImmVal(V2), VerboseAsm, TAI);
397 }
398
399 // so_reg is a 4-operand unit corresponding to register forms of the A5.1
400 // "Addressing Mode 1 - Data-processing operands" forms.  This includes:
401 //    REG 0   0    - e.g. R5
402 //    REG REG 0,SH_OPC     - e.g. R5, ROR R3
403 //    REG 0   IMM,SH_OPC  - e.g. R5, LSL #3
404 void ARMAsmPrinter::printSORegOperand(const MachineInstr *MI, int Op) {
405   const MachineOperand &MO1 = MI->getOperand(Op);
406   const MachineOperand &MO2 = MI->getOperand(Op+1);
407   const MachineOperand &MO3 = MI->getOperand(Op+2);
408
409   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
410   O << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
411
412   // Print the shift opc.
413   O << ", "
414     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO3.getImm()))
415     << " ";
416
417   if (MO2.getReg()) {
418     assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
419     O << TM.getRegisterInfo()->get(MO2.getReg()).AsmName;
420     assert(ARM_AM::getSORegOffset(MO3.getImm()) == 0);
421   } else {
422     O << "#" << ARM_AM::getSORegOffset(MO3.getImm());
423   }
424 }
425
426 void ARMAsmPrinter::printAddrMode2Operand(const MachineInstr *MI, int Op) {
427   const MachineOperand &MO1 = MI->getOperand(Op);
428   const MachineOperand &MO2 = MI->getOperand(Op+1);
429   const MachineOperand &MO3 = MI->getOperand(Op+2);
430
431   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
432     printOperand(MI, Op);
433     return;
434   }
435
436   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
437
438   if (!MO2.getReg()) {
439     if (ARM_AM::getAM2Offset(MO3.getImm()))  // Don't print +0.
440       O << ", #"
441         << (char)ARM_AM::getAM2Op(MO3.getImm())
442         << ARM_AM::getAM2Offset(MO3.getImm());
443     O << "]";
444     return;
445   }
446
447   O << ", "
448     << (char)ARM_AM::getAM2Op(MO3.getImm())
449     << TM.getRegisterInfo()->get(MO2.getReg()).AsmName;
450   
451   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm()))
452     O << ", "
453       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO3.getImm()))
454       << " #" << ShImm;
455   O << "]";
456 }
457
458 void ARMAsmPrinter::printAddrMode2OffsetOperand(const MachineInstr *MI, int Op){
459   const MachineOperand &MO1 = MI->getOperand(Op);
460   const MachineOperand &MO2 = MI->getOperand(Op+1);
461
462   if (!MO1.getReg()) {
463     unsigned ImmOffs = ARM_AM::getAM2Offset(MO2.getImm());
464     assert(ImmOffs && "Malformed indexed load / store!");
465     O << "#"
466       << (char)ARM_AM::getAM2Op(MO2.getImm())
467       << ImmOffs;
468     return;
469   }
470
471   O << (char)ARM_AM::getAM2Op(MO2.getImm())
472     << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
473   
474   if (unsigned ShImm = ARM_AM::getAM2Offset(MO2.getImm()))
475     O << ", "
476       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO2.getImm()))
477       << " #" << ShImm;
478 }
479
480 void ARMAsmPrinter::printAddrMode3Operand(const MachineInstr *MI, int Op) {
481   const MachineOperand &MO1 = MI->getOperand(Op);
482   const MachineOperand &MO2 = MI->getOperand(Op+1);
483   const MachineOperand &MO3 = MI->getOperand(Op+2);
484   
485   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
486   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
487
488   if (MO2.getReg()) {
489     O << ", "
490       << (char)ARM_AM::getAM3Op(MO3.getImm())
491       << TM.getRegisterInfo()->get(MO2.getReg()).AsmName
492       << "]";
493     return;
494   }
495   
496   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm()))
497     O << ", #"
498       << (char)ARM_AM::getAM3Op(MO3.getImm())
499       << ImmOffs;
500   O << "]";
501 }
502
503 void ARMAsmPrinter::printAddrMode3OffsetOperand(const MachineInstr *MI, int Op){
504   const MachineOperand &MO1 = MI->getOperand(Op);
505   const MachineOperand &MO2 = MI->getOperand(Op+1);
506
507   if (MO1.getReg()) {
508     O << (char)ARM_AM::getAM3Op(MO2.getImm())
509       << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
510     return;
511   }
512
513   unsigned ImmOffs = ARM_AM::getAM3Offset(MO2.getImm());
514   assert(ImmOffs && "Malformed indexed load / store!");
515   O << "#"
516     << (char)ARM_AM::getAM3Op(MO2.getImm())
517     << ImmOffs;
518 }
519   
520 void ARMAsmPrinter::printAddrMode4Operand(const MachineInstr *MI, int Op,
521                                           const char *Modifier) {
522   const MachineOperand &MO1 = MI->getOperand(Op);
523   const MachineOperand &MO2 = MI->getOperand(Op+1);
524   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
525   if (Modifier && strcmp(Modifier, "submode") == 0) {
526     if (MO1.getReg() == ARM::SP) {
527       bool isLDM = (MI->getOpcode() == ARM::LDM ||
528                     MI->getOpcode() == ARM::LDM_RET);
529       O << ARM_AM::getAMSubModeAltStr(Mode, isLDM);
530     } else
531       O << ARM_AM::getAMSubModeStr(Mode);
532   } else {
533     printOperand(MI, Op);
534     if (ARM_AM::getAM4WBFlag(MO2.getImm()))
535       O << "!";
536   }
537 }
538
539 void ARMAsmPrinter::printAddrMode5Operand(const MachineInstr *MI, int Op,
540                                           const char *Modifier) {
541   const MachineOperand &MO1 = MI->getOperand(Op);
542   const MachineOperand &MO2 = MI->getOperand(Op+1);
543
544   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
545     printOperand(MI, Op);
546     return;
547   }
548   
549   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
550
551   if (Modifier && strcmp(Modifier, "submode") == 0) {
552     ARM_AM::AMSubMode Mode = ARM_AM::getAM5SubMode(MO2.getImm());
553     if (MO1.getReg() == ARM::SP) {
554       bool isFLDM = (MI->getOpcode() == ARM::FLDMD ||
555                      MI->getOpcode() == ARM::FLDMS);
556       O << ARM_AM::getAMSubModeAltStr(Mode, isFLDM);
557     } else
558       O << ARM_AM::getAMSubModeStr(Mode);
559     return;
560   } else if (Modifier && strcmp(Modifier, "base") == 0) {
561     // Used for FSTM{D|S} and LSTM{D|S} operations.
562     O << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
563     if (ARM_AM::getAM5WBFlag(MO2.getImm()))
564       O << "!";
565     return;
566   }
567   
568   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
569   
570   if (unsigned ImmOffs = ARM_AM::getAM5Offset(MO2.getImm())) {
571     O << ", #"
572       << (char)ARM_AM::getAM5Op(MO2.getImm())
573       << ImmOffs*4;
574   }
575   O << "]";
576 }
577
578 void ARMAsmPrinter::printAddrModePCOperand(const MachineInstr *MI, int Op,
579                                            const char *Modifier) {
580   if (Modifier && strcmp(Modifier, "label") == 0) {
581     printPCLabel(MI, Op+1);
582     return;
583   }
584
585   const MachineOperand &MO1 = MI->getOperand(Op);
586   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
587   O << "[pc, +" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName << "]";
588 }
589
590 void
591 ARMAsmPrinter::printThumbAddrModeRROperand(const MachineInstr *MI, int Op) {
592   const MachineOperand &MO1 = MI->getOperand(Op);
593   const MachineOperand &MO2 = MI->getOperand(Op+1);
594   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
595   O << ", " << TM.getRegisterInfo()->get(MO2.getReg()).AsmName << "]";
596 }
597
598 void
599 ARMAsmPrinter::printThumbAddrModeRI5Operand(const MachineInstr *MI, int Op,
600                                             unsigned Scale) {
601   const MachineOperand &MO1 = MI->getOperand(Op);
602   const MachineOperand &MO2 = MI->getOperand(Op+1);
603   const MachineOperand &MO3 = MI->getOperand(Op+2);
604
605   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
606     printOperand(MI, Op);
607     return;
608   }
609
610   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
611   if (MO3.getReg())
612     O << ", " << TM.getRegisterInfo()->get(MO3.getReg()).AsmName;
613   else if (unsigned ImmOffs = MO2.getImm()) {
614     O << ", #" << ImmOffs;
615     if (Scale > 1)
616       O << " * " << Scale;
617   }
618   O << "]";
619 }
620
621 void
622 ARMAsmPrinter::printThumbAddrModeS1Operand(const MachineInstr *MI, int Op) {
623   printThumbAddrModeRI5Operand(MI, Op, 1);
624 }
625 void
626 ARMAsmPrinter::printThumbAddrModeS2Operand(const MachineInstr *MI, int Op) {
627   printThumbAddrModeRI5Operand(MI, Op, 2);
628 }
629 void
630 ARMAsmPrinter::printThumbAddrModeS4Operand(const MachineInstr *MI, int Op) {
631   printThumbAddrModeRI5Operand(MI, Op, 4);
632 }
633
634 void ARMAsmPrinter::printThumbAddrModeSPOperand(const MachineInstr *MI,int Op) {
635   const MachineOperand &MO1 = MI->getOperand(Op);
636   const MachineOperand &MO2 = MI->getOperand(Op+1);
637   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
638   if (unsigned ImmOffs = MO2.getImm())
639     O << ", #" << ImmOffs << " * 4";
640   O << "]";
641 }
642
643 void ARMAsmPrinter::printPredicateOperand(const MachineInstr *MI, int opNum) {
644   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(opNum).getImm();
645   if (CC != ARMCC::AL)
646     O << ARMCondCodeToString(CC);
647 }
648
649 void ARMAsmPrinter::printSBitModifierOperand(const MachineInstr *MI, int opNum){
650   unsigned Reg = MI->getOperand(opNum).getReg();
651   if (Reg) {
652     assert(Reg == ARM::CPSR && "Expect ARM CPSR register!");
653     O << 's';
654   }
655 }
656
657 void ARMAsmPrinter::printPCLabel(const MachineInstr *MI, int opNum) {
658   int Id = (int)MI->getOperand(opNum).getImm();
659   O << TAI->getPrivateGlobalPrefix() << "PC" << Id;
660 }
661
662 void ARMAsmPrinter::printRegisterList(const MachineInstr *MI, int opNum) {
663   O << "{";
664   for (unsigned i = opNum, e = MI->getNumOperands(); i != e; ++i) {
665     printOperand(MI, i);
666     if (i != e-1) O << ", ";
667   }
668   O << "}";
669 }
670
671 void ARMAsmPrinter::printCPInstOperand(const MachineInstr *MI, int OpNo,
672                                        const char *Modifier) {
673   assert(Modifier && "This operand only works with a modifier!");
674   // There are two aspects to a CONSTANTPOOL_ENTRY operand, the label and the
675   // data itself.
676   if (!strcmp(Modifier, "label")) {
677     unsigned ID = MI->getOperand(OpNo).getImm();
678     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
679       << '_' << ID << ":\n";
680   } else {
681     assert(!strcmp(Modifier, "cpentry") && "Unknown modifier for CPE");
682     unsigned CPI = MI->getOperand(OpNo).getIndex();
683
684     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
685     
686     if (MCPE.isMachineConstantPoolEntry()) {
687       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
688     } else {
689       EmitGlobalConstant(MCPE.Val.ConstVal);
690       // remember to emit the weak reference
691       if (const GlobalValue *GV = dyn_cast<GlobalValue>(MCPE.Val.ConstVal))
692         if (GV->hasExternalWeakLinkage())
693           ExtWeakSymbols.insert(GV);
694     }
695   }
696 }
697
698 void ARMAsmPrinter::printJTBlockOperand(const MachineInstr *MI, int OpNo) {
699   const MachineOperand &MO1 = MI->getOperand(OpNo);
700   const MachineOperand &MO2 = MI->getOperand(OpNo+1); // Unique Id
701   unsigned JTI = MO1.getIndex();
702   O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
703     << '_' << JTI << '_' << MO2.getImm() << ":\n";
704
705   const char *JTEntryDirective = TAI->getJumpTableDirective();
706   if (!JTEntryDirective)
707     JTEntryDirective = TAI->getData32bitsDirective();
708
709   const MachineFunction *MF = MI->getParent()->getParent();
710   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
711   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
712   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
713   bool UseSet= TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_;
714   std::set<MachineBasicBlock*> JTSets;
715   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
716     MachineBasicBlock *MBB = JTBBs[i];
717     if (UseSet && JTSets.insert(MBB).second)
718       printPICJumpTableSetLabel(JTI, MO2.getImm(), MBB);
719
720     O << JTEntryDirective << ' ';
721     if (UseSet)
722       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
723         << '_' << JTI << '_' << MO2.getImm()
724         << "_set_" << MBB->getNumber();
725     else if (TM.getRelocationModel() == Reloc::PIC_) {
726       printBasicBlockLabel(MBB, false, false, false);
727       // If the arch uses custom Jump Table directives, don't calc relative to JT
728       if (!TAI->getJumpTableDirective()) 
729         O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
730           << getFunctionNumber() << '_' << JTI << '_' << MO2.getImm();
731     } else
732       printBasicBlockLabel(MBB, false, false, false);
733     if (i != e-1)
734       O << '\n';
735   }
736 }
737
738
739 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
740                                     unsigned AsmVariant, const char *ExtraCode){
741   // Does this asm operand have a single letter operand modifier?
742   if (ExtraCode && ExtraCode[0]) {
743     if (ExtraCode[1] != 0) return true; // Unknown modifier.
744     
745     switch (ExtraCode[0]) {
746     default: return true;  // Unknown modifier.
747     case 'a': // Don't print "#" before a global var name or constant.
748     case 'c': // Don't print "$" before a global var name or constant.
749       printOperand(MI, OpNo, "no_hash");
750       return false;
751     case 'P': // Print a VFP double precision register.
752       printOperand(MI, OpNo);
753       return false;
754     case 'Q':
755       if (TM.getTargetData()->isLittleEndian())
756         break;
757       // Fallthrough
758     case 'R':
759       if (TM.getTargetData()->isBigEndian())
760         break;
761       // Fallthrough
762     case 'H': // Write second word of DI / DF reference.  
763       // Verify that this operand has two consecutive registers.
764       if (!MI->getOperand(OpNo).isReg() ||
765           OpNo+1 == MI->getNumOperands() ||
766           !MI->getOperand(OpNo+1).isReg())
767         return true;
768       ++OpNo;   // Return the high-part.
769     }
770   }
771   
772   printOperand(MI, OpNo);
773   return false;
774 }
775
776 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
777                                           unsigned OpNo, unsigned AsmVariant,
778                                           const char *ExtraCode) {
779   if (ExtraCode && ExtraCode[0])
780     return true; // Unknown modifier.
781   printAddrMode2Operand(MI, OpNo);
782   return false;
783 }
784
785 void ARMAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
786   ++EmittedInsts;
787
788   int Opc = MI->getOpcode();
789   switch (Opc) {
790   case ARM::CONSTPOOL_ENTRY:
791     if (!InCPMode && AFI->isThumbFunction()) {
792       EmitAlignment(2);
793       InCPMode = true;
794     }
795     break;
796   default: {
797     if (InCPMode && AFI->isThumbFunction())
798       InCPMode = false;
799   }}
800
801   // Call the autogenerated instruction printer routines.
802   printInstruction(MI);
803 }
804
805 bool ARMAsmPrinter::doInitialization(Module &M) {
806
807   bool Result = AsmPrinter::doInitialization(M);
808
809   // Emit initial debug information.
810   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
811   assert(MMI);
812   DW = getAnalysisIfAvailable<DwarfWriter>();
813   assert(DW && "Dwarf Writer is not available");
814   DW->BeginModule(&M, MMI, O, this, TAI);
815
816   // Darwin wants symbols to be quoted if they have complex names.
817   if (Subtarget->isTargetDarwin())
818     Mang->setUseQuotes(true);
819
820   // Emit ARM Build Attributes
821   if (Subtarget->isTargetELF()) {
822     // CPU Type
823     std::string CPUString = Subtarget->getCPUString();
824     if (CPUString != "generic")
825       O << "\t.cpu " << CPUString << '\n';
826
827     // FIXME: Emit FPU type
828     if (Subtarget->hasVFP2())
829       O << "\t.eabi_attribute " << ARMBuildAttrs::VFP_arch << ", 2\n";
830
831     // Signal various FP modes.
832     if (!UnsafeFPMath)
833       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_denormal << ", 1\n"
834         << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_exceptions << ", 1\n";
835
836     if (FiniteOnlyFPMath())
837       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_number_model << ", 1\n";
838     else
839       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_number_model << ", 3\n";
840
841     // 8-bytes alignment stuff.
842     O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_align8_needed << ", 1\n"
843       << "\t.eabi_attribute " << ARMBuildAttrs::ABI_align8_preserved << ", 1\n";
844
845     // FIXME: Should we signal R9 usage?
846   }
847
848   return Result;
849 }
850
851 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
852 /// Don't print things like \\n or \\0.
853 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
854   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
855        Name != E; ++Name)
856     if (isprint(*Name))
857       OS << *Name;
858 }
859
860 void ARMAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
861   const TargetData *TD = TM.getTargetData();
862
863   if (!GVar->hasInitializer())   // External global require no code
864     return;
865
866   // Check to see if this is a special global used by LLVM, if so, emit it.
867
868   if (EmitSpecialLLVMGlobal(GVar)) {
869     if (Subtarget->isTargetDarwin() &&
870         TM.getRelocationModel() == Reloc::Static) {
871       if (GVar->getName() == "llvm.global_ctors")
872         O << ".reference .constructors_used\n";
873       else if (GVar->getName() == "llvm.global_dtors")
874         O << ".reference .destructors_used\n";
875     }
876     return;
877   }
878
879   std::string name = Mang->getValueName(GVar);
880   Constant *C = GVar->getInitializer();
881   const Type *Type = C->getType();
882   unsigned Size = TD->getTypeAllocSize(Type);
883   unsigned Align = TD->getPreferredAlignmentLog(GVar);
884   bool isDarwin = Subtarget->isTargetDarwin();
885
886   printVisibility(name, GVar->getVisibility());
887
888   if (Subtarget->isTargetELF())
889     O << "\t.type " << name << ",%object\n";
890
891   if (C->isNullValue() && !GVar->hasSection() && !GVar->isThreadLocal() &&
892       !(isDarwin &&
893         TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
894     // FIXME: This seems to be pretty darwin-specific
895
896     if (GVar->hasExternalLinkage()) {
897       SwitchToSection(TAI->SectionForGlobal(GVar));
898       if (const char *Directive = TAI->getZeroFillDirective()) {
899         O << "\t.globl\t" << name << "\n";
900         O << Directive << "__DATA, __common, " << name << ", "
901           << Size << ", " << Align << "\n";
902         return;
903       }
904     }
905
906     if (GVar->hasLocalLinkage() || GVar->isWeakForLinker()) {
907       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
908
909       if (isDarwin) {
910         if (GVar->hasLocalLinkage()) {
911           O << TAI->getLCOMMDirective()  << name << "," << Size
912             << ',' << Align;
913         } else if (GVar->hasCommonLinkage()) {
914           O << TAI->getCOMMDirective()  << name << "," << Size
915             << ',' << Align;
916         } else {
917           SwitchToSection(TAI->SectionForGlobal(GVar));
918           O << "\t.globl " << name << '\n'
919             << TAI->getWeakDefDirective() << name << '\n';
920           EmitAlignment(Align, GVar);
921           O << name << ":";
922           if (VerboseAsm) {
923             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
924             PrintUnmangledNameSafely(GVar, O);
925           }
926           O << '\n';
927           EmitGlobalConstant(C);
928           return;
929         }
930       } else if (TAI->getLCOMMDirective() != NULL) {
931         if (GVar->hasLocalLinkage()) {
932           O << TAI->getLCOMMDirective() << name << "," << Size;
933         } else {
934           O << TAI->getCOMMDirective()  << name << "," << Size;
935           if (TAI->getCOMMDirectiveTakesAlignment())
936             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
937         }
938       } else {
939         SwitchToSection(TAI->SectionForGlobal(GVar));
940         if (GVar->hasLocalLinkage())
941           O << "\t.local\t" << name << "\n";
942         O << TAI->getCOMMDirective()  << name << "," << Size;
943         if (TAI->getCOMMDirectiveTakesAlignment())
944           O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
945       }
946       if (VerboseAsm) {
947         O << "\t\t" << TAI->getCommentString() << " ";
948         PrintUnmangledNameSafely(GVar, O);
949       }
950       O << "\n";
951       return;
952     }
953   }
954
955   SwitchToSection(TAI->SectionForGlobal(GVar));
956   switch (GVar->getLinkage()) {
957    case GlobalValue::CommonLinkage:
958    case GlobalValue::LinkOnceAnyLinkage:
959    case GlobalValue::LinkOnceODRLinkage:
960    case GlobalValue::WeakAnyLinkage:
961    case GlobalValue::WeakODRLinkage:
962     if (isDarwin) {
963       O << "\t.globl " << name << "\n"
964         << "\t.weak_definition " << name << "\n";
965     } else {
966       O << "\t.weak " << name << "\n";
967     }
968     break;
969    case GlobalValue::AppendingLinkage:
970     // FIXME: appending linkage variables should go into a section of
971     // their name or something.  For now, just emit them as external.
972    case GlobalValue::ExternalLinkage:
973     O << "\t.globl " << name << "\n";
974     // FALL THROUGH
975    case GlobalValue::PrivateLinkage:
976    case GlobalValue::InternalLinkage:
977     break;
978    default:
979     assert(0 && "Unknown linkage type!");
980     break;
981   }
982
983   EmitAlignment(Align, GVar);
984   O << name << ":";
985   if (VerboseAsm) {
986     O << "\t\t\t\t" << TAI->getCommentString() << " ";
987     PrintUnmangledNameSafely(GVar, O);
988   }
989   O << "\n";
990   if (TAI->hasDotTypeDotSizeDirective())
991     O << "\t.size " << name << ", " << Size << "\n";
992
993   // If the initializer is a extern weak symbol, remember to emit the weak
994   // reference!
995   if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
996     if (GV->hasExternalWeakLinkage())
997       ExtWeakSymbols.insert(GV);
998
999   EmitGlobalConstant(C);
1000   O << '\n';
1001 }
1002
1003
1004 bool ARMAsmPrinter::doFinalization(Module &M) {
1005   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1006        I != E; ++I)
1007     printModuleLevelGV(I);
1008
1009   if (Subtarget->isTargetDarwin()) {
1010     SwitchToDataSection("");
1011
1012     // Output stubs for dynamically-linked functions
1013     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1014          i != e; ++i) {
1015       if (TM.getRelocationModel() == Reloc::PIC_)
1016         SwitchToTextSection(".section __TEXT,__picsymbolstub4,symbol_stubs,"
1017                             "none,16", 0);
1018       else
1019         SwitchToTextSection(".section __TEXT,__symbol_stub4,symbol_stubs,"
1020                             "none,12", 0);
1021
1022       EmitAlignment(2);
1023       O << "\t.code\t32\n";
1024
1025       const char *p = i->getKeyData();
1026       printSuffixedName(p, "$stub");
1027       O << ":\n";
1028       O << "\t.indirect_symbol " << p << "\n";
1029       O << "\tldr ip, ";
1030       printSuffixedName(p, "$slp");
1031       O << "\n";
1032       if (TM.getRelocationModel() == Reloc::PIC_) {
1033         printSuffixedName(p, "$scv");
1034         O << ":\n";
1035         O << "\tadd ip, pc, ip\n";
1036       }
1037       O << "\tldr pc, [ip, #0]\n";
1038       printSuffixedName(p, "$slp");
1039       O << ":\n";
1040       O << "\t.long\t";
1041       printSuffixedName(p, "$lazy_ptr");
1042       if (TM.getRelocationModel() == Reloc::PIC_) {
1043         O << "-(";
1044         printSuffixedName(p, "$scv");
1045         O << "+8)\n";
1046       } else
1047         O << "\n";
1048       SwitchToDataSection(".lazy_symbol_pointer", 0);
1049       printSuffixedName(p, "$lazy_ptr");
1050       O << ":\n";
1051       O << "\t.indirect_symbol " << p << "\n";
1052       O << "\t.long\tdyld_stub_binding_helper\n";
1053     }
1054     O << "\n";
1055
1056     // Output non-lazy-pointers for external and common global variables.
1057     if (!GVNonLazyPtrs.empty()) {
1058       SwitchToDataSection("\t.non_lazy_symbol_pointer", 0);
1059       for (StringSet<>::iterator i =  GVNonLazyPtrs.begin(),
1060              e = GVNonLazyPtrs.end(); i != e; ++i) {
1061         const char *p = i->getKeyData();
1062         printSuffixedName(p, "$non_lazy_ptr");
1063         O << ":\n";
1064         O << "\t.indirect_symbol " << p << "\n";
1065         O << "\t.long\t0\n";
1066       }
1067     }
1068
1069     if (!HiddenGVNonLazyPtrs.empty()) {
1070       SwitchToSection(TAI->getDataSection());
1071       for (StringSet<>::iterator i = HiddenGVNonLazyPtrs.begin(),
1072              e = HiddenGVNonLazyPtrs.end(); i != e; ++i) {
1073         const char *p = i->getKeyData();
1074         EmitAlignment(2);
1075         printSuffixedName(p, "$non_lazy_ptr");
1076         O << ":\n";
1077         O << "\t.long " << p << "\n";
1078       }
1079     }
1080
1081
1082     // Emit initial debug information.
1083     DW->EndModule();
1084
1085     // Funny Darwin hack: This flag tells the linker that no global symbols
1086     // contain code that falls through to other global symbols (e.g. the obvious
1087     // implementation of multiple entry points).  If this doesn't occur, the
1088     // linker can safely perform dead code stripping.  Since LLVM never
1089     // generates code that does this, it is always safe to set.
1090     O << "\t.subsections_via_symbols\n";
1091   } else {
1092     // Emit final debug information for ELF.
1093     DW->EndModule();
1094   }
1095
1096   return AsmPrinter::doFinalization(M);
1097 }
1098
1099 /// createARMCodePrinterPass - Returns a pass that prints the ARM
1100 /// assembly code for a MachineFunction to the given output stream,
1101 /// using the given target machine description.  This should work
1102 /// regardless of whether the function is in SSA form.
1103 ///
1104 FunctionPass *llvm::createARMCodePrinterPass(raw_ostream &o,
1105                                              ARMTargetMachine &tm,
1106                                              CodeGenOpt::Level OptLevel,
1107                                              bool verbose) {
1108   return new ARMAsmPrinter(o, tm, tm.getTargetAsmInfo(), OptLevel, verbose);
1109 }
1110
1111 namespace {
1112   static struct Register {
1113     Register() {
1114       ARMTargetMachine::registerAsmPrinter(createARMCodePrinterPass);
1115     }
1116   } Registrator;
1117 }