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