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