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