LLVM API Documentation

AsmPrinter.cpp
Go to the documentation of this file.
00001 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the AsmPrinter class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #define DEBUG_TYPE "asm-printer"
00015 #include "llvm/CodeGen/AsmPrinter.h"
00016 #include "DwarfDebug.h"
00017 #include "DwarfException.h"
00018 #include "WinCodeViewLineTables.h"
00019 #include "llvm/ADT/SmallString.h"
00020 #include "llvm/ADT/Statistic.h"
00021 #include "llvm/Analysis/ConstantFolding.h"
00022 #include "llvm/CodeGen/GCMetadataPrinter.h"
00023 #include "llvm/CodeGen/MachineConstantPool.h"
00024 #include "llvm/CodeGen/MachineFrameInfo.h"
00025 #include "llvm/CodeGen/MachineFunction.h"
00026 #include "llvm/CodeGen/MachineInstrBundle.h"
00027 #include "llvm/CodeGen/MachineJumpTableInfo.h"
00028 #include "llvm/CodeGen/MachineLoopInfo.h"
00029 #include "llvm/CodeGen/MachineModuleInfo.h"
00030 #include "llvm/IR/DataLayout.h"
00031 #include "llvm/IR/DebugInfo.h"
00032 #include "llvm/IR/Mangler.h"
00033 #include "llvm/IR/Module.h"
00034 #include "llvm/IR/Operator.h"
00035 #include "llvm/MC/MCAsmInfo.h"
00036 #include "llvm/MC/MCContext.h"
00037 #include "llvm/MC/MCExpr.h"
00038 #include "llvm/MC/MCInst.h"
00039 #include "llvm/MC/MCSection.h"
00040 #include "llvm/MC/MCStreamer.h"
00041 #include "llvm/MC/MCSymbol.h"
00042 #include "llvm/Support/ErrorHandling.h"
00043 #include "llvm/Support/Format.h"
00044 #include "llvm/Support/MathExtras.h"
00045 #include "llvm/Support/Timer.h"
00046 #include "llvm/Target/TargetFrameLowering.h"
00047 #include "llvm/Target/TargetInstrInfo.h"
00048 #include "llvm/Target/TargetLowering.h"
00049 #include "llvm/Target/TargetLoweringObjectFile.h"
00050 #include "llvm/Target/TargetOptions.h"
00051 #include "llvm/Target/TargetRegisterInfo.h"
00052 #include "llvm/Target/TargetSubtargetInfo.h"
00053 #include "llvm/Transforms/Utils/GlobalStatus.h"
00054 using namespace llvm;
00055 
00056 static const char *const DWARFGroupName = "DWARF Emission";
00057 static const char *const DbgTimerName = "Debug Info Emission";
00058 static const char *const EHTimerName = "DWARF Exception Writer";
00059 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables";
00060 
00061 STATISTIC(EmittedInsts, "Number of machine instrs printed");
00062 
00063 char AsmPrinter::ID = 0;
00064 
00065 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type;
00066 static gcp_map_type &getGCMap(void *&P) {
00067   if (P == 0)
00068     P = new gcp_map_type();
00069   return *(gcp_map_type*)P;
00070 }
00071 
00072 
00073 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
00074 /// value in log2 form.  This rounds up to the preferred alignment if possible
00075 /// and legal.
00076 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &TD,
00077                                    unsigned InBits = 0) {
00078   unsigned NumBits = 0;
00079   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
00080     NumBits = TD.getPreferredAlignmentLog(GVar);
00081 
00082   // If InBits is specified, round it to it.
00083   if (InBits > NumBits)
00084     NumBits = InBits;
00085 
00086   // If the GV has a specified alignment, take it into account.
00087   if (GV->getAlignment() == 0)
00088     return NumBits;
00089 
00090   unsigned GVAlign = Log2_32(GV->getAlignment());
00091 
00092   // If the GVAlign is larger than NumBits, or if we are required to obey
00093   // NumBits because the GV has an assigned section, obey it.
00094   if (GVAlign > NumBits || GV->hasSection())
00095     NumBits = GVAlign;
00096   return NumBits;
00097 }
00098 
00099 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
00100   : MachineFunctionPass(ID),
00101     TM(tm), MAI(tm.getMCAsmInfo()), MII(tm.getInstrInfo()),
00102     OutContext(Streamer.getContext()),
00103     OutStreamer(Streamer),
00104     LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
00105   DD = 0; MMI = 0; LI = 0; MF = 0;
00106   CurrentFnSym = CurrentFnSymForSize = 0;
00107   GCMetadataPrinters = 0;
00108   VerboseAsm = Streamer.isVerboseAsm();
00109 }
00110 
00111 AsmPrinter::~AsmPrinter() {
00112   assert(DD == 0 && Handlers.empty() && "Debug/EH info didn't get finalized");
00113 
00114   if (GCMetadataPrinters != 0) {
00115     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
00116 
00117     delete &GCMap;
00118     GCMetadataPrinters = 0;
00119   }
00120 
00121   delete &OutStreamer;
00122 }
00123 
00124 /// getFunctionNumber - Return a unique ID for the current function.
00125 ///
00126 unsigned AsmPrinter::getFunctionNumber() const {
00127   return MF->getFunctionNumber();
00128 }
00129 
00130 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
00131   return TM.getTargetLowering()->getObjFileLowering();
00132 }
00133 
00134 /// getDataLayout - Return information about data layout.
00135 const DataLayout &AsmPrinter::getDataLayout() const {
00136   return *TM.getDataLayout();
00137 }
00138 
00139 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
00140   return TM.getSubtarget<MCSubtargetInfo>();
00141 }
00142 
00143 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
00144   S.EmitInstruction(Inst, getSubtargetInfo());
00145 }
00146 
00147 StringRef AsmPrinter::getTargetTriple() const {
00148   return TM.getTargetTriple();
00149 }
00150 
00151 /// getCurrentSection() - Return the current section we are emitting to.
00152 const MCSection *AsmPrinter::getCurrentSection() const {
00153   return OutStreamer.getCurrentSection().first;
00154 }
00155 
00156 
00157 
00158 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
00159   AU.setPreservesAll();
00160   MachineFunctionPass::getAnalysisUsage(AU);
00161   AU.addRequired<MachineModuleInfo>();
00162   AU.addRequired<GCModuleInfo>();
00163   if (isVerbose())
00164     AU.addRequired<MachineLoopInfo>();
00165 }
00166 
00167 bool AsmPrinter::doInitialization(Module &M) {
00168   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
00169   MMI->AnalyzeModule(M);
00170 
00171   // Initialize TargetLoweringObjectFile.
00172   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
00173     .Initialize(OutContext, TM);
00174 
00175   OutStreamer.InitSections();
00176 
00177   Mang = new Mangler(TM.getDataLayout());
00178 
00179   // Emit the version-min deplyment target directive if needed.
00180   //
00181   // FIXME: If we end up with a collection of these sorts of Darwin-specific
00182   // or ELF-specific things, it may make sense to have a platform helper class
00183   // that will work with the target helper class. For now keep it here, as the
00184   // alternative is duplicated code in each of the target asm printers that
00185   // use the directive, where it would need the same conditionalization
00186   // anyway.
00187   Triple TT(getTargetTriple());
00188   if (TT.isOSDarwin()) {
00189     unsigned Major, Minor, Update;
00190     TT.getOSVersion(Major, Minor, Update);
00191     // If there is a version specified, Major will be non-zero.
00192     if (Major)
00193       OutStreamer.EmitVersionMin((TT.isMacOSX() ?
00194                                   MCVM_OSXVersionMin : MCVM_IOSVersionMin),
00195                                  Major, Minor, Update);
00196   }
00197 
00198   // Allow the target to emit any magic that it wants at the start of the file.
00199   EmitStartOfAsmFile(M);
00200 
00201   // Very minimal debug info. It is ignored if we emit actual debug info. If we
00202   // don't, this at least helps the user find where a global came from.
00203   if (MAI->hasSingleParameterDotFile()) {
00204     // .file "foo.c"
00205     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
00206   }
00207 
00208   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
00209   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
00210   for (auto &I : *MI)
00211     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
00212       MP->beginAssembly(*this);
00213 
00214   // Emit module-level inline asm if it exists.
00215   if (!M.getModuleInlineAsm().empty()) {
00216     OutStreamer.AddComment("Start of file scope inline assembly");
00217     OutStreamer.AddBlankLine();
00218     EmitInlineAsm(M.getModuleInlineAsm()+"\n");
00219     OutStreamer.AddComment("End of file scope inline assembly");
00220     OutStreamer.AddBlankLine();
00221   }
00222 
00223   if (MAI->doesSupportDebugInformation()) {
00224     if (Triple(TM.getTargetTriple()).isKnownWindowsMSVCEnvironment()) {
00225       Handlers.push_back(HandlerInfo(new WinCodeViewLineTables(this),
00226                                      DbgTimerName,
00227                                      CodeViewLineTablesGroupName));
00228     } else {
00229       DD = new DwarfDebug(this, &M);
00230       Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
00231     }
00232   }
00233 
00234   DwarfException *DE = 0;
00235   switch (MAI->getExceptionHandlingType()) {
00236   case ExceptionHandling::None:
00237     break;
00238   case ExceptionHandling::SjLj:
00239   case ExceptionHandling::DwarfCFI:
00240     DE = new DwarfCFIException(this);
00241     break;
00242   case ExceptionHandling::ARM:
00243     DE = new ARMException(this);
00244     break;
00245   case ExceptionHandling::Win64:
00246     DE = new Win64Exception(this);
00247     break;
00248   }
00249   if (DE)
00250     Handlers.push_back(HandlerInfo(DE, EHTimerName, DWARFGroupName));
00251   return false;
00252 }
00253 
00254 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
00255   GlobalValue::LinkageTypes Linkage = GV->getLinkage();
00256   if (Linkage != GlobalValue::LinkOnceODRLinkage)
00257     return false;
00258 
00259   if (!MAI.hasWeakDefCanBeHiddenDirective())
00260     return false;
00261 
00262   if (GV->hasUnnamedAddr())
00263     return true;
00264 
00265   // This is only used for MachO, so right now it doesn't really matter how
00266   // we handle alias. Revisit this once the MachO linker implements aliases.
00267   if (isa<GlobalAlias>(GV))
00268     return false;
00269 
00270   // If it is a non constant variable, it needs to be uniqued across shared
00271   // objects.
00272   if (const GlobalVariable *Var = dyn_cast<GlobalVariable>(GV)) {
00273     if (!Var->isConstant())
00274       return false;
00275   }
00276 
00277   GlobalStatus GS;
00278   if (!GlobalStatus::analyzeGlobal(GV, GS) && !GS.IsCompared)
00279     return true;
00280 
00281   return false;
00282 }
00283 
00284 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
00285   GlobalValue::LinkageTypes Linkage = GV->getLinkage();
00286   switch (Linkage) {
00287   case GlobalValue::CommonLinkage:
00288   case GlobalValue::LinkOnceAnyLinkage:
00289   case GlobalValue::LinkOnceODRLinkage:
00290   case GlobalValue::WeakAnyLinkage:
00291   case GlobalValue::WeakODRLinkage:
00292     if (MAI->hasWeakDefDirective()) {
00293       // .globl _foo
00294       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
00295 
00296       if (!canBeHidden(GV, *MAI))
00297         // .weak_definition _foo
00298         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
00299       else
00300         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
00301     } else if (MAI->hasLinkOnceDirective()) {
00302       // .globl _foo
00303       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
00304       //NOTE: linkonce is handled by the section the symbol was assigned to.
00305     } else {
00306       // .weak _foo
00307       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
00308     }
00309     return;
00310   case GlobalValue::AppendingLinkage:
00311     // FIXME: appending linkage variables should go into a section of
00312     // their name or something.  For now, just emit them as external.
00313   case GlobalValue::ExternalLinkage:
00314     // If external or appending, declare as a global symbol.
00315     // .globl _foo
00316     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
00317     return;
00318   case GlobalValue::PrivateLinkage:
00319   case GlobalValue::InternalLinkage:
00320     return;
00321   case GlobalValue::AvailableExternallyLinkage:
00322     llvm_unreachable("Should never emit this");
00323   case GlobalValue::ExternalWeakLinkage:
00324     llvm_unreachable("Don't know how to emit these");
00325   }
00326   llvm_unreachable("Unknown linkage type!");
00327 }
00328 
00329 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
00330                                    const GlobalValue *GV) const {
00331   TM.getNameWithPrefix(Name, GV, *Mang);
00332 }
00333 
00334 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
00335   return TM.getSymbol(GV, *Mang);
00336 }
00337 
00338 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
00339 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
00340   if (GV->hasInitializer()) {
00341     // Check to see if this is a special global used by LLVM, if so, emit it.
00342     if (EmitSpecialLLVMGlobal(GV))
00343       return;
00344 
00345     if (isVerbose()) {
00346       GV->printAsOperand(OutStreamer.GetCommentOS(),
00347                      /*PrintType=*/false, GV->getParent());
00348       OutStreamer.GetCommentOS() << '\n';
00349     }
00350   }
00351 
00352   MCSymbol *GVSym = getSymbol(GV);
00353   EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
00354 
00355   if (!GV->hasInitializer())   // External globals require no extra code.
00356     return;
00357 
00358   if (MAI->hasDotTypeDotSizeDirective())
00359     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
00360 
00361   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
00362 
00363   const DataLayout *DL = TM.getDataLayout();
00364   uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
00365 
00366   // If the alignment is specified, we *must* obey it.  Overaligning a global
00367   // with a specified alignment is a prompt way to break globals emitted to
00368   // sections and expected to be contiguous (e.g. ObjC metadata).
00369   unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
00370 
00371   for (const HandlerInfo &HI : Handlers) {
00372     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
00373     HI.Handler->setSymbolSize(GVSym, Size);
00374   }
00375 
00376   // Handle common and BSS local symbols (.lcomm).
00377   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
00378     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
00379     unsigned Align = 1 << AlignLog;
00380 
00381     // Handle common symbols.
00382     if (GVKind.isCommon()) {
00383       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
00384         Align = 0;
00385 
00386       // .comm _foo, 42, 4
00387       OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
00388       return;
00389     }
00390 
00391     // Handle local BSS symbols.
00392     if (MAI->hasMachoZeroFillDirective()) {
00393       const MCSection *TheSection =
00394         getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
00395       // .zerofill __DATA, __bss, _foo, 400, 5
00396       OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
00397       return;
00398     }
00399 
00400     // Use .lcomm only if it supports user-specified alignment.
00401     // Otherwise, while it would still be correct to use .lcomm in some
00402     // cases (e.g. when Align == 1), the external assembler might enfore
00403     // some -unknown- default alignment behavior, which could cause
00404     // spurious differences between external and integrated assembler.
00405     // Prefer to simply fall back to .local / .comm in this case.
00406     if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
00407       // .lcomm _foo, 42
00408       OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
00409       return;
00410     }
00411 
00412     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
00413       Align = 0;
00414 
00415     // .local _foo
00416     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
00417     // .comm _foo, 42, 4
00418     OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
00419     return;
00420   }
00421 
00422   const MCSection *TheSection =
00423     getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
00424 
00425   // Handle the zerofill directive on darwin, which is a special form of BSS
00426   // emission.
00427   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
00428     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
00429 
00430     // .globl _foo
00431     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
00432     // .zerofill __DATA, __common, _foo, 400, 5
00433     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
00434     return;
00435   }
00436 
00437   // Handle thread local data for mach-o which requires us to output an
00438   // additional structure of data and mangle the original symbol so that we
00439   // can reference it later.
00440   //
00441   // TODO: This should become an "emit thread local global" method on TLOF.
00442   // All of this macho specific stuff should be sunk down into TLOFMachO and
00443   // stuff like "TLSExtraDataSection" should no longer be part of the parent
00444   // TLOF class.  This will also make it more obvious that stuff like
00445   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
00446   // specific code.
00447   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
00448     // Emit the .tbss symbol
00449     MCSymbol *MangSym =
00450       OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
00451 
00452     if (GVKind.isThreadBSS()) {
00453       TheSection = getObjFileLowering().getTLSBSSSection();
00454       OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
00455     } else if (GVKind.isThreadData()) {
00456       OutStreamer.SwitchSection(TheSection);
00457 
00458       EmitAlignment(AlignLog, GV);
00459       OutStreamer.EmitLabel(MangSym);
00460 
00461       EmitGlobalConstant(GV->getInitializer());
00462     }
00463 
00464     OutStreamer.AddBlankLine();
00465 
00466     // Emit the variable struct for the runtime.
00467     const MCSection *TLVSect
00468       = getObjFileLowering().getTLSExtraDataSection();
00469 
00470     OutStreamer.SwitchSection(TLVSect);
00471     // Emit the linkage here.
00472     EmitLinkage(GV, GVSym);
00473     OutStreamer.EmitLabel(GVSym);
00474 
00475     // Three pointers in size:
00476     //   - __tlv_bootstrap - used to make sure support exists
00477     //   - spare pointer, used when mapped by the runtime
00478     //   - pointer to mangled symbol above with initializer
00479     unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
00480     OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
00481                                 PtrSize);
00482     OutStreamer.EmitIntValue(0, PtrSize);
00483     OutStreamer.EmitSymbolValue(MangSym, PtrSize);
00484 
00485     OutStreamer.AddBlankLine();
00486     return;
00487   }
00488 
00489   OutStreamer.SwitchSection(TheSection);
00490 
00491   EmitLinkage(GV, GVSym);
00492   EmitAlignment(AlignLog, GV);
00493 
00494   OutStreamer.EmitLabel(GVSym);
00495 
00496   EmitGlobalConstant(GV->getInitializer());
00497 
00498   if (MAI->hasDotTypeDotSizeDirective())
00499     // .size foo, 42
00500     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
00501 
00502   OutStreamer.AddBlankLine();
00503 }
00504 
00505 /// EmitFunctionHeader - This method emits the header for the current
00506 /// function.
00507 void AsmPrinter::EmitFunctionHeader() {
00508   // Print out constants referenced by the function
00509   EmitConstantPool();
00510 
00511   // Print the 'header' of function.
00512   const Function *F = MF->getFunction();
00513 
00514   OutStreamer.SwitchSection(
00515       getObjFileLowering().SectionForGlobal(F, *Mang, TM));
00516   EmitVisibility(CurrentFnSym, F->getVisibility());
00517 
00518   EmitLinkage(F, CurrentFnSym);
00519   EmitAlignment(MF->getAlignment(), F);
00520 
00521   if (MAI->hasDotTypeDotSizeDirective())
00522     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
00523 
00524   if (isVerbose()) {
00525     F->printAsOperand(OutStreamer.GetCommentOS(),
00526                    /*PrintType=*/false, F->getParent());
00527     OutStreamer.GetCommentOS() << '\n';
00528   }
00529 
00530   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
00531   // do their wild and crazy things as required.
00532   EmitFunctionEntryLabel();
00533 
00534   // If the function had address-taken blocks that got deleted, then we have
00535   // references to the dangling symbols.  Emit them at the start of the function
00536   // so that we don't get references to undefined symbols.
00537   std::vector<MCSymbol*> DeadBlockSyms;
00538   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
00539   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
00540     OutStreamer.AddComment("Address taken block that was later removed");
00541     OutStreamer.EmitLabel(DeadBlockSyms[i]);
00542   }
00543 
00544   // Emit pre-function debug and/or EH information.
00545   for (const HandlerInfo &HI : Handlers) {
00546     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
00547     HI.Handler->beginFunction(MF);
00548   }
00549 
00550   // Emit the prefix data.
00551   if (F->hasPrefixData())
00552     EmitGlobalConstant(F->getPrefixData());
00553 }
00554 
00555 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
00556 /// function.  This can be overridden by targets as required to do custom stuff.
00557 void AsmPrinter::EmitFunctionEntryLabel() {
00558   // The function label could have already been emitted if two symbols end up
00559   // conflicting due to asm renaming.  Detect this and emit an error.
00560   if (CurrentFnSym->isUndefined())
00561     return OutStreamer.EmitLabel(CurrentFnSym);
00562 
00563   report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
00564                      "' label emitted multiple times to assembly file");
00565 }
00566 
00567 /// emitComments - Pretty-print comments for instructions.
00568 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
00569   const MachineFunction *MF = MI.getParent()->getParent();
00570   const TargetMachine &TM = MF->getTarget();
00571 
00572   // Check for spills and reloads
00573   int FI;
00574 
00575   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
00576 
00577   // We assume a single instruction only has a spill or reload, not
00578   // both.
00579   const MachineMemOperand *MMO;
00580   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
00581     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
00582       MMO = *MI.memoperands_begin();
00583       CommentOS << MMO->getSize() << "-byte Reload\n";
00584     }
00585   } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
00586     if (FrameInfo->isSpillSlotObjectIndex(FI))
00587       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
00588   } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
00589     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
00590       MMO = *MI.memoperands_begin();
00591       CommentOS << MMO->getSize() << "-byte Spill\n";
00592     }
00593   } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
00594     if (FrameInfo->isSpillSlotObjectIndex(FI))
00595       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
00596   }
00597 
00598   // Check for spill-induced copies
00599   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
00600     CommentOS << " Reload Reuse\n";
00601 }
00602 
00603 /// emitImplicitDef - This method emits the specified machine instruction
00604 /// that is an implicit def.
00605 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
00606   unsigned RegNo = MI->getOperand(0).getReg();
00607   OutStreamer.AddComment(Twine("implicit-def: ") +
00608                          TM.getRegisterInfo()->getName(RegNo));
00609   OutStreamer.AddBlankLine();
00610 }
00611 
00612 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
00613   std::string Str = "kill:";
00614   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00615     const MachineOperand &Op = MI->getOperand(i);
00616     assert(Op.isReg() && "KILL instruction must have only register operands");
00617     Str += ' ';
00618     Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
00619     Str += (Op.isDef() ? "<def>" : "<kill>");
00620   }
00621   AP.OutStreamer.AddComment(Str);
00622   AP.OutStreamer.AddBlankLine();
00623 }
00624 
00625 /// emitDebugValueComment - This method handles the target-independent form
00626 /// of DBG_VALUE, returning true if it was able to do so.  A false return
00627 /// means the target will need to handle MI in EmitInstruction.
00628 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
00629   // This code handles only the 3-operand target-independent form.
00630   if (MI->getNumOperands() != 3)
00631     return false;
00632 
00633   SmallString<128> Str;
00634   raw_svector_ostream OS(Str);
00635   OS << "DEBUG_VALUE: ";
00636 
00637   DIVariable V(MI->getOperand(2).getMetadata());
00638   if (V.getContext().isSubprogram()) {
00639     StringRef Name = DISubprogram(V.getContext()).getDisplayName();
00640     if (!Name.empty())
00641       OS << Name << ":";
00642   }
00643   OS << V.getName() << " <- ";
00644 
00645   // The second operand is only an offset if it's an immediate.
00646   bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
00647   int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0;
00648 
00649   // Register or immediate value. Register 0 means undef.
00650   if (MI->getOperand(0).isFPImm()) {
00651     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
00652     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
00653       OS << (double)APF.convertToFloat();
00654     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
00655       OS << APF.convertToDouble();
00656     } else {
00657       // There is no good way to print long double.  Convert a copy to
00658       // double.  Ah well, it's only a comment.
00659       bool ignored;
00660       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
00661                   &ignored);
00662       OS << "(long double) " << APF.convertToDouble();
00663     }
00664   } else if (MI->getOperand(0).isImm()) {
00665     OS << MI->getOperand(0).getImm();
00666   } else if (MI->getOperand(0).isCImm()) {
00667     MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
00668   } else {
00669     unsigned Reg;
00670     if (MI->getOperand(0).isReg()) {
00671       Reg = MI->getOperand(0).getReg();
00672     } else {
00673       assert(MI->getOperand(0).isFI() && "Unknown operand type");
00674       const TargetFrameLowering *TFI = AP.TM.getFrameLowering();
00675       Offset += TFI->getFrameIndexReference(*AP.MF,
00676                                             MI->getOperand(0).getIndex(), Reg);
00677       Deref = true;
00678     }
00679     if (Reg == 0) {
00680       // Suppress offset, it is not meaningful here.
00681       OS << "undef";
00682       // NOTE: Want this comment at start of line, don't emit with AddComment.
00683       AP.OutStreamer.emitRawComment(OS.str());
00684       return true;
00685     }
00686     if (Deref)
00687       OS << '[';
00688     OS << AP.TM.getRegisterInfo()->getName(Reg);
00689   }
00690 
00691   if (Deref)
00692     OS << '+' << Offset << ']';
00693 
00694   // NOTE: Want this comment at start of line, don't emit with AddComment.
00695   AP.OutStreamer.emitRawComment(OS.str());
00696   return true;
00697 }
00698 
00699 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
00700   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
00701       MF->getFunction()->needsUnwindTableEntry())
00702     return CFI_M_EH;
00703 
00704   if (MMI->hasDebugInfo())
00705     return CFI_M_Debug;
00706 
00707   return CFI_M_None;
00708 }
00709 
00710 bool AsmPrinter::needsSEHMoves() {
00711   return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
00712     MF->getFunction()->needsUnwindTableEntry();
00713 }
00714 
00715 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
00716   ExceptionHandling::ExceptionsType ExceptionHandlingType =
00717       MAI->getExceptionHandlingType();
00718   if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
00719       ExceptionHandlingType != ExceptionHandling::ARM)
00720     return;
00721 
00722   if (needsCFIMoves() == CFI_M_None)
00723     return;
00724 
00725   if (MMI->getCompactUnwindEncoding() != 0)
00726     OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
00727 
00728   const MachineModuleInfo &MMI = MF->getMMI();
00729   const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions();
00730   unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
00731   const MCCFIInstruction &CFI = Instrs[CFIIndex];
00732   emitCFIInstruction(CFI);
00733 }
00734 
00735 /// EmitFunctionBody - This method emits the body and trailer for a
00736 /// function.
00737 void AsmPrinter::EmitFunctionBody() {
00738   // Emit target-specific gunk before the function body.
00739   EmitFunctionBodyStart();
00740 
00741   bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
00742 
00743   // Print out code for the function.
00744   bool HasAnyRealCode = false;
00745   const MachineInstr *LastMI = 0;
00746   for (auto &MBB : *MF) {
00747     // Print a label for the basic block.
00748     EmitBasicBlockStart(MBB);
00749     for (auto &MI : MBB) {
00750       LastMI = &MI;
00751 
00752       // Print the assembly for the instruction.
00753       if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
00754           !MI.isDebugValue()) {
00755         HasAnyRealCode = true;
00756         ++EmittedInsts;
00757       }
00758 
00759       if (ShouldPrintDebugScopes) {
00760         for (const HandlerInfo &HI : Handlers) {
00761           NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
00762                              TimePassesIsEnabled);
00763           HI.Handler->beginInstruction(&MI);
00764         }
00765       }
00766 
00767       if (isVerbose())
00768         emitComments(MI, OutStreamer.GetCommentOS());
00769 
00770       switch (MI.getOpcode()) {
00771       case TargetOpcode::CFI_INSTRUCTION:
00772         emitCFIInstruction(MI);
00773         break;
00774 
00775       case TargetOpcode::EH_LABEL:
00776       case TargetOpcode::GC_LABEL:
00777         OutStreamer.EmitLabel(MI.getOperand(0).getMCSymbol());
00778         break;
00779       case TargetOpcode::INLINEASM:
00780         EmitInlineAsm(&MI);
00781         break;
00782       case TargetOpcode::DBG_VALUE:
00783         if (isVerbose()) {
00784           if (!emitDebugValueComment(&MI, *this))
00785             EmitInstruction(&MI);
00786         }
00787         break;
00788       case TargetOpcode::IMPLICIT_DEF:
00789         if (isVerbose()) emitImplicitDef(&MI);
00790         break;
00791       case TargetOpcode::KILL:
00792         if (isVerbose()) emitKill(&MI, *this);
00793         break;
00794       default:
00795         EmitInstruction(&MI);
00796         break;
00797       }
00798 
00799       if (ShouldPrintDebugScopes) {
00800         for (const HandlerInfo &HI : Handlers) {
00801           NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
00802                              TimePassesIsEnabled);
00803           HI.Handler->endInstruction();
00804         }
00805       }
00806     }
00807   }
00808 
00809   // If the last instruction was a prolog label, then we have a situation where
00810   // we emitted a prolog but no function body. This results in the ending prolog
00811   // label equaling the end of function label and an invalid "row" in the
00812   // FDE. We need to emit a noop in this situation so that the FDE's rows are
00813   // valid.
00814   bool RequiresNoop = LastMI && LastMI->isCFIInstruction();
00815 
00816   // If the function is empty and the object file uses .subsections_via_symbols,
00817   // then we need to emit *something* to the function body to prevent the
00818   // labels from collapsing together.  Just emit a noop.
00819   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
00820     MCInst Noop;
00821     TM.getInstrInfo()->getNoopForMachoTarget(Noop);
00822     if (Noop.getOpcode()) {
00823       OutStreamer.AddComment("avoids zero-length function");
00824       OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
00825     } else  // Target not mc-ized yet.
00826       OutStreamer.EmitRawText(StringRef("\tnop\n"));
00827   }
00828 
00829   const Function *F = MF->getFunction();
00830   for (const auto &BB : *F) {
00831     if (!BB.hasAddressTaken())
00832       continue;
00833     MCSymbol *Sym = GetBlockAddressSymbol(&BB);
00834     if (Sym->isDefined())
00835       continue;
00836     OutStreamer.AddComment("Address of block that was removed by CodeGen");
00837     OutStreamer.EmitLabel(Sym);
00838   }
00839 
00840   // Emit target-specific gunk after the function body.
00841   EmitFunctionBodyEnd();
00842 
00843   // If the target wants a .size directive for the size of the function, emit
00844   // it.
00845   if (MAI->hasDotTypeDotSizeDirective()) {
00846     // Create a symbol for the end of function, so we can get the size as
00847     // difference between the function label and the temp label.
00848     MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
00849     OutStreamer.EmitLabel(FnEndLabel);
00850 
00851     const MCExpr *SizeExp =
00852       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
00853                               MCSymbolRefExpr::Create(CurrentFnSymForSize,
00854                                                       OutContext),
00855                               OutContext);
00856     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
00857   }
00858 
00859   // Emit post-function debug and/or EH information.
00860   for (const HandlerInfo &HI : Handlers) {
00861     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
00862     HI.Handler->endFunction(MF);
00863   }
00864   MMI->EndFunction();
00865 
00866   // Print out jump tables referenced by the function.
00867   EmitJumpTableInfo();
00868 
00869   OutStreamer.AddBlankLine();
00870 }
00871 
00872 bool AsmPrinter::doFinalization(Module &M) {
00873   // Emit global variables.
00874   for (const auto &G : M.globals())
00875     EmitGlobalVariable(&G);
00876 
00877   // Emit visibility info for declarations
00878   for (const Function &F : M) {
00879     if (!F.isDeclaration())
00880       continue;
00881     GlobalValue::VisibilityTypes V = F.getVisibility();
00882     if (V == GlobalValue::DefaultVisibility)
00883       continue;
00884 
00885     MCSymbol *Name = getSymbol(&F);
00886     EmitVisibility(Name, V, false);
00887   }
00888 
00889   // Emit module flags.
00890   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
00891   M.getModuleFlagsMetadata(ModuleFlags);
00892   if (!ModuleFlags.empty())
00893     getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
00894 
00895   // Make sure we wrote out everything we need.
00896   OutStreamer.Flush();
00897 
00898   // Finalize debug and EH information.
00899   for (const HandlerInfo &HI : Handlers) {
00900     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
00901                        TimePassesIsEnabled);
00902     HI.Handler->endModule();
00903     delete HI.Handler;
00904   }
00905   Handlers.clear();
00906   DD = 0;
00907 
00908   // If the target wants to know about weak references, print them all.
00909   if (MAI->getWeakRefDirective()) {
00910     // FIXME: This is not lazy, it would be nice to only print weak references
00911     // to stuff that is actually used.  Note that doing so would require targets
00912     // to notice uses in operands (due to constant exprs etc).  This should
00913     // happen with the MC stuff eventually.
00914 
00915     // Print out module-level global variables here.
00916     for (const auto &G : M.globals()) {
00917       if (!G.hasExternalWeakLinkage())
00918         continue;
00919       OutStreamer.EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
00920     }
00921 
00922     for (const auto &F : M) {
00923       if (!F.hasExternalWeakLinkage())
00924         continue;
00925       OutStreamer.EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
00926     }
00927   }
00928 
00929   if (MAI->hasSetDirective()) {
00930     OutStreamer.AddBlankLine();
00931     for (const auto &Alias : M.aliases()) {
00932       MCSymbol *Name = getSymbol(&Alias);
00933 
00934       const GlobalValue *GV = Alias.getAliasedGlobal();
00935       assert(!GV->isDeclaration());
00936       MCSymbol *Target = getSymbol(GV);
00937 
00938       if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
00939         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
00940       else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
00941         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
00942       else
00943         assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
00944 
00945       EmitVisibility(Name, Alias.getVisibility());
00946 
00947       // Emit the directives as assignments aka .set:
00948       OutStreamer.EmitAssignment(Name,
00949                                  MCSymbolRefExpr::Create(Target, OutContext));
00950     }
00951   }
00952 
00953   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
00954   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
00955   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
00956     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
00957       MP->finishAssembly(*this);
00958 
00959   // Emit llvm.ident metadata in an '.ident' directive.
00960   EmitModuleIdents(M);
00961 
00962   // If we don't have any trampolines, then we don't require stack memory
00963   // to be executable. Some targets have a directive to declare this.
00964   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
00965   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
00966     if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
00967       OutStreamer.SwitchSection(S);
00968 
00969   // Allow the target to emit any magic that it wants at the end of the file,
00970   // after everything else has gone out.
00971   EmitEndOfAsmFile(M);
00972 
00973   delete Mang; Mang = 0;
00974   MMI = 0;
00975 
00976   OutStreamer.Finish();
00977   OutStreamer.reset();
00978 
00979   return false;
00980 }
00981 
00982 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
00983   this->MF = &MF;
00984   // Get the function symbol.
00985   CurrentFnSym = getSymbol(MF.getFunction());
00986   CurrentFnSymForSize = CurrentFnSym;
00987 
00988   if (isVerbose())
00989     LI = &getAnalysis<MachineLoopInfo>();
00990 }
00991 
00992 namespace {
00993   // SectionCPs - Keep track the alignment, constpool entries per Section.
00994   struct SectionCPs {
00995     const MCSection *S;
00996     unsigned Alignment;
00997     SmallVector<unsigned, 4> CPEs;
00998     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
00999   };
01000 }
01001 
01002 /// EmitConstantPool - Print to the current output stream assembly
01003 /// representations of the constants in the constant pool MCP. This is
01004 /// used to print out constants which have been "spilled to memory" by
01005 /// the code generator.
01006 ///
01007 void AsmPrinter::EmitConstantPool() {
01008   const MachineConstantPool *MCP = MF->getConstantPool();
01009   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
01010   if (CP.empty()) return;
01011 
01012   // Calculate sections for constant pool entries. We collect entries to go into
01013   // the same section together to reduce amount of section switch statements.
01014   SmallVector<SectionCPs, 4> CPSections;
01015   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
01016     const MachineConstantPoolEntry &CPE = CP[i];
01017     unsigned Align = CPE.getAlignment();
01018 
01019     SectionKind Kind;
01020     switch (CPE.getRelocationInfo()) {
01021     default: llvm_unreachable("Unknown section kind");
01022     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
01023     case 1:
01024       Kind = SectionKind::getReadOnlyWithRelLocal();
01025       break;
01026     case 0:
01027     switch (TM.getDataLayout()->getTypeAllocSize(CPE.getType())) {
01028     case 4:  Kind = SectionKind::getMergeableConst4(); break;
01029     case 8:  Kind = SectionKind::getMergeableConst8(); break;
01030     case 16: Kind = SectionKind::getMergeableConst16();break;
01031     default: Kind = SectionKind::getMergeableConst(); break;
01032     }
01033     }
01034 
01035     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
01036 
01037     // The number of sections are small, just do a linear search from the
01038     // last section to the first.
01039     bool Found = false;
01040     unsigned SecIdx = CPSections.size();
01041     while (SecIdx != 0) {
01042       if (CPSections[--SecIdx].S == S) {
01043         Found = true;
01044         break;
01045       }
01046     }
01047     if (!Found) {
01048       SecIdx = CPSections.size();
01049       CPSections.push_back(SectionCPs(S, Align));
01050     }
01051 
01052     if (Align > CPSections[SecIdx].Alignment)
01053       CPSections[SecIdx].Alignment = Align;
01054     CPSections[SecIdx].CPEs.push_back(i);
01055   }
01056 
01057   // Now print stuff into the calculated sections.
01058   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
01059     OutStreamer.SwitchSection(CPSections[i].S);
01060     EmitAlignment(Log2_32(CPSections[i].Alignment));
01061 
01062     unsigned Offset = 0;
01063     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
01064       unsigned CPI = CPSections[i].CPEs[j];
01065       MachineConstantPoolEntry CPE = CP[CPI];
01066 
01067       // Emit inter-object padding for alignment.
01068       unsigned AlignMask = CPE.getAlignment() - 1;
01069       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
01070       OutStreamer.EmitZeros(NewOffset - Offset);
01071 
01072       Type *Ty = CPE.getType();
01073       Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
01074       OutStreamer.EmitLabel(GetCPISymbol(CPI));
01075 
01076       if (CPE.isMachineConstantPoolEntry())
01077         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
01078       else
01079         EmitGlobalConstant(CPE.Val.ConstVal);
01080     }
01081   }
01082 }
01083 
01084 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
01085 /// by the current function to the current output stream.
01086 ///
01087 void AsmPrinter::EmitJumpTableInfo() {
01088   const DataLayout *DL = MF->getTarget().getDataLayout();
01089   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
01090   if (MJTI == 0) return;
01091   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
01092   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
01093   if (JT.empty()) return;
01094 
01095   // Pick the directive to use to print the jump table entries, and switch to
01096   // the appropriate section.
01097   const Function *F = MF->getFunction();
01098   bool JTInDiffSection = false;
01099   if (// In PIC mode, we need to emit the jump table to the same section as the
01100       // function body itself, otherwise the label differences won't make sense.
01101       // FIXME: Need a better predicate for this: what about custom entries?
01102       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
01103       // We should also do if the section name is NULL or function is declared
01104       // in discardable section
01105       // FIXME: this isn't the right predicate, should be based on the MCSection
01106       // for the function.
01107       F->isWeakForLinker()) {
01108     OutStreamer.SwitchSection(
01109         getObjFileLowering().SectionForGlobal(F, *Mang, TM));
01110   } else {
01111     // Otherwise, drop it in the readonly section.
01112     const MCSection *ReadOnlySection =
01113       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
01114     OutStreamer.SwitchSection(ReadOnlySection);
01115     JTInDiffSection = true;
01116   }
01117 
01118   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
01119 
01120   // Jump tables in code sections are marked with a data_region directive
01121   // where that's supported.
01122   if (!JTInDiffSection)
01123     OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
01124 
01125   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
01126     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
01127 
01128     // If this jump table was deleted, ignore it.
01129     if (JTBBs.empty()) continue;
01130 
01131     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
01132     // .set directive for each unique entry.  This reduces the number of
01133     // relocations the assembler will generate for the jump table.
01134     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
01135         MAI->hasSetDirective()) {
01136       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
01137       const TargetLowering *TLI = TM.getTargetLowering();
01138       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
01139       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
01140         const MachineBasicBlock *MBB = JTBBs[ii];
01141         if (!EmittedSets.insert(MBB)) continue;
01142 
01143         // .set LJTSet, LBB32-base
01144         const MCExpr *LHS =
01145           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
01146         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
01147                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
01148       }
01149     }
01150 
01151     // On some targets (e.g. Darwin) we want to emit two consecutive labels
01152     // before each jump table.  The first label is never referenced, but tells
01153     // the assembler and linker the extents of the jump table object.  The
01154     // second label is actually referenced by the code.
01155     if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
01156       // FIXME: This doesn't have to have any specific name, just any randomly
01157       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
01158       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
01159 
01160     OutStreamer.EmitLabel(GetJTISymbol(JTI));
01161 
01162     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
01163       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
01164   }
01165   if (!JTInDiffSection)
01166     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
01167 }
01168 
01169 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
01170 /// current stream.
01171 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
01172                                     const MachineBasicBlock *MBB,
01173                                     unsigned UID) const {
01174   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
01175   const MCExpr *Value = 0;
01176   switch (MJTI->getEntryKind()) {
01177   case MachineJumpTableInfo::EK_Inline:
01178     llvm_unreachable("Cannot emit EK_Inline jump table entry");
01179   case MachineJumpTableInfo::EK_Custom32:
01180     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
01181                                                               OutContext);
01182     break;
01183   case MachineJumpTableInfo::EK_BlockAddress:
01184     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
01185     //     .word LBB123
01186     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
01187     break;
01188   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
01189     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
01190     // with a relocation as gp-relative, e.g.:
01191     //     .gprel32 LBB123
01192     MCSymbol *MBBSym = MBB->getSymbol();
01193     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
01194     return;
01195   }
01196 
01197   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
01198     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
01199     // with a relocation as gp-relative, e.g.:
01200     //     .gpdword LBB123
01201     MCSymbol *MBBSym = MBB->getSymbol();
01202     OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
01203     return;
01204   }
01205 
01206   case MachineJumpTableInfo::EK_LabelDifference32: {
01207     // EK_LabelDifference32 - Each entry is the address of the block minus
01208     // the address of the jump table.  This is used for PIC jump tables where
01209     // gprel32 is not supported.  e.g.:
01210     //      .word LBB123 - LJTI1_2
01211     // If the .set directive is supported, this is emitted as:
01212     //      .set L4_5_set_123, LBB123 - LJTI1_2
01213     //      .word L4_5_set_123
01214 
01215     // If we have emitted set directives for the jump table entries, print
01216     // them rather than the entries themselves.  If we're emitting PIC, then
01217     // emit the table entries as differences between two text section labels.
01218     if (MAI->hasSetDirective()) {
01219       // If we used .set, reference the .set's symbol.
01220       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
01221                                       OutContext);
01222       break;
01223     }
01224     // Otherwise, use the difference as the jump table entry.
01225     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
01226     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
01227     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
01228     break;
01229   }
01230   }
01231 
01232   assert(Value && "Unknown entry kind!");
01233 
01234   unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
01235   OutStreamer.EmitValue(Value, EntrySize);
01236 }
01237 
01238 
01239 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
01240 /// special global used by LLVM.  If so, emit it and return true, otherwise
01241 /// do nothing and return false.
01242 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
01243   if (GV->getName() == "llvm.used") {
01244     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
01245       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
01246     return true;
01247   }
01248 
01249   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
01250   if (GV->getSection() == "llvm.metadata" ||
01251       GV->hasAvailableExternallyLinkage())
01252     return true;
01253 
01254   if (!GV->hasAppendingLinkage()) return false;
01255 
01256   assert(GV->hasInitializer() && "Not a special LLVM global!");
01257 
01258   if (GV->getName() == "llvm.global_ctors") {
01259     EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
01260 
01261     if (TM.getRelocationModel() == Reloc::Static &&
01262         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
01263       StringRef Sym(".constructors_used");
01264       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
01265                                       MCSA_Reference);
01266     }
01267     return true;
01268   }
01269 
01270   if (GV->getName() == "llvm.global_dtors") {
01271     EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
01272 
01273     if (TM.getRelocationModel() == Reloc::Static &&
01274         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
01275       StringRef Sym(".destructors_used");
01276       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
01277                                       MCSA_Reference);
01278     }
01279     return true;
01280   }
01281 
01282   return false;
01283 }
01284 
01285 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
01286 /// global in the specified llvm.used list for which emitUsedDirectiveFor
01287 /// is true, as being used with this directive.
01288 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
01289   // Should be an array of 'i8*'.
01290   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
01291     const GlobalValue *GV =
01292       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
01293     if (GV)
01294       OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
01295   }
01296 }
01297 
01298 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
01299 /// priority.
01300 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
01301   // Should be an array of '{ int, void ()* }' structs.  The first value is the
01302   // init priority.
01303   if (!isa<ConstantArray>(List)) return;
01304 
01305   // Sanity check the structors list.
01306   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
01307   if (!InitList) return; // Not an array!
01308   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
01309   if (!ETy || ETy->getNumElements() != 2) return; // Not an array of pairs!
01310   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
01311       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
01312 
01313   // Gather the structors in a form that's convenient for sorting by priority.
01314   typedef std::pair<unsigned, Constant *> Structor;
01315   SmallVector<Structor, 8> Structors;
01316   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
01317     ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i));
01318     if (!CS) continue; // Malformed.
01319     if (CS->getOperand(1)->isNullValue())
01320       break;  // Found a null terminator, skip the rest.
01321     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
01322     if (!Priority) continue; // Malformed.
01323     Structors.push_back(std::make_pair(Priority->getLimitedValue(65535),
01324                                        CS->getOperand(1)));
01325   }
01326 
01327   // Emit the function pointers in the target-specific order
01328   const DataLayout *DL = TM.getDataLayout();
01329   unsigned Align = Log2_32(DL->getPointerPrefAlignment());
01330   std::stable_sort(Structors.begin(), Structors.end(), less_first());
01331   for (unsigned i = 0, e = Structors.size(); i != e; ++i) {
01332     const MCSection *OutputSection =
01333       (isCtor ?
01334        getObjFileLowering().getStaticCtorSection(Structors[i].first) :
01335        getObjFileLowering().getStaticDtorSection(Structors[i].first));
01336     OutStreamer.SwitchSection(OutputSection);
01337     if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
01338       EmitAlignment(Align);
01339     EmitXXStructor(Structors[i].second);
01340   }
01341 }
01342 
01343 void AsmPrinter::EmitModuleIdents(Module &M) {
01344   if (!MAI->hasIdentDirective())
01345     return;
01346 
01347   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
01348     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
01349       const MDNode *N = NMD->getOperand(i);
01350       assert(N->getNumOperands() == 1 &&
01351              "llvm.ident metadata entry can have only one operand");
01352       const MDString *S = cast<MDString>(N->getOperand(0));
01353       OutStreamer.EmitIdent(S->getString());
01354     }
01355   }
01356 }
01357 
01358 //===--------------------------------------------------------------------===//
01359 // Emission and print routines
01360 //
01361 
01362 /// EmitInt8 - Emit a byte directive and value.
01363 ///
01364 void AsmPrinter::EmitInt8(int Value) const {
01365   OutStreamer.EmitIntValue(Value, 1);
01366 }
01367 
01368 /// EmitInt16 - Emit a short directive and value.
01369 ///
01370 void AsmPrinter::EmitInt16(int Value) const {
01371   OutStreamer.EmitIntValue(Value, 2);
01372 }
01373 
01374 /// EmitInt32 - Emit a long directive and value.
01375 ///
01376 void AsmPrinter::EmitInt32(int Value) const {
01377   OutStreamer.EmitIntValue(Value, 4);
01378 }
01379 
01380 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
01381 /// in bytes of the directive is specified by Size and Hi/Lo specify the
01382 /// labels.  This implicitly uses .set if it is available.
01383 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
01384                                      unsigned Size) const {
01385   // Get the Hi-Lo expression.
01386   const MCExpr *Diff =
01387     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
01388                             MCSymbolRefExpr::Create(Lo, OutContext),
01389                             OutContext);
01390 
01391   if (!MAI->hasSetDirective()) {
01392     OutStreamer.EmitValue(Diff, Size);
01393     return;
01394   }
01395 
01396   // Otherwise, emit with .set (aka assignment).
01397   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
01398   OutStreamer.EmitAssignment(SetLabel, Diff);
01399   OutStreamer.EmitSymbolValue(SetLabel, Size);
01400 }
01401 
01402 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
01403 /// where the size in bytes of the directive is specified by Size and Hi/Lo
01404 /// specify the labels.  This implicitly uses .set if it is available.
01405 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
01406                                            const MCSymbol *Lo,
01407                                            unsigned Size) const {
01408 
01409   // Emit Hi+Offset - Lo
01410   // Get the Hi+Offset expression.
01411   const MCExpr *Plus =
01412     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
01413                             MCConstantExpr::Create(Offset, OutContext),
01414                             OutContext);
01415 
01416   // Get the Hi+Offset-Lo expression.
01417   const MCExpr *Diff =
01418     MCBinaryExpr::CreateSub(Plus,
01419                             MCSymbolRefExpr::Create(Lo, OutContext),
01420                             OutContext);
01421 
01422   if (!MAI->hasSetDirective())
01423     OutStreamer.EmitValue(Diff, Size);
01424   else {
01425     // Otherwise, emit with .set (aka assignment).
01426     MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
01427     OutStreamer.EmitAssignment(SetLabel, Diff);
01428     OutStreamer.EmitSymbolValue(SetLabel, Size);
01429   }
01430 }
01431 
01432 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
01433 /// where the size in bytes of the directive is specified by Size and Label
01434 /// specifies the label.  This implicitly uses .set if it is available.
01435 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
01436                                      unsigned Size,
01437                                      bool IsSectionRelative) const {
01438   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
01439     OutStreamer.EmitCOFFSecRel32(Label);
01440     return;
01441   }
01442 
01443   // Emit Label+Offset (or just Label if Offset is zero)
01444   const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
01445   if (Offset)
01446     Expr = MCBinaryExpr::CreateAdd(
01447         Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
01448 
01449   OutStreamer.EmitValue(Expr, Size);
01450 }
01451 
01452 //===----------------------------------------------------------------------===//
01453 
01454 // EmitAlignment - Emit an alignment directive to the specified power of
01455 // two boundary.  For example, if you pass in 3 here, you will get an 8
01456 // byte alignment.  If a global value is specified, and if that global has
01457 // an explicit alignment requested, it will override the alignment request
01458 // if required for correctness.
01459 //
01460 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
01461   if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
01462 
01463   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
01464 
01465   if (getCurrentSection()->getKind().isText())
01466     OutStreamer.EmitCodeAlignment(1 << NumBits);
01467   else
01468     OutStreamer.EmitValueToAlignment(1 << NumBits);
01469 }
01470 
01471 //===----------------------------------------------------------------------===//
01472 // Constant emission.
01473 //===----------------------------------------------------------------------===//
01474 
01475 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
01476 ///
01477 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
01478   MCContext &Ctx = AP.OutContext;
01479 
01480   if (CV->isNullValue() || isa<UndefValue>(CV))
01481     return MCConstantExpr::Create(0, Ctx);
01482 
01483   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
01484     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
01485 
01486   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
01487     return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
01488 
01489   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
01490     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
01491 
01492   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
01493   if (CE == 0) {
01494     llvm_unreachable("Unknown constant value to lower!");
01495   }
01496 
01497   if (const MCExpr *RelocExpr =
01498           AP.getObjFileLowering().getExecutableRelativeSymbol(CE, *AP.Mang,
01499                                                               AP.TM))
01500     return RelocExpr;
01501 
01502   switch (CE->getOpcode()) {
01503   default:
01504     // If the code isn't optimized, there may be outstanding folding
01505     // opportunities. Attempt to fold the expression using DataLayout as a
01506     // last resort before giving up.
01507     if (Constant *C =
01508           ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
01509       if (C != CE)
01510         return lowerConstant(C, AP);
01511 
01512     // Otherwise report the problem to the user.
01513     {
01514       std::string S;
01515       raw_string_ostream OS(S);
01516       OS << "Unsupported expression in static initializer: ";
01517       CE->printAsOperand(OS, /*PrintType=*/false,
01518                      !AP.MF ? 0 : AP.MF->getFunction()->getParent());
01519       report_fatal_error(OS.str());
01520     }
01521   case Instruction::GetElementPtr: {
01522     const DataLayout &DL = *AP.TM.getDataLayout();
01523     // Generate a symbolic expression for the byte address
01524     APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
01525     cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
01526 
01527     const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
01528     if (!OffsetAI)
01529       return Base;
01530 
01531     int64_t Offset = OffsetAI.getSExtValue();
01532     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
01533                                    Ctx);
01534   }
01535 
01536   case Instruction::Trunc:
01537     // We emit the value and depend on the assembler to truncate the generated
01538     // expression properly.  This is important for differences between
01539     // blockaddress labels.  Since the two labels are in the same function, it
01540     // is reasonable to treat their delta as a 32-bit value.
01541     // FALL THROUGH.
01542   case Instruction::BitCast:
01543     return lowerConstant(CE->getOperand(0), AP);
01544 
01545   case Instruction::IntToPtr: {
01546     const DataLayout &DL = *AP.TM.getDataLayout();
01547     // Handle casts to pointers by changing them into casts to the appropriate
01548     // integer type.  This promotes constant folding and simplifies this code.
01549     Constant *Op = CE->getOperand(0);
01550     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
01551                                       false/*ZExt*/);
01552     return lowerConstant(Op, AP);
01553   }
01554 
01555   case Instruction::PtrToInt: {
01556     const DataLayout &DL = *AP.TM.getDataLayout();
01557     // Support only foldable casts to/from pointers that can be eliminated by
01558     // changing the pointer to the appropriately sized integer type.
01559     Constant *Op = CE->getOperand(0);
01560     Type *Ty = CE->getType();
01561 
01562     const MCExpr *OpExpr = lowerConstant(Op, AP);
01563 
01564     // We can emit the pointer value into this slot if the slot is an
01565     // integer slot equal to the size of the pointer.
01566     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
01567       return OpExpr;
01568 
01569     // Otherwise the pointer is smaller than the resultant integer, mask off
01570     // the high bits so we are sure to get a proper truncation if the input is
01571     // a constant expr.
01572     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
01573     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
01574     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
01575   }
01576 
01577   // The MC library also has a right-shift operator, but it isn't consistently
01578   // signed or unsigned between different targets.
01579   case Instruction::Add:
01580   case Instruction::Sub:
01581   case Instruction::Mul:
01582   case Instruction::SDiv:
01583   case Instruction::SRem:
01584   case Instruction::Shl:
01585   case Instruction::And:
01586   case Instruction::Or:
01587   case Instruction::Xor: {
01588     const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
01589     const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
01590     switch (CE->getOpcode()) {
01591     default: llvm_unreachable("Unknown binary operator constant cast expr");
01592     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
01593     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
01594     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
01595     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
01596     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
01597     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
01598     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
01599     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
01600     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
01601     }
01602   }
01603   }
01604 }
01605 
01606 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
01607 
01608 /// isRepeatedByteSequence - Determine whether the given value is
01609 /// composed of a repeated sequence of identical bytes and return the
01610 /// byte value.  If it is not a repeated sequence, return -1.
01611 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
01612   StringRef Data = V->getRawDataValues();
01613   assert(!Data.empty() && "Empty aggregates should be CAZ node");
01614   char C = Data[0];
01615   for (unsigned i = 1, e = Data.size(); i != e; ++i)
01616     if (Data[i] != C) return -1;
01617   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
01618 }
01619 
01620 
01621 /// isRepeatedByteSequence - Determine whether the given value is
01622 /// composed of a repeated sequence of identical bytes and return the
01623 /// byte value.  If it is not a repeated sequence, return -1.
01624 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
01625 
01626   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
01627     if (CI->getBitWidth() > 64) return -1;
01628 
01629     uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
01630     uint64_t Value = CI->getZExtValue();
01631 
01632     // Make sure the constant is at least 8 bits long and has a power
01633     // of 2 bit width.  This guarantees the constant bit width is
01634     // always a multiple of 8 bits, avoiding issues with padding out
01635     // to Size and other such corner cases.
01636     if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
01637 
01638     uint8_t Byte = static_cast<uint8_t>(Value);
01639 
01640     for (unsigned i = 1; i < Size; ++i) {
01641       Value >>= 8;
01642       if (static_cast<uint8_t>(Value) != Byte) return -1;
01643     }
01644     return Byte;
01645   }
01646   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
01647     // Make sure all array elements are sequences of the same repeated
01648     // byte.
01649     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
01650     int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
01651     if (Byte == -1) return -1;
01652 
01653     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
01654       int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
01655       if (ThisByte == -1) return -1;
01656       if (Byte != ThisByte) return -1;
01657     }
01658     return Byte;
01659   }
01660 
01661   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
01662     return isRepeatedByteSequence(CDS);
01663 
01664   return -1;
01665 }
01666 
01667 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
01668                                              AsmPrinter &AP){
01669 
01670   // See if we can aggregate this into a .fill, if so, emit it as such.
01671   int Value = isRepeatedByteSequence(CDS, AP.TM);
01672   if (Value != -1) {
01673     uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
01674     // Don't emit a 1-byte object as a .fill.
01675     if (Bytes > 1)
01676       return AP.OutStreamer.EmitFill(Bytes, Value);
01677   }
01678 
01679   // If this can be emitted with .ascii/.asciz, emit it as such.
01680   if (CDS->isString())
01681     return AP.OutStreamer.EmitBytes(CDS->getAsString());
01682 
01683   // Otherwise, emit the values in successive locations.
01684   unsigned ElementByteSize = CDS->getElementByteSize();
01685   if (isa<IntegerType>(CDS->getElementType())) {
01686     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01687       if (AP.isVerbose())
01688         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
01689                                                 CDS->getElementAsInteger(i));
01690       AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
01691                                   ElementByteSize);
01692     }
01693   } else if (ElementByteSize == 4) {
01694     // FP Constants are printed as integer constants to avoid losing
01695     // precision.
01696     assert(CDS->getElementType()->isFloatTy());
01697     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01698       union {
01699         float F;
01700         uint32_t I;
01701       };
01702 
01703       F = CDS->getElementAsFloat(i);
01704       if (AP.isVerbose())
01705         AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
01706       AP.OutStreamer.EmitIntValue(I, 4);
01707     }
01708   } else {
01709     assert(CDS->getElementType()->isDoubleTy());
01710     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01711       union {
01712         double F;
01713         uint64_t I;
01714       };
01715 
01716       F = CDS->getElementAsDouble(i);
01717       if (AP.isVerbose())
01718         AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
01719       AP.OutStreamer.EmitIntValue(I, 8);
01720     }
01721   }
01722 
01723   const DataLayout &DL = *AP.TM.getDataLayout();
01724   unsigned Size = DL.getTypeAllocSize(CDS->getType());
01725   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
01726                         CDS->getNumElements();
01727   if (unsigned Padding = Size - EmittedSize)
01728     AP.OutStreamer.EmitZeros(Padding);
01729 
01730 }
01731 
01732 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
01733   // See if we can aggregate some values.  Make sure it can be
01734   // represented as a series of bytes of the constant value.
01735   int Value = isRepeatedByteSequence(CA, AP.TM);
01736 
01737   if (Value != -1) {
01738     uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
01739     AP.OutStreamer.EmitFill(Bytes, Value);
01740   }
01741   else {
01742     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
01743       emitGlobalConstantImpl(CA->getOperand(i), AP);
01744   }
01745 }
01746 
01747 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
01748   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
01749     emitGlobalConstantImpl(CV->getOperand(i), AP);
01750 
01751   const DataLayout &DL = *AP.TM.getDataLayout();
01752   unsigned Size = DL.getTypeAllocSize(CV->getType());
01753   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
01754                          CV->getType()->getNumElements();
01755   if (unsigned Padding = Size - EmittedSize)
01756     AP.OutStreamer.EmitZeros(Padding);
01757 }
01758 
01759 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
01760   // Print the fields in successive locations. Pad to align if needed!
01761   const DataLayout *DL = AP.TM.getDataLayout();
01762   unsigned Size = DL->getTypeAllocSize(CS->getType());
01763   const StructLayout *Layout = DL->getStructLayout(CS->getType());
01764   uint64_t SizeSoFar = 0;
01765   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
01766     const Constant *Field = CS->getOperand(i);
01767 
01768     // Check if padding is needed and insert one or more 0s.
01769     uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
01770     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
01771                         - Layout->getElementOffset(i)) - FieldSize;
01772     SizeSoFar += FieldSize + PadSize;
01773 
01774     // Now print the actual field value.
01775     emitGlobalConstantImpl(Field, AP);
01776 
01777     // Insert padding - this may include padding to increase the size of the
01778     // current field up to the ABI size (if the struct is not packed) as well
01779     // as padding to ensure that the next field starts at the right offset.
01780     AP.OutStreamer.EmitZeros(PadSize);
01781   }
01782   assert(SizeSoFar == Layout->getSizeInBytes() &&
01783          "Layout of constant struct may be incorrect!");
01784 }
01785 
01786 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
01787   APInt API = CFP->getValueAPF().bitcastToAPInt();
01788 
01789   // First print a comment with what we think the original floating-point value
01790   // should have been.
01791   if (AP.isVerbose()) {
01792     SmallString<8> StrVal;
01793     CFP->getValueAPF().toString(StrVal);
01794 
01795     CFP->getType()->print(AP.OutStreamer.GetCommentOS());
01796     AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
01797   }
01798 
01799   // Now iterate through the APInt chunks, emitting them in endian-correct
01800   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
01801   // floats).
01802   unsigned NumBytes = API.getBitWidth() / 8;
01803   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
01804   const uint64_t *p = API.getRawData();
01805 
01806   // PPC's long double has odd notions of endianness compared to how LLVM
01807   // handles it: p[0] goes first for *big* endian on PPC.
01808   if (AP.TM.getDataLayout()->isBigEndian() != CFP->getType()->isPPC_FP128Ty()) {
01809     int Chunk = API.getNumWords() - 1;
01810 
01811     if (TrailingBytes)
01812       AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
01813 
01814     for (; Chunk >= 0; --Chunk)
01815       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
01816   } else {
01817     unsigned Chunk;
01818     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
01819       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
01820 
01821     if (TrailingBytes)
01822       AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
01823   }
01824 
01825   // Emit the tail padding for the long double.
01826   const DataLayout &DL = *AP.TM.getDataLayout();
01827   AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
01828                            DL.getTypeStoreSize(CFP->getType()));
01829 }
01830 
01831 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
01832   const DataLayout *DL = AP.TM.getDataLayout();
01833   unsigned BitWidth = CI->getBitWidth();
01834 
01835   // Copy the value as we may massage the layout for constants whose bit width
01836   // is not a multiple of 64-bits.
01837   APInt Realigned(CI->getValue());
01838   uint64_t ExtraBits = 0;
01839   unsigned ExtraBitsSize = BitWidth & 63;
01840 
01841   if (ExtraBitsSize) {
01842     // The bit width of the data is not a multiple of 64-bits.
01843     // The extra bits are expected to be at the end of the chunk of the memory.
01844     // Little endian:
01845     // * Nothing to be done, just record the extra bits to emit.
01846     // Big endian:
01847     // * Record the extra bits to emit.
01848     // * Realign the raw data to emit the chunks of 64-bits.
01849     if (DL->isBigEndian()) {
01850       // Basically the structure of the raw data is a chunk of 64-bits cells:
01851       //    0        1         BitWidth / 64
01852       // [chunk1][chunk2] ... [chunkN].
01853       // The most significant chunk is chunkN and it should be emitted first.
01854       // However, due to the alignment issue chunkN contains useless bits.
01855       // Realign the chunks so that they contain only useless information:
01856       // ExtraBits     0       1       (BitWidth / 64) - 1
01857       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
01858       ExtraBits = Realigned.getRawData()[0] &
01859         (((uint64_t)-1) >> (64 - ExtraBitsSize));
01860       Realigned = Realigned.lshr(ExtraBitsSize);
01861     } else
01862       ExtraBits = Realigned.getRawData()[BitWidth / 64];
01863   }
01864 
01865   // We don't expect assemblers to support integer data directives
01866   // for more than 64 bits, so we emit the data in at most 64-bit
01867   // quantities at a time.
01868   const uint64_t *RawData = Realigned.getRawData();
01869   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
01870     uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
01871     AP.OutStreamer.EmitIntValue(Val, 8);
01872   }
01873 
01874   if (ExtraBitsSize) {
01875     // Emit the extra bits after the 64-bits chunks.
01876 
01877     // Emit a directive that fills the expected size.
01878     uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
01879     Size -= (BitWidth / 64) * 8;
01880     assert(Size && Size * 8 >= ExtraBitsSize &&
01881            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
01882            == ExtraBits && "Directive too small for extra bits.");
01883     AP.OutStreamer.EmitIntValue(ExtraBits, Size);
01884   }
01885 }
01886 
01887 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
01888   const DataLayout *DL = AP.TM.getDataLayout();
01889   uint64_t Size = DL->getTypeAllocSize(CV->getType());
01890   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
01891     return AP.OutStreamer.EmitZeros(Size);
01892 
01893   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
01894     switch (Size) {
01895     case 1:
01896     case 2:
01897     case 4:
01898     case 8:
01899       if (AP.isVerbose())
01900         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
01901                                                 CI->getZExtValue());
01902       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
01903       return;
01904     default:
01905       emitGlobalConstantLargeInt(CI, AP);
01906       return;
01907     }
01908   }
01909 
01910   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
01911     return emitGlobalConstantFP(CFP, AP);
01912 
01913   if (isa<ConstantPointerNull>(CV)) {
01914     AP.OutStreamer.EmitIntValue(0, Size);
01915     return;
01916   }
01917 
01918   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
01919     return emitGlobalConstantDataSequential(CDS, AP);
01920 
01921   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
01922     return emitGlobalConstantArray(CVA, AP);
01923 
01924   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
01925     return emitGlobalConstantStruct(CVS, AP);
01926 
01927   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
01928     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
01929     // vectors).
01930     if (CE->getOpcode() == Instruction::BitCast)
01931       return emitGlobalConstantImpl(CE->getOperand(0), AP);
01932 
01933     if (Size > 8) {
01934       // If the constant expression's size is greater than 64-bits, then we have
01935       // to emit the value in chunks. Try to constant fold the value and emit it
01936       // that way.
01937       Constant *New = ConstantFoldConstantExpression(CE, DL);
01938       if (New && New != CE)
01939         return emitGlobalConstantImpl(New, AP);
01940     }
01941   }
01942 
01943   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
01944     return emitGlobalConstantVector(V, AP);
01945 
01946   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
01947   // thread the streamer with EmitValue.
01948   AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
01949 }
01950 
01951 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
01952 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
01953   uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
01954   if (Size)
01955     emitGlobalConstantImpl(CV, *this);
01956   else if (MAI->hasSubsectionsViaSymbols()) {
01957     // If the global has zero size, emit a single byte so that two labels don't
01958     // look like they are at the same location.
01959     OutStreamer.EmitIntValue(0, 1);
01960   }
01961 }
01962 
01963 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
01964   // Target doesn't support this yet!
01965   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
01966 }
01967 
01968 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
01969   if (Offset > 0)
01970     OS << '+' << Offset;
01971   else if (Offset < 0)
01972     OS << Offset;
01973 }
01974 
01975 //===----------------------------------------------------------------------===//
01976 // Symbol Lowering Routines.
01977 //===----------------------------------------------------------------------===//
01978 
01979 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
01980 /// temporary label with the specified stem and unique ID.
01981 MCSymbol *AsmPrinter::GetTempSymbol(Twine Name, unsigned ID) const {
01982   const DataLayout *DL = TM.getDataLayout();
01983   return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
01984                                       Name + Twine(ID));
01985 }
01986 
01987 /// GetTempSymbol - Return an assembler temporary label with the specified
01988 /// stem.
01989 MCSymbol *AsmPrinter::GetTempSymbol(Twine Name) const {
01990   const DataLayout *DL = TM.getDataLayout();
01991   return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
01992                                       Name);
01993 }
01994 
01995 
01996 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
01997   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
01998 }
01999 
02000 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
02001   return MMI->getAddrLabelSymbol(BB);
02002 }
02003 
02004 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
02005 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
02006   const DataLayout *DL = TM.getDataLayout();
02007   return OutContext.GetOrCreateSymbol
02008     (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
02009      + "_" + Twine(CPID));
02010 }
02011 
02012 /// GetJTISymbol - Return the symbol for the specified jump table entry.
02013 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
02014   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
02015 }
02016 
02017 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
02018 /// FIXME: privatize to AsmPrinter.
02019 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
02020   const DataLayout *DL = TM.getDataLayout();
02021   return OutContext.GetOrCreateSymbol
02022   (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
02023    Twine(UID) + "_set_" + Twine(MBBID));
02024 }
02025 
02026 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
02027                                                    StringRef Suffix) const {
02028   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
02029                                                            TM);
02030 }
02031 
02032 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
02033 /// ExternalSymbol.
02034 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
02035   SmallString<60> NameStr;
02036   Mang->getNameWithPrefix(NameStr, Sym);
02037   return OutContext.GetOrCreateSymbol(NameStr.str());
02038 }
02039 
02040 
02041 
02042 /// PrintParentLoopComment - Print comments about parent loops of this one.
02043 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
02044                                    unsigned FunctionNumber) {
02045   if (Loop == 0) return;
02046   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
02047   OS.indent(Loop->getLoopDepth()*2)
02048     << "Parent Loop BB" << FunctionNumber << "_"
02049     << Loop->getHeader()->getNumber()
02050     << " Depth=" << Loop->getLoopDepth() << '\n';
02051 }
02052 
02053 
02054 /// PrintChildLoopComment - Print comments about child loops within
02055 /// the loop for this basic block, with nesting.
02056 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
02057                                   unsigned FunctionNumber) {
02058   // Add child loop information
02059   for (const MachineLoop *CL : *Loop) {
02060     OS.indent(CL->getLoopDepth()*2)
02061       << "Child Loop BB" << FunctionNumber << "_"
02062       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
02063       << '\n';
02064     PrintChildLoopComment(OS, CL, FunctionNumber);
02065   }
02066 }
02067 
02068 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
02069 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
02070                                        const MachineLoopInfo *LI,
02071                                        const AsmPrinter &AP) {
02072   // Add loop depth information
02073   const MachineLoop *Loop = LI->getLoopFor(&MBB);
02074   if (Loop == 0) return;
02075 
02076   MachineBasicBlock *Header = Loop->getHeader();
02077   assert(Header && "No header for loop");
02078 
02079   // If this block is not a loop header, just print out what is the loop header
02080   // and return.
02081   if (Header != &MBB) {
02082     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
02083                               Twine(AP.getFunctionNumber())+"_" +
02084                               Twine(Loop->getHeader()->getNumber())+
02085                               " Depth="+Twine(Loop->getLoopDepth()));
02086     return;
02087   }
02088 
02089   // Otherwise, it is a loop header.  Print out information about child and
02090   // parent loops.
02091   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
02092 
02093   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
02094 
02095   OS << "=>";
02096   OS.indent(Loop->getLoopDepth()*2-2);
02097 
02098   OS << "This ";
02099   if (Loop->empty())
02100     OS << "Inner ";
02101   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
02102 
02103   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
02104 }
02105 
02106 
02107 /// EmitBasicBlockStart - This method prints the label for the specified
02108 /// MachineBasicBlock, an alignment (if present) and a comment describing
02109 /// it if appropriate.
02110 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
02111   // Emit an alignment directive for this block, if needed.
02112   if (unsigned Align = MBB.getAlignment())
02113     EmitAlignment(Align);
02114 
02115   // If the block has its address taken, emit any labels that were used to
02116   // reference the block.  It is possible that there is more than one label
02117   // here, because multiple LLVM BB's may have been RAUW'd to this block after
02118   // the references were generated.
02119   if (MBB.hasAddressTaken()) {
02120     const BasicBlock *BB = MBB.getBasicBlock();
02121     if (isVerbose())
02122       OutStreamer.AddComment("Block address taken");
02123 
02124     std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
02125     for (auto *Sym : Symbols)
02126       OutStreamer.EmitLabel(Sym);
02127   }
02128 
02129   // Print some verbose block comments.
02130   if (isVerbose()) {
02131     if (const BasicBlock *BB = MBB.getBasicBlock())
02132       if (BB->hasName())
02133         OutStreamer.AddComment("%" + BB->getName());
02134     emitBasicBlockLoopComments(MBB, LI, *this);
02135   }
02136 
02137   // Print the main label for the block.
02138   if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
02139     if (isVerbose()) {
02140       // NOTE: Want this comment at start of line, don't emit with AddComment.
02141       OutStreamer.emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
02142     }
02143   } else {
02144     OutStreamer.EmitLabel(MBB.getSymbol());
02145   }
02146 }
02147 
02148 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
02149                                 bool IsDefinition) const {
02150   MCSymbolAttr Attr = MCSA_Invalid;
02151 
02152   switch (Visibility) {
02153   default: break;
02154   case GlobalValue::HiddenVisibility:
02155     if (IsDefinition)
02156       Attr = MAI->getHiddenVisibilityAttr();
02157     else
02158       Attr = MAI->getHiddenDeclarationVisibilityAttr();
02159     break;
02160   case GlobalValue::ProtectedVisibility:
02161     Attr = MAI->getProtectedVisibilityAttr();
02162     break;
02163   }
02164 
02165   if (Attr != MCSA_Invalid)
02166     OutStreamer.EmitSymbolAttribute(Sym, Attr);
02167 }
02168 
02169 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
02170 /// exactly one predecessor and the control transfer mechanism between
02171 /// the predecessor and this block is a fall-through.
02172 bool AsmPrinter::
02173 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
02174   // If this is a landing pad, it isn't a fall through.  If it has no preds,
02175   // then nothing falls through to it.
02176   if (MBB->isLandingPad() || MBB->pred_empty())
02177     return false;
02178 
02179   // If there isn't exactly one predecessor, it can't be a fall through.
02180   if (MBB->pred_size() > 1)
02181     return false;
02182 
02183   // The predecessor has to be immediately before this block.
02184   MachineBasicBlock *Pred = *MBB->pred_begin();
02185   if (!Pred->isLayoutSuccessor(MBB))
02186     return false;
02187 
02188   // If the block is completely empty, then it definitely does fall through.
02189   if (Pred->empty())
02190     return true;
02191 
02192   // Check the terminators in the previous blocks
02193   for (const auto &MI : Pred->terminators()) {
02194     // If it is not a simple branch, we are in a table somewhere.
02195     if (!MI.isBranch() || MI.isIndirectBranch())
02196       return false;
02197 
02198     // If we are the operands of one of the branches, this is not a fall
02199     // through. Note that targets with delay slots will usually bundle
02200     // terminators with the delay slot instruction.
02201     for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
02202       if (OP->isJTI())
02203         return false;
02204       if (OP->isMBB() && OP->getMBB() == MBB)
02205         return false;
02206     }
02207   }
02208 
02209   return true;
02210 }
02211 
02212 
02213 
02214 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
02215   if (!S.usesMetadata())
02216     return 0;
02217 
02218   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
02219   gcp_map_type::iterator GCPI = GCMap.find(&S);
02220   if (GCPI != GCMap.end())
02221     return GCPI->second.get();
02222 
02223   const char *Name = S.getName().c_str();
02224 
02225   for (GCMetadataPrinterRegistry::iterator
02226          I = GCMetadataPrinterRegistry::begin(),
02227          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
02228     if (strcmp(Name, I->getName()) == 0) {
02229       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
02230       GMP->S = &S;
02231       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
02232       return IterBool.first->second.get();
02233     }
02234 
02235   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
02236 }
02237 
02238 /// Pin vtable to this file.
02239 AsmPrinterHandler::~AsmPrinterHandler() {}