d8a7ac3b44ed07213ea6416e2f8b77aaa840d69f
[oota-llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinter.cpp
1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
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 implements the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "DwarfDebug.h"
17 #include "DwarfException.h"
18 #include "llvm/Module.h"
19 #include "llvm/CodeGen/GCMetadataPrinter.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineJumpTableInfo.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/DebugInfo.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Target/Mangler.h"
36 #include "llvm/Target/TargetAsmInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetInstrInfo.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Assembly/Writer.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Statistic.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/Format.h"
48 #include "llvm/Support/Timer.h"
49 using namespace llvm;
50
51 static const char *DWARFGroupName = "DWARF Emission";
52 static const char *DbgTimerName = "DWARF Debug Writer";
53 static const char *EHTimerName = "DWARF Exception Writer";
54
55 STATISTIC(EmittedInsts, "Number of machine instrs printed");
56
57 char AsmPrinter::ID = 0;
58
59 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
60 static gcp_map_type &getGCMap(void *&P) {
61   if (P == 0)
62     P = new gcp_map_type();
63   return *(gcp_map_type*)P;
64 }
65
66
67 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
68 /// value in log2 form.  This rounds up to the preferred alignment if possible
69 /// and legal.
70 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD,
71                                    unsigned InBits = 0) {
72   unsigned NumBits = 0;
73   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
74     NumBits = TD.getPreferredAlignmentLog(GVar);
75
76   // If InBits is specified, round it to it.
77   if (InBits > NumBits)
78     NumBits = InBits;
79
80   // If the GV has a specified alignment, take it into account.
81   if (GV->getAlignment() == 0)
82     return NumBits;
83
84   unsigned GVAlign = Log2_32(GV->getAlignment());
85
86   // If the GVAlign is larger than NumBits, or if we are required to obey
87   // NumBits because the GV has an assigned section, obey it.
88   if (GVAlign > NumBits || GV->hasSection())
89     NumBits = GVAlign;
90   return NumBits;
91 }
92
93
94
95
96 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
97   : MachineFunctionPass(ID),
98     TM(tm), MAI(tm.getMCAsmInfo()),
99     OutContext(Streamer.getContext()),
100     OutStreamer(Streamer),
101     LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
102   DD = 0; DE = 0; MMI = 0; LI = 0;
103   GCMetadataPrinters = 0;
104   VerboseAsm = Streamer.isVerboseAsm();
105 }
106
107 AsmPrinter::~AsmPrinter() {
108   assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
109
110   if (GCMetadataPrinters != 0) {
111     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
112
113     for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
114       delete I->second;
115     delete &GCMap;
116     GCMetadataPrinters = 0;
117   }
118
119   delete &OutStreamer;
120 }
121
122 /// getFunctionNumber - Return a unique ID for the current function.
123 ///
124 unsigned AsmPrinter::getFunctionNumber() const {
125   return MF->getFunctionNumber();
126 }
127
128 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
129   return TM.getTargetLowering()->getObjFileLowering();
130 }
131
132
133 /// getTargetData - Return information about data layout.
134 const TargetData &AsmPrinter::getTargetData() const {
135   return *TM.getTargetData();
136 }
137
138 /// getCurrentSection() - Return the current section we are emitting to.
139 const MCSection *AsmPrinter::getCurrentSection() const {
140   return OutStreamer.getCurrentSection();
141 }
142
143
144
145 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
146   AU.setPreservesAll();
147   MachineFunctionPass::getAnalysisUsage(AU);
148   AU.addRequired<MachineModuleInfo>();
149   AU.addRequired<GCModuleInfo>();
150   if (isVerbose())
151     AU.addRequired<MachineLoopInfo>();
152 }
153
154 bool AsmPrinter::doInitialization(Module &M) {
155   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
156   MMI->AnalyzeModule(M);
157
158   // Initialize TargetLoweringObjectFile.
159   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
160     .Initialize(OutContext, TM);
161
162   Mang = new Mangler(OutContext, *TM.getTargetData());
163
164   // Allow the target to emit any magic that it wants at the start of the file.
165   EmitStartOfAsmFile(M);
166
167   // Very minimal debug info. It is ignored if we emit actual debug info. If we
168   // don't, this at least helps the user find where a global came from.
169   if (MAI->hasSingleParameterDotFile()) {
170     // .file "foo.c"
171     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
172   }
173
174   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
175   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
176   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
177     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
178       MP->beginAssembly(*this);
179
180   // Emit module-level inline asm if it exists.
181   if (!M.getModuleInlineAsm().empty()) {
182     OutStreamer.AddComment("Start of file scope inline assembly");
183     OutStreamer.AddBlankLine();
184     EmitInlineAsm(M.getModuleInlineAsm()+"\n");
185     OutStreamer.AddComment("End of file scope inline assembly");
186     OutStreamer.AddBlankLine();
187   }
188
189   if (MAI->doesSupportDebugInformation())
190     DD = new DwarfDebug(this, &M);
191
192   switch (MAI->getExceptionHandlingType()) {
193   case ExceptionHandling::None:
194     return false;
195   case ExceptionHandling::SjLj:
196   case ExceptionHandling::DwarfCFI:
197     DE = new DwarfCFIException(this);
198     return false;
199   case ExceptionHandling::ARM:
200     DE = new ARMException(this);
201     return false;
202   }
203
204   llvm_unreachable("Unknown exception type.");
205 }
206
207 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
208   switch ((GlobalValue::LinkageTypes)Linkage) {
209   case GlobalValue::CommonLinkage:
210   case GlobalValue::LinkOnceAnyLinkage:
211   case GlobalValue::LinkOnceODRLinkage:
212   case GlobalValue::WeakAnyLinkage:
213   case GlobalValue::WeakODRLinkage:
214   case GlobalValue::LinkerPrivateWeakLinkage:
215   case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
216     if (MAI->getWeakDefDirective() != 0) {
217       // .globl _foo
218       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
219
220       if ((GlobalValue::LinkageTypes)Linkage !=
221           GlobalValue::LinkerPrivateWeakDefAutoLinkage)
222         // .weak_definition _foo
223         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
224       else
225         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
226     } else if (MAI->getLinkOnceDirective() != 0) {
227       // .globl _foo
228       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
229       //NOTE: linkonce is handled by the section the symbol was assigned to.
230     } else {
231       // .weak _foo
232       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
233     }
234     break;
235   case GlobalValue::DLLExportLinkage:
236   case GlobalValue::AppendingLinkage:
237     // FIXME: appending linkage variables should go into a section of
238     // their name or something.  For now, just emit them as external.
239   case GlobalValue::ExternalLinkage:
240     // If external or appending, declare as a global symbol.
241     // .globl _foo
242     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
243     break;
244   case GlobalValue::PrivateLinkage:
245   case GlobalValue::InternalLinkage:
246   case GlobalValue::LinkerPrivateLinkage:
247     break;
248   default:
249     llvm_unreachable("Unknown linkage type!");
250   }
251 }
252
253
254 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
255 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
256   if (GV->hasInitializer()) {
257     // Check to see if this is a special global used by LLVM, if so, emit it.
258     if (EmitSpecialLLVMGlobal(GV))
259       return;
260
261     if (isVerbose()) {
262       WriteAsOperand(OutStreamer.GetCommentOS(), GV,
263                      /*PrintType=*/false, GV->getParent());
264       OutStreamer.GetCommentOS() << '\n';
265     }
266   }
267
268   MCSymbol *GVSym = Mang->getSymbol(GV);
269   EmitVisibility(GVSym, GV->getVisibility());
270
271   if (!GV->hasInitializer())   // External globals require no extra code.
272     return;
273
274   if (MAI->hasDotTypeDotSizeDirective())
275     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
276
277   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
278
279   const TargetData *TD = TM.getTargetData();
280   uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
281
282   // If the alignment is specified, we *must* obey it.  Overaligning a global
283   // with a specified alignment is a prompt way to break globals emitted to
284   // sections and expected to be contiguous (e.g. ObjC metadata).
285   unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
286
287   // Handle common and BSS local symbols (.lcomm).
288   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
289     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
290
291     // Handle common symbols.
292     if (GVKind.isCommon()) {
293       unsigned Align = 1 << AlignLog;
294       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
295         Align = 0;
296
297       // .comm _foo, 42, 4
298       OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
299       return;
300     }
301
302     // Handle local BSS symbols.
303     if (MAI->hasMachoZeroFillDirective()) {
304       const MCSection *TheSection =
305         getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
306       // .zerofill __DATA, __bss, _foo, 400, 5
307       OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
308       return;
309     }
310
311     if (MAI->hasLCOMMDirective()) {
312       // .lcomm _foo, 42
313       OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
314       return;
315     }
316
317     unsigned Align = 1 << AlignLog;
318     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
319       Align = 0;
320
321     // .local _foo
322     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
323     // .comm _foo, 42, 4
324     OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
325     return;
326   }
327
328   const MCSection *TheSection =
329     getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
330
331   // Handle the zerofill directive on darwin, which is a special form of BSS
332   // emission.
333   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
334     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
335
336     // .globl _foo
337     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
338     // .zerofill __DATA, __common, _foo, 400, 5
339     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
340     return;
341   }
342
343   // Handle thread local data for mach-o which requires us to output an
344   // additional structure of data and mangle the original symbol so that we
345   // can reference it later.
346   //
347   // TODO: This should become an "emit thread local global" method on TLOF.
348   // All of this macho specific stuff should be sunk down into TLOFMachO and
349   // stuff like "TLSExtraDataSection" should no longer be part of the parent
350   // TLOF class.  This will also make it more obvious that stuff like
351   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
352   // specific code.
353   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
354     // Emit the .tbss symbol
355     MCSymbol *MangSym =
356       OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
357
358     if (GVKind.isThreadBSS())
359       OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
360     else if (GVKind.isThreadData()) {
361       OutStreamer.SwitchSection(TheSection);
362
363       EmitAlignment(AlignLog, GV);
364       OutStreamer.EmitLabel(MangSym);
365
366       EmitGlobalConstant(GV->getInitializer());
367     }
368
369     OutStreamer.AddBlankLine();
370
371     // Emit the variable struct for the runtime.
372     const MCSection *TLVSect
373       = getObjFileLowering().getTLSExtraDataSection();
374
375     OutStreamer.SwitchSection(TLVSect);
376     // Emit the linkage here.
377     EmitLinkage(GV->getLinkage(), GVSym);
378     OutStreamer.EmitLabel(GVSym);
379
380     // Three pointers in size:
381     //   - __tlv_bootstrap - used to make sure support exists
382     //   - spare pointer, used when mapped by the runtime
383     //   - pointer to mangled symbol above with initializer
384     unsigned PtrSize = TD->getPointerSizeInBits()/8;
385     OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
386                           PtrSize, 0);
387     OutStreamer.EmitIntValue(0, PtrSize, 0);
388     OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
389
390     OutStreamer.AddBlankLine();
391     return;
392   }
393
394   OutStreamer.SwitchSection(TheSection);
395
396   EmitLinkage(GV->getLinkage(), GVSym);
397   EmitAlignment(AlignLog, GV);
398
399   OutStreamer.EmitLabel(GVSym);
400
401   EmitGlobalConstant(GV->getInitializer());
402
403   if (MAI->hasDotTypeDotSizeDirective())
404     // .size foo, 42
405     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
406
407   OutStreamer.AddBlankLine();
408 }
409
410 /// EmitFunctionHeader - This method emits the header for the current
411 /// function.
412 void AsmPrinter::EmitFunctionHeader() {
413   // Print out constants referenced by the function
414   EmitConstantPool();
415
416   // Print the 'header' of function.
417   const Function *F = MF->getFunction();
418
419   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
420   EmitVisibility(CurrentFnSym, F->getVisibility());
421
422   EmitLinkage(F->getLinkage(), CurrentFnSym);
423   EmitAlignment(MF->getAlignment(), F);
424
425   if (MAI->hasDotTypeDotSizeDirective())
426     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
427
428   if (isVerbose()) {
429     WriteAsOperand(OutStreamer.GetCommentOS(), F,
430                    /*PrintType=*/false, F->getParent());
431     OutStreamer.GetCommentOS() << '\n';
432   }
433
434   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
435   // do their wild and crazy things as required.
436   EmitFunctionEntryLabel();
437
438   // If the function had address-taken blocks that got deleted, then we have
439   // references to the dangling symbols.  Emit them at the start of the function
440   // so that we don't get references to undefined symbols.
441   std::vector<MCSymbol*> DeadBlockSyms;
442   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
443   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
444     OutStreamer.AddComment("Address taken block that was later removed");
445     OutStreamer.EmitLabel(DeadBlockSyms[i]);
446   }
447
448   // Add some workaround for linkonce linkage on Cygwin\MinGW.
449   if (MAI->getLinkOnceDirective() != 0 &&
450       (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
451     // FIXME: What is this?
452     MCSymbol *FakeStub =
453       OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
454                                    CurrentFnSym->getName());
455     OutStreamer.EmitLabel(FakeStub);
456   }
457
458   // Emit pre-function debug and/or EH information.
459   if (DE) {
460     NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
461     DE->BeginFunction(MF);
462   }
463   if (DD) {
464     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
465     DD->beginFunction(MF);
466   }
467 }
468
469 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
470 /// function.  This can be overridden by targets as required to do custom stuff.
471 void AsmPrinter::EmitFunctionEntryLabel() {
472   // The function label could have already been emitted if two symbols end up
473   // conflicting due to asm renaming.  Detect this and emit an error.
474   if (CurrentFnSym->isUndefined())
475     return OutStreamer.EmitLabel(CurrentFnSym);
476
477   report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
478                      "' label emitted multiple times to assembly file");
479 }
480
481
482 /// EmitComments - Pretty-print comments for instructions.
483 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
484   const MachineFunction *MF = MI.getParent()->getParent();
485   const TargetMachine &TM = MF->getTarget();
486
487   // Check for spills and reloads
488   int FI;
489
490   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
491
492   // We assume a single instruction only has a spill or reload, not
493   // both.
494   const MachineMemOperand *MMO;
495   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
496     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
497       MMO = *MI.memoperands_begin();
498       CommentOS << MMO->getSize() << "-byte Reload\n";
499     }
500   } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
501     if (FrameInfo->isSpillSlotObjectIndex(FI))
502       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
503   } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
504     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
505       MMO = *MI.memoperands_begin();
506       CommentOS << MMO->getSize() << "-byte Spill\n";
507     }
508   } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
509     if (FrameInfo->isSpillSlotObjectIndex(FI))
510       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
511   }
512
513   // Check for spill-induced copies
514   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
515     CommentOS << " Reload Reuse\n";
516 }
517
518 /// EmitImplicitDef - This method emits the specified machine instruction
519 /// that is an implicit def.
520 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
521   unsigned RegNo = MI->getOperand(0).getReg();
522   AP.OutStreamer.AddComment(Twine("implicit-def: ") +
523                             AP.TM.getRegisterInfo()->getName(RegNo));
524   AP.OutStreamer.AddBlankLine();
525 }
526
527 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
528   std::string Str = "kill:";
529   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
530     const MachineOperand &Op = MI->getOperand(i);
531     assert(Op.isReg() && "KILL instruction must have only register operands");
532     Str += ' ';
533     Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
534     Str += (Op.isDef() ? "<def>" : "<kill>");
535   }
536   AP.OutStreamer.AddComment(Str);
537   AP.OutStreamer.AddBlankLine();
538 }
539
540 /// EmitDebugValueComment - This method handles the target-independent form
541 /// of DBG_VALUE, returning true if it was able to do so.  A false return
542 /// means the target will need to handle MI in EmitInstruction.
543 static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
544   // This code handles only the 3-operand target-independent form.
545   if (MI->getNumOperands() != 3)
546     return false;
547
548   SmallString<128> Str;
549   raw_svector_ostream OS(Str);
550   OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
551
552   // cast away const; DIetc do not take const operands for some reason.
553   DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
554   if (V.getContext().isSubprogram())
555     OS << DISubprogram(V.getContext()).getDisplayName() << ":";
556   OS << V.getName() << " <- ";
557
558   // Register or immediate value. Register 0 means undef.
559   if (MI->getOperand(0).isFPImm()) {
560     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
561     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
562       OS << (double)APF.convertToFloat();
563     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
564       OS << APF.convertToDouble();
565     } else {
566       // There is no good way to print long double.  Convert a copy to
567       // double.  Ah well, it's only a comment.
568       bool ignored;
569       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
570                   &ignored);
571       OS << "(long double) " << APF.convertToDouble();
572     }
573   } else if (MI->getOperand(0).isImm()) {
574     OS << MI->getOperand(0).getImm();
575   } else {
576     assert(MI->getOperand(0).isReg() && "Unknown operand type");
577     if (MI->getOperand(0).getReg() == 0) {
578       // Suppress offset, it is not meaningful here.
579       OS << "undef";
580       // NOTE: Want this comment at start of line, don't emit with AddComment.
581       AP.OutStreamer.EmitRawText(OS.str());
582       return true;
583     }
584     OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
585   }
586
587   OS << '+' << MI->getOperand(1).getImm();
588   // NOTE: Want this comment at start of line, don't emit with AddComment.
589   AP.OutStreamer.EmitRawText(OS.str());
590   return true;
591 }
592
593 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
594   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
595       MF->getFunction()->needsUnwindTableEntry())
596     return CFI_M_EH;
597
598   if (MMI->hasDebugInfo())
599     return CFI_M_Debug;
600
601   return CFI_M_None;
602 }
603
604 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
605   MCSymbol *Label = MI.getOperand(0).getMCSymbol();
606
607   if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
608     return;
609
610   if (needsCFIMoves() == CFI_M_None)
611     return;
612
613   MachineModuleInfo &MMI = MF->getMMI();
614   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
615   bool FoundOne = false;
616   (void)FoundOne;
617   for (std::vector<MachineMove>::iterator I = Moves.begin(),
618          E = Moves.end(); I != E; ++I) {
619     if (I->getLabel() == Label) {
620       EmitCFIFrameMove(*I);
621       FoundOne = true;
622     }
623   }
624   assert(FoundOne);
625 }
626
627 /// EmitFunctionBody - This method emits the body and trailer for a
628 /// function.
629 void AsmPrinter::EmitFunctionBody() {
630   // Emit target-specific gunk before the function body.
631   EmitFunctionBodyStart();
632
633   bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
634
635   // Print out code for the function.
636   bool HasAnyRealCode = false;
637   const MachineInstr *LastMI = 0;
638   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
639        I != E; ++I) {
640     // Print a label for the basic block.
641     EmitBasicBlockStart(I);
642     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
643          II != IE; ++II) {
644       LastMI = II;
645
646       // Print the assembly for the instruction.
647       if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
648           !II->isDebugValue()) {
649         HasAnyRealCode = true;
650         ++EmittedInsts;
651       }
652
653       if (ShouldPrintDebugScopes) {
654         NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
655         DD->beginInstruction(II);
656       }
657
658       if (isVerbose())
659         EmitComments(*II, OutStreamer.GetCommentOS());
660
661       switch (II->getOpcode()) {
662       case TargetOpcode::PROLOG_LABEL:
663         emitPrologLabel(*II);
664         break;
665
666       case TargetOpcode::EH_LABEL:
667       case TargetOpcode::GC_LABEL:
668         OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
669         break;
670       case TargetOpcode::INLINEASM:
671         EmitInlineAsm(II);
672         break;
673       case TargetOpcode::DBG_VALUE:
674         if (isVerbose()) {
675           if (!EmitDebugValueComment(II, *this))
676             EmitInstruction(II);
677         }
678         break;
679       case TargetOpcode::IMPLICIT_DEF:
680         if (isVerbose()) EmitImplicitDef(II, *this);
681         break;
682       case TargetOpcode::KILL:
683         if (isVerbose()) EmitKill(II, *this);
684         break;
685       default:
686         if (!TM.hasMCUseLoc())
687           MCLineEntry::Make(&OutStreamer, getCurrentSection());
688
689         EmitInstruction(II);
690         break;
691       }
692
693       if (ShouldPrintDebugScopes) {
694         NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
695         DD->endInstruction(II);
696       }
697     }
698   }
699
700   // If the last instruction was a prolog label, then we have a situation where
701   // we emitted a prolog but no function body. This results in the ending prolog
702   // label equaling the end of function label and an invalid "row" in the
703   // FDE. We need to emit a noop in this situation so that the FDE's rows are
704   // valid.
705   bool RequiresNoop = LastMI && LastMI->isPrologLabel();
706
707   // If the function is empty and the object file uses .subsections_via_symbols,
708   // then we need to emit *something* to the function body to prevent the
709   // labels from collapsing together.  Just emit a noop.
710   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
711     MCInst Noop;
712     TM.getInstrInfo()->getNoopForMachoTarget(Noop);
713     if (Noop.getOpcode()) {
714       OutStreamer.AddComment("avoids zero-length function");
715       OutStreamer.EmitInstruction(Noop);
716     } else  // Target not mc-ized yet.
717       OutStreamer.EmitRawText(StringRef("\tnop\n"));
718   }
719
720   // Emit target-specific gunk after the function body.
721   EmitFunctionBodyEnd();
722
723   // If the target wants a .size directive for the size of the function, emit
724   // it.
725   if (MAI->hasDotTypeDotSizeDirective()) {
726     // Create a symbol for the end of function, so we can get the size as
727     // difference between the function label and the temp label.
728     MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
729     OutStreamer.EmitLabel(FnEndLabel);
730
731     const MCExpr *SizeExp =
732       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
733                               MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
734                               OutContext);
735     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
736   }
737
738   // Emit post-function debug information.
739   if (DD) {
740     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
741     DD->endFunction(MF);
742   }
743   if (DE) {
744     NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
745     DE->EndFunction();
746   }
747   MMI->EndFunction();
748
749   // Print out jump tables referenced by the function.
750   EmitJumpTableInfo();
751
752   OutStreamer.AddBlankLine();
753 }
754
755 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
756 /// operands.
757 MachineLocation AsmPrinter::
758 getDebugValueLocation(const MachineInstr *MI) const {
759   // Target specific DBG_VALUE instructions are handled by each target.
760   return MachineLocation();
761 }
762
763 /// EmitDwarfRegOp - Emit dwarf register operation.
764 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
765   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
766   int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
767
768   for (const unsigned *SR = TRI->getSuperRegisters(MLoc.getReg());
769        *SR && Reg == -1; ++SR) {
770     Reg = TRI->getDwarfRegNum(*SR, false);
771     // FIXME: Get the bit range this register uses of the superregister
772     // so that we can produce a DW_OP_bit_piece
773   }
774
775   // FIXME: Handle cases like a super register being encoded as
776   // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
777
778   // FIXME: We have no reasonable way of handling errors in here. The
779   // caller might be in the middle of an dwarf expression. We should
780   // probably assert that Reg >= 0 once debug info generation is more mature.
781
782   if (int Offset =  MLoc.getOffset()) {
783     if (Reg < 32) {
784       OutStreamer.AddComment(
785         dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
786       EmitInt8(dwarf::DW_OP_breg0 + Reg);
787     } else {
788       OutStreamer.AddComment("DW_OP_bregx");
789       EmitInt8(dwarf::DW_OP_bregx);
790       OutStreamer.AddComment(Twine(Reg));
791       EmitULEB128(Reg);
792     }
793     EmitSLEB128(Offset);
794   } else {
795     if (Reg < 32) {
796       OutStreamer.AddComment(
797         dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
798       EmitInt8(dwarf::DW_OP_reg0 + Reg);
799     } else {
800       OutStreamer.AddComment("DW_OP_regx");
801       EmitInt8(dwarf::DW_OP_regx);
802       OutStreamer.AddComment(Twine(Reg));
803       EmitULEB128(Reg);
804     }
805   }
806
807   // FIXME: Produce a DW_OP_bit_piece if we used a superregister
808 }
809
810 bool AsmPrinter::doFinalization(Module &M) {
811   // Emit global variables.
812   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
813        I != E; ++I)
814     EmitGlobalVariable(I);
815
816   // Emit visibility info for declarations
817   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
818     const Function &F = *I;
819     if (!F.isDeclaration())
820       continue;
821     GlobalValue::VisibilityTypes V = F.getVisibility();
822     if (V == GlobalValue::DefaultVisibility)
823       continue;
824
825     MCSymbol *Name = Mang->getSymbol(&F);
826     EmitVisibility(Name, V, false);
827   }
828
829   // Finalize debug and EH information.
830   if (DE) {
831     {
832       NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
833       DE->EndModule();
834     }
835     delete DE; DE = 0;
836   }
837   if (DD) {
838     {
839       NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
840       DD->endModule();
841     }
842     delete DD; DD = 0;
843   }
844
845   // If the target wants to know about weak references, print them all.
846   if (MAI->getWeakRefDirective()) {
847     // FIXME: This is not lazy, it would be nice to only print weak references
848     // to stuff that is actually used.  Note that doing so would require targets
849     // to notice uses in operands (due to constant exprs etc).  This should
850     // happen with the MC stuff eventually.
851
852     // Print out module-level global variables here.
853     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
854          I != E; ++I) {
855       if (!I->hasExternalWeakLinkage()) continue;
856       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
857     }
858
859     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
860       if (!I->hasExternalWeakLinkage()) continue;
861       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
862     }
863   }
864
865   if (MAI->hasSetDirective()) {
866     OutStreamer.AddBlankLine();
867     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
868          I != E; ++I) {
869       MCSymbol *Name = Mang->getSymbol(I);
870
871       const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
872       MCSymbol *Target = Mang->getSymbol(GV);
873
874       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
875         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
876       else if (I->hasWeakLinkage())
877         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
878       else
879         assert(I->hasLocalLinkage() && "Invalid alias linkage");
880
881       EmitVisibility(Name, I->getVisibility());
882
883       // Emit the directives as assignments aka .set:
884       OutStreamer.EmitAssignment(Name,
885                                  MCSymbolRefExpr::Create(Target, OutContext));
886     }
887   }
888
889   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
890   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
891   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
892     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
893       MP->finishAssembly(*this);
894
895   // If we don't have any trampolines, then we don't require stack memory
896   // to be executable. Some targets have a directive to declare this.
897   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
898   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
899     if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
900       OutStreamer.SwitchSection(S);
901
902   // Allow the target to emit any magic that it wants at the end of the file,
903   // after everything else has gone out.
904   EmitEndOfAsmFile(M);
905
906   delete Mang; Mang = 0;
907   MMI = 0;
908
909   OutStreamer.Finish();
910   return false;
911 }
912
913 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
914   this->MF = &MF;
915   // Get the function symbol.
916   CurrentFnSym = Mang->getSymbol(MF.getFunction());
917
918   if (isVerbose())
919     LI = &getAnalysis<MachineLoopInfo>();
920 }
921
922 namespace {
923   // SectionCPs - Keep track the alignment, constpool entries per Section.
924   struct SectionCPs {
925     const MCSection *S;
926     unsigned Alignment;
927     SmallVector<unsigned, 4> CPEs;
928     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
929   };
930 }
931
932 /// EmitConstantPool - Print to the current output stream assembly
933 /// representations of the constants in the constant pool MCP. This is
934 /// used to print out constants which have been "spilled to memory" by
935 /// the code generator.
936 ///
937 void AsmPrinter::EmitConstantPool() {
938   const MachineConstantPool *MCP = MF->getConstantPool();
939   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
940   if (CP.empty()) return;
941
942   // Calculate sections for constant pool entries. We collect entries to go into
943   // the same section together to reduce amount of section switch statements.
944   SmallVector<SectionCPs, 4> CPSections;
945   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
946     const MachineConstantPoolEntry &CPE = CP[i];
947     unsigned Align = CPE.getAlignment();
948
949     SectionKind Kind;
950     switch (CPE.getRelocationInfo()) {
951     default: llvm_unreachable("Unknown section kind");
952     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
953     case 1:
954       Kind = SectionKind::getReadOnlyWithRelLocal();
955       break;
956     case 0:
957     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
958     case 4:  Kind = SectionKind::getMergeableConst4(); break;
959     case 8:  Kind = SectionKind::getMergeableConst8(); break;
960     case 16: Kind = SectionKind::getMergeableConst16();break;
961     default: Kind = SectionKind::getMergeableConst(); break;
962     }
963     }
964
965     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
966
967     // The number of sections are small, just do a linear search from the
968     // last section to the first.
969     bool Found = false;
970     unsigned SecIdx = CPSections.size();
971     while (SecIdx != 0) {
972       if (CPSections[--SecIdx].S == S) {
973         Found = true;
974         break;
975       }
976     }
977     if (!Found) {
978       SecIdx = CPSections.size();
979       CPSections.push_back(SectionCPs(S, Align));
980     }
981
982     if (Align > CPSections[SecIdx].Alignment)
983       CPSections[SecIdx].Alignment = Align;
984     CPSections[SecIdx].CPEs.push_back(i);
985   }
986
987   // Now print stuff into the calculated sections.
988   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
989     OutStreamer.SwitchSection(CPSections[i].S);
990     EmitAlignment(Log2_32(CPSections[i].Alignment));
991
992     unsigned Offset = 0;
993     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
994       unsigned CPI = CPSections[i].CPEs[j];
995       MachineConstantPoolEntry CPE = CP[CPI];
996
997       // Emit inter-object padding for alignment.
998       unsigned AlignMask = CPE.getAlignment() - 1;
999       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
1000       OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
1001
1002       const Type *Ty = CPE.getType();
1003       Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
1004       OutStreamer.EmitLabel(GetCPISymbol(CPI));
1005
1006       if (CPE.isMachineConstantPoolEntry())
1007         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
1008       else
1009         EmitGlobalConstant(CPE.Val.ConstVal);
1010     }
1011   }
1012 }
1013
1014 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
1015 /// by the current function to the current output stream.
1016 ///
1017 void AsmPrinter::EmitJumpTableInfo() {
1018   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
1019   if (MJTI == 0) return;
1020   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
1021   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
1022   if (JT.empty()) return;
1023
1024   // Pick the directive to use to print the jump table entries, and switch to
1025   // the appropriate section.
1026   const Function *F = MF->getFunction();
1027   bool JTInDiffSection = false;
1028   if (// In PIC mode, we need to emit the jump table to the same section as the
1029       // function body itself, otherwise the label differences won't make sense.
1030       // FIXME: Need a better predicate for this: what about custom entries?
1031       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
1032       // We should also do if the section name is NULL or function is declared
1033       // in discardable section
1034       // FIXME: this isn't the right predicate, should be based on the MCSection
1035       // for the function.
1036       F->isWeakForLinker()) {
1037     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
1038   } else {
1039     // Otherwise, drop it in the readonly section.
1040     const MCSection *ReadOnlySection =
1041       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
1042     OutStreamer.SwitchSection(ReadOnlySection);
1043     JTInDiffSection = true;
1044   }
1045
1046   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
1047
1048   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
1049     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
1050
1051     // If this jump table was deleted, ignore it.
1052     if (JTBBs.empty()) continue;
1053
1054     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
1055     // .set directive for each unique entry.  This reduces the number of
1056     // relocations the assembler will generate for the jump table.
1057     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
1058         MAI->hasSetDirective()) {
1059       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
1060       const TargetLowering *TLI = TM.getTargetLowering();
1061       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
1062       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
1063         const MachineBasicBlock *MBB = JTBBs[ii];
1064         if (!EmittedSets.insert(MBB)) continue;
1065
1066         // .set LJTSet, LBB32-base
1067         const MCExpr *LHS =
1068           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1069         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
1070                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
1071       }
1072     }
1073
1074     // On some targets (e.g. Darwin) we want to emit two consecutive labels
1075     // before each jump table.  The first label is never referenced, but tells
1076     // the assembler and linker the extents of the jump table object.  The
1077     // second label is actually referenced by the code.
1078     if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
1079       // FIXME: This doesn't have to have any specific name, just any randomly
1080       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
1081       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
1082
1083     OutStreamer.EmitLabel(GetJTISymbol(JTI));
1084
1085     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
1086       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
1087   }
1088 }
1089
1090 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
1091 /// current stream.
1092 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
1093                                     const MachineBasicBlock *MBB,
1094                                     unsigned UID) const {
1095   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
1096   const MCExpr *Value = 0;
1097   switch (MJTI->getEntryKind()) {
1098   case MachineJumpTableInfo::EK_Inline:
1099     llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
1100   case MachineJumpTableInfo::EK_Custom32:
1101     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
1102                                                               OutContext);
1103     break;
1104   case MachineJumpTableInfo::EK_BlockAddress:
1105     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
1106     //     .word LBB123
1107     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1108     break;
1109   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
1110     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
1111     // with a relocation as gp-relative, e.g.:
1112     //     .gprel32 LBB123
1113     MCSymbol *MBBSym = MBB->getSymbol();
1114     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
1115     return;
1116   }
1117
1118   case MachineJumpTableInfo::EK_LabelDifference32: {
1119     // EK_LabelDifference32 - Each entry is the address of the block minus
1120     // the address of the jump table.  This is used for PIC jump tables where
1121     // gprel32 is not supported.  e.g.:
1122     //      .word LBB123 - LJTI1_2
1123     // If the .set directive is supported, this is emitted as:
1124     //      .set L4_5_set_123, LBB123 - LJTI1_2
1125     //      .word L4_5_set_123
1126
1127     // If we have emitted set directives for the jump table entries, print
1128     // them rather than the entries themselves.  If we're emitting PIC, then
1129     // emit the table entries as differences between two text section labels.
1130     if (MAI->hasSetDirective()) {
1131       // If we used .set, reference the .set's symbol.
1132       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
1133                                       OutContext);
1134       break;
1135     }
1136     // Otherwise, use the difference as the jump table entry.
1137     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
1138     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
1139     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
1140     break;
1141   }
1142   }
1143
1144   assert(Value && "Unknown entry kind!");
1145
1146   unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
1147   OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
1148 }
1149
1150
1151 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
1152 /// special global used by LLVM.  If so, emit it and return true, otherwise
1153 /// do nothing and return false.
1154 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
1155   if (GV->getName() == "llvm.used") {
1156     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
1157       EmitLLVMUsedList(GV->getInitializer());
1158     return true;
1159   }
1160
1161   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
1162   if (GV->getSection() == "llvm.metadata" ||
1163       GV->hasAvailableExternallyLinkage())
1164     return true;
1165
1166   if (!GV->hasAppendingLinkage()) return false;
1167
1168   assert(GV->hasInitializer() && "Not a special LLVM global!");
1169
1170   const TargetData *TD = TM.getTargetData();
1171   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
1172   if (GV->getName() == "llvm.global_ctors") {
1173     OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
1174     EmitAlignment(Align);
1175     EmitXXStructorList(GV->getInitializer());
1176
1177     if (TM.getRelocationModel() == Reloc::Static &&
1178         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1179       StringRef Sym(".constructors_used");
1180       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1181                                       MCSA_Reference);
1182     }
1183     return true;
1184   }
1185
1186   if (GV->getName() == "llvm.global_dtors") {
1187     OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
1188     EmitAlignment(Align);
1189     EmitXXStructorList(GV->getInitializer());
1190
1191     if (TM.getRelocationModel() == Reloc::Static &&
1192         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
1193       StringRef Sym(".destructors_used");
1194       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
1195                                       MCSA_Reference);
1196     }
1197     return true;
1198   }
1199
1200   return false;
1201 }
1202
1203 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
1204 /// global in the specified llvm.used list for which emitUsedDirectiveFor
1205 /// is true, as being used with this directive.
1206 void AsmPrinter::EmitLLVMUsedList(Constant *List) {
1207   // Should be an array of 'i8*'.
1208   ConstantArray *InitList = dyn_cast<ConstantArray>(List);
1209   if (InitList == 0) return;
1210
1211   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
1212     const GlobalValue *GV =
1213       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
1214     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
1215       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
1216   }
1217 }
1218
1219 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the
1220 /// function pointers, ignoring the init priority.
1221 void AsmPrinter::EmitXXStructorList(Constant *List) {
1222   // Should be an array of '{ int, void ()* }' structs.  The first value is the
1223   // init priority, which we ignore.
1224   if (!isa<ConstantArray>(List)) return;
1225   ConstantArray *InitList = cast<ConstantArray>(List);
1226   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
1227     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
1228       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
1229
1230       if (CS->getOperand(1)->isNullValue())
1231         return;  // Found a null terminator, exit printing.
1232       // Emit the function pointer.
1233       EmitGlobalConstant(CS->getOperand(1));
1234     }
1235 }
1236
1237 //===--------------------------------------------------------------------===//
1238 // Emission and print routines
1239 //
1240
1241 /// EmitInt8 - Emit a byte directive and value.
1242 ///
1243 void AsmPrinter::EmitInt8(int Value) const {
1244   OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
1245 }
1246
1247 /// EmitInt16 - Emit a short directive and value.
1248 ///
1249 void AsmPrinter::EmitInt16(int Value) const {
1250   OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
1251 }
1252
1253 /// EmitInt32 - Emit a long directive and value.
1254 ///
1255 void AsmPrinter::EmitInt32(int Value) const {
1256   OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
1257 }
1258
1259 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
1260 /// in bytes of the directive is specified by Size and Hi/Lo specify the
1261 /// labels.  This implicitly uses .set if it is available.
1262 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
1263                                      unsigned Size) const {
1264   // Get the Hi-Lo expression.
1265   const MCExpr *Diff =
1266     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
1267                             MCSymbolRefExpr::Create(Lo, OutContext),
1268                             OutContext);
1269
1270   if (!MAI->hasSetDirective()) {
1271     OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
1272     return;
1273   }
1274
1275   // Otherwise, emit with .set (aka assignment).
1276   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1277   OutStreamer.EmitAssignment(SetLabel, Diff);
1278   OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
1279 }
1280
1281 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
1282 /// where the size in bytes of the directive is specified by Size and Hi/Lo
1283 /// specify the labels.  This implicitly uses .set if it is available.
1284 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
1285                                            const MCSymbol *Lo, unsigned Size)
1286   const {
1287
1288   // Emit Hi+Offset - Lo
1289   // Get the Hi+Offset expression.
1290   const MCExpr *Plus =
1291     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
1292                             MCConstantExpr::Create(Offset, OutContext),
1293                             OutContext);
1294
1295   // Get the Hi+Offset-Lo expression.
1296   const MCExpr *Diff =
1297     MCBinaryExpr::CreateSub(Plus,
1298                             MCSymbolRefExpr::Create(Lo, OutContext),
1299                             OutContext);
1300
1301   if (!MAI->hasSetDirective())
1302     OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
1303   else {
1304     // Otherwise, emit with .set (aka assignment).
1305     MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
1306     OutStreamer.EmitAssignment(SetLabel, Diff);
1307     OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
1308   }
1309 }
1310
1311 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
1312 /// where the size in bytes of the directive is specified by Size and Label
1313 /// specifies the label.  This implicitly uses .set if it is available.
1314 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
1315                                       unsigned Size)
1316   const {
1317
1318   // Emit Label+Offset
1319   const MCExpr *Plus =
1320     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Label, OutContext),
1321                             MCConstantExpr::Create(Offset, OutContext),
1322                             OutContext);
1323
1324   OutStreamer.EmitValue(Plus, 4, 0/*AddrSpace*/);
1325 }
1326
1327
1328 //===----------------------------------------------------------------------===//
1329
1330 // EmitAlignment - Emit an alignment directive to the specified power of
1331 // two boundary.  For example, if you pass in 3 here, you will get an 8
1332 // byte alignment.  If a global value is specified, and if that global has
1333 // an explicit alignment requested, it will override the alignment request
1334 // if required for correctness.
1335 //
1336 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
1337   if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
1338
1339   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
1340
1341   if (getCurrentSection()->getKind().isText())
1342     OutStreamer.EmitCodeAlignment(1 << NumBits);
1343   else
1344     OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
1345 }
1346
1347 //===----------------------------------------------------------------------===//
1348 // Constant emission.
1349 //===----------------------------------------------------------------------===//
1350
1351 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
1352 ///
1353 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
1354   MCContext &Ctx = AP.OutContext;
1355
1356   if (CV->isNullValue() || isa<UndefValue>(CV))
1357     return MCConstantExpr::Create(0, Ctx);
1358
1359   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1360     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
1361
1362   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
1363     return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
1364
1365   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
1366     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
1367
1368   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
1369   if (CE == 0) {
1370     llvm_unreachable("Unknown constant value to lower!");
1371     return MCConstantExpr::Create(0, Ctx);
1372   }
1373
1374   switch (CE->getOpcode()) {
1375   default:
1376     // If the code isn't optimized, there may be outstanding folding
1377     // opportunities. Attempt to fold the expression using TargetData as a
1378     // last resort before giving up.
1379     if (Constant *C =
1380           ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
1381       if (C != CE)
1382         return LowerConstant(C, AP);
1383
1384     // Otherwise report the problem to the user.
1385     {
1386       std::string S;
1387       raw_string_ostream OS(S);
1388       OS << "Unsupported expression in static initializer: ";
1389       WriteAsOperand(OS, CE, /*PrintType=*/false,
1390                      !AP.MF ? 0 : AP.MF->getFunction()->getParent());
1391       report_fatal_error(OS.str());
1392     }
1393     return MCConstantExpr::Create(0, Ctx);
1394   case Instruction::GetElementPtr: {
1395     const TargetData &TD = *AP.TM.getTargetData();
1396     // Generate a symbolic expression for the byte address
1397     const Constant *PtrVal = CE->getOperand(0);
1398     SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
1399     int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0],
1400                                          IdxVec.size());
1401
1402     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
1403     if (Offset == 0)
1404       return Base;
1405
1406     // Truncate/sext the offset to the pointer size.
1407     if (TD.getPointerSizeInBits() != 64) {
1408       int SExtAmount = 64-TD.getPointerSizeInBits();
1409       Offset = (Offset << SExtAmount) >> SExtAmount;
1410     }
1411
1412     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
1413                                    Ctx);
1414   }
1415
1416   case Instruction::Trunc:
1417     // We emit the value and depend on the assembler to truncate the generated
1418     // expression properly.  This is important for differences between
1419     // blockaddress labels.  Since the two labels are in the same function, it
1420     // is reasonable to treat their delta as a 32-bit value.
1421     // FALL THROUGH.
1422   case Instruction::BitCast:
1423     return LowerConstant(CE->getOperand(0), AP);
1424
1425   case Instruction::IntToPtr: {
1426     const TargetData &TD = *AP.TM.getTargetData();
1427     // Handle casts to pointers by changing them into casts to the appropriate
1428     // integer type.  This promotes constant folding and simplifies this code.
1429     Constant *Op = CE->getOperand(0);
1430     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
1431                                       false/*ZExt*/);
1432     return LowerConstant(Op, AP);
1433   }
1434
1435   case Instruction::PtrToInt: {
1436     const TargetData &TD = *AP.TM.getTargetData();
1437     // Support only foldable casts to/from pointers that can be eliminated by
1438     // changing the pointer to the appropriately sized integer type.
1439     Constant *Op = CE->getOperand(0);
1440     const Type *Ty = CE->getType();
1441
1442     const MCExpr *OpExpr = LowerConstant(Op, AP);
1443
1444     // We can emit the pointer value into this slot if the slot is an
1445     // integer slot equal to the size of the pointer.
1446     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
1447       return OpExpr;
1448
1449     // Otherwise the pointer is smaller than the resultant integer, mask off
1450     // the high bits so we are sure to get a proper truncation if the input is
1451     // a constant expr.
1452     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
1453     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
1454     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
1455   }
1456
1457   // The MC library also has a right-shift operator, but it isn't consistently
1458   // signed or unsigned between different targets.
1459   case Instruction::Add:
1460   case Instruction::Sub:
1461   case Instruction::Mul:
1462   case Instruction::SDiv:
1463   case Instruction::SRem:
1464   case Instruction::Shl:
1465   case Instruction::And:
1466   case Instruction::Or:
1467   case Instruction::Xor: {
1468     const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
1469     const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
1470     switch (CE->getOpcode()) {
1471     default: llvm_unreachable("Unknown binary operator constant cast expr");
1472     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
1473     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
1474     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
1475     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
1476     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
1477     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
1478     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
1479     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
1480     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
1481     }
1482   }
1483   }
1484 }
1485
1486 static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
1487                                    AsmPrinter &AP);
1488
1489 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
1490                                     AsmPrinter &AP) {
1491   if (AddrSpace != 0 || !CA->isString()) {
1492     // Not a string.  Print the values in successive locations
1493     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1494       EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
1495     return;
1496   }
1497
1498   // Otherwise, it can be emitted as .ascii.
1499   SmallVector<char, 128> TmpVec;
1500   TmpVec.reserve(CA->getNumOperands());
1501   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1502     TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
1503
1504   AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
1505 }
1506
1507 static void EmitGlobalConstantVector(const ConstantVector *CV,
1508                                      unsigned AddrSpace, AsmPrinter &AP) {
1509   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
1510     EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
1511 }
1512
1513 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
1514                                      unsigned AddrSpace, AsmPrinter &AP) {
1515   // Print the fields in successive locations. Pad to align if needed!
1516   const TargetData *TD = AP.TM.getTargetData();
1517   unsigned Size = TD->getTypeAllocSize(CS->getType());
1518   const StructLayout *Layout = TD->getStructLayout(CS->getType());
1519   uint64_t SizeSoFar = 0;
1520   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
1521     const Constant *Field = CS->getOperand(i);
1522
1523     // Check if padding is needed and insert one or more 0s.
1524     uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
1525     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
1526                         - Layout->getElementOffset(i)) - FieldSize;
1527     SizeSoFar += FieldSize + PadSize;
1528
1529     // Now print the actual field value.
1530     EmitGlobalConstantImpl(Field, AddrSpace, AP);
1531
1532     // Insert padding - this may include padding to increase the size of the
1533     // current field up to the ABI size (if the struct is not packed) as well
1534     // as padding to ensure that the next field starts at the right offset.
1535     AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
1536   }
1537   assert(SizeSoFar == Layout->getSizeInBytes() &&
1538          "Layout of constant struct may be incorrect!");
1539 }
1540
1541 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
1542                                  AsmPrinter &AP) {
1543   // FP Constants are printed as integer constants to avoid losing
1544   // precision.
1545   if (CFP->getType()->isDoubleTy()) {
1546     if (AP.isVerbose()) {
1547       double Val = CFP->getValueAPF().convertToDouble();
1548       AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
1549     }
1550
1551     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1552     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1553     return;
1554   }
1555
1556   if (CFP->getType()->isFloatTy()) {
1557     if (AP.isVerbose()) {
1558       float Val = CFP->getValueAPF().convertToFloat();
1559       AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
1560     }
1561     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
1562     AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
1563     return;
1564   }
1565
1566   if (CFP->getType()->isX86_FP80Ty()) {
1567     // all long double variants are printed as hex
1568     // API needed to prevent premature destruction
1569     APInt API = CFP->getValueAPF().bitcastToAPInt();
1570     const uint64_t *p = API.getRawData();
1571     if (AP.isVerbose()) {
1572       // Convert to double so we can print the approximate val as a comment.
1573       APFloat DoubleVal = CFP->getValueAPF();
1574       bool ignored;
1575       DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1576                         &ignored);
1577       AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
1578         << DoubleVal.convertToDouble() << '\n';
1579     }
1580
1581     if (AP.TM.getTargetData()->isBigEndian()) {
1582       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1583       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1584     } else {
1585       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1586       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
1587     }
1588
1589     // Emit the tail padding for the long double.
1590     const TargetData &TD = *AP.TM.getTargetData();
1591     AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
1592                              TD.getTypeStoreSize(CFP->getType()), AddrSpace);
1593     return;
1594   }
1595
1596   assert(CFP->getType()->isPPC_FP128Ty() &&
1597          "Floating point constant type not handled");
1598   // All long double variants are printed as hex
1599   // API needed to prevent premature destruction.
1600   APInt API = CFP->getValueAPF().bitcastToAPInt();
1601   const uint64_t *p = API.getRawData();
1602   if (AP.TM.getTargetData()->isBigEndian()) {
1603     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1604     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1605   } else {
1606     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
1607     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
1608   }
1609 }
1610
1611 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
1612                                        unsigned AddrSpace, AsmPrinter &AP) {
1613   const TargetData *TD = AP.TM.getTargetData();
1614   unsigned BitWidth = CI->getBitWidth();
1615   assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
1616
1617   // We don't expect assemblers to support integer data directives
1618   // for more than 64 bits, so we emit the data in at most 64-bit
1619   // quantities at a time.
1620   const uint64_t *RawData = CI->getValue().getRawData();
1621   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
1622     uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
1623     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
1624   }
1625 }
1626
1627 static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
1628                                    AsmPrinter &AP) {
1629   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
1630     uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1631     return AP.OutStreamer.EmitZeros(Size, AddrSpace);
1632   }
1633
1634   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
1635     unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1636     switch (Size) {
1637     case 1:
1638     case 2:
1639     case 4:
1640     case 8:
1641       if (AP.isVerbose())
1642         AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
1643       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
1644       return;
1645     default:
1646       EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
1647       return;
1648     }
1649   }
1650
1651   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
1652     return EmitGlobalConstantArray(CVA, AddrSpace, AP);
1653
1654   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
1655     return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
1656
1657   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
1658     return EmitGlobalConstantFP(CFP, AddrSpace, AP);
1659
1660   if (isa<ConstantPointerNull>(CV)) {
1661     unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
1662     AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
1663     return;
1664   }
1665
1666   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
1667     return EmitGlobalConstantVector(V, AddrSpace, AP);
1668
1669   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
1670   // thread the streamer with EmitValue.
1671   AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
1672                          AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
1673                            AddrSpace);
1674 }
1675
1676 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
1677 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
1678   uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
1679   if (Size)
1680     EmitGlobalConstantImpl(CV, AddrSpace, *this);
1681   else if (MAI->hasSubsectionsViaSymbols()) {
1682     // If the global has zero size, emit a single byte so that two labels don't
1683     // look like they are at the same location.
1684     OutStreamer.EmitIntValue(0, 1, AddrSpace);
1685   }
1686 }
1687
1688 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
1689   // Target doesn't support this yet!
1690   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
1691 }
1692
1693 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
1694   if (Offset > 0)
1695     OS << '+' << Offset;
1696   else if (Offset < 0)
1697     OS << Offset;
1698 }
1699
1700 //===----------------------------------------------------------------------===//
1701 // Symbol Lowering Routines.
1702 //===----------------------------------------------------------------------===//
1703
1704 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
1705 /// temporary label with the specified stem and unique ID.
1706 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
1707   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
1708                                       Name + Twine(ID));
1709 }
1710
1711 /// GetTempSymbol - Return an assembler temporary label with the specified
1712 /// stem.
1713 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
1714   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
1715                                       Name);
1716 }
1717
1718
1719 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
1720   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
1721 }
1722
1723 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
1724   return MMI->getAddrLabelSymbol(BB);
1725 }
1726
1727 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
1728 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
1729   return OutContext.GetOrCreateSymbol
1730     (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
1731      + "_" + Twine(CPID));
1732 }
1733
1734 /// GetJTISymbol - Return the symbol for the specified jump table entry.
1735 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
1736   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
1737 }
1738
1739 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
1740 /// FIXME: privatize to AsmPrinter.
1741 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
1742   return OutContext.GetOrCreateSymbol
1743   (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
1744    Twine(UID) + "_set_" + Twine(MBBID));
1745 }
1746
1747 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
1748 /// global value name as its base, with the specified suffix, and where the
1749 /// symbol is forced to have private linkage if ForcePrivate is true.
1750 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
1751                                                    StringRef Suffix,
1752                                                    bool ForcePrivate) const {
1753   SmallString<60> NameStr;
1754   Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
1755   NameStr.append(Suffix.begin(), Suffix.end());
1756   return OutContext.GetOrCreateSymbol(NameStr.str());
1757 }
1758
1759 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
1760 /// ExternalSymbol.
1761 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
1762   SmallString<60> NameStr;
1763   Mang->getNameWithPrefix(NameStr, Sym);
1764   return OutContext.GetOrCreateSymbol(NameStr.str());
1765 }
1766
1767
1768
1769 /// PrintParentLoopComment - Print comments about parent loops of this one.
1770 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1771                                    unsigned FunctionNumber) {
1772   if (Loop == 0) return;
1773   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
1774   OS.indent(Loop->getLoopDepth()*2)
1775     << "Parent Loop BB" << FunctionNumber << "_"
1776     << Loop->getHeader()->getNumber()
1777     << " Depth=" << Loop->getLoopDepth() << '\n';
1778 }
1779
1780
1781 /// PrintChildLoopComment - Print comments about child loops within
1782 /// the loop for this basic block, with nesting.
1783 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
1784                                   unsigned FunctionNumber) {
1785   // Add child loop information
1786   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
1787     OS.indent((*CL)->getLoopDepth()*2)
1788       << "Child Loop BB" << FunctionNumber << "_"
1789       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
1790       << '\n';
1791     PrintChildLoopComment(OS, *CL, FunctionNumber);
1792   }
1793 }
1794
1795 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
1796 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
1797                                        const MachineLoopInfo *LI,
1798                                        const AsmPrinter &AP) {
1799   // Add loop depth information
1800   const MachineLoop *Loop = LI->getLoopFor(&MBB);
1801   if (Loop == 0) return;
1802
1803   MachineBasicBlock *Header = Loop->getHeader();
1804   assert(Header && "No header for loop");
1805
1806   // If this block is not a loop header, just print out what is the loop header
1807   // and return.
1808   if (Header != &MBB) {
1809     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
1810                               Twine(AP.getFunctionNumber())+"_" +
1811                               Twine(Loop->getHeader()->getNumber())+
1812                               " Depth="+Twine(Loop->getLoopDepth()));
1813     return;
1814   }
1815
1816   // Otherwise, it is a loop header.  Print out information about child and
1817   // parent loops.
1818   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
1819
1820   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
1821
1822   OS << "=>";
1823   OS.indent(Loop->getLoopDepth()*2-2);
1824
1825   OS << "This ";
1826   if (Loop->empty())
1827     OS << "Inner ";
1828   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
1829
1830   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
1831 }
1832
1833
1834 /// EmitBasicBlockStart - This method prints the label for the specified
1835 /// MachineBasicBlock, an alignment (if present) and a comment describing
1836 /// it if appropriate.
1837 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
1838   // Emit an alignment directive for this block, if needed.
1839   if (unsigned Align = MBB->getAlignment())
1840     EmitAlignment(Log2_32(Align));
1841
1842   // If the block has its address taken, emit any labels that were used to
1843   // reference the block.  It is possible that there is more than one label
1844   // here, because multiple LLVM BB's may have been RAUW'd to this block after
1845   // the references were generated.
1846   if (MBB->hasAddressTaken()) {
1847     const BasicBlock *BB = MBB->getBasicBlock();
1848     if (isVerbose())
1849       OutStreamer.AddComment("Block address taken");
1850
1851     std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
1852
1853     for (unsigned i = 0, e = Syms.size(); i != e; ++i)
1854       OutStreamer.EmitLabel(Syms[i]);
1855   }
1856
1857   // Print the main label for the block.
1858   if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
1859     if (isVerbose() && OutStreamer.hasRawTextSupport()) {
1860       if (const BasicBlock *BB = MBB->getBasicBlock())
1861         if (BB->hasName())
1862           OutStreamer.AddComment("%" + BB->getName());
1863
1864       EmitBasicBlockLoopComments(*MBB, LI, *this);
1865
1866       // NOTE: Want this comment at start of line, don't emit with AddComment.
1867       OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
1868                               Twine(MBB->getNumber()) + ":");
1869     }
1870   } else {
1871     if (isVerbose()) {
1872       if (const BasicBlock *BB = MBB->getBasicBlock())
1873         if (BB->hasName())
1874           OutStreamer.AddComment("%" + BB->getName());
1875       EmitBasicBlockLoopComments(*MBB, LI, *this);
1876     }
1877
1878     OutStreamer.EmitLabel(MBB->getSymbol());
1879   }
1880 }
1881
1882 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
1883                                 bool IsDefinition) const {
1884   MCSymbolAttr Attr = MCSA_Invalid;
1885
1886   switch (Visibility) {
1887   default: break;
1888   case GlobalValue::HiddenVisibility:
1889     if (IsDefinition)
1890       Attr = MAI->getHiddenVisibilityAttr();
1891     else
1892       Attr = MAI->getHiddenDeclarationVisibilityAttr();
1893     break;
1894   case GlobalValue::ProtectedVisibility:
1895     Attr = MAI->getProtectedVisibilityAttr();
1896     break;
1897   }
1898
1899   if (Attr != MCSA_Invalid)
1900     OutStreamer.EmitSymbolAttribute(Sym, Attr);
1901 }
1902
1903 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
1904 /// exactly one predecessor and the control transfer mechanism between
1905 /// the predecessor and this block is a fall-through.
1906 bool AsmPrinter::
1907 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
1908   // If this is a landing pad, it isn't a fall through.  If it has no preds,
1909   // then nothing falls through to it.
1910   if (MBB->isLandingPad() || MBB->pred_empty())
1911     return false;
1912
1913   // If there isn't exactly one predecessor, it can't be a fall through.
1914   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
1915   ++PI2;
1916   if (PI2 != MBB->pred_end())
1917     return false;
1918
1919   // The predecessor has to be immediately before this block.
1920   const MachineBasicBlock *Pred = *PI;
1921
1922   if (!Pred->isLayoutSuccessor(MBB))
1923     return false;
1924
1925   // If the block is completely empty, then it definitely does fall through.
1926   if (Pred->empty())
1927     return true;
1928
1929   // Otherwise, check the last instruction.
1930   const MachineInstr &LastInst = Pred->back();
1931   return !LastInst.getDesc().isBarrier();
1932 }
1933
1934
1935
1936 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
1937   if (!S->usesMetadata())
1938     return 0;
1939
1940   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
1941   gcp_map_type::iterator GCPI = GCMap.find(S);
1942   if (GCPI != GCMap.end())
1943     return GCPI->second;
1944
1945   const char *Name = S->getName().c_str();
1946
1947   for (GCMetadataPrinterRegistry::iterator
1948          I = GCMetadataPrinterRegistry::begin(),
1949          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
1950     if (strcmp(Name, I->getName()) == 0) {
1951       GCMetadataPrinter *GMP = I->instantiate();
1952       GMP->S = S;
1953       GCMap.insert(std::make_pair(S, GMP));
1954       return GMP;
1955     }
1956
1957   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
1958   return 0;
1959 }
1960