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