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