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