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