Switch obvious clients to Twine instead of utostr (when they were already using
[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/Metadata.h"
25 #include "llvm/CodeGen/AsmPrinter.h"
26 #include "llvm/CodeGen/DwarfWriter.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/ADT/SmallPtrSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/StringSet.h"
39 #include "llvm/Support/Compiler.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/Mangler.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include <cctype>
45 using namespace llvm;
46
47 STATISTIC(EmittedInsts, "Number of machine instrs printed");
48
49 namespace {
50   class VISIBILITY_HIDDEN ARMAsmPrinter : public AsmPrinter {
51     DwarfWriter *DW;
52
53     /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
54     /// make the right decision when printing asm code for different targets.
55     const ARMSubtarget *Subtarget;
56
57     /// AFI - Keep a pointer to ARMFunctionInfo for the current
58     /// MachineFunction.
59     ARMFunctionInfo *AFI;
60
61     /// MCP - Keep a pointer to constantpool entries of the current
62     /// MachineFunction.
63     const MachineConstantPool *MCP;
64
65     /// We name each basic block in a Function with a unique number, so
66     /// that we can consistently refer to them later. This is cleared
67     /// at the beginning of each call to runOnMachineFunction().
68     ///
69     typedef std::map<const Value *, unsigned> ValueMapTy;
70     ValueMapTy NumberForBB;
71
72     /// GVNonLazyPtrs - Keeps the set of GlobalValues that require
73     /// non-lazy-pointers for indirect access.
74     StringMap<std::string> GVNonLazyPtrs;
75
76     /// HiddenGVNonLazyPtrs - Keeps the set of GlobalValues with hidden
77     /// visibility that require non-lazy-pointers for indirect access.
78     StringMap<std::string> HiddenGVNonLazyPtrs;
79
80     struct FnStubInfo {
81       std::string Stub, LazyPtr, SLP, SCV;
82       
83       FnStubInfo() {}
84       
85       void Init(const GlobalValue *GV, Mangler *Mang) {
86         // Already initialized.
87         if (!Stub.empty()) return;
88         Stub = Mang->getMangledName(GV, "$stub", true);
89         LazyPtr = Mang->getMangledName(GV, "$lazy_ptr", true);
90         SLP = Mang->getMangledName(GV, "$slp", true);
91         SCV = Mang->getMangledName(GV, "$scv", true);
92       }
93       
94       void Init(const std::string &GV, Mangler *Mang) {
95         // Already initialized.
96         if (!Stub.empty()) return;
97         Stub = Mang->makeNameProper(GV + "$stub", Mangler::Private);
98         LazyPtr = Mang->makeNameProper(GV + "$lazy_ptr", Mangler::Private);
99         SLP = Mang->makeNameProper(GV + "$slp", Mangler::Private);
100         SCV = Mang->makeNameProper(GV + "$scv", Mangler::Private);
101       }
102     };
103     
104     /// FnStubs - Keeps the set of external function GlobalAddresses that the
105     /// asm printer should generate stubs for.
106     StringMap<FnStubInfo> FnStubs;
107
108     /// True if asm printer is printing a series of CONSTPOOL_ENTRY.
109     bool InCPMode;
110   public:
111     explicit ARMAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
112                            const TargetAsmInfo *T, bool V)
113       : AsmPrinter(O, TM, T, V), DW(0), AFI(NULL), MCP(NULL),
114         InCPMode(false) {
115       Subtarget = &TM.getSubtarget<ARMSubtarget>();
116     }
117
118     virtual const char *getPassName() const {
119       return "ARM Assembly Printer";
120     }
121
122     void printOperand(const MachineInstr *MI, int OpNum,
123                       const char *Modifier = 0);
124     void printSOImmOperand(const MachineInstr *MI, int OpNum);
125     void printSOImm2PartOperand(const MachineInstr *MI, int OpNum);
126     void printSORegOperand(const MachineInstr *MI, int OpNum);
127     void printAddrMode2Operand(const MachineInstr *MI, int OpNum);
128     void printAddrMode2OffsetOperand(const MachineInstr *MI, int OpNum);
129     void printAddrMode3Operand(const MachineInstr *MI, int OpNum);
130     void printAddrMode3OffsetOperand(const MachineInstr *MI, int OpNum);
131     void printAddrMode4Operand(const MachineInstr *MI, int OpNum,
132                                const char *Modifier = 0);
133     void printAddrMode5Operand(const MachineInstr *MI, int OpNum,
134                                const char *Modifier = 0);
135     void printAddrMode6Operand(const MachineInstr *MI, int OpNum);
136     void printAddrModePCOperand(const MachineInstr *MI, int OpNum,
137                                 const char *Modifier = 0);
138     void printBitfieldInvMaskImmOperand (const MachineInstr *MI, int OpNum);
139
140     void printThumbITMask(const MachineInstr *MI, int OpNum);
141     void printThumbAddrModeRROperand(const MachineInstr *MI, int OpNum);
142     void printThumbAddrModeRI5Operand(const MachineInstr *MI, int OpNum,
143                                       unsigned Scale);
144     void printThumbAddrModeS1Operand(const MachineInstr *MI, int OpNum);
145     void printThumbAddrModeS2Operand(const MachineInstr *MI, int OpNum);
146     void printThumbAddrModeS4Operand(const MachineInstr *MI, int OpNum);
147     void printThumbAddrModeSPOperand(const MachineInstr *MI, int OpNum);
148
149     void printT2SOOperand(const MachineInstr *MI, int OpNum);
150     void printT2AddrModeImm12Operand(const MachineInstr *MI, int OpNum);
151     void printT2AddrModeImm8Operand(const MachineInstr *MI, int OpNum);
152     void printT2AddrModeImm8s4Operand(const MachineInstr *MI, int OpNum);
153     void printT2AddrModeImm8OffsetOperand(const MachineInstr *MI, int OpNum);
154     void printT2AddrModeSoRegOperand(const MachineInstr *MI, int OpNum);
155
156     void printPredicateOperand(const MachineInstr *MI, int OpNum);
157     void printSBitModifierOperand(const MachineInstr *MI, int OpNum);
158     void printPCLabel(const MachineInstr *MI, int OpNum);
159     void printRegisterList(const MachineInstr *MI, int OpNum);
160     void printCPInstOperand(const MachineInstr *MI, int OpNum,
161                             const char *Modifier);
162     void printJTBlockOperand(const MachineInstr *MI, int OpNum);
163     void printJT2BlockOperand(const MachineInstr *MI, int OpNum);
164     void printTBAddrMode(const MachineInstr *MI, int OpNum);
165
166     virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
167                                  unsigned AsmVariant, const char *ExtraCode);
168     virtual bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNum,
169                                        unsigned AsmVariant,
170                                        const char *ExtraCode);
171
172     void PrintGlobalVariable(const GlobalVariable* GVar);
173     bool printInstruction(const MachineInstr *MI);  // autogenerated.
174     void printMachineInstruction(const MachineInstr *MI);
175     bool runOnMachineFunction(MachineFunction &F);
176     bool doInitialization(Module &M);
177     bool doFinalization(Module &M);
178
179     /// EmitMachineConstantPoolValue - Print a machine constantpool value to
180     /// the .s file.
181     virtual void EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
182       printDataDirective(MCPV->getType());
183
184       ARMConstantPoolValue *ACPV = static_cast<ARMConstantPoolValue*>(MCPV);
185       GlobalValue *GV = ACPV->getGV();
186       std::string Name;
187       
188       
189       if (ACPV->isNonLazyPointer()) {
190         std::string SymName = Mang->getMangledName(GV);
191         Name = Mang->getMangledName(GV, "$non_lazy_ptr", true);
192         
193         if (GV->hasHiddenVisibility())
194           HiddenGVNonLazyPtrs[SymName] = Name;
195         else
196           GVNonLazyPtrs[SymName] = Name;
197       } else if (ACPV->isStub()) {
198         if (GV) {
199           FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
200           FnInfo.Init(GV, Mang);
201           Name = FnInfo.Stub;
202         } else {
203           FnStubInfo &FnInfo = FnStubs[Mang->makeNameProper(ACPV->getSymbol())];
204           FnInfo.Init(ACPV->getSymbol(), Mang);
205           Name = FnInfo.Stub;
206         }
207       } else {
208         if (GV)
209           Name = Mang->getMangledName(GV);
210         else
211           Name = Mang->makeNameProper(ACPV->getSymbol());
212       }
213       O << Name;
214       
215       
216       
217       if (ACPV->hasModifier()) O << "(" << ACPV->getModifier() << ")";
218       if (ACPV->getPCAdjustment() != 0) {
219         O << "-(" << TAI->getPrivateGlobalPrefix() << "PC"
220           << ACPV->getLabelId()
221           << "+" << (unsigned)ACPV->getPCAdjustment();
222          if (ACPV->mustAddCurrentAddress())
223            O << "-.";
224          O << ")";
225       }
226       O << "\n";
227     }
228     
229     void getAnalysisUsage(AnalysisUsage &AU) const {
230       AsmPrinter::getAnalysisUsage(AU);
231       AU.setPreservesAll();
232       AU.addRequired<MachineModuleInfo>();
233       AU.addRequired<DwarfWriter>();
234     }
235   };
236 } // end of anonymous namespace
237
238 #include "ARMGenAsmWriter.inc"
239
240 /// runOnMachineFunction - This uses the printInstruction()
241 /// method to print assembly for each instruction.
242 ///
243 bool ARMAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
244   this->MF = &MF;
245
246   AFI = MF.getInfo<ARMFunctionInfo>();
247   MCP = MF.getConstantPool();
248
249   SetupMachineFunction(MF);
250   O << "\n";
251
252   // NOTE: we don't print out constant pools here, they are handled as
253   // instructions.
254
255   O << "\n";
256   // Print out labels for the function.
257   const Function *F = MF.getFunction();
258   switch (F->getLinkage()) {
259   default: llvm_unreachable("Unknown linkage type!");
260   case Function::PrivateLinkage:
261   case Function::LinkerPrivateLinkage:
262   case Function::InternalLinkage:
263     SwitchToTextSection("\t.text", F);
264     break;
265   case Function::ExternalLinkage:
266     SwitchToTextSection("\t.text", F);
267     O << "\t.globl\t" << CurrentFnName << "\n";
268     break;
269   case Function::WeakAnyLinkage:
270   case Function::WeakODRLinkage:
271   case Function::LinkOnceAnyLinkage:
272   case Function::LinkOnceODRLinkage:
273     if (Subtarget->isTargetDarwin()) {
274       SwitchToTextSection(
275                 ".section __TEXT,__textcoal_nt,coalesced,pure_instructions", F);
276       O << "\t.globl\t" << CurrentFnName << "\n";
277       O << "\t.weak_definition\t" << CurrentFnName << "\n";
278     } else {
279       O << TAI->getWeakRefDirective() << CurrentFnName << "\n";
280     }
281     break;
282   }
283
284   printVisibility(CurrentFnName, F->getVisibility());
285
286   if (AFI->isThumbFunction()) {
287     EmitAlignment(MF.getAlignment(), F, AFI->getAlign());
288     O << "\t.code\t16\n";
289     O << "\t.thumb_func";
290     if (Subtarget->isTargetDarwin())
291       O << "\t" << CurrentFnName;
292     O << "\n";
293     InCPMode = false;
294   } else {
295     EmitAlignment(MF.getAlignment(), F);
296   }
297
298   O << CurrentFnName << ":\n";
299   // Emit pre-function debug information.
300   DW->BeginFunction(&MF);
301
302   if (Subtarget->isTargetDarwin()) {
303     // If the function is empty, then we need to emit *something*. Otherwise,
304     // the function's label might be associated with something that it wasn't
305     // meant to be associated with. We emit a noop in this situation.
306     MachineFunction::iterator I = MF.begin();
307
308     if (++I == MF.end() && MF.front().empty())
309       O << "\tnop\n";
310   }
311
312   // Print out code for the function.
313   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
314        I != E; ++I) {
315     // Print a label for the basic block.
316     if (I != MF.begin()) {
317       printBasicBlockLabel(I, true, true, VerboseAsm);
318       O << '\n';
319     }
320     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
321          II != E; ++II) {
322       // Print the assembly for the instruction.
323       printMachineInstruction(II);
324     }
325   }
326
327   if (TAI->hasDotTypeDotSizeDirective())
328     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
329
330   // Emit post-function debug information.
331   DW->EndFunction(&MF);
332
333   O.flush();
334
335   return false;
336 }
337
338 void ARMAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
339                                  const char *Modifier) {
340   const MachineOperand &MO = MI->getOperand(OpNum);
341   switch (MO.getType()) {
342   case MachineOperand::MO_Register: {
343     unsigned Reg = MO.getReg();
344     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
345       if (Modifier && strcmp(Modifier, "dregpair") == 0) {
346         unsigned DRegLo = TRI->getSubReg(Reg, 5); // arm_dsubreg_0
347         unsigned DRegHi = TRI->getSubReg(Reg, 6); // arm_dsubreg_1
348         O << '{'
349           << TRI->getAsmName(DRegLo) << ',' << TRI->getAsmName(DRegHi)
350           << '}';
351       } else if (Modifier && strcmp(Modifier, "dregsingle") == 0) {
352         O << '{' << TRI->getAsmName(Reg) << '}';
353       } else {
354         O << TRI->getAsmName(Reg);
355       }
356     } else
357       llvm_unreachable("not implemented");
358     break;
359   }
360   case MachineOperand::MO_Immediate: {
361     if (!Modifier || strcmp(Modifier, "no_hash") != 0)
362       O << "#";
363
364     O << MO.getImm();
365     break;
366   }
367   case MachineOperand::MO_MachineBasicBlock:
368     printBasicBlockLabel(MO.getMBB());
369     return;
370   case MachineOperand::MO_GlobalAddress: {
371     bool isCallOp = Modifier && !strcmp(Modifier, "call");
372     GlobalValue *GV = MO.getGlobal();
373     std::string Name;
374     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
375     if (isExt && isCallOp && Subtarget->isTargetDarwin() &&
376         TM.getRelocationModel() != Reloc::Static) {
377       FnStubInfo &FnInfo = FnStubs[Mang->getMangledName(GV)];
378       FnInfo.Init(GV, Mang);
379       Name = FnInfo.Stub;
380     } else {
381       Name = Mang->getMangledName(GV);
382     }
383     
384     O << Name;
385
386     printOffset(MO.getOffset());
387
388     if (isCallOp && Subtarget->isTargetELF() &&
389         TM.getRelocationModel() == Reloc::PIC_)
390       O << "(PLT)";
391     break;
392   }
393   case MachineOperand::MO_ExternalSymbol: {
394     bool isCallOp = Modifier && !strcmp(Modifier, "call");
395     std::string Name;
396     if (isCallOp && Subtarget->isTargetDarwin() &&
397         TM.getRelocationModel() != Reloc::Static) {
398       FnStubInfo &FnInfo = FnStubs[Mang->makeNameProper(MO.getSymbolName())];
399       FnInfo.Init(MO.getSymbolName(), Mang);
400       Name = FnInfo.Stub;
401     } else
402       Name = Mang->makeNameProper(MO.getSymbolName());
403     
404     O << Name;
405     if (isCallOp && Subtarget->isTargetELF() &&
406         TM.getRelocationModel() == Reloc::PIC_)
407       O << "(PLT)";
408     break;
409   }
410   case MachineOperand::MO_ConstantPoolIndex:
411     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
412       << '_' << MO.getIndex();
413     break;
414   case MachineOperand::MO_JumpTableIndex:
415     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
416       << '_' << MO.getIndex();
417     break;
418   default:
419     O << "<unknown operand type>"; abort (); break;
420   }
421 }
422
423 static void printSOImm(formatted_raw_ostream &O, int64_t V, bool VerboseAsm,
424                        const TargetAsmInfo *TAI) {
425   // Break it up into two parts that make up a shifter immediate.
426   V = ARM_AM::getSOImmVal(V);
427   assert(V != -1 && "Not a valid so_imm value!");
428
429   unsigned Imm = ARM_AM::getSOImmValImm(V);
430   unsigned Rot = ARM_AM::getSOImmValRot(V);
431
432   // Print low-level immediate formation info, per
433   // A5.1.3: "Data-processing operands - Immediate".
434   if (Rot) {
435     O << "#" << Imm << ", " << Rot;
436     // Pretty printed version.
437     if (VerboseAsm)
438       O << ' ' << TAI->getCommentString()
439         << ' ' << (int)ARM_AM::rotr32(Imm, Rot);
440   } else {
441     O << "#" << Imm;
442   }
443 }
444
445 /// printSOImmOperand - SOImm is 4-bit rotate amount in bits 8-11 with 8-bit
446 /// immediate in bits 0-7.
447 void ARMAsmPrinter::printSOImmOperand(const MachineInstr *MI, int OpNum) {
448   const MachineOperand &MO = MI->getOperand(OpNum);
449   assert(MO.isImm() && "Not a valid so_imm value!");
450   printSOImm(O, MO.getImm(), VerboseAsm, TAI);
451 }
452
453 /// printSOImm2PartOperand - SOImm is broken into two pieces using a 'mov'
454 /// followed by an 'orr' to materialize.
455 void ARMAsmPrinter::printSOImm2PartOperand(const MachineInstr *MI, int OpNum) {
456   const MachineOperand &MO = MI->getOperand(OpNum);
457   assert(MO.isImm() && "Not a valid so_imm value!");
458   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO.getImm());
459   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO.getImm());
460   printSOImm(O, V1, VerboseAsm, TAI);
461   O << "\n\torr";
462   printPredicateOperand(MI, 2);
463   O << " ";
464   printOperand(MI, 0); 
465   O << ", ";
466   printOperand(MI, 0); 
467   O << ", ";
468   printSOImm(O, V2, VerboseAsm, TAI);
469 }
470
471 // so_reg is a 4-operand unit corresponding to register forms of the A5.1
472 // "Addressing Mode 1 - Data-processing operands" forms.  This includes:
473 //    REG 0   0           - e.g. R5
474 //    REG REG 0,SH_OPC    - e.g. R5, ROR R3
475 //    REG 0   IMM,SH_OPC  - e.g. R5, LSL #3
476 void ARMAsmPrinter::printSORegOperand(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 << TRI->getAsmName(MO1.getReg());
483
484   // Print the shift opc.
485   O << ", "
486     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO3.getImm()))
487     << " ";
488
489   if (MO2.getReg()) {
490     assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
491     O << TRI->getAsmName(MO2.getReg());
492     assert(ARM_AM::getSORegOffset(MO3.getImm()) == 0);
493   } else {
494     O << "#" << ARM_AM::getSORegOffset(MO3.getImm());
495   }
496 }
497
498 void ARMAsmPrinter::printAddrMode2Operand(const MachineInstr *MI, int Op) {
499   const MachineOperand &MO1 = MI->getOperand(Op);
500   const MachineOperand &MO2 = MI->getOperand(Op+1);
501   const MachineOperand &MO3 = MI->getOperand(Op+2);
502
503   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
504     printOperand(MI, Op);
505     return;
506   }
507
508   O << "[" << TRI->getAsmName(MO1.getReg());
509
510   if (!MO2.getReg()) {
511     if (ARM_AM::getAM2Offset(MO3.getImm()))  // Don't print +0.
512       O << ", #"
513         << (char)ARM_AM::getAM2Op(MO3.getImm())
514         << ARM_AM::getAM2Offset(MO3.getImm());
515     O << "]";
516     return;
517   }
518
519   O << ", "
520     << (char)ARM_AM::getAM2Op(MO3.getImm())
521     << TRI->getAsmName(MO2.getReg());
522   
523   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm()))
524     O << ", "
525       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO3.getImm()))
526       << " #" << ShImm;
527   O << "]";
528 }
529
530 void ARMAsmPrinter::printAddrMode2OffsetOperand(const MachineInstr *MI, int Op){
531   const MachineOperand &MO1 = MI->getOperand(Op);
532   const MachineOperand &MO2 = MI->getOperand(Op+1);
533
534   if (!MO1.getReg()) {
535     unsigned ImmOffs = ARM_AM::getAM2Offset(MO2.getImm());
536     assert(ImmOffs && "Malformed indexed load / store!");
537     O << "#"
538       << (char)ARM_AM::getAM2Op(MO2.getImm())
539       << ImmOffs;
540     return;
541   }
542
543   O << (char)ARM_AM::getAM2Op(MO2.getImm())
544     << TRI->getAsmName(MO1.getReg());
545   
546   if (unsigned ShImm = ARM_AM::getAM2Offset(MO2.getImm()))
547     O << ", "
548       << ARM_AM::getShiftOpcStr(ARM_AM::getAM2ShiftOpc(MO2.getImm()))
549       << " #" << ShImm;
550 }
551
552 void ARMAsmPrinter::printAddrMode3Operand(const MachineInstr *MI, int Op) {
553   const MachineOperand &MO1 = MI->getOperand(Op);
554   const MachineOperand &MO2 = MI->getOperand(Op+1);
555   const MachineOperand &MO3 = MI->getOperand(Op+2);
556   
557   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
558   O << "[" << TRI->getAsmName(MO1.getReg());
559
560   if (MO2.getReg()) {
561     O << ", "
562       << (char)ARM_AM::getAM3Op(MO3.getImm())
563       << TRI->getAsmName(MO2.getReg())
564       << "]";
565     return;
566   }
567   
568   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm()))
569     O << ", #"
570       << (char)ARM_AM::getAM3Op(MO3.getImm())
571       << ImmOffs;
572   O << "]";
573 }
574
575 void ARMAsmPrinter::printAddrMode3OffsetOperand(const MachineInstr *MI, int Op){
576   const MachineOperand &MO1 = MI->getOperand(Op);
577   const MachineOperand &MO2 = MI->getOperand(Op+1);
578
579   if (MO1.getReg()) {
580     O << (char)ARM_AM::getAM3Op(MO2.getImm())
581       << TRI->getAsmName(MO1.getReg());
582     return;
583   }
584
585   unsigned ImmOffs = ARM_AM::getAM3Offset(MO2.getImm());
586   assert(ImmOffs && "Malformed indexed load / store!");
587   O << "#"
588     << (char)ARM_AM::getAM3Op(MO2.getImm())
589     << ImmOffs;
590 }
591   
592 void ARMAsmPrinter::printAddrMode4Operand(const MachineInstr *MI, int Op,
593                                           const char *Modifier) {
594   const MachineOperand &MO1 = MI->getOperand(Op);
595   const MachineOperand &MO2 = MI->getOperand(Op+1);
596   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO2.getImm());
597   if (Modifier && strcmp(Modifier, "submode") == 0) {
598     if (MO1.getReg() == ARM::SP) {
599       bool isLDM = (MI->getOpcode() == ARM::LDM ||
600                     MI->getOpcode() == ARM::LDM_RET);
601       O << ARM_AM::getAMSubModeAltStr(Mode, isLDM);
602     } else
603       O << ARM_AM::getAMSubModeStr(Mode);
604   } else {
605     printOperand(MI, Op);
606     if (ARM_AM::getAM4WBFlag(MO2.getImm()))
607       O << "!";
608   }
609 }
610
611 void ARMAsmPrinter::printAddrMode5Operand(const MachineInstr *MI, int Op,
612                                           const char *Modifier) {
613   const MachineOperand &MO1 = MI->getOperand(Op);
614   const MachineOperand &MO2 = MI->getOperand(Op+1);
615
616   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
617     printOperand(MI, Op);
618     return;
619   }
620   
621   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
622
623   if (Modifier && strcmp(Modifier, "submode") == 0) {
624     ARM_AM::AMSubMode Mode = ARM_AM::getAM5SubMode(MO2.getImm());
625     if (MO1.getReg() == ARM::SP) {
626       bool isFLDM = (MI->getOpcode() == ARM::FLDMD ||
627                      MI->getOpcode() == ARM::FLDMS);
628       O << ARM_AM::getAMSubModeAltStr(Mode, isFLDM);
629     } else
630       O << ARM_AM::getAMSubModeStr(Mode);
631     return;
632   } else if (Modifier && strcmp(Modifier, "base") == 0) {
633     // Used for FSTM{D|S} and LSTM{D|S} operations.
634     O << TRI->getAsmName(MO1.getReg());
635     if (ARM_AM::getAM5WBFlag(MO2.getImm()))
636       O << "!";
637     return;
638   }
639   
640   O << "[" << TRI->getAsmName(MO1.getReg());
641   
642   if (unsigned ImmOffs = ARM_AM::getAM5Offset(MO2.getImm())) {
643     O << ", #"
644       << (char)ARM_AM::getAM5Op(MO2.getImm())
645       << ImmOffs*4;
646   }
647   O << "]";
648 }
649
650 void ARMAsmPrinter::printAddrMode6Operand(const MachineInstr *MI, int Op) {
651   const MachineOperand &MO1 = MI->getOperand(Op);
652   const MachineOperand &MO2 = MI->getOperand(Op+1);
653   const MachineOperand &MO3 = MI->getOperand(Op+2);
654
655   // FIXME: No support yet for specifying alignment.
656   O << "[" << TRI->getAsmName(MO1.getReg()) << "]";
657
658   if (ARM_AM::getAM6WBFlag(MO3.getImm())) {
659     if (MO2.getReg() == 0)
660       O << "!";
661     else
662       O << ", " << TRI->getAsmName(MO2.getReg());
663   }
664 }
665
666 void ARMAsmPrinter::printAddrModePCOperand(const MachineInstr *MI, int Op,
667                                            const char *Modifier) {
668   if (Modifier && strcmp(Modifier, "label") == 0) {
669     printPCLabel(MI, Op+1);
670     return;
671   }
672
673   const MachineOperand &MO1 = MI->getOperand(Op);
674   assert(TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
675   O << "[pc, +" << TRI->getAsmName(MO1.getReg()) << "]";
676 }
677
678 void
679 ARMAsmPrinter::printBitfieldInvMaskImmOperand(const MachineInstr *MI, int Op) {
680   const MachineOperand &MO = MI->getOperand(Op);
681   uint32_t v = ~MO.getImm();
682   int32_t lsb = CountTrailingZeros_32(v);
683   int32_t width = (32 - CountLeadingZeros_32 (v)) - lsb;
684   assert(MO.isImm() && "Not a valid bf_inv_mask_imm value!");
685   O << "#" << lsb << ", #" << width;
686 }
687
688 //===--------------------------------------------------------------------===//
689
690 void
691 ARMAsmPrinter::printThumbITMask(const MachineInstr *MI, int Op) {
692   // (3 - the number of trailing zeros) is the number of then / else.
693   unsigned Mask = MI->getOperand(Op).getImm();
694   unsigned NumTZ = CountTrailingZeros_32(Mask);
695   assert(NumTZ <= 3 && "Invalid IT mask!");
696   for (unsigned Pos = 3, e = NumTZ; Pos > e; --Pos) {
697     bool T = (Mask & (1 << Pos)) != 0;
698     if (T)
699       O << 't';
700     else
701       O << 'e';
702   }
703 }
704
705 void
706 ARMAsmPrinter::printThumbAddrModeRROperand(const MachineInstr *MI, int Op) {
707   const MachineOperand &MO1 = MI->getOperand(Op);
708   const MachineOperand &MO2 = MI->getOperand(Op+1);
709   O << "[" << TRI->getAsmName(MO1.getReg());
710   O << ", " << TRI->getAsmName(MO2.getReg()) << "]";
711 }
712
713 void
714 ARMAsmPrinter::printThumbAddrModeRI5Operand(const MachineInstr *MI, int Op,
715                                             unsigned Scale) {
716   const MachineOperand &MO1 = MI->getOperand(Op);
717   const MachineOperand &MO2 = MI->getOperand(Op+1);
718   const MachineOperand &MO3 = MI->getOperand(Op+2);
719
720   if (!MO1.isReg()) {   // FIXME: This is for CP entries, but isn't right.
721     printOperand(MI, Op);
722     return;
723   }
724
725   O << "[" << TRI->getAsmName(MO1.getReg());
726   if (MO3.getReg())
727     O << ", " << TRI->getAsmName(MO3.getReg());
728   else if (unsigned ImmOffs = MO2.getImm()) {
729     O << ", #" << ImmOffs;
730     if (Scale > 1)
731       O << " * " << Scale;
732   }
733   O << "]";
734 }
735
736 void
737 ARMAsmPrinter::printThumbAddrModeS1Operand(const MachineInstr *MI, int Op) {
738   printThumbAddrModeRI5Operand(MI, Op, 1);
739 }
740 void
741 ARMAsmPrinter::printThumbAddrModeS2Operand(const MachineInstr *MI, int Op) {
742   printThumbAddrModeRI5Operand(MI, Op, 2);
743 }
744 void
745 ARMAsmPrinter::printThumbAddrModeS4Operand(const MachineInstr *MI, int Op) {
746   printThumbAddrModeRI5Operand(MI, Op, 4);
747 }
748
749 void ARMAsmPrinter::printThumbAddrModeSPOperand(const MachineInstr *MI,int Op) {
750   const MachineOperand &MO1 = MI->getOperand(Op);
751   const MachineOperand &MO2 = MI->getOperand(Op+1);
752   O << "[" << TRI->getAsmName(MO1.getReg());
753   if (unsigned ImmOffs = MO2.getImm())
754     O << ", #" << ImmOffs << " * 4";
755   O << "]";
756 }
757
758 //===--------------------------------------------------------------------===//
759
760 // Constant shifts t2_so_reg is a 2-operand unit corresponding to the Thumb2
761 // register with shift forms.
762 // REG 0   0           - e.g. R5
763 // REG IMM, SH_OPC     - e.g. R5, LSL #3
764 void ARMAsmPrinter::printT2SOOperand(const MachineInstr *MI, int OpNum) {
765   const MachineOperand &MO1 = MI->getOperand(OpNum);
766   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
767
768   unsigned Reg = MO1.getReg();
769   assert(TargetRegisterInfo::isPhysicalRegister(Reg));
770   O << TRI->getAsmName(Reg);
771
772   // Print the shift opc.
773   O << ", "
774     << ARM_AM::getShiftOpcStr(ARM_AM::getSORegShOp(MO2.getImm()))
775     << " ";
776
777   assert(MO2.isImm() && "Not a valid t2_so_reg value!");
778   O << "#" << ARM_AM::getSORegOffset(MO2.getImm());
779 }
780
781 void ARMAsmPrinter::printT2AddrModeImm12Operand(const MachineInstr *MI,
782                                                 int OpNum) {
783   const MachineOperand &MO1 = MI->getOperand(OpNum);
784   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
785
786   O << "[" << TRI->getAsmName(MO1.getReg());
787
788   unsigned OffImm = MO2.getImm();
789   if (OffImm)  // Don't print +0.
790     O << ", #+" << OffImm;
791   O << "]";
792 }
793
794 void ARMAsmPrinter::printT2AddrModeImm8Operand(const MachineInstr *MI,
795                                                int OpNum) {
796   const MachineOperand &MO1 = MI->getOperand(OpNum);
797   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
798
799   O << "[" << TRI->getAsmName(MO1.getReg());
800
801   int32_t OffImm = (int32_t)MO2.getImm();
802   // Don't print +0.
803   if (OffImm < 0)
804     O << ", #-" << -OffImm;
805   else if (OffImm > 0)
806     O << ", #+" << OffImm;
807   O << "]";
808 }
809
810 void ARMAsmPrinter::printT2AddrModeImm8s4Operand(const MachineInstr *MI,
811                                                  int OpNum) {
812   const MachineOperand &MO1 = MI->getOperand(OpNum);
813   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
814
815   O << "[" << TRI->getAsmName(MO1.getReg());
816
817   int32_t OffImm = (int32_t)MO2.getImm() / 4;
818   // Don't print +0.
819   if (OffImm < 0)
820     O << ", #-" << -OffImm << " * 4";
821   else if (OffImm > 0)
822     O << ", #+" << OffImm << " * 4";
823   O << "]";
824 }
825
826 void ARMAsmPrinter::printT2AddrModeImm8OffsetOperand(const MachineInstr *MI,
827                                                      int OpNum) {
828   const MachineOperand &MO1 = MI->getOperand(OpNum);
829   int32_t OffImm = (int32_t)MO1.getImm();
830   // Don't print +0.
831   if (OffImm < 0)
832     O << "#-" << -OffImm;
833   else if (OffImm > 0)
834     O << "#+" << OffImm;
835 }
836
837 void ARMAsmPrinter::printT2AddrModeSoRegOperand(const MachineInstr *MI,
838                                                 int OpNum) {
839   const MachineOperand &MO1 = MI->getOperand(OpNum);
840   const MachineOperand &MO2 = MI->getOperand(OpNum+1);
841   const MachineOperand &MO3 = MI->getOperand(OpNum+2);
842
843   O << "[" << TRI->getAsmName(MO1.getReg());
844
845   if (MO2.getReg()) {
846     O << ", +" << TRI->getAsmName(MO2.getReg());
847
848     unsigned ShAmt = MO3.getImm();
849     if (ShAmt) {
850       assert(ShAmt <= 3 && "Not a valid Thumb2 addressing mode!");
851       O << ", lsl #" << ShAmt;
852     }
853   }
854   O << "]";
855 }
856
857
858 //===--------------------------------------------------------------------===//
859
860 void ARMAsmPrinter::printPredicateOperand(const MachineInstr *MI, int OpNum) {
861   ARMCC::CondCodes CC = (ARMCC::CondCodes)MI->getOperand(OpNum).getImm();
862   if (CC != ARMCC::AL)
863     O << ARMCondCodeToString(CC);
864 }
865
866 void ARMAsmPrinter::printSBitModifierOperand(const MachineInstr *MI, int OpNum){
867   unsigned Reg = MI->getOperand(OpNum).getReg();
868   if (Reg) {
869     assert(Reg == ARM::CPSR && "Expect ARM CPSR register!");
870     O << 's';
871   }
872 }
873
874 void ARMAsmPrinter::printPCLabel(const MachineInstr *MI, int OpNum) {
875   int Id = (int)MI->getOperand(OpNum).getImm();
876   O << TAI->getPrivateGlobalPrefix() << "PC" << Id;
877 }
878
879 void ARMAsmPrinter::printRegisterList(const MachineInstr *MI, int OpNum) {
880   O << "{";
881   for (unsigned i = OpNum, e = MI->getNumOperands(); i != e; ++i) {
882     printOperand(MI, i);
883     if (i != e-1) O << ", ";
884   }
885   O << "}";
886 }
887
888 void ARMAsmPrinter::printCPInstOperand(const MachineInstr *MI, int OpNum,
889                                        const char *Modifier) {
890   assert(Modifier && "This operand only works with a modifier!");
891   // There are two aspects to a CONSTANTPOOL_ENTRY operand, the label and the
892   // data itself.
893   if (!strcmp(Modifier, "label")) {
894     unsigned ID = MI->getOperand(OpNum).getImm();
895     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
896       << '_' << ID << ":\n";
897   } else {
898     assert(!strcmp(Modifier, "cpentry") && "Unknown modifier for CPE");
899     unsigned CPI = MI->getOperand(OpNum).getIndex();
900
901     const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
902     
903     if (MCPE.isMachineConstantPoolEntry()) {
904       EmitMachineConstantPoolValue(MCPE.Val.MachineCPVal);
905     } else {
906       EmitGlobalConstant(MCPE.Val.ConstVal);
907     }
908   }
909 }
910
911 void ARMAsmPrinter::printJTBlockOperand(const MachineInstr *MI, int OpNum) {
912   assert(!Subtarget->isThumb2() && "Thumb2 should use double-jump jumptables!");
913
914   const MachineOperand &MO1 = MI->getOperand(OpNum);
915   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
916   unsigned JTI = MO1.getIndex();
917   O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
918     << '_' << JTI << '_' << MO2.getImm() << ":\n";
919
920   const char *JTEntryDirective = TAI->getJumpTableDirective();
921   if (!JTEntryDirective)
922     JTEntryDirective = TAI->getData32bitsDirective();
923
924   const MachineFunction *MF = MI->getParent()->getParent();
925   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
926   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
927   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
928   bool UseSet= TAI->getSetDirective() && TM.getRelocationModel() == Reloc::PIC_;
929   SmallPtrSet<MachineBasicBlock*, 8> JTSets;
930   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
931     MachineBasicBlock *MBB = JTBBs[i];
932     bool isNew = JTSets.insert(MBB);
933
934     if (UseSet && isNew)
935       printPICJumpTableSetLabel(JTI, MO2.getImm(), MBB);
936
937     O << JTEntryDirective << ' ';
938     if (UseSet)
939       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
940         << '_' << JTI << '_' << MO2.getImm()
941         << "_set_" << MBB->getNumber();
942     else if (TM.getRelocationModel() == Reloc::PIC_) {
943       printBasicBlockLabel(MBB, false, false, false);
944       // If the arch uses custom Jump Table directives, don't calc relative to JT
945       if (!TAI->getJumpTableDirective()) 
946         O << '-' << TAI->getPrivateGlobalPrefix() << "JTI"
947           << getFunctionNumber() << '_' << JTI << '_' << MO2.getImm();
948     } else {
949       printBasicBlockLabel(MBB, false, false, false);
950     }
951     if (i != e-1)
952       O << '\n';
953   }
954 }
955
956 void ARMAsmPrinter::printJT2BlockOperand(const MachineInstr *MI, int OpNum) {
957   const MachineOperand &MO1 = MI->getOperand(OpNum);
958   const MachineOperand &MO2 = MI->getOperand(OpNum+1); // Unique Id
959   unsigned JTI = MO1.getIndex();
960   O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
961     << '_' << JTI << '_' << MO2.getImm() << ":\n";
962
963   const MachineFunction *MF = MI->getParent()->getParent();
964   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
965   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
966   const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
967   bool ByteOffset = false, HalfWordOffset = false;
968   if (MI->getOpcode() == ARM::t2TBB)
969     ByteOffset = true;
970   else if (MI->getOpcode() == ARM::t2TBH)
971     HalfWordOffset = true;
972
973   for (unsigned i = 0, e = JTBBs.size(); i != e; ++i) {
974     MachineBasicBlock *MBB = JTBBs[i];
975     if (ByteOffset)
976       O << TAI->getData8bitsDirective();
977     else if (HalfWordOffset)
978       O << TAI->getData16bitsDirective();
979     if (ByteOffset || HalfWordOffset) {
980       O << '(';
981       printBasicBlockLabel(MBB, false, false, false);
982       O << "-" << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
983         << '_' << JTI << '_' << MO2.getImm() << ")/2";
984     } else {
985       O << "\tb.w ";
986       printBasicBlockLabel(MBB, false, false, false);
987     }
988     if (i != e-1)
989       O << '\n';
990   }
991 }
992
993 void ARMAsmPrinter::printTBAddrMode(const MachineInstr *MI, int OpNum) {
994   O << "[pc, " << TRI->getAsmName(MI->getOperand(OpNum).getReg());
995   if (MI->getOpcode() == ARM::t2TBH)
996     O << ", lsl #1";
997   O << ']';
998 }
999
1000
1001 bool ARMAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
1002                                     unsigned AsmVariant, const char *ExtraCode){
1003   // Does this asm operand have a single letter operand modifier?
1004   if (ExtraCode && ExtraCode[0]) {
1005     if (ExtraCode[1] != 0) return true; // Unknown modifier.
1006     
1007     switch (ExtraCode[0]) {
1008     default: return true;  // Unknown modifier.
1009     case 'a': // Print as a memory address.
1010       if (MI->getOperand(OpNum).isReg()) {
1011         O << "[" << TRI->getAsmName(MI->getOperand(OpNum).getReg()) << "]";
1012         return false;
1013       }
1014       // Fallthrough
1015     case 'c': // Don't print "#" before an immediate operand.
1016       printOperand(MI, OpNum, "no_hash");
1017       return false;
1018     case 'P': // Print a VFP double precision register.
1019       printOperand(MI, OpNum);
1020       return false;
1021     case 'Q':
1022       if (TM.getTargetData()->isLittleEndian())
1023         break;
1024       // Fallthrough
1025     case 'R':
1026       if (TM.getTargetData()->isBigEndian())
1027         break;
1028       // Fallthrough
1029     case 'H': // Write second word of DI / DF reference.  
1030       // Verify that this operand has two consecutive registers.
1031       if (!MI->getOperand(OpNum).isReg() ||
1032           OpNum+1 == MI->getNumOperands() ||
1033           !MI->getOperand(OpNum+1).isReg())
1034         return true;
1035       ++OpNum;   // Return the high-part.
1036     }
1037   }
1038   
1039   printOperand(MI, OpNum);
1040   return false;
1041 }
1042
1043 bool ARMAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1044                                           unsigned OpNum, unsigned AsmVariant,
1045                                           const char *ExtraCode) {
1046   if (ExtraCode && ExtraCode[0])
1047     return true; // Unknown modifier.
1048   printAddrMode2Operand(MI, OpNum);
1049   return false;
1050 }
1051
1052 void ARMAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
1053   ++EmittedInsts;
1054
1055   int Opc = MI->getOpcode();
1056   switch (Opc) {
1057   case ARM::CONSTPOOL_ENTRY:
1058     if (!InCPMode && AFI->isThumbFunction()) {
1059       EmitAlignment(2);
1060       InCPMode = true;
1061     }
1062     break;
1063   default: {
1064     if (InCPMode && AFI->isThumbFunction())
1065       InCPMode = false;
1066   }}
1067
1068   // Call the autogenerated instruction printer routines.
1069   printInstruction(MI);
1070 }
1071
1072 bool ARMAsmPrinter::doInitialization(Module &M) {
1073
1074   bool Result = AsmPrinter::doInitialization(M);
1075   DW = getAnalysisIfAvailable<DwarfWriter>();
1076
1077   // Use unified assembler syntax mode for Thumb.
1078   if (Subtarget->isThumb())
1079     O << "\t.syntax unified\n";
1080
1081   // Emit ARM Build Attributes
1082   if (Subtarget->isTargetELF()) {
1083     // CPU Type
1084     std::string CPUString = Subtarget->getCPUString();
1085     if (CPUString != "generic")
1086       O << "\t.cpu " << CPUString << '\n';
1087
1088     // FIXME: Emit FPU type
1089     if (Subtarget->hasVFP2())
1090       O << "\t.eabi_attribute " << ARMBuildAttrs::VFP_arch << ", 2\n";
1091
1092     // Signal various FP modes.
1093     if (!UnsafeFPMath)
1094       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_denormal << ", 1\n"
1095         << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_exceptions << ", 1\n";
1096
1097     if (FiniteOnlyFPMath())
1098       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_number_model << ", 1\n";
1099     else
1100       O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_FP_number_model << ", 3\n";
1101
1102     // 8-bytes alignment stuff.
1103     O << "\t.eabi_attribute " << ARMBuildAttrs::ABI_align8_needed << ", 1\n"
1104       << "\t.eabi_attribute " << ARMBuildAttrs::ABI_align8_preserved << ", 1\n";
1105
1106     // FIXME: Should we signal R9 usage?
1107   }
1108
1109   return Result;
1110 }
1111
1112 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
1113 /// Don't print things like \\n or \\0.
1114 static void PrintUnmangledNameSafely(const Value *V, 
1115                                      formatted_raw_ostream &OS) {
1116   for (StringRef::iterator it = V->getName().begin(), 
1117          ie = V->getName().end(); it != ie; ++it)
1118     if (isprint(*it))
1119       OS << *it;
1120 }
1121
1122 void ARMAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
1123   const TargetData *TD = TM.getTargetData();
1124
1125   if (!GVar->hasInitializer())   // External global require no code
1126     return;
1127
1128   // Check to see if this is a special global used by LLVM, if so, emit it.
1129
1130   if (EmitSpecialLLVMGlobal(GVar)) {
1131     if (Subtarget->isTargetDarwin() &&
1132         TM.getRelocationModel() == Reloc::Static) {
1133       if (GVar->getName() == "llvm.global_ctors")
1134         O << ".reference .constructors_used\n";
1135       else if (GVar->getName() == "llvm.global_dtors")
1136         O << ".reference .destructors_used\n";
1137     }
1138     return;
1139   }
1140
1141   std::string name = Mang->getMangledName(GVar);
1142   Constant *C = GVar->getInitializer();
1143   if (isa<MDNode>(C) || isa<MDString>(C))
1144     return;
1145   const Type *Type = C->getType();
1146   unsigned Size = TD->getTypeAllocSize(Type);
1147   unsigned Align = TD->getPreferredAlignmentLog(GVar);
1148   bool isDarwin = Subtarget->isTargetDarwin();
1149
1150   printVisibility(name, GVar->getVisibility());
1151
1152   if (Subtarget->isTargetELF())
1153     O << "\t.type " << name << ",%object\n";
1154   
1155   const Section *TheSection =
1156     getObjFileLowering().SectionForGlobal(GVar, Mang, TM);
1157   SwitchToSection(TheSection);
1158
1159   // FIXME: get this stuff from section kind flags.
1160   if (C->isNullValue() && !GVar->hasSection() && !GVar->isThreadLocal() &&
1161       // Don't put things that should go in the cstring section into "comm".
1162       !TheSection->getKind().isMergeableCString()) {
1163     if (GVar->hasExternalLinkage()) {
1164       if (const char *Directive = TAI->getZeroFillDirective()) {
1165         O << "\t.globl\t" << name << "\n";
1166         O << Directive << "__DATA, __common, " << name << ", "
1167           << Size << ", " << Align << "\n";
1168         return;
1169       }
1170     }
1171
1172     if (GVar->hasLocalLinkage() || GVar->isWeakForLinker()) {
1173       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
1174
1175       if (isDarwin) {
1176         if (GVar->hasLocalLinkage()) {
1177           O << TAI->getLCOMMDirective()  << name << "," << Size
1178             << ',' << Align;
1179         } else if (GVar->hasCommonLinkage()) {
1180           O << TAI->getCOMMDirective()  << name << "," << Size
1181             << ',' << Align;
1182         } else {
1183           SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, Mang,TM));
1184           O << "\t.globl " << name << '\n'
1185             << TAI->getWeakDefDirective() << name << '\n';
1186           EmitAlignment(Align, GVar);
1187           O << name << ":";
1188           if (VerboseAsm) {
1189             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1190             PrintUnmangledNameSafely(GVar, O);
1191           }
1192           O << '\n';
1193           EmitGlobalConstant(C);
1194           return;
1195         }
1196       } else if (TAI->getLCOMMDirective() != NULL) {
1197         if (GVar->hasLocalLinkage()) {
1198           O << TAI->getLCOMMDirective() << name << "," << Size;
1199         } else {
1200           O << TAI->getCOMMDirective()  << name << "," << Size;
1201           if (TAI->getCOMMDirectiveTakesAlignment())
1202             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1203         }
1204       } else {
1205         if (GVar->hasLocalLinkage())
1206           O << "\t.local\t" << name << "\n";
1207         O << TAI->getCOMMDirective()  << name << "," << Size;
1208         if (TAI->getCOMMDirectiveTakesAlignment())
1209           O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1210       }
1211       if (VerboseAsm) {
1212         O << "\t\t" << TAI->getCommentString() << " ";
1213         PrintUnmangledNameSafely(GVar, O);
1214       }
1215       O << "\n";
1216       return;
1217     }
1218   }
1219   
1220   switch (GVar->getLinkage()) {
1221   case GlobalValue::CommonLinkage:
1222   case GlobalValue::LinkOnceAnyLinkage:
1223   case GlobalValue::LinkOnceODRLinkage:
1224   case GlobalValue::WeakAnyLinkage:
1225   case GlobalValue::WeakODRLinkage:
1226     if (isDarwin) {
1227       O << "\t.globl " << name << "\n"
1228         << "\t.weak_definition " << name << "\n";
1229     } else {
1230       O << "\t.weak " << name << "\n";
1231     }
1232     break;
1233   case GlobalValue::AppendingLinkage:
1234   // FIXME: appending linkage variables should go into a section of
1235   // their name or something.  For now, just emit them as external.
1236   case GlobalValue::ExternalLinkage:
1237     O << "\t.globl " << name << "\n";
1238     break;
1239   case GlobalValue::PrivateLinkage:
1240   case GlobalValue::LinkerPrivateLinkage:
1241   case GlobalValue::InternalLinkage:
1242     break;
1243   default:
1244     llvm_unreachable("Unknown linkage type!");
1245   }
1246
1247   EmitAlignment(Align, GVar);
1248   O << name << ":";
1249   if (VerboseAsm) {
1250     O << "\t\t\t\t" << TAI->getCommentString() << " ";
1251     PrintUnmangledNameSafely(GVar, O);
1252   }
1253   O << "\n";
1254   if (TAI->hasDotTypeDotSizeDirective())
1255     O << "\t.size " << name << ", " << Size << "\n";
1256
1257   EmitGlobalConstant(C);
1258   O << '\n';
1259 }
1260
1261
1262 bool ARMAsmPrinter::doFinalization(Module &M) {
1263   if (Subtarget->isTargetDarwin()) {
1264     SwitchToDataSection("");
1265
1266     O << '\n';
1267     // Output stubs for dynamically-linked functions
1268     for (StringMap<FnStubInfo>::iterator I = FnStubs.begin(), E = FnStubs.end();
1269          I != E; ++I) {
1270       const FnStubInfo &Info = I->second;
1271       if (TM.getRelocationModel() == Reloc::PIC_)
1272         SwitchToTextSection(".section __TEXT,__picsymbolstub4,symbol_stubs,"
1273                             "none,16", 0);
1274       else
1275         SwitchToTextSection(".section __TEXT,__symbol_stub4,symbol_stubs,"
1276                             "none,12", 0);
1277
1278       EmitAlignment(2);
1279       O << "\t.code\t32\n";
1280
1281       O << Info.Stub << ":\n";
1282       O << "\t.indirect_symbol " << I->getKeyData() << '\n';
1283       O << "\tldr ip, " << Info.SLP << '\n';
1284       if (TM.getRelocationModel() == Reloc::PIC_) {
1285         O << Info.SCV << ":\n";
1286         O << "\tadd ip, pc, ip\n";
1287       }
1288       O << "\tldr pc, [ip, #0]\n";
1289       O << Info.SLP << ":\n";
1290       O << "\t.long\t" << Info.LazyPtr;
1291       if (TM.getRelocationModel() == Reloc::PIC_)
1292         O << "-(" << Info.SCV << "+8)";
1293       O << '\n';
1294       
1295       SwitchToDataSection(".lazy_symbol_pointer", 0);
1296       O << Info.LazyPtr << ":\n";
1297       O << "\t.indirect_symbol " << I->getKeyData() << "\n";
1298       O << "\t.long\tdyld_stub_binding_helper\n";
1299     }
1300     O << '\n';
1301
1302     // Output non-lazy-pointers for external and common global variables.
1303     if (!GVNonLazyPtrs.empty()) {
1304       SwitchToDataSection("\t.non_lazy_symbol_pointer", 0);
1305       for (StringMap<std::string>::iterator I =  GVNonLazyPtrs.begin(),
1306              E = GVNonLazyPtrs.end(); I != E; ++I) {
1307         O << I->second << ":\n";
1308         O << "\t.indirect_symbol " << I->getKeyData() << "\n";
1309         O << "\t.long\t0\n";
1310       }
1311     }
1312
1313     if (!HiddenGVNonLazyPtrs.empty()) {
1314       SwitchToSection(getObjFileLowering().getDataSection());
1315       for (StringMap<std::string>::iterator I = HiddenGVNonLazyPtrs.begin(),
1316              E = HiddenGVNonLazyPtrs.end(); I != E; ++I) {
1317         EmitAlignment(2);
1318         O << I->second << ":\n";
1319         O << "\t.long " << I->getKeyData() << "\n";
1320       }
1321     }
1322
1323
1324     // Funny Darwin hack: This flag tells the linker that no global symbols
1325     // contain code that falls through to other global symbols (e.g. the obvious
1326     // implementation of multiple entry points).  If this doesn't occur, the
1327     // linker can safely perform dead code stripping.  Since LLVM never
1328     // generates code that does this, it is always safe to set.
1329     O << "\t.subsections_via_symbols\n";
1330   }
1331
1332   return AsmPrinter::doFinalization(M);
1333 }
1334
1335 // Force static initialization.
1336 extern "C" void LLVMInitializeARMAsmPrinter() { 
1337   RegisterAsmPrinter<ARMAsmPrinter> X(TheARMTarget);
1338   RegisterAsmPrinter<ARMAsmPrinter> Y(TheThumbTarget);
1339 }