Rename getABITypeSize to getTypePaddedSize, as
[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/Statistic.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringSet.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(0), MMI(NULL), AFI(NULL), MCP(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     /// MCP - Keep a pointer to constantpool entries of the current
64     /// MachineFunction.
65     const MachineConstantPool *MCP;
66
67     /// We name each basic block in a Function with a unique number, so
68     /// that we can consistently refer to them later. This is cleared
69     /// at the beginning of each call to runOnMachineFunction().
70     ///
71     typedef std::map<const Value *, unsigned> ValueMapTy;
72     ValueMapTy NumberForBB;
73
74     /// GVNonLazyPtrs - Keeps the set of GlobalValues that require
75     /// non-lazy-pointers for indirect access.
76     StringSet<> GVNonLazyPtrs;
77
78     /// HiddenGVNonLazyPtrs - Keeps the set of GlobalValues with hidden
79     /// visibility that require non-lazy-pointers for indirect access.
80     StringSet<> HiddenGVNonLazyPtrs;
81
82     /// FnStubs - Keeps the set of external function GlobalAddresses that the
83     /// asm printer should generate stubs for.
84     StringSet<> FnStubs;
85
86     /// True if asm printer is printing a series of CONSTPOOL_ENTRY.
87     bool InCPMode;
88     
89     virtual const char *getPassName() const {
90       return "ARM Assembly Printer";
91     }
92
93     void printOperand(const MachineInstr *MI, int opNum,
94                       const char *Modifier = 0);
95     void printSOImmOperand(const MachineInstr *MI, int opNum);
96     void printSOImm2PartOperand(const MachineInstr *MI, int opNum);
97     void printSORegOperand(const MachineInstr *MI, int opNum);
98     void printAddrMode2Operand(const MachineInstr *MI, int OpNo);
99     void printAddrMode2OffsetOperand(const MachineInstr *MI, int OpNo);
100     void printAddrMode3Operand(const MachineInstr *MI, int OpNo);
101     void printAddrMode3OffsetOperand(const MachineInstr *MI, int OpNo);
102     void printAddrMode4Operand(const MachineInstr *MI, int OpNo,
103                                const char *Modifier = 0);
104     void printAddrMode5Operand(const MachineInstr *MI, int OpNo,
105                                const char *Modifier = 0);
106     void printAddrModePCOperand(const MachineInstr *MI, int OpNo,
107                                 const char *Modifier = 0);
108     void printThumbAddrModeRROperand(const MachineInstr *MI, int OpNo);
109     void printThumbAddrModeRI5Operand(const MachineInstr *MI, int OpNo,
110                                       unsigned Scale);
111     void printThumbAddrModeS1Operand(const MachineInstr *MI, int OpNo);
112     void printThumbAddrModeS2Operand(const MachineInstr *MI, int OpNo);
113     void printThumbAddrModeS4Operand(const MachineInstr *MI, int OpNo);
114     void printThumbAddrModeSPOperand(const MachineInstr *MI, int OpNo);
115     void printPredicateOperand(const MachineInstr *MI, int opNum);
116     void printSBitModifierOperand(const MachineInstr *MI, int opNum);
117     void printPCLabel(const MachineInstr *MI, int opNum);
118     void printRegisterList(const MachineInstr *MI, int opNum);
119     void printCPInstOperand(const MachineInstr *MI, int opNum,
120                             const char *Modifier);
121     void printJTBlockOperand(const MachineInstr *MI, int opNum);
122
123     virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
124                                  unsigned AsmVariant, const char *ExtraCode);
125
126     void printModuleLevelGV(const GlobalVariable* GVar);
127     bool printInstruction(const MachineInstr *MI);  // autogenerated.
128     void printMachineInstruction(const MachineInstr *MI);
129     bool runOnMachineFunction(MachineFunction &F);
130     bool doInitialization(Module &M);
131     bool doFinalization(Module &M);
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         if (GV->hasHiddenVisibility())
145           HiddenGVNonLazyPtrs.insert(Name);
146         else
147           GVNonLazyPtrs.insert(Name);
148         printSuffixedName(Name, "$non_lazy_ptr");
149       } else if (ACPV->isStub()) {
150         FnStubs.insert(Name);
151         printSuffixedName(Name, "$stub");
152       } else
153         O << Name;
154       if (ACPV->hasModifier()) O << "(" << ACPV->getModifier() << ")";
155       if (ACPV->getPCAdjustment() != 0) {
156         O << "-(" << TAI->getPrivateGlobalPrefix() << "PC"
157           << utostr(ACPV->getLabelId())
158           << "+" << (unsigned)ACPV->getPCAdjustment();
159          if (ACPV->mustAddCurrentAddress())
160            O << "-.";
161          O << ")";
162       }
163       O << "\n";
164
165       // If the constant pool value is a extern weak symbol, remember to emit
166       // the weak reference.
167       if (GV && GV->hasExternalWeakLinkage())
168         ExtWeakSymbols.insert(GV);
169     }
170     
171     void getAnalysisUsage(AnalysisUsage &AU) const {
172       AsmPrinter::getAnalysisUsage(AU);
173       AU.setPreservesAll();
174       AU.addRequired<MachineModuleInfo>();
175       AU.addRequired<DwarfWriter>();
176     }
177   };
178 } // end of anonymous namespace
179
180 #include "ARMGenAsmWriter.inc"
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   MCP = MF.getConstantPool();
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   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   DW->EndFunction(&MF);
267
268   O.flush();
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     printOffset(MO.getOffset());
307
308     if (isCallOp && Subtarget->isTargetELF() &&
309         TM.getRelocationModel() == Reloc::PIC_)
310       O << "(PLT)";
311     if (GV->hasExternalWeakLinkage())
312       ExtWeakSymbols.insert(GV);
313     break;
314   }
315   case MachineOperand::MO_ExternalSymbol: {
316     bool isCallOp = Modifier && !strcmp(Modifier, "call");
317     std::string Name(TAI->getGlobalPrefix());
318     Name += MO.getSymbolName();
319     if (isCallOp && Subtarget->isTargetDarwin() &&
320         TM.getRelocationModel() != Reloc::Static) {
321       printSuffixedName(Name, "$stub");
322       FnStubs.insert(Name);
323     } else
324       O << Name;
325     if (isCallOp && Subtarget->isTargetELF() &&
326         TM.getRelocationModel() == Reloc::PIC_)
327       O << "(PLT)";
328     break;
329   }
330   case MachineOperand::MO_ConstantPoolIndex:
331     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
332       << '_' << MO.getIndex();
333     break;
334   case MachineOperand::MO_JumpTableIndex:
335     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
336       << '_' << MO.getIndex();
337     break;
338   default:
339     O << "<unknown operand type>"; abort (); break;
340   }
341 }
342
343 static void printSOImm(raw_ostream &O, int64_t V, const TargetAsmInfo *TAI) {
344   assert(V < (1 << 12) && "Not a valid so_imm value!");
345   unsigned Imm = ARM_AM::getSOImmValImm(V);
346   unsigned Rot = ARM_AM::getSOImmValRot(V);
347
348   // Print low-level immediate formation info, per
349   // A5.1.3: "Data-processing operands - Immediate".
350   if (Rot) {
351     O << "#" << Imm << ", " << Rot;
352     // Pretty printed version.
353     O << ' ' << TAI->getCommentString() << ' ' << (int)ARM_AM::rotr32(Imm, Rot);
354   } else {
355     O << "#" << Imm;
356   }
357 }
358
359 /// printSOImmOperand - SOImm is 4-bit rotate amount in bits 8-11 with 8-bit
360 /// immediate in bits 0-7.
361 void ARMAsmPrinter::printSOImmOperand(const MachineInstr *MI, int OpNum) {
362   const MachineOperand &MO = MI->getOperand(OpNum);
363   assert(MO.isImm() && "Not a valid so_imm value!");
364   printSOImm(O, MO.getImm(), TAI);
365 }
366
367 /// printSOImm2PartOperand - SOImm is broken into two pieces using a 'mov'
368 /// followed by an 'orr' to materialize.
369 void ARMAsmPrinter::printSOImm2PartOperand(const MachineInstr *MI, int OpNum) {
370   const MachineOperand &MO = MI->getOperand(OpNum);
371   assert(MO.isImm() && "Not a valid so_imm value!");
372   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO.getImm());
373   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO.getImm());
374   printSOImm(O, ARM_AM::getSOImmVal(V1), TAI);
375   O << "\n\torr";
376   printPredicateOperand(MI, 2);
377   O << " ";
378   printOperand(MI, 0); 
379   O << ", ";
380   printOperand(MI, 0); 
381   O << ", ";
382   printSOImm(O, ARM_AM::getSOImmVal(V2), TAI);
383 }
384
385 // so_reg is a 4-operand unit corresponding to register forms of the A5.1
386 // "Addressing Mode 1 - Data-processing operands" forms.  This includes:
387 //    REG 0   0    - e.g. R5
388 //    REG REG 0,SH_OPC     - e.g. R5, ROR R3
389 //    REG 0   IMM,SH_OPC  - e.g. R5, LSL #3
390 void ARMAsmPrinter::printSORegOperand(const MachineInstr *MI, int Op) {
391   const MachineOperand &MO1 = MI->getOperand(Op);
392   const MachineOperand &MO2 = MI->getOperand(Op+1);
393   const MachineOperand &MO3 = MI->getOperand(Op+2);
394
395   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
396   O << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
397
398   // Print the shift opc.
399   O << ", "
400     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO3.getImm()))
401     << " ";
402
403   if (MO2.getReg()) {
404     assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
405     O << TM.getRegisterInfo()->get(MO2.getReg()).AsmName;
406     assert(ARM_AM::getSORegOffset(MO3.getImm()) == 0);
407   } else {
408     O << "#" << ARM_AM::getSORegOffset(MO3.getImm());
409   }
410 }
411
412 void ARMAsmPrinter::printAddrMode2Operand(const MachineInstr *MI, int Op) {
413   const MachineOperand &MO1 = MI->getOperand(Op);
414   const MachineOperand &MO2 = MI->getOperand(Op+1);
415   const MachineOperand &MO3 = MI->getOperand(Op+2);
416
417   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
418     printOperand(MI, Op);
419     return;
420   }
421
422   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
423
424   if (!MO2.getReg()) {
425     if (ARM_AM::getAM2Offset(MO3.getImm()))  // Don't print +0.
426       O << ", #"
427         << (char)ARM_AM::getAM2Op(MO3.getImm())
428         << ARM_AM::getAM2Offset(MO3.getImm());
429     O << "]";
430     return;
431   }
432
433   O << ", "
434     << (char)ARM_AM::getAM2Op(MO3.getImm())
435     << TM.getRegisterInfo()->get(MO2.getReg()).AsmName;
436   
437   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm()))
438     O << ", "
439       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO3.getImm()))
440       << " #" << ShImm;
441   O << "]";
442 }
443
444 void ARMAsmPrinter::printAddrMode2OffsetOperand(const MachineInstr *MI, int Op){
445   const MachineOperand &MO1 = MI->getOperand(Op);
446   const MachineOperand &MO2 = MI->getOperand(Op+1);
447
448   if (!MO1.getReg()) {
449     unsigned ImmOffs = ARM_AM::getAM2Offset(MO2.getImm());
450     assert(ImmOffs && "Malformed indexed load / store!");
451     O << "#"
452       << (char)ARM_AM::getAM2Op(MO2.getImm())
453       << ImmOffs;
454     return;
455   }
456
457   O << (char)ARM_AM::getAM2Op(MO2.getImm())
458     << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
459   
460   if (unsigned ShImm = ARM_AM::getAM2Offset(MO2.getImm()))
461     O << ", "
462       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO2.getImm()))
463       << " #" << ShImm;
464 }
465
466 void ARMAsmPrinter::printAddrMode3Operand(const MachineInstr *MI, int Op) {
467   const MachineOperand &MO1 = MI->getOperand(Op);
468   const MachineOperand &MO2 = MI->getOperand(Op+1);
469   const MachineOperand &MO3 = MI->getOperand(Op+2);
470   
471   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
472   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
473
474   if (MO2.getReg()) {
475     O << ", "
476       << (char)ARM_AM::getAM3Op(MO3.getImm())
477       << TM.getRegisterInfo()->get(MO2.getReg()).AsmName
478       << "]";
479     return;
480   }
481   
482   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm()))
483     O << ", #"
484       << (char)ARM_AM::getAM3Op(MO3.getImm())
485       << ImmOffs;
486   O << "]";
487 }
488
489 void ARMAsmPrinter::printAddrMode3OffsetOperand(const MachineInstr *MI, int Op){
490   const MachineOperand &MO1 = MI->getOperand(Op);
491   const MachineOperand &MO2 = MI->getOperand(Op+1);
492
493   if (MO1.getReg()) {
494     O << (char)ARM_AM::getAM3Op(MO2.getImm())
495       << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
496     return;
497   }
498
499   unsigned ImmOffs = ARM_AM::getAM3Offset(MO2.getImm());
500   assert(ImmOffs && "Malformed indexed load / store!");
501   O << "#"
502     << (char)ARM_AM::getAM3Op(MO2.getImm())
503     << ImmOffs;
504 }
505   
506 void ARMAsmPrinter::printAddrMode4Operand(const MachineInstr *MI, int Op,
507                                           const char *Modifier) {
508   const MachineOperand &MO1 = MI->getOperand(Op);
509   const MachineOperand &MO2 = MI->getOperand(Op+1);
510   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
511   if (Modifier && strcmp(Modifier, "submode") == 0) {
512     if (MO1.getReg() == ARM::SP) {
513       bool isLDM = (MI->getOpcode() == ARM::LDM ||
514                     MI->getOpcode() == ARM::LDM_RET);
515       O << ARM_AM::getAMSubModeAltStr(Mode, isLDM);
516     } else
517       O << ARM_AM::getAMSubModeStr(Mode);
518   } else {
519     printOperand(MI, Op);
520     if (ARM_AM::getAM4WBFlag(MO2.getImm()))
521       O << "!";
522   }
523 }
524
525 void ARMAsmPrinter::printAddrMode5Operand(const MachineInstr *MI, int Op,
526                                           const char *Modifier) {
527   const MachineOperand &MO1 = MI->getOperand(Op);
528   const MachineOperand &MO2 = MI->getOperand(Op+1);
529
530   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
531     printOperand(MI, Op);
532     return;
533   }
534   
535   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
536
537   if (Modifier && strcmp(Modifier, "submode") == 0) {
538     ARM_AM::AMSubMode Mode = ARM_AM::getAM5SubMode(MO2.getImm());
539     if (MO1.getReg() == ARM::SP) {
540       bool isFLDM = (MI->getOpcode() == ARM::FLDMD ||
541                      MI->getOpcode() == ARM::FLDMS);
542       O << ARM_AM::getAMSubModeAltStr(Mode, isFLDM);
543     } else
544       O << ARM_AM::getAMSubModeStr(Mode);
545     return;
546   } else if (Modifier && strcmp(Modifier, "base") == 0) {
547     // Used for FSTM{D|S} and LSTM{D|S} operations.
548     O << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
549     if (ARM_AM::getAM5WBFlag(MO2.getImm()))
550       O << "!";
551     return;
552   }
553   
554   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
555   
556   if (unsigned ImmOffs = ARM_AM::getAM5Offset(MO2.getImm())) {
557     O << ", #"
558       << (char)ARM_AM::getAM5Op(MO2.getImm())
559       << ImmOffs*4;
560   }
561   O << "]";
562 }
563
564 void ARMAsmPrinter::printAddrModePCOperand(const MachineInstr *MI, int Op,
565                                            const char *Modifier) {
566   if (Modifier && strcmp(Modifier, "label") == 0) {
567     printPCLabel(MI, Op+1);
568     return;
569   }
570
571   const MachineOperand &MO1 = MI->getOperand(Op);
572   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
573   O << "[pc, +" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName << "]";
574 }
575
576 void
577 ARMAsmPrinter::printThumbAddrModeRROperand(const MachineInstr *MI, int Op) {
578   const MachineOperand &MO1 = MI->getOperand(Op);
579   const MachineOperand &MO2 = MI->getOperand(Op+1);
580   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
581   O << ", " << TM.getRegisterInfo()->get(MO2.getReg()).AsmName << "]";
582 }
583
584 void
585 ARMAsmPrinter::printThumbAddrModeRI5Operand(const MachineInstr *MI, int Op,
586                                             unsigned Scale) {
587   const MachineOperand &MO1 = MI->getOperand(Op);
588   const MachineOperand &MO2 = MI->getOperand(Op+1);
589   const MachineOperand &MO3 = MI->getOperand(Op+2);
590
591   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
592     printOperand(MI, Op);
593     return;
594   }
595
596   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
597   if (MO3.getReg())
598     O << ", " << TM.getRegisterInfo()->get(MO3.getReg()).AsmName;
599   else if (unsigned ImmOffs = MO2.getImm()) {
600     O << ", #" << ImmOffs;
601     if (Scale > 1)
602       O << " * " << Scale;
603   }
604   O << "]";
605 }
606
607 void
608 ARMAsmPrinter::printThumbAddrModeS1Operand(const MachineInstr *MI, int Op) {
609   printThumbAddrModeRI5Operand(MI, Op, 1);
610 }
611 void
612 ARMAsmPrinter::printThumbAddrModeS2Operand(const MachineInstr *MI, int Op) {
613   printThumbAddrModeRI5Operand(MI, Op, 2);
614 }
615 void
616 ARMAsmPrinter::printThumbAddrModeS4Operand(const MachineInstr *MI, int Op) {
617   printThumbAddrModeRI5Operand(MI, Op, 4);
618 }
619
620 void ARMAsmPrinter::printThumbAddrModeSPOperand(const MachineInstr *MI,int Op) {
621   const MachineOperand &MO1 = MI->getOperand(Op);
622   const MachineOperand &MO2 = MI->getOperand(Op+1);
623   O << "[" << TM.getRegisterInfo()->get(MO1.getReg()).AsmName;
624   if (unsigned ImmOffs = MO2.getImm())
625     O << ", #" << ImmOffs << " * 4";
626   O << "]";
627 }
628
629 void ARMAsmPrinter::printPredicateOperand(const MachineInstr *MI, int opNum) {
630   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(opNum).getImm();
631   if (CC != ARMCC::AL)
632     O << ARMCondCodeToString(CC);
633 }
634
635 void ARMAsmPrinter::printSBitModifierOperand(const MachineInstr *MI, int opNum){
636   unsigned Reg = MI->getOperand(opNum).getReg();
637   if (Reg) {
638     assert(Reg == ARM::CPSR && "Expect ARM CPSR register!");
639     O << 's';
640   }
641 }
642
643 void ARMAsmPrinter::printPCLabel(const MachineInstr *MI, int opNum) {
644   int Id = (int)MI->getOperand(opNum).getImm();
645   O << TAI->getPrivateGlobalPrefix() << "PC" << Id;
646 }
647
648 void ARMAsmPrinter::printRegisterList(const MachineInstr *MI, int opNum) {
649   O << "{";
650   for (unsigned i = opNum, e = MI->getNumOperands(); i != e; ++i) {
651     printOperand(MI, i);
652     if (i != e-1) O << ", ";
653   }
654   O << "}";
655 }
656
657 void ARMAsmPrinter::printCPInstOperand(const MachineInstr *MI, int OpNo,
658                                        const char *Modifier) {
659   assert(Modifier && "This operand only works with a modifier!");
660   // There are two aspects to a CONSTANTPOOL_ENTRY operand, the label and the
661   // data itself.
662   if (!strcmp(Modifier, "label")) {
663     unsigned ID = MI->getOperand(OpNo).getImm();
664     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
665       << '_' << ID << ":\n";
666   } else {
667     assert(!strcmp(Modifier, "cpentry") && "Unknown modifier for CPE");
668     unsigned CPI = MI->getOperand(OpNo).getIndex();
669
670     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
671     
672     if (MCPE.isMachineConstantPoolEntry()) {
673       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
674     } else {
675       EmitGlobalConstant(MCPE.Val.ConstVal);
676       // remember to emit the weak reference
677       if (const GlobalValue *GV = dyn_cast<GlobalValue>(MCPE.Val.ConstVal))
678         if (GV->hasExternalWeakLinkage())
679           ExtWeakSymbols.insert(GV);
680     }
681   }
682 }
683
684 void ARMAsmPrinter::printJTBlockOperand(const MachineInstr *MI, int OpNo) {
685   const MachineOperand &MO1 = MI->getOperand(OpNo);
686   const MachineOperand &MO2 = MI->getOperand(OpNo+1); // Unique Id
687   unsigned JTI = MO1.getIndex();
688   O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
689     << '_' << JTI << '_' << MO2.getImm() << ":\n";
690
691   const char *JTEntryDirective = TAI->getJumpTableDirective();
692   if (!JTEntryDirective)
693     JTEntryDirective = TAI->getData32bitsDirective();
694
695   const MachineFunction *MF = MI->getParent()->getParent();
696   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
697   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
698   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
699   bool UseSet= TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_;
700   std::set<MachineBasicBlock*> JTSets;
701   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
702     MachineBasicBlock *MBB = JTBBs[i];
703     if (UseSet && JTSets.insert(MBB).second)
704       printPICJumpTableSetLabel(JTI, MO2.getImm(), MBB);
705
706     O << JTEntryDirective << ' ';
707     if (UseSet)
708       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
709         << '_' << JTI << '_' << MO2.getImm()
710         << "_set_" << MBB->getNumber();
711     else if (TM.getRelocationModel() == Reloc::PIC_) {
712       printBasicBlockLabel(MBB, false, false, false);
713       // If the arch uses custom Jump Table directives, don't calc relative to JT
714       if (!TAI->getJumpTableDirective()) 
715         O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
716           << getFunctionNumber() << '_' << JTI << '_' << MO2.getImm();
717     } else
718       printBasicBlockLabel(MBB, false, false, false);
719     if (i != e-1)
720       O << '\n';
721   }
722 }
723
724
725 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
726                                     unsigned AsmVariant, const char *ExtraCode){
727   // Does this asm operand have a single letter operand modifier?
728   if (ExtraCode && ExtraCode[0]) {
729     if (ExtraCode[1] != 0) return true; // Unknown modifier.
730     
731     switch (ExtraCode[0]) {
732     default: return true;  // Unknown modifier.
733     case 'c': // Don't print "$" before a global var name or constant.
734     case 'P': // Print a VFP double precision register.
735       printOperand(MI, OpNo);
736       return false;
737     case 'Q':
738       if (TM.getTargetData()->isLittleEndian())
739         break;
740       // Fallthrough
741     case 'R':
742       if (TM.getTargetData()->isBigEndian())
743         break;
744       // Fallthrough
745     case 'H': // Write second word of DI / DF reference.  
746       // Verify that this operand has two consecutive registers.
747       if (!MI->getOperand(OpNo).isReg() ||
748           OpNo+1 == MI->getNumOperands() ||
749           !MI->getOperand(OpNo+1).isReg())
750         return true;
751       ++OpNo;   // Return the high-part.
752     }
753   }
754   
755   printOperand(MI, OpNo);
756   return false;
757 }
758
759 void ARMAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
760   ++EmittedInsts;
761
762   int Opc = MI->getOpcode();
763   switch (Opc) {
764   case ARM::CONSTPOOL_ENTRY:
765     if (!InCPMode && AFI->isThumbFunction()) {
766       EmitAlignment(2);
767       InCPMode = true;
768     }
769     break;
770   default: {
771     if (InCPMode && AFI->isThumbFunction())
772       InCPMode = false;
773   }}
774
775   // Call the autogenerated instruction printer routines.
776   printInstruction(MI);
777 }
778
779 bool ARMAsmPrinter::doInitialization(Module &M) {
780
781   bool Result = AsmPrinter::doInitialization(M);
782
783   // Emit initial debug information.
784   MMI = getAnalysisToUpdate<MachineModuleInfo>();
785   assert(MMI);
786   DW = getAnalysisToUpdate<DwarfWriter>();
787   assert(DW && "Dwarf Writer is not available");
788   DW->BeginModule(&M, MMI, O, this, TAI);
789
790   // Darwin wants symbols to be quoted if they have complex names.
791   if (Subtarget->isTargetDarwin())
792     Mang->setUseQuotes(true);
793
794   return Result;
795 }
796
797 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
798 /// Don't print things like \n or \0.
799 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
800   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
801        Name != E; ++Name)
802     if (isprint(*Name))
803       OS << *Name;
804 }
805
806 void ARMAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
807   const TargetData *TD = TM.getTargetData();
808
809   if (!GVar->hasInitializer())   // External global require no code
810     return;
811
812   // Check to see if this is a special global used by LLVM, if so, emit it.
813
814   if (EmitSpecialLLVMGlobal(GVar)) {
815     if (Subtarget->isTargetDarwin() &&
816         TM.getRelocationModel() == Reloc::Static) {
817       if (GVar->getName() == "llvm.global_ctors")
818         O << ".reference .constructors_used\n";
819       else if (GVar->getName() == "llvm.global_dtors")
820         O << ".reference .destructors_used\n";
821     }
822     return;
823   }
824
825   std::string name = Mang->getValueName(GVar);
826   Constant *C = GVar->getInitializer();
827   const Type *Type = C->getType();
828   unsigned Size = TD->getTypePaddedSize(Type);
829   unsigned Align = TD->getPreferredAlignmentLog(GVar);
830   bool isDarwin = Subtarget->isTargetDarwin();
831
832   printVisibility(name, GVar->getVisibility());
833
834   if (Subtarget->isTargetELF())
835     O << "\t.type " << name << ",%object\n";
836
837   if (C->isNullValue() && !GVar->hasSection() && !GVar->isThreadLocal()) {
838     // FIXME: This seems to be pretty darwin-specific
839
840     if (GVar->hasExternalLinkage()) {
841       SwitchToSection(TAI->SectionForGlobal(GVar));
842       if (const char *Directive = TAI->getZeroFillDirective()) {
843         O << "\t.globl\t" << name << "\n";
844         O << Directive << "__DATA, __common, " << name << ", "
845           << Size << ", " << Align << "\n";
846         return;
847       }
848     }
849
850     if (GVar->hasInternalLinkage() || GVar->mayBeOverridden()) {
851       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
852
853       if (isDarwin) {
854         if (GVar->hasInternalLinkage()) {
855           O << TAI->getLCOMMDirective()  << name << "," << Size
856             << ',' << Align;
857         } else if (GVar->hasCommonLinkage()) {
858           O << TAI->getCOMMDirective()  << name << "," << Size
859             << ',' << Align;
860         } else {
861           SwitchToSection(TAI->SectionForGlobal(GVar));
862           O << "\t.globl " << name << '\n'
863             << TAI->getWeakDefDirective() << name << '\n';
864           EmitAlignment(Align, GVar);
865           O << name << ":\t\t\t\t" << TAI->getCommentString() << ' ';
866           PrintUnmangledNameSafely(GVar, O);
867           O << '\n';
868           EmitGlobalConstant(C);
869           return;
870         }
871       } else if (TAI->getLCOMMDirective() != NULL) {
872         if (GVar->hasInternalLinkage()) {
873           O << TAI->getLCOMMDirective() << name << "," << Size;
874         } else {
875           O << TAI->getCOMMDirective()  << name << "," << Size;
876           if (TAI->getCOMMDirectiveTakesAlignment())
877             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
878         }
879       } else {
880         SwitchToSection(TAI->SectionForGlobal(GVar));
881         if (GVar->hasInternalLinkage())
882           O << "\t.local\t" << name << "\n";
883         O << TAI->getCOMMDirective()  << name << "," << Size;
884         if (TAI->getCOMMDirectiveTakesAlignment())
885           O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
886       }
887       O << "\t\t" << TAI->getCommentString() << " ";
888       PrintUnmangledNameSafely(GVar, O);
889       O << "\n";
890       return;
891     }
892   }
893
894   SwitchToSection(TAI->SectionForGlobal(GVar));
895   switch (GVar->getLinkage()) {
896    case GlobalValue::CommonLinkage:
897    case GlobalValue::LinkOnceLinkage:
898    case GlobalValue::WeakLinkage:
899     if (isDarwin) {
900       O << "\t.globl " << name << "\n"
901         << "\t.weak_definition " << name << "\n";
902     } else {
903       O << "\t.weak " << name << "\n";
904     }
905     break;
906    case GlobalValue::AppendingLinkage:
907     // FIXME: appending linkage variables should go into a section of
908     // their name or something.  For now, just emit them as external.
909    case GlobalValue::ExternalLinkage:
910     O << "\t.globl " << name << "\n";
911     // FALL THROUGH
912    case GlobalValue::InternalLinkage:
913     break;
914    default:
915     assert(0 && "Unknown linkage type!");
916     break;
917   }
918
919   EmitAlignment(Align, GVar);
920   O << name << ":\t\t\t\t" << TAI->getCommentString() << " ";
921   PrintUnmangledNameSafely(GVar, O);
922   O << "\n";
923   if (TAI->hasDotTypeDotSizeDirective())
924     O << "\t.size " << name << ", " << Size << "\n";
925
926   // If the initializer is a extern weak symbol, remember to emit the weak
927   // reference!
928   if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
929     if (GV->hasExternalWeakLinkage())
930       ExtWeakSymbols.insert(GV);
931
932   EmitGlobalConstant(C);
933   O << '\n';
934 }
935
936
937 bool ARMAsmPrinter::doFinalization(Module &M) {
938   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
939        I != E; ++I)
940     printModuleLevelGV(I);
941
942   if (Subtarget->isTargetDarwin()) {
943     SwitchToDataSection("");
944
945     // Output stubs for dynamically-linked functions
946     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
947          i != e; ++i) {
948       if (TM.getRelocationModel() == Reloc::PIC_)
949         SwitchToTextSection(".section __TEXT,__picsymbolstub4,symbol_stubs,"
950                             "none,16", 0);
951       else
952         SwitchToTextSection(".section __TEXT,__symbol_stub4,symbol_stubs,"
953                             "none,12", 0);
954
955       EmitAlignment(2);
956       O << "\t.code\t32\n";
957
958       const char *p = i->getKeyData();
959       printSuffixedName(p, "$stub");
960       O << ":\n";
961       O << "\t.indirect_symbol " << p << "\n";
962       O << "\tldr ip, ";
963       printSuffixedName(p, "$slp");
964       O << "\n";
965       if (TM.getRelocationModel() == Reloc::PIC_) {
966         printSuffixedName(p, "$scv");
967         O << ":\n";
968         O << "\tadd ip, pc, ip\n";
969       }
970       O << "\tldr pc, [ip, #0]\n";
971       printSuffixedName(p, "$slp");
972       O << ":\n";
973       O << "\t.long\t";
974       printSuffixedName(p, "$lazy_ptr");
975       if (TM.getRelocationModel() == Reloc::PIC_) {
976         O << "-(";
977         printSuffixedName(p, "$scv");
978         O << "+8)\n";
979       } else
980         O << "\n";
981       SwitchToDataSection(".lazy_symbol_pointer", 0);
982       printSuffixedName(p, "$lazy_ptr");
983       O << ":\n";
984       O << "\t.indirect_symbol " << p << "\n";
985       O << "\t.long\tdyld_stub_binding_helper\n";
986     }
987     O << "\n";
988
989     // Output non-lazy-pointers for external and common global variables.
990     if (!GVNonLazyPtrs.empty()) {
991       SwitchToDataSection("\t.non_lazy_symbol_pointer", 0);
992       for (StringSet<>::iterator i =  GVNonLazyPtrs.begin(),
993              e = GVNonLazyPtrs.end(); i != e; ++i) {
994         const char *p = i->getKeyData();
995         printSuffixedName(p, "$non_lazy_ptr");
996         O << ":\n";
997         O << "\t.indirect_symbol " << p << "\n";
998         O << "\t.long\t0\n";
999       }
1000     }
1001
1002     if (!HiddenGVNonLazyPtrs.empty()) {
1003       SwitchToSection(TAI->getDataSection());
1004       for (StringSet<>::iterator i = HiddenGVNonLazyPtrs.begin(),
1005              e = HiddenGVNonLazyPtrs.end(); i != e; ++i) {
1006         const char *p = i->getKeyData();
1007         EmitAlignment(2);
1008         printSuffixedName(p, "$non_lazy_ptr");
1009         O << ":\n";
1010         O << "\t.long " << p << "\n";
1011       }
1012     }
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 }
1031
1032 /// createARMCodePrinterPass - Returns a pass that prints the ARM
1033 /// assembly code for a MachineFunction to the given output stream,
1034 /// using the given target machine description.  This should work
1035 /// regardless of whether the function is in SSA form.
1036 ///
1037 FunctionPass *llvm::createARMCodePrinterPass(raw_ostream &o,
1038                                              ARMTargetMachine &tm) {
1039   return new ARMAsmPrinter(o, tm, tm.getTargetAsmInfo());
1040 }
1041
1042 namespace {
1043   static struct Register {
1044     Register() {
1045       ARMTargetMachine::registerAsmPrinter(createARMCodePrinterPass);
1046     }
1047   } Registrator;
1048 }