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