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