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