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