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     EmitBasicBlockEnd(MBB);
00809   }
00810 
00811   // If the last instruction was a prolog label, then we have a situation where
00812   // we emitted a prolog but no function body. This results in the ending prolog
00813   // label equaling the end of function label and an invalid "row" in the
00814   // FDE. We need to emit a noop in this situation so that the FDE's rows are
00815   // valid.
00816   bool RequiresNoop = LastMI && LastMI->isCFIInstruction();
00817 
00818   // If the function is empty and the object file uses .subsections_via_symbols,
00819   // then we need to emit *something* to the function body to prevent the
00820   // labels from collapsing together.  Just emit a noop.
00821   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
00822     MCInst Noop;
00823     TM.getInstrInfo()->getNoopForMachoTarget(Noop);
00824     if (Noop.getOpcode()) {
00825       OutStreamer.AddComment("avoids zero-length function");
00826       OutStreamer.EmitInstruction(Noop, getSubtargetInfo());
00827     } else  // Target not mc-ized yet.
00828       OutStreamer.EmitRawText(StringRef("\tnop\n"));
00829   }
00830 
00831   const Function *F = MF->getFunction();
00832   for (const auto &BB : *F) {
00833     if (!BB.hasAddressTaken())
00834       continue;
00835     MCSymbol *Sym = GetBlockAddressSymbol(&BB);
00836     if (Sym->isDefined())
00837       continue;
00838     OutStreamer.AddComment("Address of block that was removed by CodeGen");
00839     OutStreamer.EmitLabel(Sym);
00840   }
00841 
00842   // Emit target-specific gunk after the function body.
00843   EmitFunctionBodyEnd();
00844 
00845   // If the target wants a .size directive for the size of the function, emit
00846   // it.
00847   if (MAI->hasDotTypeDotSizeDirective()) {
00848     // Create a symbol for the end of function, so we can get the size as
00849     // difference between the function label and the temp label.
00850     MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
00851     OutStreamer.EmitLabel(FnEndLabel);
00852 
00853     const MCExpr *SizeExp =
00854       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
00855                               MCSymbolRefExpr::Create(CurrentFnSymForSize,
00856                                                       OutContext),
00857                               OutContext);
00858     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
00859   }
00860 
00861   // Emit post-function debug and/or EH information.
00862   for (const HandlerInfo &HI : Handlers) {
00863     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
00864     HI.Handler->endFunction(MF);
00865   }
00866   MMI->EndFunction();
00867 
00868   // Print out jump tables referenced by the function.
00869   EmitJumpTableInfo();
00870 
00871   OutStreamer.AddBlankLine();
00872 }
00873 
00874 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP);
00875 
00876 bool AsmPrinter::doFinalization(Module &M) {
00877   // Emit global variables.
00878   for (const auto &G : M.globals())
00879     EmitGlobalVariable(&G);
00880 
00881   // Emit visibility info for declarations
00882   for (const Function &F : M) {
00883     if (!F.isDeclaration())
00884       continue;
00885     GlobalValue::VisibilityTypes V = F.getVisibility();
00886     if (V == GlobalValue::DefaultVisibility)
00887       continue;
00888 
00889     MCSymbol *Name = getSymbol(&F);
00890     EmitVisibility(Name, V, false);
00891   }
00892 
00893   // Get information about jump-instruction tables to print.
00894   JumpInstrTableInfo *JITI = getAnalysisIfAvailable<JumpInstrTableInfo>();
00895 
00896   if (JITI && !JITI->getTables().empty()) {
00897     unsigned Arch = Triple(getTargetTriple()).getArch();
00898     bool IsThumb = (Arch == Triple::thumb || Arch == Triple::thumbeb);
00899     MCInst TrapInst;
00900     TM.getInstrInfo()->getTrap(TrapInst);
00901     for (const auto &KV : JITI->getTables()) {
00902       uint64_t Count = 0;
00903       for (const auto &FunPair : KV.second) {
00904         // Emit the function labels to make this be a function entry point.
00905         MCSymbol *FunSym =
00906           OutContext.GetOrCreateSymbol(FunPair.second->getName());
00907         OutStreamer.EmitSymbolAttribute(FunSym, MCSA_Global);
00908         // FIXME: JumpTableInstrInfo should store information about the required
00909         // alignment of table entries and the size of the padding instruction.
00910         EmitAlignment(3);
00911         if (IsThumb)
00912           OutStreamer.EmitThumbFunc(FunSym);
00913         if (MAI->hasDotTypeDotSizeDirective())
00914           OutStreamer.EmitSymbolAttribute(FunSym, MCSA_ELF_TypeFunction);
00915         OutStreamer.EmitLabel(FunSym);
00916 
00917         // Emit the jump instruction to transfer control to the original
00918         // function.
00919         MCInst JumpToFun;
00920         MCSymbol *TargetSymbol =
00921           OutContext.GetOrCreateSymbol(FunPair.first->getName());
00922         const MCSymbolRefExpr *TargetSymRef =
00923           MCSymbolRefExpr::Create(TargetSymbol, MCSymbolRefExpr::VK_PLT,
00924                                   OutContext);
00925         TM.getInstrInfo()->getUnconditionalBranch(JumpToFun, TargetSymRef);
00926         OutStreamer.EmitInstruction(JumpToFun, getSubtargetInfo());
00927         ++Count;
00928       }
00929 
00930       // Emit enough padding instructions to fill up to the next power of two.
00931       // This assumes that the trap instruction takes 8 bytes or fewer.
00932       uint64_t Remaining = NextPowerOf2(Count) - Count;
00933       for (uint64_t C = 0; C < Remaining; ++C) {
00934         EmitAlignment(3);
00935         OutStreamer.EmitInstruction(TrapInst, getSubtargetInfo());
00936       }
00937 
00938     }
00939   }
00940 
00941   // Emit module flags.
00942   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
00943   M.getModuleFlagsMetadata(ModuleFlags);
00944   if (!ModuleFlags.empty())
00945     getObjFileLowering().emitModuleFlags(OutStreamer, ModuleFlags, *Mang, TM);
00946 
00947   // Make sure we wrote out everything we need.
00948   OutStreamer.Flush();
00949 
00950   // Finalize debug and EH information.
00951   for (const HandlerInfo &HI : Handlers) {
00952     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName,
00953                        TimePassesIsEnabled);
00954     HI.Handler->endModule();
00955     delete HI.Handler;
00956   }
00957   Handlers.clear();
00958   DD = nullptr;
00959 
00960   // If the target wants to know about weak references, print them all.
00961   if (MAI->getWeakRefDirective()) {
00962     // FIXME: This is not lazy, it would be nice to only print weak references
00963     // to stuff that is actually used.  Note that doing so would require targets
00964     // to notice uses in operands (due to constant exprs etc).  This should
00965     // happen with the MC stuff eventually.
00966 
00967     // Print out module-level global variables here.
00968     for (const auto &G : M.globals()) {
00969       if (!G.hasExternalWeakLinkage())
00970         continue;
00971       OutStreamer.EmitSymbolAttribute(getSymbol(&G), MCSA_WeakReference);
00972     }
00973 
00974     for (const auto &F : M) {
00975       if (!F.hasExternalWeakLinkage())
00976         continue;
00977       OutStreamer.EmitSymbolAttribute(getSymbol(&F), MCSA_WeakReference);
00978     }
00979   }
00980 
00981   if (MAI->hasSetDirective()) {
00982     OutStreamer.AddBlankLine();
00983     for (const auto &Alias : M.aliases()) {
00984       MCSymbol *Name = getSymbol(&Alias);
00985 
00986       if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
00987         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
00988       else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
00989         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
00990       else
00991         assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
00992 
00993       EmitVisibility(Name, Alias.getVisibility());
00994 
00995       // Emit the directives as assignments aka .set:
00996       OutStreamer.EmitAssignment(Name,
00997                                  lowerConstant(Alias.getAliasee(), *this));
00998     }
00999   }
01000 
01001   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
01002   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
01003   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
01004     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
01005       MP->finishAssembly(*this);
01006 
01007   // Emit llvm.ident metadata in an '.ident' directive.
01008   EmitModuleIdents(M);
01009 
01010   // If we don't have any trampolines, then we don't require stack memory
01011   // to be executable. Some targets have a directive to declare this.
01012   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
01013   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
01014     if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
01015       OutStreamer.SwitchSection(S);
01016 
01017   // Allow the target to emit any magic that it wants at the end of the file,
01018   // after everything else has gone out.
01019   EmitEndOfAsmFile(M);
01020 
01021   delete Mang; Mang = nullptr;
01022   MMI = nullptr;
01023 
01024   OutStreamer.Finish();
01025   OutStreamer.reset();
01026 
01027   return false;
01028 }
01029 
01030 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
01031   this->MF = &MF;
01032   // Get the function symbol.
01033   CurrentFnSym = getSymbol(MF.getFunction());
01034   CurrentFnSymForSize = CurrentFnSym;
01035 
01036   if (isVerbose())
01037     LI = &getAnalysis<MachineLoopInfo>();
01038 }
01039 
01040 namespace {
01041   // SectionCPs - Keep track the alignment, constpool entries per Section.
01042   struct SectionCPs {
01043     const MCSection *S;
01044     unsigned Alignment;
01045     SmallVector<unsigned, 4> CPEs;
01046     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
01047   };
01048 }
01049 
01050 /// EmitConstantPool - Print to the current output stream assembly
01051 /// representations of the constants in the constant pool MCP. This is
01052 /// used to print out constants which have been "spilled to memory" by
01053 /// the code generator.
01054 ///
01055 void AsmPrinter::EmitConstantPool() {
01056   const MachineConstantPool *MCP = MF->getConstantPool();
01057   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
01058   if (CP.empty()) return;
01059 
01060   // Calculate sections for constant pool entries. We collect entries to go into
01061   // the same section together to reduce amount of section switch statements.
01062   SmallVector<SectionCPs, 4> CPSections;
01063   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
01064     const MachineConstantPoolEntry &CPE = CP[i];
01065     unsigned Align = CPE.getAlignment();
01066 
01067     SectionKind Kind = CPE.getSectionKind(TM.getDataLayout());
01068 
01069     const Constant *C = nullptr;
01070     if (!CPE.isMachineConstantPoolEntry())
01071       C = CPE.Val.ConstVal;
01072 
01073     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
01074 
01075     // The number of sections are small, just do a linear search from the
01076     // last section to the first.
01077     bool Found = false;
01078     unsigned SecIdx = CPSections.size();
01079     while (SecIdx != 0) {
01080       if (CPSections[--SecIdx].S == S) {
01081         Found = true;
01082         break;
01083       }
01084     }
01085     if (!Found) {
01086       SecIdx = CPSections.size();
01087       CPSections.push_back(SectionCPs(S, Align));
01088     }
01089 
01090     if (Align > CPSections[SecIdx].Alignment)
01091       CPSections[SecIdx].Alignment = Align;
01092     CPSections[SecIdx].CPEs.push_back(i);
01093   }
01094 
01095   // Now print stuff into the calculated sections.
01096   const MCSection *CurSection = nullptr;
01097   unsigned Offset = 0;
01098   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
01099     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
01100       unsigned CPI = CPSections[i].CPEs[j];
01101       MCSymbol *Sym = GetCPISymbol(CPI);
01102       if (!Sym->isUndefined())
01103         continue;
01104 
01105       if (CurSection != CPSections[i].S) {
01106         OutStreamer.SwitchSection(CPSections[i].S);
01107         EmitAlignment(Log2_32(CPSections[i].Alignment));
01108         CurSection = CPSections[i].S;
01109         Offset = 0;
01110       }
01111 
01112       MachineConstantPoolEntry CPE = CP[CPI];
01113 
01114       // Emit inter-object padding for alignment.
01115       unsigned AlignMask = CPE.getAlignment() - 1;
01116       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
01117       OutStreamer.EmitZeros(NewOffset - Offset);
01118 
01119       Type *Ty = CPE.getType();
01120       Offset = NewOffset + TM.getDataLayout()->getTypeAllocSize(Ty);
01121 
01122       OutStreamer.EmitLabel(Sym);
01123       if (CPE.isMachineConstantPoolEntry())
01124         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
01125       else
01126         EmitGlobalConstant(CPE.Val.ConstVal);
01127     }
01128   }
01129 }
01130 
01131 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
01132 /// by the current function to the current output stream.
01133 ///
01134 void AsmPrinter::EmitJumpTableInfo() {
01135   const DataLayout *DL = MF->getTarget().getDataLayout();
01136   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
01137   if (!MJTI) return;
01138   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
01139   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
01140   if (JT.empty()) return;
01141 
01142   // Pick the directive to use to print the jump table entries, and switch to
01143   // the appropriate section.
01144   const Function *F = MF->getFunction();
01145   bool JTInDiffSection = false;
01146   if (// In PIC mode, we need to emit the jump table to the same section as the
01147       // function body itself, otherwise the label differences won't make sense.
01148       // FIXME: Need a better predicate for this: what about custom entries?
01149       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
01150       // We should also do if the section name is NULL or function is declared
01151       // in discardable section
01152       // FIXME: this isn't the right predicate, should be based on the MCSection
01153       // for the function.
01154       F->isWeakForLinker()) {
01155     OutStreamer.SwitchSection(
01156         getObjFileLowering().SectionForGlobal(F, *Mang, TM));
01157   } else {
01158     // Otherwise, drop it in the readonly section.
01159     const MCSection *ReadOnlySection =
01160         getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
01161                                                    /*C=*/nullptr);
01162     OutStreamer.SwitchSection(ReadOnlySection);
01163     JTInDiffSection = true;
01164   }
01165 
01166   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getDataLayout())));
01167 
01168   // Jump tables in code sections are marked with a data_region directive
01169   // where that's supported.
01170   if (!JTInDiffSection)
01171     OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
01172 
01173   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
01174     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
01175 
01176     // If this jump table was deleted, ignore it.
01177     if (JTBBs.empty()) continue;
01178 
01179     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
01180     // .set directive for each unique entry.  This reduces the number of
01181     // relocations the assembler will generate for the jump table.
01182     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
01183         MAI->hasSetDirective()) {
01184       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
01185       const TargetLowering *TLI = TM.getTargetLowering();
01186       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
01187       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
01188         const MachineBasicBlock *MBB = JTBBs[ii];
01189         if (!EmittedSets.insert(MBB)) continue;
01190 
01191         // .set LJTSet, LBB32-base
01192         const MCExpr *LHS =
01193           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
01194         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
01195                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
01196       }
01197     }
01198 
01199     // On some targets (e.g. Darwin) we want to emit two consecutive labels
01200     // before each jump table.  The first label is never referenced, but tells
01201     // the assembler and linker the extents of the jump table object.  The
01202     // second label is actually referenced by the code.
01203     if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
01204       // FIXME: This doesn't have to have any specific name, just any randomly
01205       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
01206       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
01207 
01208     OutStreamer.EmitLabel(GetJTISymbol(JTI));
01209 
01210     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
01211       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
01212   }
01213   if (!JTInDiffSection)
01214     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
01215 }
01216 
01217 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
01218 /// current stream.
01219 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
01220                                     const MachineBasicBlock *MBB,
01221                                     unsigned UID) const {
01222   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
01223   const MCExpr *Value = nullptr;
01224   switch (MJTI->getEntryKind()) {
01225   case MachineJumpTableInfo::EK_Inline:
01226     llvm_unreachable("Cannot emit EK_Inline jump table entry");
01227   case MachineJumpTableInfo::EK_Custom32:
01228     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
01229                                                               OutContext);
01230     break;
01231   case MachineJumpTableInfo::EK_BlockAddress:
01232     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
01233     //     .word LBB123
01234     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
01235     break;
01236   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
01237     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
01238     // with a relocation as gp-relative, e.g.:
01239     //     .gprel32 LBB123
01240     MCSymbol *MBBSym = MBB->getSymbol();
01241     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
01242     return;
01243   }
01244 
01245   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
01246     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
01247     // with a relocation as gp-relative, e.g.:
01248     //     .gpdword LBB123
01249     MCSymbol *MBBSym = MBB->getSymbol();
01250     OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
01251     return;
01252   }
01253 
01254   case MachineJumpTableInfo::EK_LabelDifference32: {
01255     // EK_LabelDifference32 - Each entry is the address of the block minus
01256     // the address of the jump table.  This is used for PIC jump tables where
01257     // gprel32 is not supported.  e.g.:
01258     //      .word LBB123 - LJTI1_2
01259     // If the .set directive is supported, this is emitted as:
01260     //      .set L4_5_set_123, LBB123 - LJTI1_2
01261     //      .word L4_5_set_123
01262 
01263     // If we have emitted set directives for the jump table entries, print
01264     // them rather than the entries themselves.  If we're emitting PIC, then
01265     // emit the table entries as differences between two text section labels.
01266     if (MAI->hasSetDirective()) {
01267       // If we used .set, reference the .set's symbol.
01268       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
01269                                       OutContext);
01270       break;
01271     }
01272     // Otherwise, use the difference as the jump table entry.
01273     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
01274     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
01275     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
01276     break;
01277   }
01278   }
01279 
01280   assert(Value && "Unknown entry kind!");
01281 
01282   unsigned EntrySize = MJTI->getEntrySize(*TM.getDataLayout());
01283   OutStreamer.EmitValue(Value, EntrySize);
01284 }
01285 
01286 
01287 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
01288 /// special global used by LLVM.  If so, emit it and return true, otherwise
01289 /// do nothing and return false.
01290 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
01291   if (GV->getName() == "llvm.used") {
01292     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
01293       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
01294     return true;
01295   }
01296 
01297   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
01298   if (StringRef(GV->getSection()) == "llvm.metadata" ||
01299       GV->hasAvailableExternallyLinkage())
01300     return true;
01301 
01302   if (!GV->hasAppendingLinkage()) return false;
01303 
01304   assert(GV->hasInitializer() && "Not a special LLVM global!");
01305 
01306   if (GV->getName() == "llvm.global_ctors") {
01307     EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
01308 
01309     if (TM.getRelocationModel() == Reloc::Static &&
01310         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
01311       StringRef Sym(".constructors_used");
01312       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
01313                                       MCSA_Reference);
01314     }
01315     return true;
01316   }
01317 
01318   if (GV->getName() == "llvm.global_dtors") {
01319     EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
01320 
01321     if (TM.getRelocationModel() == Reloc::Static &&
01322         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
01323       StringRef Sym(".destructors_used");
01324       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
01325                                       MCSA_Reference);
01326     }
01327     return true;
01328   }
01329 
01330   return false;
01331 }
01332 
01333 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
01334 /// global in the specified llvm.used list for which emitUsedDirectiveFor
01335 /// is true, as being used with this directive.
01336 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
01337   // Should be an array of 'i8*'.
01338   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
01339     const GlobalValue *GV =
01340       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
01341     if (GV)
01342       OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
01343   }
01344 }
01345 
01346 namespace {
01347 struct Structor {
01348   Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
01349   int Priority;
01350   llvm::Constant *Func;
01351   llvm::GlobalValue *ComdatKey;
01352 };
01353 } // end namespace
01354 
01355 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
01356 /// priority.
01357 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
01358   // Should be an array of '{ int, void ()* }' structs.  The first value is the
01359   // init priority.
01360   if (!isa<ConstantArray>(List)) return;
01361 
01362   // Sanity check the structors list.
01363   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
01364   if (!InitList) return; // Not an array!
01365   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
01366   // FIXME: Only allow the 3-field form in LLVM 4.0.
01367   if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
01368     return; // Not an array of two or three elements!
01369   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
01370       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
01371   if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
01372     return; // Not (int, ptr, ptr).
01373 
01374   // Gather the structors in a form that's convenient for sorting by priority.
01375   SmallVector<Structor, 8> Structors;
01376   for (Value *O : InitList->operands()) {
01377     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
01378     if (!CS) continue; // Malformed.
01379     if (CS->getOperand(1)->isNullValue())
01380       break;  // Found a null terminator, skip the rest.
01381     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
01382     if (!Priority) continue; // Malformed.
01383     Structors.push_back(Structor());
01384     Structor &S = Structors.back();
01385     S.Priority = Priority->getLimitedValue(65535);
01386     S.Func = CS->getOperand(1);
01387     if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
01388       S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
01389   }
01390 
01391   // Emit the function pointers in the target-specific order
01392   const DataLayout *DL = TM.getDataLayout();
01393   unsigned Align = Log2_32(DL->getPointerPrefAlignment());
01394   std::stable_sort(Structors.begin(), Structors.end(),
01395                    [](const Structor &L,
01396                       const Structor &R) { return L.Priority < R.Priority; });
01397   for (Structor &S : Structors) {
01398     const TargetLoweringObjectFile &Obj = getObjFileLowering();
01399     const MCSymbol *KeySym = nullptr;
01400     if (GlobalValue *GV = S.ComdatKey) {
01401       if (GV->hasAvailableExternallyLinkage())
01402         // If the associated variable is available_externally, some other TU
01403         // will provide its dynamic initializer.
01404         continue;
01405 
01406       KeySym = getSymbol(GV);
01407     }
01408     const MCSection *OutputSection =
01409         (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
01410                 : Obj.getStaticDtorSection(S.Priority, KeySym));
01411     OutStreamer.SwitchSection(OutputSection);
01412     if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
01413       EmitAlignment(Align);
01414     EmitXXStructor(S.Func);
01415   }
01416 }
01417 
01418 void AsmPrinter::EmitModuleIdents(Module &M) {
01419   if (!MAI->hasIdentDirective())
01420     return;
01421 
01422   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
01423     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
01424       const MDNode *N = NMD->getOperand(i);
01425       assert(N->getNumOperands() == 1 &&
01426              "llvm.ident metadata entry can have only one operand");
01427       const MDString *S = cast<MDString>(N->getOperand(0));
01428       OutStreamer.EmitIdent(S->getString());
01429     }
01430   }
01431 }
01432 
01433 //===--------------------------------------------------------------------===//
01434 // Emission and print routines
01435 //
01436 
01437 /// EmitInt8 - Emit a byte directive and value.
01438 ///
01439 void AsmPrinter::EmitInt8(int Value) const {
01440   OutStreamer.EmitIntValue(Value, 1);
01441 }
01442 
01443 /// EmitInt16 - Emit a short directive and value.
01444 ///
01445 void AsmPrinter::EmitInt16(int Value) const {
01446   OutStreamer.EmitIntValue(Value, 2);
01447 }
01448 
01449 /// EmitInt32 - Emit a long directive and value.
01450 ///
01451 void AsmPrinter::EmitInt32(int Value) const {
01452   OutStreamer.EmitIntValue(Value, 4);
01453 }
01454 
01455 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
01456 /// in bytes of the directive is specified by Size and Hi/Lo specify the
01457 /// labels.  This implicitly uses .set if it is available.
01458 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
01459                                      unsigned Size) const {
01460   // Get the Hi-Lo expression.
01461   const MCExpr *Diff =
01462     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
01463                             MCSymbolRefExpr::Create(Lo, OutContext),
01464                             OutContext);
01465 
01466   if (!MAI->hasSetDirective()) {
01467     OutStreamer.EmitValue(Diff, Size);
01468     return;
01469   }
01470 
01471   // Otherwise, emit with .set (aka assignment).
01472   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
01473   OutStreamer.EmitAssignment(SetLabel, Diff);
01474   OutStreamer.EmitSymbolValue(SetLabel, Size);
01475 }
01476 
01477 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
01478 /// where the size in bytes of the directive is specified by Size and Hi/Lo
01479 /// specify the labels.  This implicitly uses .set if it is available.
01480 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
01481                                            const MCSymbol *Lo,
01482                                            unsigned Size) const {
01483 
01484   // Emit Hi+Offset - Lo
01485   // Get the Hi+Offset expression.
01486   const MCExpr *Plus =
01487     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
01488                             MCConstantExpr::Create(Offset, OutContext),
01489                             OutContext);
01490 
01491   // Get the Hi+Offset-Lo expression.
01492   const MCExpr *Diff =
01493     MCBinaryExpr::CreateSub(Plus,
01494                             MCSymbolRefExpr::Create(Lo, OutContext),
01495                             OutContext);
01496 
01497   if (!MAI->hasSetDirective())
01498     OutStreamer.EmitValue(Diff, Size);
01499   else {
01500     // Otherwise, emit with .set (aka assignment).
01501     MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
01502     OutStreamer.EmitAssignment(SetLabel, Diff);
01503     OutStreamer.EmitSymbolValue(SetLabel, Size);
01504   }
01505 }
01506 
01507 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
01508 /// where the size in bytes of the directive is specified by Size and Label
01509 /// specifies the label.  This implicitly uses .set if it is available.
01510 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
01511                                      unsigned Size,
01512                                      bool IsSectionRelative) const {
01513   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
01514     OutStreamer.EmitCOFFSecRel32(Label);
01515     return;
01516   }
01517 
01518   // Emit Label+Offset (or just Label if Offset is zero)
01519   const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
01520   if (Offset)
01521     Expr = MCBinaryExpr::CreateAdd(
01522         Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
01523 
01524   OutStreamer.EmitValue(Expr, Size);
01525 }
01526 
01527 //===----------------------------------------------------------------------===//
01528 
01529 // EmitAlignment - Emit an alignment directive to the specified power of
01530 // two boundary.  For example, if you pass in 3 here, you will get an 8
01531 // byte alignment.  If a global value is specified, and if that global has
01532 // an explicit alignment requested, it will override the alignment request
01533 // if required for correctness.
01534 //
01535 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
01536   if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getDataLayout(), NumBits);
01537 
01538   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
01539 
01540   if (getCurrentSection()->getKind().isText())
01541     OutStreamer.EmitCodeAlignment(1 << NumBits);
01542   else
01543     OutStreamer.EmitValueToAlignment(1 << NumBits);
01544 }
01545 
01546 //===----------------------------------------------------------------------===//
01547 // Constant emission.
01548 //===----------------------------------------------------------------------===//
01549 
01550 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
01551 ///
01552 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
01553   MCContext &Ctx = AP.OutContext;
01554 
01555   if (CV->isNullValue() || isa<UndefValue>(CV))
01556     return MCConstantExpr::Create(0, Ctx);
01557 
01558   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
01559     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
01560 
01561   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
01562     return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
01563 
01564   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
01565     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
01566 
01567   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
01568   if (!CE) {
01569     llvm_unreachable("Unknown constant value to lower!");
01570   }
01571 
01572   if (const MCExpr *RelocExpr =
01573           AP.getObjFileLowering().getExecutableRelativeSymbol(CE, *AP.Mang,
01574                                                               AP.TM))
01575     return RelocExpr;
01576 
01577   switch (CE->getOpcode()) {
01578   default:
01579     // If the code isn't optimized, there may be outstanding folding
01580     // opportunities. Attempt to fold the expression using DataLayout as a
01581     // last resort before giving up.
01582     if (Constant *C =
01583           ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
01584       if (C != CE)
01585         return lowerConstant(C, AP);
01586 
01587     // Otherwise report the problem to the user.
01588     {
01589       std::string S;
01590       raw_string_ostream OS(S);
01591       OS << "Unsupported expression in static initializer: ";
01592       CE->printAsOperand(OS, /*PrintType=*/false,
01593                      !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
01594       report_fatal_error(OS.str());
01595     }
01596   case Instruction::GetElementPtr: {
01597     const DataLayout &DL = *AP.TM.getDataLayout();
01598     // Generate a symbolic expression for the byte address
01599     APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
01600     cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
01601 
01602     const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
01603     if (!OffsetAI)
01604       return Base;
01605 
01606     int64_t Offset = OffsetAI.getSExtValue();
01607     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
01608                                    Ctx);
01609   }
01610 
01611   case Instruction::Trunc:
01612     // We emit the value and depend on the assembler to truncate the generated
01613     // expression properly.  This is important for differences between
01614     // blockaddress labels.  Since the two labels are in the same function, it
01615     // is reasonable to treat their delta as a 32-bit value.
01616     // FALL THROUGH.
01617   case Instruction::BitCast:
01618     return lowerConstant(CE->getOperand(0), AP);
01619 
01620   case Instruction::IntToPtr: {
01621     const DataLayout &DL = *AP.TM.getDataLayout();
01622     // Handle casts to pointers by changing them into casts to the appropriate
01623     // integer type.  This promotes constant folding and simplifies this code.
01624     Constant *Op = CE->getOperand(0);
01625     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
01626                                       false/*ZExt*/);
01627     return lowerConstant(Op, AP);
01628   }
01629 
01630   case Instruction::PtrToInt: {
01631     const DataLayout &DL = *AP.TM.getDataLayout();
01632     // Support only foldable casts to/from pointers that can be eliminated by
01633     // changing the pointer to the appropriately sized integer type.
01634     Constant *Op = CE->getOperand(0);
01635     Type *Ty = CE->getType();
01636 
01637     const MCExpr *OpExpr = lowerConstant(Op, AP);
01638 
01639     // We can emit the pointer value into this slot if the slot is an
01640     // integer slot equal to the size of the pointer.
01641     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
01642       return OpExpr;
01643 
01644     // Otherwise the pointer is smaller than the resultant integer, mask off
01645     // the high bits so we are sure to get a proper truncation if the input is
01646     // a constant expr.
01647     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
01648     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
01649     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
01650   }
01651 
01652   // The MC library also has a right-shift operator, but it isn't consistently
01653   // signed or unsigned between different targets.
01654   case Instruction::Add:
01655   case Instruction::Sub:
01656   case Instruction::Mul:
01657   case Instruction::SDiv:
01658   case Instruction::SRem:
01659   case Instruction::Shl:
01660   case Instruction::And:
01661   case Instruction::Or:
01662   case Instruction::Xor: {
01663     const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
01664     const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
01665     switch (CE->getOpcode()) {
01666     default: llvm_unreachable("Unknown binary operator constant cast expr");
01667     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
01668     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
01669     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
01670     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
01671     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
01672     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
01673     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
01674     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
01675     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
01676     }
01677   }
01678   }
01679 }
01680 
01681 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
01682 
01683 /// isRepeatedByteSequence - Determine whether the given value is
01684 /// composed of a repeated sequence of identical bytes and return the
01685 /// byte value.  If it is not a repeated sequence, return -1.
01686 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
01687   StringRef Data = V->getRawDataValues();
01688   assert(!Data.empty() && "Empty aggregates should be CAZ node");
01689   char C = Data[0];
01690   for (unsigned i = 1, e = Data.size(); i != e; ++i)
01691     if (Data[i] != C) return -1;
01692   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
01693 }
01694 
01695 
01696 /// isRepeatedByteSequence - Determine whether the given value is
01697 /// composed of a repeated sequence of identical bytes and return the
01698 /// byte value.  If it is not a repeated sequence, return -1.
01699 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
01700 
01701   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
01702     if (CI->getBitWidth() > 64) return -1;
01703 
01704     uint64_t Size = TM.getDataLayout()->getTypeAllocSize(V->getType());
01705     uint64_t Value = CI->getZExtValue();
01706 
01707     // Make sure the constant is at least 8 bits long and has a power
01708     // of 2 bit width.  This guarantees the constant bit width is
01709     // always a multiple of 8 bits, avoiding issues with padding out
01710     // to Size and other such corner cases.
01711     if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
01712 
01713     uint8_t Byte = static_cast<uint8_t>(Value);
01714 
01715     for (unsigned i = 1; i < Size; ++i) {
01716       Value >>= 8;
01717       if (static_cast<uint8_t>(Value) != Byte) return -1;
01718     }
01719     return Byte;
01720   }
01721   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
01722     // Make sure all array elements are sequences of the same repeated
01723     // byte.
01724     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
01725     int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
01726     if (Byte == -1) return -1;
01727 
01728     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
01729       int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
01730       if (ThisByte == -1) return -1;
01731       if (Byte != ThisByte) return -1;
01732     }
01733     return Byte;
01734   }
01735 
01736   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
01737     return isRepeatedByteSequence(CDS);
01738 
01739   return -1;
01740 }
01741 
01742 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
01743                                              AsmPrinter &AP){
01744 
01745   // See if we can aggregate this into a .fill, if so, emit it as such.
01746   int Value = isRepeatedByteSequence(CDS, AP.TM);
01747   if (Value != -1) {
01748     uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CDS->getType());
01749     // Don't emit a 1-byte object as a .fill.
01750     if (Bytes > 1)
01751       return AP.OutStreamer.EmitFill(Bytes, Value);
01752   }
01753 
01754   // If this can be emitted with .ascii/.asciz, emit it as such.
01755   if (CDS->isString())
01756     return AP.OutStreamer.EmitBytes(CDS->getAsString());
01757 
01758   // Otherwise, emit the values in successive locations.
01759   unsigned ElementByteSize = CDS->getElementByteSize();
01760   if (isa<IntegerType>(CDS->getElementType())) {
01761     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01762       if (AP.isVerbose())
01763         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
01764                                                 CDS->getElementAsInteger(i));
01765       AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
01766                                   ElementByteSize);
01767     }
01768   } else if (ElementByteSize == 4) {
01769     // FP Constants are printed as integer constants to avoid losing
01770     // precision.
01771     assert(CDS->getElementType()->isFloatTy());
01772     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01773       union {
01774         float F;
01775         uint32_t I;
01776       };
01777 
01778       F = CDS->getElementAsFloat(i);
01779       if (AP.isVerbose())
01780         AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
01781       AP.OutStreamer.EmitIntValue(I, 4);
01782     }
01783   } else {
01784     assert(CDS->getElementType()->isDoubleTy());
01785     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01786       union {
01787         double F;
01788         uint64_t I;
01789       };
01790 
01791       F = CDS->getElementAsDouble(i);
01792       if (AP.isVerbose())
01793         AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
01794       AP.OutStreamer.EmitIntValue(I, 8);
01795     }
01796   }
01797 
01798   const DataLayout &DL = *AP.TM.getDataLayout();
01799   unsigned Size = DL.getTypeAllocSize(CDS->getType());
01800   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
01801                         CDS->getNumElements();
01802   if (unsigned Padding = Size - EmittedSize)
01803     AP.OutStreamer.EmitZeros(Padding);
01804 
01805 }
01806 
01807 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
01808   // See if we can aggregate some values.  Make sure it can be
01809   // represented as a series of bytes of the constant value.
01810   int Value = isRepeatedByteSequence(CA, AP.TM);
01811 
01812   if (Value != -1) {
01813     uint64_t Bytes = AP.TM.getDataLayout()->getTypeAllocSize(CA->getType());
01814     AP.OutStreamer.EmitFill(Bytes, Value);
01815   }
01816   else {
01817     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
01818       emitGlobalConstantImpl(CA->getOperand(i), AP);
01819   }
01820 }
01821 
01822 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
01823   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
01824     emitGlobalConstantImpl(CV->getOperand(i), AP);
01825 
01826   const DataLayout &DL = *AP.TM.getDataLayout();
01827   unsigned Size = DL.getTypeAllocSize(CV->getType());
01828   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
01829                          CV->getType()->getNumElements();
01830   if (unsigned Padding = Size - EmittedSize)
01831     AP.OutStreamer.EmitZeros(Padding);
01832 }
01833 
01834 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
01835   // Print the fields in successive locations. Pad to align if needed!
01836   const DataLayout *DL = AP.TM.getDataLayout();
01837   unsigned Size = DL->getTypeAllocSize(CS->getType());
01838   const StructLayout *Layout = DL->getStructLayout(CS->getType());
01839   uint64_t SizeSoFar = 0;
01840   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
01841     const Constant *Field = CS->getOperand(i);
01842 
01843     // Check if padding is needed and insert one or more 0s.
01844     uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
01845     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
01846                         - Layout->getElementOffset(i)) - FieldSize;
01847     SizeSoFar += FieldSize + PadSize;
01848 
01849     // Now print the actual field value.
01850     emitGlobalConstantImpl(Field, AP);
01851 
01852     // Insert padding - this may include padding to increase the size of the
01853     // current field up to the ABI size (if the struct is not packed) as well
01854     // as padding to ensure that the next field starts at the right offset.
01855     AP.OutStreamer.EmitZeros(PadSize);
01856   }
01857   assert(SizeSoFar == Layout->getSizeInBytes() &&
01858          "Layout of constant struct may be incorrect!");
01859 }
01860 
01861 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
01862   APInt API = CFP->getValueAPF().bitcastToAPInt();
01863 
01864   // First print a comment with what we think the original floating-point value
01865   // should have been.
01866   if (AP.isVerbose()) {
01867     SmallString<8> StrVal;
01868     CFP->getValueAPF().toString(StrVal);
01869 
01870     if (CFP->getType())
01871       CFP->getType()->print(AP.OutStreamer.GetCommentOS());
01872     else
01873       AP.OutStreamer.GetCommentOS() << "Printing <null> Type";
01874     AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
01875   }
01876 
01877   // Now iterate through the APInt chunks, emitting them in endian-correct
01878   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
01879   // floats).
01880   unsigned NumBytes = API.getBitWidth() / 8;
01881   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
01882   const uint64_t *p = API.getRawData();
01883 
01884   // PPC's long double has odd notions of endianness compared to how LLVM
01885   // handles it: p[0] goes first for *big* endian on PPC.
01886   if (AP.TM.getDataLayout()->isBigEndian() &&
01887       !CFP->getType()->isPPC_FP128Ty()) {
01888     int Chunk = API.getNumWords() - 1;
01889 
01890     if (TrailingBytes)
01891       AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
01892 
01893     for (; Chunk >= 0; --Chunk)
01894       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
01895   } else {
01896     unsigned Chunk;
01897     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
01898       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
01899 
01900     if (TrailingBytes)
01901       AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
01902   }
01903 
01904   // Emit the tail padding for the long double.
01905   const DataLayout &DL = *AP.TM.getDataLayout();
01906   AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
01907                            DL.getTypeStoreSize(CFP->getType()));
01908 }
01909 
01910 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
01911   const DataLayout *DL = AP.TM.getDataLayout();
01912   unsigned BitWidth = CI->getBitWidth();
01913 
01914   // Copy the value as we may massage the layout for constants whose bit width
01915   // is not a multiple of 64-bits.
01916   APInt Realigned(CI->getValue());
01917   uint64_t ExtraBits = 0;
01918   unsigned ExtraBitsSize = BitWidth & 63;
01919 
01920   if (ExtraBitsSize) {
01921     // The bit width of the data is not a multiple of 64-bits.
01922     // The extra bits are expected to be at the end of the chunk of the memory.
01923     // Little endian:
01924     // * Nothing to be done, just record the extra bits to emit.
01925     // Big endian:
01926     // * Record the extra bits to emit.
01927     // * Realign the raw data to emit the chunks of 64-bits.
01928     if (DL->isBigEndian()) {
01929       // Basically the structure of the raw data is a chunk of 64-bits cells:
01930       //    0        1         BitWidth / 64
01931       // [chunk1][chunk2] ... [chunkN].
01932       // The most significant chunk is chunkN and it should be emitted first.
01933       // However, due to the alignment issue chunkN contains useless bits.
01934       // Realign the chunks so that they contain only useless information:
01935       // ExtraBits     0       1       (BitWidth / 64) - 1
01936       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
01937       ExtraBits = Realigned.getRawData()[0] &
01938         (((uint64_t)-1) >> (64 - ExtraBitsSize));
01939       Realigned = Realigned.lshr(ExtraBitsSize);
01940     } else
01941       ExtraBits = Realigned.getRawData()[BitWidth / 64];
01942   }
01943 
01944   // We don't expect assemblers to support integer data directives
01945   // for more than 64 bits, so we emit the data in at most 64-bit
01946   // quantities at a time.
01947   const uint64_t *RawData = Realigned.getRawData();
01948   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
01949     uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
01950     AP.OutStreamer.EmitIntValue(Val, 8);
01951   }
01952 
01953   if (ExtraBitsSize) {
01954     // Emit the extra bits after the 64-bits chunks.
01955 
01956     // Emit a directive that fills the expected size.
01957     uint64_t Size = AP.TM.getDataLayout()->getTypeAllocSize(CI->getType());
01958     Size -= (BitWidth / 64) * 8;
01959     assert(Size && Size * 8 >= ExtraBitsSize &&
01960            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
01961            == ExtraBits && "Directive too small for extra bits.");
01962     AP.OutStreamer.EmitIntValue(ExtraBits, Size);
01963   }
01964 }
01965 
01966 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
01967   const DataLayout *DL = AP.TM.getDataLayout();
01968   uint64_t Size = DL->getTypeAllocSize(CV->getType());
01969   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
01970     return AP.OutStreamer.EmitZeros(Size);
01971 
01972   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
01973     switch (Size) {
01974     case 1:
01975     case 2:
01976     case 4:
01977     case 8:
01978       if (AP.isVerbose())
01979         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
01980                                                 CI->getZExtValue());
01981       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
01982       return;
01983     default:
01984       emitGlobalConstantLargeInt(CI, AP);
01985       return;
01986     }
01987   }
01988 
01989   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
01990     return emitGlobalConstantFP(CFP, AP);
01991 
01992   if (isa<ConstantPointerNull>(CV)) {
01993     AP.OutStreamer.EmitIntValue(0, Size);
01994     return;
01995   }
01996 
01997   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
01998     return emitGlobalConstantDataSequential(CDS, AP);
01999 
02000   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
02001     return emitGlobalConstantArray(CVA, AP);
02002 
02003   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
02004     return emitGlobalConstantStruct(CVS, AP);
02005 
02006   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
02007     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
02008     // vectors).
02009     if (CE->getOpcode() == Instruction::BitCast)
02010       return emitGlobalConstantImpl(CE->getOperand(0), AP);
02011 
02012     if (Size > 8) {
02013       // If the constant expression's size is greater than 64-bits, then we have
02014       // to emit the value in chunks. Try to constant fold the value and emit it
02015       // that way.
02016       Constant *New = ConstantFoldConstantExpression(CE, DL);
02017       if (New && New != CE)
02018         return emitGlobalConstantImpl(New, AP);
02019     }
02020   }
02021 
02022   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
02023     return emitGlobalConstantVector(V, AP);
02024 
02025   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
02026   // thread the streamer with EmitValue.
02027   AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
02028 }
02029 
02030 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
02031 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
02032   uint64_t Size = TM.getDataLayout()->getTypeAllocSize(CV->getType());
02033   if (Size)
02034     emitGlobalConstantImpl(CV, *this);
02035   else if (MAI->hasSubsectionsViaSymbols()) {
02036     // If the global has zero size, emit a single byte so that two labels don't
02037     // look like they are at the same location.
02038     OutStreamer.EmitIntValue(0, 1);
02039   }
02040 }
02041 
02042 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
02043   // Target doesn't support this yet!
02044   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
02045 }
02046 
02047 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
02048   if (Offset > 0)
02049     OS << '+' << Offset;
02050   else if (Offset < 0)
02051     OS << Offset;
02052 }
02053 
02054 //===----------------------------------------------------------------------===//
02055 // Symbol Lowering Routines.
02056 //===----------------------------------------------------------------------===//
02057 
02058 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
02059 /// temporary label with the specified stem and unique ID.
02060 MCSymbol *AsmPrinter::GetTempSymbol(Twine Name, unsigned ID) const {
02061   const DataLayout *DL = TM.getDataLayout();
02062   return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
02063                                       Name + Twine(ID));
02064 }
02065 
02066 /// GetTempSymbol - Return an assembler temporary label with the specified
02067 /// stem.
02068 MCSymbol *AsmPrinter::GetTempSymbol(Twine Name) const {
02069   const DataLayout *DL = TM.getDataLayout();
02070   return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
02071                                       Name);
02072 }
02073 
02074 
02075 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
02076   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
02077 }
02078 
02079 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
02080   return MMI->getAddrLabelSymbol(BB);
02081 }
02082 
02083 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
02084 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
02085   const DataLayout *DL = TM.getDataLayout();
02086   return OutContext.GetOrCreateSymbol
02087     (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
02088      + "_" + Twine(CPID));
02089 }
02090 
02091 /// GetJTISymbol - Return the symbol for the specified jump table entry.
02092 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
02093   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
02094 }
02095 
02096 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
02097 /// FIXME: privatize to AsmPrinter.
02098 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
02099   const DataLayout *DL = TM.getDataLayout();
02100   return OutContext.GetOrCreateSymbol
02101   (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
02102    Twine(UID) + "_set_" + Twine(MBBID));
02103 }
02104 
02105 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
02106                                                    StringRef Suffix) const {
02107   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
02108                                                            TM);
02109 }
02110 
02111 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
02112 /// ExternalSymbol.
02113 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
02114   SmallString<60> NameStr;
02115   Mang->getNameWithPrefix(NameStr, Sym);
02116   return OutContext.GetOrCreateSymbol(NameStr.str());
02117 }
02118 
02119 
02120 
02121 /// PrintParentLoopComment - Print comments about parent loops of this one.
02122 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
02123                                    unsigned FunctionNumber) {
02124   if (!Loop) return;
02125   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
02126   OS.indent(Loop->getLoopDepth()*2)
02127     << "Parent Loop BB" << FunctionNumber << "_"
02128     << Loop->getHeader()->getNumber()
02129     << " Depth=" << Loop->getLoopDepth() << '\n';
02130 }
02131 
02132 
02133 /// PrintChildLoopComment - Print comments about child loops within
02134 /// the loop for this basic block, with nesting.
02135 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
02136                                   unsigned FunctionNumber) {
02137   // Add child loop information
02138   for (const MachineLoop *CL : *Loop) {
02139     OS.indent(CL->getLoopDepth()*2)
02140       << "Child Loop BB" << FunctionNumber << "_"
02141       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
02142       << '\n';
02143     PrintChildLoopComment(OS, CL, FunctionNumber);
02144   }
02145 }
02146 
02147 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
02148 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
02149                                        const MachineLoopInfo *LI,
02150                                        const AsmPrinter &AP) {
02151   // Add loop depth information
02152   const MachineLoop *Loop = LI->getLoopFor(&MBB);
02153   if (!Loop) return;
02154 
02155   MachineBasicBlock *Header = Loop->getHeader();
02156   assert(Header && "No header for loop");
02157 
02158   // If this block is not a loop header, just print out what is the loop header
02159   // and return.
02160   if (Header != &MBB) {
02161     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
02162                               Twine(AP.getFunctionNumber())+"_" +
02163                               Twine(Loop->getHeader()->getNumber())+
02164                               " Depth="+Twine(Loop->getLoopDepth()));
02165     return;
02166   }
02167 
02168   // Otherwise, it is a loop header.  Print out information about child and
02169   // parent loops.
02170   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
02171 
02172   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
02173 
02174   OS << "=>";
02175   OS.indent(Loop->getLoopDepth()*2-2);
02176 
02177   OS << "This ";
02178   if (Loop->empty())
02179     OS << "Inner ";
02180   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
02181 
02182   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
02183 }
02184 
02185 
02186 /// EmitBasicBlockStart - This method prints the label for the specified
02187 /// MachineBasicBlock, an alignment (if present) and a comment describing
02188 /// it if appropriate.
02189 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
02190   // Emit an alignment directive for this block, if needed.
02191   if (unsigned Align = MBB.getAlignment())
02192     EmitAlignment(Align);
02193 
02194   // If the block has its address taken, emit any labels that were used to
02195   // reference the block.  It is possible that there is more than one label
02196   // here, because multiple LLVM BB's may have been RAUW'd to this block after
02197   // the references were generated.
02198   if (MBB.hasAddressTaken()) {
02199     const BasicBlock *BB = MBB.getBasicBlock();
02200     if (isVerbose())
02201       OutStreamer.AddComment("Block address taken");
02202 
02203     std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
02204     for (auto *Sym : Symbols)
02205       OutStreamer.EmitLabel(Sym);
02206   }
02207 
02208   // Print some verbose block comments.
02209   if (isVerbose()) {
02210     if (const BasicBlock *BB = MBB.getBasicBlock())
02211       if (BB->hasName())
02212         OutStreamer.AddComment("%" + BB->getName());
02213     emitBasicBlockLoopComments(MBB, LI, *this);
02214   }
02215 
02216   // Print the main label for the block.
02217   if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
02218     if (isVerbose()) {
02219       // NOTE: Want this comment at start of line, don't emit with AddComment.
02220       OutStreamer.emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
02221     }
02222   } else {
02223     OutStreamer.EmitLabel(MBB.getSymbol());
02224   }
02225 }
02226 
02227 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
02228                                 bool IsDefinition) const {
02229   MCSymbolAttr Attr = MCSA_Invalid;
02230 
02231   switch (Visibility) {
02232   default: break;
02233   case GlobalValue::HiddenVisibility:
02234     if (IsDefinition)
02235       Attr = MAI->getHiddenVisibilityAttr();
02236     else
02237       Attr = MAI->getHiddenDeclarationVisibilityAttr();
02238     break;
02239   case GlobalValue::ProtectedVisibility:
02240     Attr = MAI->getProtectedVisibilityAttr();
02241     break;
02242   }
02243 
02244   if (Attr != MCSA_Invalid)
02245     OutStreamer.EmitSymbolAttribute(Sym, Attr);
02246 }
02247 
02248 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
02249 /// exactly one predecessor and the control transfer mechanism between
02250 /// the predecessor and this block is a fall-through.
02251 bool AsmPrinter::
02252 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
02253   // If this is a landing pad, it isn't a fall through.  If it has no preds,
02254   // then nothing falls through to it.
02255   if (MBB->isLandingPad() || MBB->pred_empty())
02256     return false;
02257 
02258   // If there isn't exactly one predecessor, it can't be a fall through.
02259   if (MBB->pred_size() > 1)
02260     return false;
02261 
02262   // The predecessor has to be immediately before this block.
02263   MachineBasicBlock *Pred = *MBB->pred_begin();
02264   if (!Pred->isLayoutSuccessor(MBB))
02265     return false;
02266 
02267   // If the block is completely empty, then it definitely does fall through.
02268   if (Pred->empty())
02269     return true;
02270 
02271   // Check the terminators in the previous blocks
02272   for (const auto &MI : Pred->terminators()) {
02273     // If it is not a simple branch, we are in a table somewhere.
02274     if (!MI.isBranch() || MI.isIndirectBranch())
02275       return false;
02276 
02277     // If we are the operands of one of the branches, this is not a fall
02278     // through. Note that targets with delay slots will usually bundle
02279     // terminators with the delay slot instruction.
02280     for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
02281       if (OP->isJTI())
02282         return false;
02283       if (OP->isMBB() && OP->getMBB() == MBB)
02284         return false;
02285     }
02286   }
02287 
02288   return true;
02289 }
02290 
02291 
02292 
02293 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
02294   if (!S.usesMetadata())
02295     return nullptr;
02296 
02297   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
02298   gcp_map_type::iterator GCPI = GCMap.find(&S);
02299   if (GCPI != GCMap.end())
02300     return GCPI->second.get();
02301 
02302   const char *Name = S.getName().c_str();
02303 
02304   for (GCMetadataPrinterRegistry::iterator
02305          I = GCMetadataPrinterRegistry::begin(),
02306          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
02307     if (strcmp(Name, I->getName()) == 0) {
02308       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
02309       GMP->S = &S;
02310       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
02311       return IterBool.first->second.get();
02312     }
02313 
02314   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
02315 }
02316 
02317 /// Pin vtable to this file.
02318 AsmPrinterHandler::~AsmPrinterHandler() {}