LCOV - code coverage report
Current view: top level - lib/CodeGen/AsmPrinter - AsmPrinter.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 1245 1293 96.3 %
Date: 2018-06-17 00:07:59 Functions: 93 96 96.9 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements the AsmPrinter class.
      11             : //
      12             : //===----------------------------------------------------------------------===//
      13             : 
      14             : #include "llvm/CodeGen/AsmPrinter.h"
      15             : #include "AsmPrinterHandler.h"
      16             : #include "CodeViewDebug.h"
      17             : #include "DwarfDebug.h"
      18             : #include "DwarfException.h"
      19             : #include "WinCFGuard.h"
      20             : #include "WinException.h"
      21             : #include "llvm/ADT/APFloat.h"
      22             : #include "llvm/ADT/APInt.h"
      23             : #include "llvm/ADT/DenseMap.h"
      24             : #include "llvm/ADT/STLExtras.h"
      25             : #include "llvm/ADT/SmallPtrSet.h"
      26             : #include "llvm/ADT/SmallString.h"
      27             : #include "llvm/ADT/SmallVector.h"
      28             : #include "llvm/ADT/Statistic.h"
      29             : #include "llvm/ADT/StringRef.h"
      30             : #include "llvm/ADT/Triple.h"
      31             : #include "llvm/ADT/Twine.h"
      32             : #include "llvm/Analysis/ConstantFolding.h"
      33             : #include "llvm/Analysis/EHPersonalities.h"
      34             : #include "llvm/Analysis/OptimizationRemarkEmitter.h"
      35             : #include "llvm/BinaryFormat/Dwarf.h"
      36             : #include "llvm/BinaryFormat/ELF.h"
      37             : #include "llvm/CodeGen/GCMetadata.h"
      38             : #include "llvm/CodeGen/GCMetadataPrinter.h"
      39             : #include "llvm/CodeGen/GCStrategy.h"
      40             : #include "llvm/CodeGen/MachineBasicBlock.h"
      41             : #include "llvm/CodeGen/MachineConstantPool.h"
      42             : #include "llvm/CodeGen/MachineDominators.h"
      43             : #include "llvm/CodeGen/MachineFrameInfo.h"
      44             : #include "llvm/CodeGen/MachineFunction.h"
      45             : #include "llvm/CodeGen/MachineFunctionPass.h"
      46             : #include "llvm/CodeGen/MachineInstr.h"
      47             : #include "llvm/CodeGen/MachineInstrBundle.h"
      48             : #include "llvm/CodeGen/MachineJumpTableInfo.h"
      49             : #include "llvm/CodeGen/MachineLoopInfo.h"
      50             : #include "llvm/CodeGen/MachineMemOperand.h"
      51             : #include "llvm/CodeGen/MachineModuleInfo.h"
      52             : #include "llvm/CodeGen/MachineModuleInfoImpls.h"
      53             : #include "llvm/CodeGen/MachineOperand.h"
      54             : #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
      55             : #include "llvm/CodeGen/TargetFrameLowering.h"
      56             : #include "llvm/CodeGen/TargetInstrInfo.h"
      57             : #include "llvm/CodeGen/TargetLowering.h"
      58             : #include "llvm/CodeGen/TargetOpcodes.h"
      59             : #include "llvm/CodeGen/TargetRegisterInfo.h"
      60             : #include "llvm/CodeGen/TargetSubtargetInfo.h"
      61             : #include "llvm/IR/BasicBlock.h"
      62             : #include "llvm/IR/Comdat.h"
      63             : #include "llvm/IR/Constant.h"
      64             : #include "llvm/IR/Constants.h"
      65             : #include "llvm/IR/DataLayout.h"
      66             : #include "llvm/IR/DebugInfoMetadata.h"
      67             : #include "llvm/IR/DerivedTypes.h"
      68             : #include "llvm/IR/Function.h"
      69             : #include "llvm/IR/GlobalAlias.h"
      70             : #include "llvm/IR/GlobalIFunc.h"
      71             : #include "llvm/IR/GlobalIndirectSymbol.h"
      72             : #include "llvm/IR/GlobalObject.h"
      73             : #include "llvm/IR/GlobalValue.h"
      74             : #include "llvm/IR/GlobalVariable.h"
      75             : #include "llvm/IR/Instruction.h"
      76             : #include "llvm/IR/Mangler.h"
      77             : #include "llvm/IR/Metadata.h"
      78             : #include "llvm/IR/Module.h"
      79             : #include "llvm/IR/Operator.h"
      80             : #include "llvm/IR/Type.h"
      81             : #include "llvm/IR/Value.h"
      82             : #include "llvm/MC/MCAsmInfo.h"
      83             : #include "llvm/MC/MCCodePadder.h"
      84             : #include "llvm/MC/MCContext.h"
      85             : #include "llvm/MC/MCDirectives.h"
      86             : #include "llvm/MC/MCDwarf.h"
      87             : #include "llvm/MC/MCExpr.h"
      88             : #include "llvm/MC/MCInst.h"
      89             : #include "llvm/MC/MCSection.h"
      90             : #include "llvm/MC/MCSectionELF.h"
      91             : #include "llvm/MC/MCSectionMachO.h"
      92             : #include "llvm/MC/MCStreamer.h"
      93             : #include "llvm/MC/MCSubtargetInfo.h"
      94             : #include "llvm/MC/MCSymbol.h"
      95             : #include "llvm/MC/MCSymbolELF.h"
      96             : #include "llvm/MC/MCTargetOptions.h"
      97             : #include "llvm/MC/MCValue.h"
      98             : #include "llvm/MC/SectionKind.h"
      99             : #include "llvm/Pass.h"
     100             : #include "llvm/Support/Casting.h"
     101             : #include "llvm/Support/CommandLine.h"
     102             : #include "llvm/Support/Compiler.h"
     103             : #include "llvm/Support/ErrorHandling.h"
     104             : #include "llvm/Support/Format.h"
     105             : #include "llvm/Support/MathExtras.h"
     106             : #include "llvm/Support/Path.h"
     107             : #include "llvm/Support/TargetRegistry.h"
     108             : #include "llvm/Support/Timer.h"
     109             : #include "llvm/Support/raw_ostream.h"
     110             : #include "llvm/Target/TargetLoweringObjectFile.h"
     111             : #include "llvm/Target/TargetMachine.h"
     112             : #include "llvm/Target/TargetOptions.h"
     113             : #include <algorithm>
     114             : #include <cassert>
     115             : #include <cinttypes>
     116             : #include <cstdint>
     117             : #include <iterator>
     118             : #include <limits>
     119             : #include <memory>
     120             : #include <string>
     121             : #include <utility>
     122             : #include <vector>
     123             : 
     124             : using namespace llvm;
     125             : 
     126             : #define DEBUG_TYPE "asm-printer"
     127             : 
     128             : static const char *const DWARFGroupName = "dwarf";
     129             : static const char *const DWARFGroupDescription = "DWARF Emission";
     130             : static const char *const DbgTimerName = "emit";
     131             : static const char *const DbgTimerDescription = "Debug Info Emission";
     132             : static const char *const EHTimerName = "write_exception";
     133             : static const char *const EHTimerDescription = "DWARF Exception Writer";
     134             : static const char *const CFGuardName = "Control Flow Guard";
     135             : static const char *const CFGuardDescription = "Control Flow Guard Tables";
     136             : static const char *const CodeViewLineTablesGroupName = "linetables";
     137             : static const char *const CodeViewLineTablesGroupDescription =
     138             :   "CodeView Line Tables";
     139             : 
     140             : STATISTIC(EmittedInsts, "Number of machine instrs printed");
     141             : 
     142             : static cl::opt<bool>
     143      303507 :     PrintSchedule("print-schedule", cl::Hidden, cl::init(false),
     144      202338 :                   cl::desc("Print 'sched: [latency:throughput]' in .s output"));
     145             : 
     146             : char AsmPrinter::ID = 0;
     147             : 
     148             : using gcp_map_type = DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>>;
     149             : 
     150          18 : static gcp_map_type &getGCMap(void *&P) {
     151          18 :   if (!P)
     152          12 :     P = new gcp_map_type();
     153          18 :   return *(gcp_map_type*)P;
     154             : }
     155             : 
     156             : /// getGVAlignmentLog2 - Return the alignment to use for the specified global
     157             : /// value in log2 form.  This rounds up to the preferred alignment if possible
     158             : /// and legal.
     159      398011 : static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL,
     160             :                                    unsigned InBits = 0) {
     161             :   unsigned NumBits = 0;
     162             :   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
     163      172349 :     NumBits = DL.getPreferredAlignmentLog(GVar);
     164             : 
     165             :   // If InBits is specified, round it to it.
     166      398011 :   if (InBits > NumBits)
     167             :     NumBits = InBits;
     168             : 
     169             :   // If the GV has a specified alignment, take it into account.
     170      398011 :   if (GV->getAlignment() == 0)
     171             :     return NumBits;
     172             : 
     173      113898 :   unsigned GVAlign = Log2_32(GV->getAlignment());
     174             : 
     175             :   // If the GVAlign is larger than NumBits, or if we are required to obey
     176             :   // NumBits because the GV has an assigned section, obey it.
     177      227792 :   if (GVAlign > NumBits || GV->hasSection())
     178             :     NumBits = GVAlign;
     179             :   return NumBits;
     180             : }
     181             : 
     182       22765 : AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer)
     183       22765 :     : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()),
     184      159355 :       OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) {
     185       22765 :   VerboseAsm = OutStreamer->isVerboseAsm();
     186       22765 : }
     187             : 
     188       90628 : AsmPrinter::~AsmPrinter() {
     189             :   assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized");
     190             : 
     191       22657 :   if (GCMetadataPrinters) {
     192           6 :     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
     193             : 
     194          12 :     delete &GCMap;
     195           6 :     GCMetadataPrinters = nullptr;
     196             :   }
     197       22657 : }
     198             : 
     199        8384 : bool AsmPrinter::isPositionIndependent() const {
     200        8384 :   return TM.isPositionIndependent();
     201             : }
     202             : 
     203             : /// getFunctionNumber - Return a unique ID for the current function.
     204       76709 : unsigned AsmPrinter::getFunctionNumber() const {
     205       76709 :   return MF->getFunctionNumber();
     206             : }
     207             : 
     208     1641107 : const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
     209     1641107 :   return *TM.getObjFileLowering();
     210             : }
     211             : 
     212      536307 : const DataLayout &AsmPrinter::getDataLayout() const {
     213      536307 :   return MMI->getModule()->getDataLayout();
     214             : }
     215             : 
     216             : // Do not use the cached DataLayout because some client use it without a Module
     217             : // (dsymutil, llvm-dwarfdump).
     218     4843020 : unsigned AsmPrinter::getPointerSize() const {
     219     9686040 :   return TM.getPointerSize(0); // FIXME: Default address space
     220             : }
     221             : 
     222     6692027 : const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const {
     223             :   assert(MF && "getSubtargetInfo requires a valid MachineFunction!");
     224     6692027 :   return MF->getSubtarget<MCSubtargetInfo>();
     225             : }
     226             : 
     227      900552 : void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) {
     228      900552 :   S.EmitInstruction(Inst, getSubtargetInfo());
     229      900552 : }
     230             : 
     231             : /// getCurrentSection() - Return the current section we are emitting to.
     232      327163 : const MCSection *AsmPrinter::getCurrentSection() const {
     233      327163 :   return OutStreamer->getCurrentSectionOnly();
     234             : }
     235             : 
     236       22617 : void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
     237             :   AU.setPreservesAll();
     238       22617 :   MachineFunctionPass::getAnalysisUsage(AU);
     239             :   AU.addRequired<MachineModuleInfo>();
     240             :   AU.addRequired<MachineOptimizationRemarkEmitterPass>();
     241             :   AU.addRequired<GCModuleInfo>();
     242       22617 : }
     243             : 
     244       22619 : bool AsmPrinter::doInitialization(Module &M) {
     245       22619 :   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
     246             : 
     247             :   // Initialize TargetLoweringObjectFile.
     248       22619 :   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
     249       22619 :     .Initialize(OutContext, TM);
     250             : 
     251       22619 :   OutStreamer->InitSections(false);
     252             : 
     253             :   // Emit the version-min deployment target directive if needed.
     254             :   //
     255             :   // FIXME: If we end up with a collection of these sorts of Darwin-specific
     256             :   // or ELF-specific things, it may make sense to have a platform helper class
     257             :   // that will work with the target helper class. For now keep it here, as the
     258             :   // alternative is duplicated code in each of the target asm printers that
     259             :   // use the directive, where it would need the same conditionalization
     260             :   // anyway.
     261       22619 :   const Triple &Target = TM.getTargetTriple();
     262       22619 :   OutStreamer->EmitVersionForTarget(Target);
     263             : 
     264             :   // Allow the target to emit any magic that it wants at the start of the file.
     265       22619 :   EmitStartOfAsmFile(M);
     266             : 
     267             :   // Very minimal debug info. It is ignored if we emit actual debug info. If we
     268             :   // don't, this at least helps the user find where a global came from.
     269       22619 :   if (MAI->hasSingleParameterDotFile()) {
     270             :     // .file "foo.c"
     271       16955 :     OutStreamer->EmitFileDirective(
     272       16955 :         llvm::sys::path::filename(M.getSourceFileName()));
     273             :   }
     274             : 
     275       22619 :   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
     276             :   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
     277       22669 :   for (auto &I : *MI)
     278          25 :     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
     279           6 :       MP->beginAssembly(M, *MI, *this);
     280             : 
     281             :   // Emit module-level inline asm if it exists.
     282       22619 :   if (!M.getModuleInlineAsm().empty()) {
     283             :     // We're at the module level. Construct MCSubtarget from the default CPU
     284             :     // and target triple.
     285          78 :     std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
     286             :         TM.getTargetTriple().str(), TM.getTargetCPU(),
     287          78 :         TM.getTargetFeatureString()));
     288         156 :     OutStreamer->AddComment("Start of file scope inline assembly");
     289          78 :     OutStreamer->AddBlankLine();
     290         312 :     EmitInlineAsm(M.getModuleInlineAsm()+"\n",
     291         156 :                   OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions);
     292         156 :     OutStreamer->AddComment("End of file scope inline assembly");
     293          78 :     OutStreamer->AddBlankLine();
     294             :   }
     295             : 
     296       22619 :   if (MAI->doesSupportDebugInformation()) {
     297       22477 :     bool EmitCodeView = MMI->getModule()->getCodeViewFlag();
     298       22603 :     if (EmitCodeView && TM.getTargetTriple().isOSWindows()) {
     299         248 :       Handlers.push_back(HandlerInfo(new CodeViewDebug(this),
     300             :                                      DbgTimerName, DbgTimerDescription,
     301             :                                      CodeViewLineTablesGroupName,
     302             :                                      CodeViewLineTablesGroupDescription));
     303             :     }
     304       22477 :     if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) {
     305       22352 :       DD = new DwarfDebug(this, &M);
     306       22352 :       DD->beginModule();
     307       44704 :       Handlers.push_back(HandlerInfo(DD, DbgTimerName, DbgTimerDescription,
     308             :                                      DWARFGroupName, DWARFGroupDescription));
     309             :     }
     310             :   }
     311             : 
     312       22619 :   switch (MAI->getExceptionHandlingType()) {
     313       19302 :   case ExceptionHandling::SjLj:
     314             :   case ExceptionHandling::DwarfCFI:
     315             :   case ExceptionHandling::ARM:
     316       19302 :     isCFIMoveForDebugging = true;
     317       19302 :     if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
     318             :       break;
     319       64648 :     for (auto &F: M.getFunctionList()) {
     320             :       // If the module contains any function with unwind data,
     321             :       // .eh_frame has to be emitted.
     322             :       // Ignore functions that won't get emitted.
     323      118134 :       if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) {
     324       11151 :         isCFIMoveForDebugging = false;
     325       11151 :         break;
     326             :       }
     327             :     }
     328             :     break;
     329        3317 :   default:
     330        3317 :     isCFIMoveForDebugging = false;
     331        3317 :     break;
     332             :   }
     333             : 
     334             :   EHStreamer *ES = nullptr;
     335       22619 :   switch (MAI->getExceptionHandlingType()) {
     336             :   case ExceptionHandling::None:
     337             :     break;
     338       17438 :   case ExceptionHandling::SjLj:
     339             :   case ExceptionHandling::DwarfCFI:
     340       17438 :     ES = new DwarfCFIException(this);
     341       17438 :     break;
     342        1864 :   case ExceptionHandling::ARM:
     343        1864 :     ES = new ARMException(this);
     344        1864 :     break;
     345         622 :   case ExceptionHandling::WinEH:
     346         622 :     switch (MAI->getWinEHEncodingType()) {
     347           0 :     default: llvm_unreachable("unsupported unwinding information encoding");
     348             :     case WinEH::EncodingType::Invalid:
     349             :       break;
     350         575 :     case WinEH::EncodingType::X86:
     351             :     case WinEH::EncodingType::Itanium:
     352         575 :       ES = new WinException(this);
     353         575 :       break;
     354             :     }
     355             :     break;
     356             :   case ExceptionHandling::Wasm:
     357             :     // TODO to prevent warning
     358             :     break;
     359             :   }
     360             :   if (ES)
     361       39754 :     Handlers.push_back(HandlerInfo(ES, EHTimerName, EHTimerDescription,
     362             :                                    DWARFGroupName, DWARFGroupDescription));
     363             : 
     364           1 :   if (mdconst::extract_or_null<ConstantInt>(
     365       67857 :           MMI->getModule()->getModuleFlag("cfguard")))
     366           2 :     Handlers.push_back(HandlerInfo(new WinCFGuard(this), CFGuardName,
     367             :                                    CFGuardDescription, DWARFGroupName,
     368             :                                    DWARFGroupDescription));
     369             : 
     370       22619 :   return false;
     371             : }
     372             : 
     373             : static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
     374         226 :   if (!MAI.hasWeakDefCanBeHiddenDirective())
     375             :     return false;
     376             : 
     377          68 :   return GV->canBeOmittedFromSymbolTable();
     378             : }
     379             : 
     380      311564 : void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
     381             :   GlobalValue::LinkageTypes Linkage = GV->getLinkage();
     382      311564 :   switch (Linkage) {
     383       37445 :   case GlobalValue::CommonLinkage:
     384             :   case GlobalValue::LinkOnceAnyLinkage:
     385             :   case GlobalValue::LinkOnceODRLinkage:
     386             :   case GlobalValue::WeakAnyLinkage:
     387             :   case GlobalValue::WeakODRLinkage:
     388       37445 :     if (MAI->hasWeakDefDirective()) {
     389             :       // .globl _foo
     390         226 :       OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
     391             : 
     392         294 :       if (!canBeHidden(GV, *MAI))
     393             :         // .weak_definition _foo
     394         209 :         OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
     395             :       else
     396          17 :         OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
     397       37219 :     } else if (MAI->hasLinkOnceDirective()) {
     398             :       // .globl _foo
     399         309 :       OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
     400             :       //NOTE: linkonce is handled by the section the symbol was assigned to.
     401             :     } else {
     402             :       // .weak _foo
     403       36910 :       OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak);
     404             :     }
     405             :     return;
     406      197345 :   case GlobalValue::ExternalLinkage:
     407             :     // If external, declare as a global symbol: .globl _foo
     408      197345 :     OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global);
     409      197345 :     return;
     410             :   case GlobalValue::PrivateLinkage:
     411             :   case GlobalValue::InternalLinkage:
     412             :     return;
     413           0 :   case GlobalValue::AppendingLinkage:
     414             :   case GlobalValue::AvailableExternallyLinkage:
     415             :   case GlobalValue::ExternalWeakLinkage:
     416           0 :     llvm_unreachable("Should never emit this");
     417             :   }
     418           0 :   llvm_unreachable("Unknown linkage type!");
     419             : }
     420             : 
     421      739346 : void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
     422             :                                    const GlobalValue *GV) const {
     423      739346 :   TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler());
     424      739346 : }
     425             : 
     426      564821 : MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
     427      564821 :   return TM.getSymbol(GV);
     428             : }
     429             : 
     430             : /// EmitGlobalVariable - Emit the specified global variable to the .s file.
     431       96011 : void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
     432       96976 :   bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal();
     433             :   assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) &&
     434             :          "No emulated TLS variables in the common section");
     435             : 
     436             :   // Never emit TLS variable xyz in emulated TLS model.
     437             :   // The initialization value is in __emutls_t.xyz instead of xyz.
     438             :   if (IsEmuTLSVar)
     439       11959 :     return;
     440             : 
     441       95755 :   if (GV->hasInitializer()) {
     442             :     // Check to see if this is a special global used by LLVM, if so, emit it.
     443       88752 :     if (EmitSpecialLLVMGlobal(GV))
     444             :       return;
     445             : 
     446             :     // Skip the emission of global equivalents. The symbol can be emitted later
     447             :     // on by emitGlobalGOTEquivs in case it turns out to be needed.
     448       88251 :     if (GlobalGOTEquivs.count(getSymbol(GV)))
     449             :       return;
     450             : 
     451       88242 :     if (isVerbose()) {
     452             :       // When printing the control variable __emutls_v.*,
     453             :       // we don't need to print the original TLS variable name.
     454       23152 :       GV->printAsOperand(OutStreamer->GetCommentOS(),
     455             :                      /*PrintType=*/false, GV->getParent());
     456       11576 :       OutStreamer->GetCommentOS() << '\n';
     457             :     }
     458             :   }
     459             : 
     460       95245 :   MCSymbol *GVSym = getSymbol(GV);
     461             :   MCSymbol *EmittedSym = GVSym;
     462             : 
     463             :   // getOrCreateEmuTLSControlSym only creates the symbol with name and default
     464             :   // attributes.
     465             :   // GV's or GVSym's attributes will be used for the EmittedSym.
     466      190490 :   EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration());
     467             : 
     468       95245 :   if (!GV->hasInitializer())   // External globals require no extra code.
     469             :     return;
     470             : 
     471             :   GVSym->redefineIfPossible();
     472      176484 :   if (GVSym->isDefined() || GVSym->isVariable())
     473           2 :     report_fatal_error("symbol '" + Twine(GVSym->getName()) +
     474             :                        "' is already defined");
     475             : 
     476       88241 :   if (MAI->hasDotTypeDotSizeDirective())
     477       86108 :     OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject);
     478             : 
     479       88241 :   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
     480             : 
     481       88241 :   const DataLayout &DL = GV->getParent()->getDataLayout();
     482       88241 :   uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType());
     483             : 
     484             :   // If the alignment is specified, we *must* obey it.  Overaligning a global
     485             :   // with a specified alignment is a prompt way to break globals emitted to
     486             :   // sections and expected to be contiguous (e.g. ObjC metadata).
     487       88241 :   unsigned AlignLog = getGVAlignmentLog2(GV, DL);
     488             : 
     489      440217 :   for (const HandlerInfo &HI : Handlers) {
     490      351976 :     NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
     491      351976 :                        HI.TimerGroupName, HI.TimerGroupDescription,
     492      351976 :                        TimePassesIsEnabled);
     493      175988 :     HI.Handler->setSymbolSize(GVSym, Size);
     494             :   }
     495             : 
     496             :   // Handle common symbols
     497       88241 :   if (GVKind.isCommon()) {
     498        2772 :     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
     499        2772 :     unsigned Align = 1 << AlignLog;
     500        2772 :     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
     501             :       Align = 0;
     502             : 
     503             :     // .comm _foo, 42, 4
     504        2772 :     OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
     505        2772 :     return;
     506             :   }
     507             : 
     508             :   // Determine to which section this global should be emitted.
     509       85469 :   MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM);
     510             : 
     511             :   // If we have a bss global going to a section that supports the
     512             :   // zerofill directive, do so here.
     513       85820 :   if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() &&
     514         354 :       TheSection->isVirtualSection()) {
     515         323 :     if (Size == 0)
     516             :       Size = 1; // zerofill of 0 bytes is undefined.
     517         323 :     unsigned Align = 1 << AlignLog;
     518         323 :     EmitLinkage(GV, GVSym);
     519             :     // .zerofill __DATA, __bss, _foo, 400, 5
     520         323 :     OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align);
     521         323 :     return;
     522             :   }
     523             : 
     524             :   // If this is a BSS local symbol and we are emitting in the BSS
     525             :   // section use .lcomm/.comm directive.
     526      109857 :   if (GVKind.isBSSLocal() &&
     527       24714 :       getObjFileLowering().getBSSSection() == TheSection) {
     528        1010 :     if (Size == 0)
     529             :       Size = 1; // .comm Foo, 0 is undefined, avoid it.
     530        1010 :     unsigned Align = 1 << AlignLog;
     531             : 
     532             :     // Use .lcomm only if it supports user-specified alignment.
     533             :     // Otherwise, while it would still be correct to use .lcomm in some
     534             :     // cases (e.g. when Align == 1), the external assembler might enfore
     535             :     // some -unknown- default alignment behavior, which could cause
     536             :     // spurious differences between external and integrated assembler.
     537             :     // Prefer to simply fall back to .local / .comm in this case.
     538        1010 :     if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
     539             :       // .lcomm _foo, 42
     540          39 :       OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align);
     541          39 :       return;
     542             :     }
     543             : 
     544         971 :     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
     545             :       Align = 0;
     546             : 
     547             :     // .local _foo
     548         971 :     OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local);
     549             :     // .comm _foo, 42, 4
     550         971 :     OutStreamer->EmitCommonSymbol(GVSym, Size, Align);
     551         971 :     return;
     552             :   }
     553             : 
     554             :   // Handle thread local data for mach-o which requires us to output an
     555             :   // additional structure of data and mangle the original symbol so that we
     556             :   // can reference it later.
     557             :   //
     558             :   // TODO: This should become an "emit thread local global" method on TLOF.
     559             :   // All of this macho specific stuff should be sunk down into TLOFMachO and
     560             :   // stuff like "TLSExtraDataSection" should no longer be part of the parent
     561             :   // TLOF class.  This will also make it more obvious that stuff like
     562             :   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
     563             :   // specific code.
     564       84459 :   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
     565             :     // Emit the .tbss symbol
     566             :     MCSymbol *MangSym =
     567         258 :         OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
     568             : 
     569          86 :     if (GVKind.isThreadBSS()) {
     570          76 :       TheSection = getObjFileLowering().getTLSBSSSection();
     571          76 :       OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
     572          10 :     } else if (GVKind.isThreadData()) {
     573          10 :       OutStreamer->SwitchSection(TheSection);
     574             : 
     575          10 :       EmitAlignment(AlignLog, GV);
     576          10 :       OutStreamer->EmitLabel(MangSym);
     577             : 
     578          10 :       EmitGlobalConstant(GV->getParent()->getDataLayout(),
     579             :                          GV->getInitializer());
     580             :     }
     581             : 
     582          86 :     OutStreamer->AddBlankLine();
     583             : 
     584             :     // Emit the variable struct for the runtime.
     585          86 :     MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection();
     586             : 
     587          86 :     OutStreamer->SwitchSection(TLVSect);
     588             :     // Emit the linkage here.
     589          86 :     EmitLinkage(GV, GVSym);
     590          86 :     OutStreamer->EmitLabel(GVSym);
     591             : 
     592             :     // Three pointers in size:
     593             :     //   - __tlv_bootstrap - used to make sure support exists
     594             :     //   - spare pointer, used when mapped by the runtime
     595             :     //   - pointer to mangled symbol above with initializer
     596             :     unsigned PtrSize = DL.getPointerTypeSize(GV->getType());
     597          86 :     OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
     598             :                                 PtrSize);
     599          86 :     OutStreamer->EmitIntValue(0, PtrSize);
     600          86 :     OutStreamer->EmitSymbolValue(MangSym, PtrSize);
     601             : 
     602          86 :     OutStreamer->AddBlankLine();
     603          86 :     return;
     604             :   }
     605             : 
     606             :   MCSymbol *EmittedInitSym = GVSym;
     607             : 
     608       84047 :   OutStreamer->SwitchSection(TheSection);
     609             : 
     610       84047 :   EmitLinkage(GV, EmittedInitSym);
     611       84047 :   EmitAlignment(AlignLog, GV);
     612             : 
     613       84047 :   OutStreamer->EmitLabel(EmittedInitSym);
     614             : 
     615       84047 :   EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer());
     616             : 
     617       84045 :   if (MAI->hasDotTypeDotSizeDirective())
     618             :     // .size foo, 42
     619       82701 :     OutStreamer->emitELFSize(EmittedInitSym,
     620       82701 :                              MCConstantExpr::create(Size, OutContext));
     621             : 
     622       84045 :   OutStreamer->AddBlankLine();
     623             : }
     624             : 
     625             : /// Emit the directive and value for debug thread local expression
     626             : ///
     627             : /// \p Value - The value to emit.
     628             : /// \p Size - The size of the integer (in bytes) to emit.
     629          24 : void AsmPrinter::EmitDebugThreadLocal(const MCExpr *Value,
     630             :                                       unsigned Size) const {
     631          24 :   OutStreamer->EmitValue(Value, Size);
     632          24 : }
     633             : 
     634             : /// EmitFunctionHeader - This method emits the header for the current
     635             : /// function.
     636      227108 : void AsmPrinter::EmitFunctionHeader() {
     637      227108 :   const Function &F = MF->getFunction();
     638             : 
     639      227108 :   if (isVerbose())
     640      174228 :     OutStreamer->GetCommentOS()
     641      174228 :         << "-- Begin function "
     642      174228 :         << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n';
     643             : 
     644             :   // Print out constants referenced by the function
     645      227108 :   EmitConstantPool();
     646             : 
     647             :   // Print the 'header' of function.
     648      227108 :   OutStreamer->SwitchSection(getObjFileLowering().SectionForGlobal(&F, TM));
     649      227108 :   EmitVisibility(CurrentFnSym, F.getVisibility());
     650             : 
     651      227108 :   EmitLinkage(&F, CurrentFnSym);
     652      227108 :   if (MAI->hasFunctionAlignment())
     653      225546 :     EmitAlignment(MF->getAlignment(), &F);
     654             : 
     655      227108 :   if (MAI->hasDotTypeDotSizeDirective())
     656      204587 :     OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
     657             : 
     658      227108 :   if (isVerbose()) {
     659      348456 :     F.printAsOperand(OutStreamer->GetCommentOS(),
     660             :                    /*PrintType=*/false, F.getParent());
     661      174228 :     OutStreamer->GetCommentOS() << '\n';
     662             :   }
     663             : 
     664             :   // Emit the prefix data.
     665      227108 :   if (F.hasPrefixData()) {
     666           8 :     if (MAI->hasSubsectionsViaSymbols()) {
     667             :       // Preserving prefix data on platforms which use subsections-via-symbols
     668             :       // is a bit tricky. Here we introduce a symbol for the prefix data
     669             :       // and use the .alt_entry attribute to mark the function's real entry point
     670             :       // as an alternative entry point to the prefix-data symbol.
     671           4 :       MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol();
     672           4 :       OutStreamer->EmitLabel(PrefixSym);
     673             : 
     674           4 :       EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
     675             : 
     676             :       // Emit an .alt_entry directive for the actual function symbol.
     677           4 :       OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_AltEntry);
     678             :     } else {
     679           4 :       EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData());
     680             :     }
     681             :   }
     682             : 
     683             :   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
     684             :   // do their wild and crazy things as required.
     685      227108 :   EmitFunctionEntryLabel();
     686             : 
     687             :   // If the function had address-taken blocks that got deleted, then we have
     688             :   // references to the dangling symbols.  Emit them at the start of the function
     689             :   // so that we don't get references to undefined symbols.
     690             :   std::vector<MCSymbol*> DeadBlockSyms;
     691      227105 :   MMI->takeDeletedSymbolsForFunction(&F, DeadBlockSyms);
     692      454210 :   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
     693           0 :     OutStreamer->AddComment("Address taken block that was later removed");
     694           0 :     OutStreamer->EmitLabel(DeadBlockSyms[i]);
     695             :   }
     696             : 
     697      227105 :   if (CurrentFnBegin) {
     698       55525 :     if (MAI->useAssignmentForEHBegin()) {
     699          28 :       MCSymbol *CurPos = OutContext.createTempSymbol();
     700          28 :       OutStreamer->EmitLabel(CurPos);
     701          28 :       OutStreamer->EmitAssignment(CurrentFnBegin,
     702          28 :                                  MCSymbolRefExpr::create(CurPos, OutContext));
     703             :     } else {
     704       55497 :       OutStreamer->EmitLabel(CurrentFnBegin);
     705             :     }
     706             :   }
     707             : 
     708             :   // Emit pre-function debug and/or EH information.
     709     1087223 :   for (const HandlerInfo &HI : Handlers) {
     710     1290177 :     NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
     711      860118 :                        HI.TimerGroupDescription, TimePassesIsEnabled);
     712      430059 :     HI.Handler->beginFunction(MF);
     713             :   }
     714             : 
     715             :   // Emit the prologue data.
     716      227105 :   if (F.hasPrologueData())
     717           2 :     EmitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData());
     718      227105 : }
     719             : 
     720             : /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
     721             : /// function.  This can be overridden by targets as required to do custom stuff.
     722      194886 : void AsmPrinter::EmitFunctionEntryLabel() {
     723      194886 :   CurrentFnSym->redefineIfPossible();
     724             : 
     725             :   // The function label could have already been emitted if two symbols end up
     726             :   // conflicting due to asm renaming.  Detect this and emit an error.
     727      389772 :   if (CurrentFnSym->isVariable())
     728           2 :     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
     729             :                        "' is a protected alias");
     730      194885 :   if (CurrentFnSym->isDefined())
     731           3 :     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
     732             :                        "' label emitted multiple times to assembly file");
     733             : 
     734      194884 :   return OutStreamer->EmitLabel(CurrentFnSym);
     735             : }
     736             : 
     737             : /// emitComments - Pretty-print comments for instructions.
     738             : /// It returns true iff the sched comment was emitted.
     739             : ///   Otherwise it returns false.
     740     1526426 : static bool emitComments(const MachineInstr &MI, raw_ostream &CommentOS,
     741             :                          AsmPrinter *AP) {
     742     1526426 :   const MachineFunction *MF = MI.getMF();
     743     1526426 :   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
     744             : 
     745             :   // Check for spills and reloads
     746             :   int FI;
     747             : 
     748     1526426 :   const MachineFrameInfo &MFI = MF->getFrameInfo();
     749             :   bool Commented = false;
     750             : 
     751             :   // We assume a single instruction only has a spill or reload, not
     752             :   // both.
     753             :   const MachineMemOperand *MMO;
     754     1526426 :   if (TII->isLoadFromStackSlotPostFE(MI, FI)) {
     755       52878 :     if (MFI.isSpillSlotObjectIndex(FI)) {
     756        8866 :       MMO = *MI.memoperands_begin();
     757        8866 :       CommentOS << MMO->getSize() << "-byte Reload";
     758             :       Commented = true;
     759             :     }
     760     1499987 :   } else if (TII->hasLoadFromStackSlot(MI, MMO, FI)) {
     761       67690 :     if (MFI.isSpillSlotObjectIndex(FI)) {
     762       18125 :       CommentOS << MMO->getSize() << "-byte Folded Reload";
     763             :       Commented = true;
     764             :     }
     765     1466142 :   } else if (TII->isStoreToStackSlotPostFE(MI, FI)) {
     766       32854 :     if (MFI.isSpillSlotObjectIndex(FI)) {
     767       10805 :       MMO = *MI.memoperands_begin();
     768       10805 :       CommentOS << MMO->getSize() << "-byte Spill";
     769             :       Commented = true;
     770             :     }
     771     1449715 :   } else if (TII->hasStoreToStackSlot(MI, MMO, FI)) {
     772       50060 :     if (MFI.isSpillSlotObjectIndex(FI)) {
     773       18227 :       CommentOS << MMO->getSize() << "-byte Folded Spill";
     774             :       Commented = true;
     775             :     }
     776             :   }
     777             : 
     778             :   // Check for spill-induced copies
     779     1526426 :   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse)) {
     780             :     Commented = true;
     781           0 :     CommentOS << " Reload Reuse";
     782             :   }
     783             : 
     784     1526426 :   if (Commented) {
     785       56023 :     if (AP->EnablePrintSchedInfo) {
     786             :       // If any comment was added above and we need sched info comment then add
     787             :       // this new comment just after the above comment w/o "\n" between them.
     788          24 :       CommentOS << " " << MF->getSubtarget().getSchedInfoStr(MI) << "\n";
     789             :       return true;
     790             :     }
     791       56015 :     CommentOS << "\n";
     792             :   }
     793             :   return false;
     794             : }
     795             : 
     796             : /// emitImplicitDef - This method emits the specified machine instruction
     797             : /// that is an implicit def.
     798        3348 : void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
     799        3348 :   unsigned RegNo = MI->getOperand(0).getReg();
     800             : 
     801             :   SmallString<128> Str;
     802             :   raw_svector_ostream OS(Str);
     803             :   OS << "implicit-def: "
     804        6696 :      << printReg(RegNo, MF->getSubtarget().getRegisterInfo());
     805             : 
     806       10044 :   OutStreamer->AddComment(OS.str());
     807        3348 :   OutStreamer->AddBlankLine();
     808        3348 : }
     809             : 
     810       10932 : static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
     811             :   std::string Str;
     812       10932 :   raw_string_ostream OS(Str);
     813       10932 :   OS << "kill:";
     814       44968 :   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
     815       34036 :     const MachineOperand &Op = MI->getOperand(i);
     816             :     assert(Op.isReg() && "KILL instruction must have only register operands");
     817             :     OS << ' ' << (Op.isDef() ? "def " : "killed ")
     818       68072 :        << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo());
     819             :   }
     820       21864 :   AP.OutStreamer->AddComment(OS.str());
     821       10932 :   AP.OutStreamer->AddBlankLine();
     822       10932 : }
     823             : 
     824             : /// emitDebugValueComment - This method handles the target-independent form
     825             : /// of DBG_VALUE, returning true if it was able to do so.  A false return
     826             : /// means the target will need to handle MI in EmitInstruction.
     827         820 : static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
     828             :   // This code handles only the 4-operand target-independent form.
     829         820 :   if (MI->getNumOperands() != 4)
     830             :     return false;
     831             : 
     832             :   SmallString<128> Str;
     833             :   raw_svector_ostream OS(Str);
     834         820 :   OS << "DEBUG_VALUE: ";
     835             : 
     836         820 :   const DILocalVariable *V = MI->getDebugVariable();
     837             :   if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
     838         672 :     StringRef Name = SP->getName();
     839         672 :     if (!Name.empty())
     840         670 :       OS << Name << ":";
     841             :   }
     842         820 :   OS << V->getName();
     843         820 :   OS << " <- ";
     844             : 
     845             :   // The second operand is only an offset if it's an immediate.
     846        2424 :   bool MemLoc = MI->getOperand(0).isReg() && MI->getOperand(1).isImm();
     847         117 :   int64_t Offset = MemLoc ? MI->getOperand(1).getImm() : 0;
     848         820 :   const DIExpression *Expr = MI->getDebugExpression();
     849         820 :   if (Expr->getNumElements()) {
     850             :     OS << '[';
     851             :     bool NeedSep = false;
     852         536 :     for (auto Op : Expr->expr_ops()) {
     853         252 :       if (NeedSep)
     854         110 :         OS << ", ";
     855             :       else
     856             :         NeedSep = true;
     857         252 :       OS << dwarf::OperationEncodingString(Op.getOp());
     858         552 :       for (unsigned I = 0; I < Op.getNumArgs(); ++I)
     859         150 :         OS << ' ' << Op.getArg(I);
     860             :     }
     861         142 :     OS << "] ";
     862             :   }
     863             : 
     864             :   // Register or immediate value. Register 0 means undef.
     865        1640 :   if (MI->getOperand(0).isFPImm()) {
     866           1 :     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
     867           2 :     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
     868           0 :       OS << (double)APF.convertToFloat();
     869           1 :     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
     870           1 :       OS << APF.convertToDouble();
     871             :     } else {
     872             :       // There is no good way to print long double.  Convert a copy to
     873             :       // double.  Ah well, it's only a comment.
     874             :       bool ignored;
     875           0 :       APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven,
     876             :                   &ignored);
     877           0 :       OS << "(long double) " << APF.convertToDouble();
     878             :     }
     879         819 :   } else if (MI->getOperand(0).isImm()) {
     880          34 :     OS << MI->getOperand(0).getImm();
     881         785 :   } else if (MI->getOperand(0).isCImm()) {
     882           2 :     MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
     883             :   } else {
     884             :     unsigned Reg;
     885         784 :     if (MI->getOperand(0).isReg()) {
     886         784 :       Reg = MI->getOperand(0).getReg();
     887             :     } else {
     888             :       assert(MI->getOperand(0).isFI() && "Unknown operand type");
     889           0 :       const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering();
     890           0 :       Offset += TFI->getFrameIndexReference(*AP.MF,
     891           0 :                                             MI->getOperand(0).getIndex(), Reg);
     892             :       MemLoc = true;
     893             :     }
     894         784 :     if (Reg == 0) {
     895             :       // Suppress offset, it is not meaningful here.
     896           5 :       OS << "undef";
     897             :       // NOTE: Want this comment at start of line, don't emit with AddComment.
     898          15 :       AP.OutStreamer->emitRawComment(OS.str());
     899           5 :       return true;
     900             :     }
     901         779 :     if (MemLoc)
     902             :       OS << '[';
     903        1558 :     OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo());
     904             :   }
     905             : 
     906         815 :   if (MemLoc)
     907         117 :     OS << '+' << Offset << ']';
     908             : 
     909             :   // NOTE: Want this comment at start of line, don't emit with AddComment.
     910        2445 :   AP.OutStreamer->emitRawComment(OS.str());
     911         815 :   return true;
     912             : }
     913             : 
     914             : /// This method handles the target-independent form of DBG_LABEL, returning
     915             : /// true if it was able to do so.  A false return means the target will need
     916             : /// to handle MI in EmitInstruction.
     917           0 : static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) {
     918           0 :   if (MI->getNumOperands() != 1)
     919             :     return false;
     920             : 
     921             :   SmallString<128> Str;
     922             :   raw_svector_ostream OS(Str);
     923           0 :   OS << "DEBUG_LABEL: ";
     924             : 
     925           0 :   const DILabel *V = MI->getDebugLabel();
     926             :   if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) {
     927           0 :     StringRef Name = SP->getName();
     928           0 :     if (!Name.empty())
     929           0 :       OS << Name << ":";
     930             :   }
     931           0 :   OS << V->getName();
     932             : 
     933             :   // NOTE: Want this comment at start of line, don't emit with AddComment.
     934           0 :   AP.OutStreamer->emitRawComment(OS.str());
     935             :   return true;
     936             : }
     937             : 
     938      510607 : AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() const {
     939      994845 :   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
     940      484238 :       MF->getFunction().needsUnwindTableEntry())
     941             :     return CFI_M_EH;
     942             : 
     943       76860 :   if (MMI->hasDebugInfo())
     944             :     return CFI_M_Debug;
     945             : 
     946       69892 :   return CFI_M_None;
     947             : }
     948             : 
     949        2359 : bool AsmPrinter::needsSEHMoves() {
     950        3805 :   return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry();
     951             : }
     952             : 
     953      316722 : void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) {
     954      316722 :   ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType();
     955      633444 :   if (ExceptionHandlingType != ExceptionHandling::DwarfCFI &&
     956      316722 :       ExceptionHandlingType != ExceptionHandling::ARM)
     957             :     return;
     958             : 
     959      309431 :   if (needsCFIMoves() == CFI_M_None)
     960             :     return;
     961             : 
     962             :   // If there is no "real" instruction following this CFI instruction, skip
     963             :   // emitting it; it would be beyond the end of the function's FDE range.
     964      292102 :   auto *MBB = MI.getParent();
     965      292102 :   auto I = std::next(MI.getIterator());
     966      452091 :   while (I != MBB->end() && I->isTransient())
     967             :     ++I;
     968      294768 :   if (I == MBB->instr_end() &&
     969        5332 :       MBB->getReverseIterator() == MBB->getParent()->rbegin())
     970             :     return;
     971             : 
     972      291761 :   const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions();
     973      291761 :   unsigned CFIIndex = MI.getOperand(0).getCFIIndex();
     974      291761 :   const MCCFIInstruction &CFI = Instrs[CFIIndex];
     975      291761 :   emitCFIInstruction(CFI);
     976             : }
     977             : 
     978          16 : void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) {
     979             :   // The operands are the MCSymbol and the frame offset of the allocation.
     980          16 :   MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol();
     981          16 :   int FrameOffset = MI.getOperand(1).getImm();
     982             : 
     983             :   // Emit a symbol assignment.
     984          16 :   OutStreamer->EmitAssignment(FrameAllocSym,
     985          16 :                              MCConstantExpr::create(FrameOffset, OutContext));
     986          16 : }
     987             : 
     988      227105 : void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) {
     989      227105 :   if (!MF.getTarget().Options.EmitStackSizeSection)
     990             :     return;
     991             : 
     992          15 :   MCSection *StackSizeSection = getObjFileLowering().getStackSizesSection();
     993          15 :   if (!StackSizeSection)
     994             :     return;
     995             : 
     996          15 :   const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
     997             :   // Don't emit functions with dynamic stack allocations.
     998          15 :   if (FrameInfo.hasVarSizedObjects())
     999             :     return;
    1000             : 
    1001          12 :   OutStreamer->PushSection();
    1002          12 :   OutStreamer->SwitchSection(StackSizeSection);
    1003             : 
    1004          12 :   const MCSymbol *FunctionSymbol = getFunctionBegin();
    1005          12 :   uint64_t StackSize = FrameInfo.getStackSize();
    1006          24 :   OutStreamer->EmitSymbolValue(FunctionSymbol, TM.getProgramPointerSize());
    1007          12 :   OutStreamer->EmitULEB128IntValue(StackSize);
    1008             : 
    1009          12 :   OutStreamer->PopSection();
    1010             : }
    1011             : 
    1012      454213 : static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF,
    1013             :                                            MachineModuleInfo *MMI) {
    1014      454213 :   if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI->hasDebugInfo())
    1015             :     return true;
    1016             : 
    1017             :   // We might emit an EH table that uses function begin and end labels even if
    1018             :   // we don't have any landingpads.
    1019      721810 :   if (!MF.getFunction().hasPersonalityFn())
    1020             :     return false;
    1021          50 :   return !isNoOpWithoutInvoke(
    1022         100 :       classifyEHPersonality(MF.getFunction().getPersonalityFn()));
    1023             : }
    1024             : 
    1025             : /// EmitFunctionBody - This method emits the body and trailer for a
    1026             : /// function.
    1027      227108 : void AsmPrinter::EmitFunctionBody() {
    1028      227108 :   EmitFunctionHeader();
    1029             : 
    1030             :   // Emit target-specific gunk before the function body.
    1031      227105 :   EmitFunctionBodyStart();
    1032             : 
    1033      227105 :   bool ShouldPrintDebugScopes = MMI->hasDebugInfo();
    1034             : 
    1035      227105 :   if (isVerbose()) {
    1036             :     // Get MachineDominatorTree or compute it on the fly if it's unavailable
    1037      174225 :     MDT = getAnalysisIfAvailable<MachineDominatorTree>();
    1038      174225 :     if (!MDT) {
    1039             :       OwnedMDT = make_unique<MachineDominatorTree>();
    1040      173097 :       OwnedMDT->getBase().recalculate(*MF);
    1041      173097 :       MDT = OwnedMDT.get();
    1042             :     }
    1043             : 
    1044             :     // Get MachineLoopInfo or compute it on the fly if it's unavailable
    1045      174225 :     MLI = getAnalysisIfAvailable<MachineLoopInfo>();
    1046      174225 :     if (!MLI) {
    1047             :       OwnedMLI = make_unique<MachineLoopInfo>();
    1048      173097 :       OwnedMLI->getBase().analyze(MDT->getBase());
    1049      173097 :       MLI = OwnedMLI.get();
    1050             :     }
    1051             :   }
    1052             : 
    1053             :   // Print out code for the function.
    1054             :   bool HasAnyRealCode = false;
    1055             :   int NumInstsInFunction = 0;
    1056      890828 :   for (auto &MBB : *MF) {
    1057             :     // Print a label for the basic block.
    1058      436618 :     EmitBasicBlockStart(MBB);
    1059     4924316 :     for (auto &MI : MBB) {
    1060             :       // Print the assembly for the instruction.
    1061     3620574 :       if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() &&
    1062             :           !MI.isDebugInstr()) {
    1063             :         HasAnyRealCode = true;
    1064     3536760 :         ++NumInstsInFunction;
    1065             :       }
    1066             : 
    1067     4051080 :       if (ShouldPrintDebugScopes) {
    1068    12370916 :         for (const HandlerInfo &HI : Handlers) {
    1069     9896128 :           NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
    1070     9896128 :                              HI.TimerGroupName, HI.TimerGroupDescription,
    1071     9896128 :                              TimePassesIsEnabled);
    1072     4948064 :           HI.Handler->beginInstruction(&MI);
    1073             :         }
    1074             :       }
    1075             : 
    1076     5577506 :       if (isVerbose() && emitComments(MI, OutStreamer->GetCommentOS(), this)) {
    1077             :         MachineInstr *MIP = const_cast<MachineInstr *>(&MI);
    1078             :         MIP->setAsmPrinterFlag(MachineInstr::NoSchedComment);
    1079             :       }
    1080             : 
    1081     8102160 :       switch (MI.getOpcode()) {
    1082      316722 :       case TargetOpcode::CFI_INSTRUCTION:
    1083      316722 :         emitCFIInstruction(MI);
    1084      316722 :         break;
    1085          16 :       case TargetOpcode::LOCAL_ESCAPE:
    1086          16 :         emitFrameAlloc(MI);
    1087          16 :         break;
    1088      113784 :       case TargetOpcode::EH_LABEL:
    1089             :       case TargetOpcode::GC_LABEL:
    1090      113784 :         OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol());
    1091      113784 :         break;
    1092       16185 :       case TargetOpcode::INLINEASM:
    1093       16185 :         EmitInlineAsm(&MI);
    1094       16185 :         break;
    1095       67420 :       case TargetOpcode::DBG_VALUE:
    1096       67420 :         if (isVerbose()) {
    1097         820 :           if (!emitDebugValueComment(&MI, *this))
    1098           0 :             EmitInstruction(&MI);
    1099             :         }
    1100             :         break;
    1101           0 :       case TargetOpcode::DBG_LABEL:
    1102           0 :         if (isVerbose()) {
    1103           0 :           if (!emitDebugLabelComment(&MI, *this))
    1104           0 :             EmitInstruction(&MI);
    1105             :         }
    1106             :         break;
    1107        3456 :       case TargetOpcode::IMPLICIT_DEF:
    1108        3456 :         if (isVerbose()) emitImplicitDef(&MI);
    1109             :         break;
    1110       12938 :       case TargetOpcode::KILL:
    1111       12938 :         if (isVerbose()) emitKill(&MI, *this);
    1112             :         break;
    1113     3520559 :       default:
    1114     3520559 :         EmitInstruction(&MI);
    1115     3520559 :         break;
    1116             :       }
    1117             : 
    1118     4051080 :       if (ShouldPrintDebugScopes) {
    1119    12370916 :         for (const HandlerInfo &HI : Handlers) {
    1120     9896128 :           NamedRegionTimer T(HI.TimerName, HI.TimerDescription,
    1121     9896128 :                              HI.TimerGroupName, HI.TimerGroupDescription,
    1122     9896128 :                              TimePassesIsEnabled);
    1123     4948064 :           HI.Handler->endInstruction();
    1124             :         }
    1125             :       }
    1126             :     }
    1127             : 
    1128      436618 :     EmitBasicBlockEnd(MBB);
    1129             :   }
    1130             : 
    1131             :   EmittedInsts += NumInstsInFunction;
    1132             :   MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount",
    1133      227105 :                                       MF->getFunction().getSubprogram(),
    1134      681315 :                                       &MF->front());
    1135      454210 :   R << ore::NV("NumInstructions", NumInstsInFunction)
    1136      227105 :     << " instructions in function";
    1137      227105 :   ORE->emit(R);
    1138             : 
    1139             :   // If the function is empty and the object file uses .subsections_via_symbols,
    1140             :   // then we need to emit *something* to the function body to prevent the
    1141             :   // labels from collapsing together.  Just emit a noop.
    1142             :   // Similarly, don't emit empty functions on Windows either. It can lead to
    1143             :   // duplicate entries (two functions with the same RVA) in the Guard CF Table
    1144             :   // after linking, causing the kernel not to load the binary:
    1145             :   // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html
    1146             :   // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer.
    1147      227105 :   const Triple &TT = TM.getTargetTriple();
    1148      227136 :   if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() ||
    1149           1 :                           (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) {
    1150             :     MCInst Noop;
    1151           6 :     MF->getSubtarget().getInstrInfo()->getNoop(Noop);
    1152             : 
    1153             :     // Targets can opt-out of emitting the noop here by leaving the opcode
    1154             :     // unspecified.
    1155           6 :     if (Noop.getOpcode()) {
    1156          12 :       OutStreamer->AddComment("avoids zero-length function");
    1157           6 :       OutStreamer->EmitInstruction(Noop, getSubtargetInfo());
    1158             :     }
    1159             :   }
    1160             : 
    1161      227105 :   const Function &F = MF->getFunction();
    1162      654332 :   for (const auto &BB : F) {
    1163      427227 :     if (!BB.hasAddressTaken())
    1164      426755 :       continue;
    1165         472 :     MCSymbol *Sym = GetBlockAddressSymbol(&BB);
    1166         472 :     if (Sym->isDefined())
    1167         340 :       continue;
    1168         264 :     OutStreamer->AddComment("Address of block that was removed by CodeGen");
    1169         132 :     OutStreamer->EmitLabel(Sym);
    1170             :   }
    1171             : 
    1172             :   // Emit target-specific gunk after the function body.
    1173      227105 :   EmitFunctionBodyEnd();
    1174             : 
    1175      407550 :   if (needFuncLabelsForEHOrDebugInfo(*MF, MMI) ||
    1176      180445 :       MAI->hasDotTypeDotSizeDirective()) {
    1177             :     // Create a symbol for the end of function.
    1178      205699 :     CurrentFnEnd = createTempSymbol("func_end");
    1179      205699 :     OutStreamer->EmitLabel(CurrentFnEnd);
    1180             :   }
    1181             : 
    1182             :   // If the target wants a .size directive for the size of the function, emit
    1183             :   // it.
    1184      227105 :   if (MAI->hasDotTypeDotSizeDirective()) {
    1185             :     // We can get the size as difference between the function label and the
    1186             :     // temp label.
    1187      204585 :     const MCExpr *SizeExp = MCBinaryExpr::createSub(
    1188      204585 :         MCSymbolRefExpr::create(CurrentFnEnd, OutContext),
    1189      204585 :         MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext);
    1190      204585 :     OutStreamer->emitELFSize(CurrentFnSym, SizeExp);
    1191             :   }
    1192             : 
    1193     1087223 :   for (const HandlerInfo &HI : Handlers) {
    1194     1290177 :     NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
    1195      860118 :                        HI.TimerGroupDescription, TimePassesIsEnabled);
    1196      430059 :     HI.Handler->markFunctionEnd();
    1197             :   }
    1198             : 
    1199             :   // Print out jump tables referenced by the function.
    1200      227105 :   EmitJumpTableInfo();
    1201             : 
    1202             :   // Emit post-function debug and/or EH information.
    1203     1087223 :   for (const HandlerInfo &HI : Handlers) {
    1204     1290177 :     NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
    1205      860118 :                        HI.TimerGroupDescription, TimePassesIsEnabled);
    1206      430059 :     HI.Handler->endFunction(MF);
    1207             :   }
    1208             : 
    1209             :   // Emit section containing stack size metadata.
    1210      227105 :   emitStackSizeSection(*MF);
    1211             : 
    1212      227105 :   if (isVerbose())
    1213      174225 :     OutStreamer->GetCommentOS() << "-- End function\n";
    1214             : 
    1215      227105 :   OutStreamer->AddBlankLine();
    1216      227105 : }
    1217             : 
    1218             : /// Compute the number of Global Variables that uses a Constant.
    1219         119 : static unsigned getNumGlobalVariableUses(const Constant *C) {
    1220         119 :   if (!C)
    1221             :     return 0;
    1222             : 
    1223         113 :   if (isa<GlobalVariable>(C))
    1224             :     return 1;
    1225             : 
    1226             :   unsigned NumUses = 0;
    1227         196 :   for (auto *CU : C->users())
    1228         104 :     NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU));
    1229             : 
    1230             :   return NumUses;
    1231             : }
    1232             : 
    1233             : /// Only consider global GOT equivalents if at least one user is a
    1234             : /// cstexpr inside an initializer of another global variables. Also, don't
    1235             : /// handle cstexpr inside instructions. During global variable emission,
    1236             : /// candidates are skipped and are emitted later in case at least one cstexpr
    1237             : /// isn't replaced by a PC relative GOT entry access.
    1238        2438 : static bool isGOTEquivalentCandidate(const GlobalVariable *GV,
    1239             :                                      unsigned &NumGOTEquivUsers) {
    1240             :   // Global GOT equivalents are unnamed private globals with a constant
    1241             :   // pointer initializer to another global symbol. They must point to a
    1242             :   // GlobalVariable or Function, i.e., as GlobalValue.
    1243         575 :   if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() ||
    1244        2438 :       !GV->isConstant() || !GV->isDiscardableIfUnused() ||
    1245             :       !dyn_cast<GlobalValue>(GV->getOperand(0)))
    1246             :     return false;
    1247             : 
    1248             :   // To be a got equivalent, at least one of its users need to be a constant
    1249             :   // expression used by another global variable.
    1250          31 :   for (auto *U : GV->users())
    1251          15 :     NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U));
    1252             : 
    1253          16 :   return NumGOTEquivUsers > 0;
    1254             : }
    1255             : 
    1256             : /// Unnamed constant global variables solely contaning a pointer to
    1257             : /// another globals variable is equivalent to a GOT table entry; it contains the
    1258             : /// the address of another symbol. Optimize it and replace accesses to these
    1259             : /// "GOT equivalents" by using the GOT entry for the final global instead.
    1260             : /// Compute GOT equivalent candidates among all global variables to avoid
    1261             : /// emitting them if possible later on, after it use is replaced by a GOT entry
    1262             : /// access.
    1263       22523 : void AsmPrinter::computeGlobalGOTEquivs(Module &M) {
    1264       22523 :   if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
    1265             :     return;
    1266             : 
    1267        5036 :   for (const auto &G : M.globals()) {
    1268        2438 :     unsigned NumGOTEquivUsers = 0;
    1269        2438 :     if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers))
    1270        2429 :       continue;
    1271             : 
    1272           9 :     const MCSymbol *GOTEquivSym = getSymbol(&G);
    1273           9 :     GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers);
    1274             :   }
    1275             : }
    1276             : 
    1277             : /// Constant expressions using GOT equivalent globals may not be eligible
    1278             : /// for PC relative GOT entry conversion, in such cases we need to emit such
    1279             : /// globals we previously omitted in EmitGlobalVariable.
    1280       22516 : void AsmPrinter::emitGlobalGOTEquivs() {
    1281       22516 :   if (!getObjFileLowering().supportIndirectSymViaGOTPCRel())
    1282       19919 :     return;
    1283             : 
    1284             :   SmallVector<const GlobalVariable *, 8> FailedCandidates;
    1285        2606 :   for (auto &I : GlobalGOTEquivs) {
    1286           9 :     const GlobalVariable *GV = I.second.first;
    1287           9 :     unsigned Cnt = I.second.second;
    1288           9 :     if (Cnt)
    1289           3 :       FailedCandidates.push_back(GV);
    1290             :   }
    1291             :   GlobalGOTEquivs.clear();
    1292             : 
    1293        2603 :   for (auto *GV : FailedCandidates)
    1294           3 :     EmitGlobalVariable(GV);
    1295             : }
    1296             : 
    1297         505 : void AsmPrinter::emitGlobalIndirectSymbol(Module &M,
    1298             :                                           const GlobalIndirectSymbol& GIS) {
    1299         505 :   MCSymbol *Name = getSymbol(&GIS);
    1300             : 
    1301         505 :   if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective())
    1302         393 :     OutStreamer->EmitSymbolAttribute(Name, MCSA_Global);
    1303          23 :   else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage())
    1304          90 :     OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference);
    1305             :   else
    1306             :     assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage");
    1307             : 
    1308             :   // Set the symbol type to function if the alias has a function type.
    1309             :   // This affects codegen when the aliasee is not a function.
    1310        1010 :   if (GIS.getType()->getPointerElementType()->isFunctionTy()) {
    1311         266 :     OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeFunction);
    1312         266 :     if (isa<GlobalIFunc>(GIS))
    1313           2 :       OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction);
    1314             :   }
    1315             : 
    1316         505 :   EmitVisibility(Name, GIS.getVisibility());
    1317             : 
    1318        1010 :   const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol());
    1319             : 
    1320         551 :   if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr))
    1321           4 :     OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry);
    1322             : 
    1323             :   // Emit the directives as assignments aka .set:
    1324         505 :   OutStreamer->EmitAssignment(Name, Expr);
    1325             : 
    1326             :   if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) {
    1327             :     // If the aliasee does not correspond to a symbol in the output, i.e. the
    1328             :     // alias is not of an object or the aliased object is private, then set the
    1329             :     // size of the alias symbol from the type of the alias. We don't do this in
    1330             :     // other situations as the alias and aliasee having differing types but same
    1331             :     // size may be intentional.
    1332         503 :     const GlobalObject *BaseObject = GA->getBaseObject();
    1333         503 :     if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() &&
    1334         128 :         (!BaseObject || BaseObject->hasPrivateLinkage())) {
    1335          60 :       const DataLayout &DL = M.getDataLayout();
    1336          60 :       uint64_t Size = DL.getTypeAllocSize(GA->getValueType());
    1337          60 :       OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext));
    1338             :     }
    1339             :   }
    1340         505 : }
    1341             : 
    1342       22523 : bool AsmPrinter::doFinalization(Module &M) {
    1343             :   // Set the MachineFunction to nullptr so that we can catch attempted
    1344             :   // accesses to MF specific features at the module level and so that
    1345             :   // we can conditionalize accesses based on whether or not it is nullptr.
    1346       22523 :   MF = nullptr;
    1347             : 
    1348             :   // Gather all GOT equivalent globals in the module. We really need two
    1349             :   // passes over the globals: one to compute and another to avoid its emission
    1350             :   // in EmitGlobalVariable, otherwise we would not be able to handle cases
    1351             :   // where the got equivalent shows up before its use.
    1352       22523 :   computeGlobalGOTEquivs(M);
    1353             : 
    1354             :   // Emit global variables.
    1355      118883 :   for (const auto &G : M.globals())
    1356       96367 :     EmitGlobalVariable(&G);
    1357             : 
    1358             :   // Emit remaining GOT equivalent globals.
    1359       22516 :   emitGlobalGOTEquivs();
    1360             : 
    1361             :   // Emit visibility info for declarations
    1362      341841 :   for (const Function &F : M) {
    1363      638617 :     if (!F.isDeclarationForLinker())
    1364      227103 :       continue;
    1365             :     GlobalValue::VisibilityTypes V = F.getVisibility();
    1366       92222 :     if (V == GlobalValue::DefaultVisibility)
    1367       92126 :       continue;
    1368             : 
    1369          96 :     MCSymbol *Name = getSymbol(&F);
    1370          96 :     EmitVisibility(Name, V, false);
    1371             :   }
    1372             : 
    1373       22516 :   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
    1374             : 
    1375       45032 :   TLOF.emitModuleMetadata(*OutStreamer, M);
    1376             : 
    1377       45032 :   if (TM.getTargetTriple().isOSBinFormatELF()) {
    1378       18946 :     MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
    1379             : 
    1380             :     // Output stubs for external and common global variables.
    1381             :     MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
    1382       18946 :     if (!Stubs.empty()) {
    1383          27 :       OutStreamer->SwitchSection(TLOF.getDataSection());
    1384          27 :       const DataLayout &DL = M.getDataLayout();
    1385             : 
    1386          54 :       EmitAlignment(Log2_32(DL.getPointerSize()));
    1387          58 :       for (const auto &Stub : Stubs) {
    1388          31 :         OutStreamer->EmitLabel(Stub.first);
    1389          62 :         OutStreamer->EmitSymbolValue(Stub.second.getPointer(),
    1390             :                                      DL.getPointerSize());
    1391             :       }
    1392             :     }
    1393             :   }
    1394             : 
    1395             :   // Finalize debug and EH information.
    1396      106836 :   for (const HandlerInfo &HI : Handlers) {
    1397      126483 :     NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName,
    1398       84322 :                        HI.TimerGroupDescription, TimePassesIsEnabled);
    1399       42161 :     HI.Handler->endModule();
    1400       42160 :     delete HI.Handler;
    1401             :   }
    1402             :   Handlers.clear();
    1403       22515 :   DD = nullptr;
    1404             : 
    1405             :   // If the target wants to know about weak references, print them all.
    1406       22515 :   if (MAI->getWeakRefDirective()) {
    1407             :     // FIXME: This is not lazy, it would be nice to only print weak references
    1408             :     // to stuff that is actually used.  Note that doing so would require targets
    1409             :     // to notice uses in operands (due to constant exprs etc).  This should
    1410             :     // happen with the MC stuff eventually.
    1411             : 
    1412             :     // Print out module-level global objects here.
    1413             :     for (const auto &GO : M.global_objects()) {
    1414      413107 :       if (!GO.hasExternalWeakLinkage())
    1415      412817 :         continue;
    1416         290 :       OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference);
    1417             :     }
    1418             :   }
    1419             : 
    1420       22515 :   OutStreamer->AddBlankLine();
    1421             : 
    1422             :   // Print aliases in topological order, that is, for each alias a = b,
    1423             :   // b must be printed before a.
    1424             :   // This is because on some targets (e.g. PowerPC) linker expects aliases in
    1425             :   // such an order to generate correct TOC information.
    1426             :   SmallVector<const GlobalAlias *, 16> AliasStack;
    1427             :   SmallPtrSet<const GlobalAlias *, 16> AliasVisited;
    1428       23018 :   for (const auto &Alias : M.aliases()) {
    1429        1006 :     for (const GlobalAlias *Cur = &Alias; Cur;
    1430        1006 :          Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) {
    1431         506 :       if (!AliasVisited.insert(Cur).second)
    1432             :         break;
    1433         503 :       AliasStack.push_back(Cur);
    1434             :     }
    1435        1006 :     for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack))
    1436         503 :       emitGlobalIndirectSymbol(M, *AncestorAlias);
    1437             :     AliasStack.clear();
    1438             :   }
    1439       22517 :   for (const auto &IFunc : M.ifuncs())
    1440           2 :     emitGlobalIndirectSymbol(M, IFunc);
    1441             : 
    1442       22515 :   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
    1443             :   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
    1444       22540 :   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
    1445          50 :     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
    1446           6 :       MP->finishAssembly(M, *MI, *this);
    1447             : 
    1448             :   // Emit llvm.ident metadata in an '.ident' directive.
    1449       22515 :   EmitModuleIdents(M);
    1450             : 
    1451             :   // Emit __morestack address if needed for indirect calls.
    1452       22515 :   if (MMI->usesMorestackAddr()) {
    1453           1 :     unsigned Align = 1;
    1454           2 :     MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant(
    1455             :         getDataLayout(), SectionKind::getReadOnly(),
    1456           2 :         /*C=*/nullptr, Align);
    1457           1 :     OutStreamer->SwitchSection(ReadOnlySection);
    1458             : 
    1459             :     MCSymbol *AddrSymbol =
    1460           2 :         OutContext.getOrCreateSymbol(StringRef("__morestack_addr"));
    1461           1 :     OutStreamer->EmitLabel(AddrSymbol);
    1462             : 
    1463           1 :     unsigned PtrSize = MAI->getCodePointerSize();
    1464           1 :     OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"),
    1465             :                                  PtrSize);
    1466             :   }
    1467             : 
    1468             :   // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if
    1469             :   // split-stack is used.
    1470       45030 :   if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) {
    1471          39 :     OutStreamer->SwitchSection(
    1472          78 :         OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0));
    1473          39 :     if (MMI->hasNosplitStack())
    1474          13 :       OutStreamer->SwitchSection(
    1475          26 :           OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0));
    1476             :   }
    1477             : 
    1478             :   // If we don't have any trampolines, then we don't require stack memory
    1479             :   // to be executable. Some targets have a directive to declare this.
    1480       22515 :   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
    1481       22515 :   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
    1482       22511 :     if (MCSection *S = MAI->getNonexecutableStackSection(OutContext))
    1483       18564 :       OutStreamer->SwitchSection(S);
    1484             : 
    1485       45030 :   if (TM.getTargetTriple().isOSBinFormatCOFF()) {
    1486             :     // Emit /EXPORT: flags for each exported global as necessary.
    1487         723 :     const auto &TLOF = getObjFileLowering();
    1488             :     std::string Flags;
    1489             : 
    1490        6226 :     for (const GlobalValue &GV : M.global_values()) {
    1491        5503 :       raw_string_ostream OS(Flags);
    1492        5503 :       TLOF.emitLinkerFlagsForGlobal(OS, &GV);
    1493             :       OS.flush();
    1494        5503 :       if (!Flags.empty()) {
    1495         249 :         OutStreamer->SwitchSection(TLOF.getDrectveSection());
    1496         498 :         OutStreamer->EmitBytes(Flags);
    1497             :       }
    1498             :       Flags.clear();
    1499             :     }
    1500             : 
    1501             :     // Emit /INCLUDE: flags for each used global as necessary.
    1502         723 :     if (const auto *LU = M.getNamedGlobal("llvm.used")) {
    1503             :       assert(LU->hasInitializer() &&
    1504             :              "expected llvm.used to have an initializer");
    1505             :       assert(isa<ArrayType>(LU->getValueType()) &&
    1506             :              "expected llvm.used to be an array type");
    1507           3 :       if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
    1508          32 :         for (const Value *Op : A->operands()) {
    1509             :           const auto *GV =
    1510          13 :               cast<GlobalValue>(Op->stripPointerCastsNoFollowAliases());
    1511             :           // Global symbols with internal or private linkage are not visible to
    1512             :           // the linker, and thus would cause an error when the linker tried to
    1513             :           // preserve the symbol due to the `/include:` directive.
    1514           5 :           if (GV->hasLocalLinkage())
    1515           5 :             continue;
    1516             : 
    1517           8 :           raw_string_ostream OS(Flags);
    1518           8 :           TLOF.emitLinkerFlagsForUsed(OS, GV);
    1519             :           OS.flush();
    1520             : 
    1521           8 :           if (!Flags.empty()) {
    1522           8 :             OutStreamer->SwitchSection(TLOF.getDrectveSection());
    1523          16 :             OutStreamer->EmitBytes(Flags);
    1524             :           }
    1525             :           Flags.clear();
    1526             :         }
    1527             :       }
    1528             :     }
    1529             :   }
    1530             : 
    1531             :   // Allow the target to emit any magic that it wants at the end of the file,
    1532             :   // after everything else has gone out.
    1533       22515 :   EmitEndOfAsmFile(M);
    1534             : 
    1535       22515 :   MMI = nullptr;
    1536             : 
    1537       22515 :   OutStreamer->Finish();
    1538       22514 :   OutStreamer->reset();
    1539             :   OwnedMLI.reset();
    1540             :   OwnedMDT.reset();
    1541             : 
    1542       22514 :   return false;
    1543             : }
    1544             : 
    1545       13027 : MCSymbol *AsmPrinter::getCurExceptionSym() {
    1546       13027 :   if (!CurExceptionSym)
    1547        6540 :     CurExceptionSym = createTempSymbol("exception");
    1548       13027 :   return CurExceptionSym;
    1549             : }
    1550             : 
    1551      227108 : void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
    1552      227108 :   this->MF = &MF;
    1553             :   // Get the function symbol.
    1554      227108 :   CurrentFnSym = getSymbol(&MF.getFunction());
    1555      227108 :   CurrentFnSymForSize = CurrentFnSym;
    1556      227108 :   CurrentFnBegin = nullptr;
    1557      227108 :   CurExceptionSym = nullptr;
    1558      227108 :   bool NeedsLocalForSize = MAI->needsLocalForSize();
    1559      398706 :   if (needFuncLabelsForEHOrDebugInfo(MF, MMI) || NeedsLocalForSize ||
    1560      171598 :       MF.getTarget().Options.EmitStackSizeSection) {
    1561       55525 :     CurrentFnBegin = createTempSymbol("func_begin");
    1562       55525 :     if (NeedsLocalForSize)
    1563        8862 :       CurrentFnSymForSize = CurrentFnBegin;
    1564             :   }
    1565             : 
    1566      454216 :   ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
    1567             : 
    1568      227108 :   const TargetSubtargetInfo &STI = MF.getSubtarget();
    1569      454216 :   EnablePrintSchedInfo = PrintSchedule.getNumOccurrences()
    1570      439308 :                              ? PrintSchedule
    1571      212200 :                              : STI.supportPrintSchedInfo();
    1572      227108 : }
    1573             : 
    1574             : namespace {
    1575             : 
    1576             : // Keep track the alignment, constpool entries per Section.
    1577       32188 :   struct SectionCPs {
    1578             :     MCSection *S;
    1579             :     unsigned Alignment;
    1580             :     SmallVector<unsigned, 4> CPEs;
    1581             : 
    1582       16094 :     SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {}
    1583             :   };
    1584             : 
    1585             : } // end anonymous namespace
    1586             : 
    1587             : /// EmitConstantPool - Print to the current output stream assembly
    1588             : /// representations of the constants in the constant pool MCP. This is
    1589             : /// used to print out constants which have been "spilled to memory" by
    1590             : /// the code generator.
    1591      211865 : void AsmPrinter::EmitConstantPool() {
    1592      211865 :   const MachineConstantPool *MCP = MF->getConstantPool();
    1593             :   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
    1594      408106 :   if (CP.empty()) return;
    1595             : 
    1596             :   // Calculate sections for constant pool entries. We collect entries to go into
    1597             :   // the same section together to reduce amount of section switch statements.
    1598       15624 :   SmallVector<SectionCPs, 4> CPSections;
    1599       52762 :   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
    1600       21514 :     const MachineConstantPoolEntry &CPE = CP[i];
    1601       43028 :     unsigned Align = CPE.getAlignment();
    1602             : 
    1603       21514 :     SectionKind Kind = CPE.getSectionKind(&getDataLayout());
    1604             : 
    1605             :     const Constant *C = nullptr;
    1606       43028 :     if (!CPE.isMachineConstantPoolEntry())
    1607       21497 :       C = CPE.Val.ConstVal;
    1608             : 
    1609       43028 :     MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(),
    1610       43028 :                                                               Kind, C, Align);
    1611             : 
    1612             :     // The number of sections are small, just do a linear search from the
    1613             :     // last section to the first.
    1614             :     bool Found = false;
    1615       21514 :     unsigned SecIdx = CPSections.size();
    1616       22055 :     while (SecIdx != 0) {
    1617       11922 :       if (CPSections[--SecIdx].S == S) {
    1618             :         Found = true;
    1619             :         break;
    1620             :       }
    1621             :     }
    1622       21514 :     if (!Found) {
    1623             :       SecIdx = CPSections.size();
    1624       48282 :       CPSections.push_back(SectionCPs(S, Align));
    1625             :     }
    1626             : 
    1627       43028 :     if (Align > CPSections[SecIdx].Alignment)
    1628           0 :       CPSections[SecIdx].Alignment = Align;
    1629       21514 :     CPSections[SecIdx].CPEs.push_back(i);
    1630             :   }
    1631             : 
    1632             :   // Now print stuff into the calculated sections.
    1633             :   const MCSection *CurSection = nullptr;
    1634             :   unsigned Offset = 0;
    1635       31718 :   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
    1636       53702 :     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
    1637       43028 :       unsigned CPI = CPSections[i].CPEs[j];
    1638       21514 :       MCSymbol *Sym = GetCPISymbol(CPI);
    1639       21514 :       if (!Sym->isUndefined())
    1640          19 :         continue;
    1641             : 
    1642       21495 :       if (CurSection != CPSections[i].S) {
    1643       16075 :         OutStreamer->SwitchSection(CPSections[i].S);
    1644       32150 :         EmitAlignment(Log2_32(CPSections[i].Alignment));
    1645       16075 :         CurSection = CPSections[i].S;
    1646             :         Offset = 0;
    1647             :       }
    1648             : 
    1649       42990 :       MachineConstantPoolEntry CPE = CP[CPI];
    1650             : 
    1651             :       // Emit inter-object padding for alignment.
    1652       42990 :       unsigned AlignMask = CPE.getAlignment() - 1;
    1653       21495 :       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
    1654       21495 :       OutStreamer->EmitZeros(NewOffset - Offset);
    1655             : 
    1656       21495 :       Type *Ty = CPE.getType();
    1657       21495 :       Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty);
    1658             : 
    1659       21495 :       OutStreamer->EmitLabel(Sym);
    1660       42990 :       if (CPE.isMachineConstantPoolEntry())
    1661          17 :         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
    1662             :       else
    1663       21478 :         EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal);
    1664             :     }
    1665             :   }
    1666             : }
    1667             : 
    1668             : /// EmitJumpTableInfo - Print assembly representations of the jump tables used
    1669             : /// by the current function to the current output stream.
    1670      225875 : void AsmPrinter::EmitJumpTableInfo() {
    1671      225875 :   const DataLayout &DL = MF->getDataLayout();
    1672      225875 :   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
    1673      225875 :   if (!MJTI) return;
    1674         275 :   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
    1675             :   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
    1676         204 :   if (JT.empty()) return;
    1677             : 
    1678             :   // Pick the directive to use to print the jump table entries, and switch to
    1679             :   // the appropriate section.
    1680         204 :   const Function &F = MF->getFunction();
    1681         204 :   const TargetLoweringObjectFile &TLOF = getObjFileLowering();
    1682         204 :   bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection(
    1683         204 :       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32,
    1684         408 :       F);
    1685         204 :   if (JTInDiffSection) {
    1686             :     // Drop it in the readonly section.
    1687         187 :     MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM);
    1688         187 :     OutStreamer->SwitchSection(ReadOnlySection);
    1689             :   }
    1690             : 
    1691         408 :   EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL)));
    1692             : 
    1693             :   // Jump tables in code sections are marked with a data_region directive
    1694             :   // where that's supported.
    1695         204 :   if (!JTInDiffSection)
    1696          17 :     OutStreamer->EmitDataRegion(MCDR_DataRegionJT32);
    1697             : 
    1698         624 :   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
    1699         216 :     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
    1700             : 
    1701             :     // If this jump table was deleted, ignore it.
    1702         216 :     if (JTBBs.empty()) continue;
    1703             : 
    1704             :     // For the EK_LabelDifference32 entry, if using .set avoids a relocation,
    1705             :     /// emit a .set directive for each unique entry.
    1706         259 :     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
    1707          43 :         MAI->doesSetDirectiveSuppressReloc()) {
    1708             :       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
    1709          14 :       const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
    1710          14 :       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
    1711         725 :       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
    1712        1394 :         const MachineBasicBlock *MBB = JTBBs[ii];
    1713         697 :         if (!EmittedSets.insert(MBB).second)
    1714         525 :           continue;
    1715             : 
    1716             :         // .set LJTSet, LBB32-base
    1717             :         const MCExpr *LHS =
    1718         172 :           MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
    1719         172 :         OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
    1720         172 :                                     MCBinaryExpr::createSub(LHS, Base,
    1721         172 :                                                             OutContext));
    1722             :       }
    1723             :     }
    1724             : 
    1725             :     // On some targets (e.g. Darwin) we want to emit two consecutive labels
    1726             :     // before each jump table.  The first label is never referenced, but tells
    1727             :     // the assembler and linker the extents of the jump table object.  The
    1728             :     // second label is actually referenced by the code.
    1729         216 :     if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix())
    1730             :       // FIXME: This doesn't have to have any specific name, just any randomly
    1731             :       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
    1732           7 :       OutStreamer->EmitLabel(GetJTISymbol(JTI, true));
    1733             : 
    1734         216 :     OutStreamer->EmitLabel(GetJTISymbol(JTI));
    1735             : 
    1736        4514 :     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
    1737        8164 :       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
    1738             :   }
    1739         204 :   if (!JTInDiffSection)
    1740          17 :     OutStreamer->EmitDataRegion(MCDR_DataRegionEnd);
    1741             : }
    1742             : 
    1743             : /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
    1744             : /// current stream.
    1745        4082 : void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
    1746             :                                     const MachineBasicBlock *MBB,
    1747             :                                     unsigned UID) const {
    1748             :   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
    1749             :   const MCExpr *Value = nullptr;
    1750        4082 :   switch (MJTI->getEntryKind()) {
    1751           0 :   case MachineJumpTableInfo::EK_Inline:
    1752           0 :     llvm_unreachable("Cannot emit EK_Inline jump table entry");
    1753         419 :   case MachineJumpTableInfo::EK_Custom32:
    1754         838 :     Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry(
    1755         419 :         MJTI, MBB, UID, OutContext);
    1756         419 :     break;
    1757        2375 :   case MachineJumpTableInfo::EK_BlockAddress:
    1758             :     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
    1759             :     //     .word LBB123
    1760        2375 :     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
    1761        2375 :     break;
    1762          18 :   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
    1763             :     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
    1764             :     // with a relocation as gp-relative, e.g.:
    1765             :     //     .gprel32 LBB123
    1766          18 :     MCSymbol *MBBSym = MBB->getSymbol();
    1767          36 :     OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext));
    1768          18 :     return;
    1769             :   }
    1770             : 
    1771          33 :   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
    1772             :     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
    1773             :     // with a relocation as gp-relative, e.g.:
    1774             :     //     .gpdword LBB123
    1775          33 :     MCSymbol *MBBSym = MBB->getSymbol();
    1776          66 :     OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext));
    1777          33 :     return;
    1778             :   }
    1779             : 
    1780        1237 :   case MachineJumpTableInfo::EK_LabelDifference32: {
    1781             :     // Each entry is the address of the block minus the address of the jump
    1782             :     // table. This is used for PIC jump tables where gprel32 is not supported.
    1783             :     // e.g.:
    1784             :     //      .word LBB123 - LJTI1_2
    1785             :     // If the .set directive avoids relocations, this is emitted as:
    1786             :     //      .set L4_5_set_123, LBB123 - LJTI1_2
    1787             :     //      .word L4_5_set_123
    1788        1237 :     if (MAI->doesSetDirectiveSuppressReloc()) {
    1789         697 :       Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()),
    1790             :                                       OutContext);
    1791         697 :       break;
    1792             :     }
    1793         540 :     Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext);
    1794         540 :     const TargetLowering *TLI = MF->getSubtarget().getTargetLowering();
    1795         540 :     const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext);
    1796         540 :     Value = MCBinaryExpr::createSub(Value, Base, OutContext);
    1797         540 :     break;
    1798             :   }
    1799             :   }
    1800             : 
    1801             :   assert(Value && "Unknown entry kind!");
    1802             : 
    1803        4031 :   unsigned EntrySize = MJTI->getEntrySize(getDataLayout());
    1804        4031 :   OutStreamer->EmitValue(Value, EntrySize);
    1805             : }
    1806             : 
    1807             : /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
    1808             : /// special global used by LLVM.  If so, emit it and return true, otherwise
    1809             : /// do nothing and return false.
    1810       88803 : bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
    1811       88803 :   if (GV->getName() == "llvm.used") {
    1812          60 :     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
    1813          35 :       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
    1814             :     return true;
    1815             :   }
    1816             : 
    1817             :   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
    1818      177440 :   if (GV->getSection() == "llvm.metadata" ||
    1819             :       GV->hasAvailableExternallyLinkage())
    1820             :     return true;
    1821             : 
    1822       88676 :   if (!GV->hasAppendingLinkage()) return false;
    1823             : 
    1824             :   assert(GV->hasInitializer() && "Not a special LLVM global!");
    1825             : 
    1826         374 :   if (GV->getName() == "llvm.global_ctors") {
    1827         360 :     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
    1828             :                        /* isCtor */ true);
    1829             : 
    1830         360 :     return true;
    1831             :   }
    1832             : 
    1833          14 :   if (GV->getName() == "llvm.global_dtors") {
    1834          13 :     EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(),
    1835             :                        /* isCtor */ false);
    1836             : 
    1837          13 :     return true;
    1838             :   }
    1839             : 
    1840           1 :   report_fatal_error("unknown special variable");
    1841             : }
    1842             : 
    1843             : /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
    1844             : /// global in the specified llvm.used list for which emitUsedDirectiveFor
    1845             : /// is true, as being used with this directive.
    1846          35 : void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
    1847             :   // Should be an array of 'i8*'.
    1848         167 :   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
    1849             :     const GlobalValue *GV =
    1850          66 :       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
    1851             :     if (GV)
    1852          66 :       OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
    1853             :   }
    1854          35 : }
    1855             : 
    1856             : namespace {
    1857             : 
    1858             : struct Structor {
    1859             :   int Priority = 0;
    1860             :   Constant *Func = nullptr;
    1861             :   GlobalValue *ComdatKey = nullptr;
    1862             : 
    1863             :   Structor() = default;
    1864             : };
    1865             : 
    1866             : } // end anonymous namespace
    1867             : 
    1868             : /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
    1869             : /// priority.
    1870         373 : void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List,
    1871             :                                     bool isCtor) {
    1872             :   // Should be an array of '{ int, void ()* }' structs.  The first value is the
    1873             :   // init priority.
    1874         380 :   if (!isa<ConstantArray>(List)) return;
    1875             : 
    1876             :   // Sanity check the structors list.
    1877             :   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
    1878             :   if (!InitList) return; // Not an array!
    1879         366 :   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
    1880             :   // FIXME: Only allow the 3-field form in LLVM 4.0.
    1881         366 :   if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
    1882             :     return; // Not an array of two or three elements!
    1883        1098 :   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
    1884         366 :       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
    1885         692 :   if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
    1886             :     return; // Not (int, ptr, ptr).
    1887             : 
    1888             :   // Gather the structors in a form that's convenient for sorting by priority.
    1889             :   SmallVector<Structor, 8> Structors;
    1890        1700 :   for (Value *O : InitList->operands()) {
    1891             :     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
    1892           0 :     if (!CS) continue; // Malformed.
    1893         968 :     if (CS->getOperand(1)->isNullValue())
    1894             :       break;  // Found a null terminator, skip the rest.
    1895             :     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
    1896           0 :     if (!Priority) continue; // Malformed.
    1897         484 :     Structors.push_back(Structor());
    1898         484 :     Structor &S = Structors.back();
    1899         484 :     S.Priority = Priority->getLimitedValue(65535);
    1900         484 :     S.Func = CS->getOperand(1);
    1901         914 :     if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
    1902          36 :       S.ComdatKey =
    1903             :           dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
    1904             :   }
    1905             : 
    1906             :   // Emit the function pointers in the target-specific order
    1907         366 :   unsigned Align = Log2_32(DL.getPointerPrefAlignment());
    1908             :   std::stable_sort(Structors.begin(), Structors.end(),
    1909             :                    [](const Structor &L,
    1910             :                       const Structor &R) { return L.Priority < R.Priority; });
    1911        1334 :   for (Structor &S : Structors) {
    1912         484 :     const TargetLoweringObjectFile &Obj = getObjFileLowering();
    1913             :     const MCSymbol *KeySym = nullptr;
    1914         484 :     if (GlobalValue *GV = S.ComdatKey) {
    1915          32 :       if (GV->isDeclarationForLinker())
    1916             :         // If the associated variable is not defined in this module
    1917             :         // (it might be available_externally, or have been an
    1918             :         // available_externally definition that was dropped by the
    1919             :         // EliminateAvailableExternally pass), some other TU
    1920             :         // will provide its dynamic initializer.
    1921           8 :         continue;
    1922             : 
    1923          28 :       KeySym = getSymbol(GV);
    1924             :     }
    1925             :     MCSection *OutputSection =
    1926         493 :         (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
    1927          17 :                 : Obj.getStaticDtorSection(S.Priority, KeySym));
    1928         476 :     OutStreamer->SwitchSection(OutputSection);
    1929             :     if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection())
    1930         460 :       EmitAlignment(Align);
    1931         476 :     EmitXXStructor(DL, S.Func);
    1932             :   }
    1933             : }
    1934             : 
    1935       22515 : void AsmPrinter::EmitModuleIdents(Module &M) {
    1936       22515 :   if (!MAI->hasIdentDirective())
    1937             :     return;
    1938             : 
    1939       18820 :   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
    1940        5753 :     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
    1941        2914 :       const MDNode *N = NMD->getOperand(i);
    1942             :       assert(N->getNumOperands() == 1 &&
    1943             :              "llvm.ident metadata entry can have only one operand");
    1944             :       const MDString *S = cast<MDString>(N->getOperand(0));
    1945        2914 :       OutStreamer->EmitIdent(S->getString());
    1946             :     }
    1947             :   }
    1948             : }
    1949             : 
    1950             : //===--------------------------------------------------------------------===//
    1951             : // Emission and print routines
    1952             : //
    1953             : 
    1954             : /// Emit a byte directive and value.
    1955             : ///
    1956      500935 : void AsmPrinter::emitInt8(int Value) const {
    1957      500935 :   OutStreamer->EmitIntValue(Value, 1);
    1958      500935 : }
    1959             : 
    1960             : /// Emit a short directive and value.
    1961       43894 : void AsmPrinter::emitInt16(int Value) const {
    1962       43894 :   OutStreamer->EmitIntValue(Value, 2);
    1963       43894 : }
    1964             : 
    1965             : /// Emit a long directive and value.
    1966      157192 : void AsmPrinter::emitInt32(int Value) const {
    1967      157192 :   OutStreamer->EmitIntValue(Value, 4);
    1968      157192 : }
    1969             : 
    1970             : /// Emit a long long directive and value.
    1971          16 : void AsmPrinter::emitInt64(uint64_t Value) const {
    1972          16 :   OutStreamer->EmitIntValue(Value, 8);
    1973          16 : }
    1974             : 
    1975             : /// Emit something like ".long Hi-Lo" where the size in bytes of the directive
    1976             : /// is specified by Size and Hi/Lo specify the labels. This implicitly uses
    1977             : /// .set if it avoids relocations.
    1978      102962 : void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
    1979             :                                      unsigned Size) const {
    1980      102962 :   OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size);
    1981      102962 : }
    1982             : 
    1983             : /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
    1984             : /// where the size in bytes of the directive is specified by Size and Label
    1985             : /// specifies the label.  This implicitly uses .set if it is available.
    1986      846945 : void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
    1987             :                                      unsigned Size,
    1988             :                                      bool IsSectionRelative) const {
    1989      846945 :   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
    1990         268 :     OutStreamer->EmitCOFFSecRel32(Label, Offset);
    1991         268 :     if (Size > 4)
    1992           2 :       OutStreamer->EmitZeros(Size - 4);
    1993             :     return;
    1994             :   }
    1995             : 
    1996             :   // Emit Label+Offset (or just Label if Offset is zero)
    1997      846677 :   const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext);
    1998      846677 :   if (Offset)
    1999         299 :     Expr = MCBinaryExpr::createAdd(
    2000         299 :         Expr, MCConstantExpr::create(Offset, OutContext), OutContext);
    2001             : 
    2002      846677 :   OutStreamer->EmitValue(Expr, Size);
    2003             : }
    2004             : 
    2005             : //===----------------------------------------------------------------------===//
    2006             : 
    2007             : // EmitAlignment - Emit an alignment directive to the specified power of
    2008             : // two boundary.  For example, if you pass in 3 here, you will get an 8
    2009             : // byte alignment.  If a global value is specified, and if that global has
    2010             : // an explicit alignment requested, it will override the alignment request
    2011             : // if required for correctness.
    2012      351655 : void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
    2013      351655 :   if (GV)
    2014      309770 :     NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits);
    2015             : 
    2016      351655 :   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
    2017             : 
    2018             :   assert(NumBits <
    2019             :              static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
    2020             :          "undefined behavior");
    2021      654326 :   if (getCurrentSection()->getKind().isText())
    2022      227846 :     OutStreamer->EmitCodeAlignment(1u << NumBits);
    2023             :   else
    2024       99317 :     OutStreamer->EmitValueToAlignment(1u << NumBits);
    2025             : }
    2026             : 
    2027             : //===----------------------------------------------------------------------===//
    2028             : // Constant emission.
    2029             : //===----------------------------------------------------------------------===//
    2030             : 
    2031      201395 : const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) {
    2032      201395 :   MCContext &Ctx = OutContext;
    2033             : 
    2034      402789 :   if (CV->isNullValue() || isa<UndefValue>(CV))
    2035           1 :     return MCConstantExpr::create(0, Ctx);
    2036             : 
    2037             :   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
    2038         210 :     return MCConstantExpr::create(CI->getZExtValue(), Ctx);
    2039             : 
    2040             :   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
    2041      207634 :     return MCSymbolRefExpr::create(getSymbol(GV), Ctx);
    2042             : 
    2043             :   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
    2044         250 :     return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx);
    2045             : 
    2046             :   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
    2047             :   if (!CE) {
    2048           0 :     llvm_unreachable("Unknown constant value to lower!");
    2049             :   }
    2050             : 
    2051       97242 :   switch (CE->getOpcode()) {
    2052           2 :   default:
    2053             :     // If the code isn't optimized, there may be outstanding folding
    2054             :     // opportunities. Attempt to fold the expression using DataLayout as a
    2055             :     // last resort before giving up.
    2056           2 :     if (Constant *C = ConstantFoldConstant(CE, getDataLayout()))
    2057           2 :       if (C != CE)
    2058           0 :         return lowerConstant(C);
    2059             : 
    2060             :     // Otherwise report the problem to the user.
    2061             :     {
    2062             :       std::string S;
    2063             :       raw_string_ostream OS(S);
    2064           2 :       OS << "Unsupported expression in static initializer: ";
    2065           4 :       CE->printAsOperand(OS, /*PrintType=*/false,
    2066           2 :                      !MF ? nullptr : MF->getFunction().getParent());
    2067           2 :       report_fatal_error(OS.str());
    2068             :     }
    2069       96633 :   case Instruction::GetElementPtr: {
    2070             :     // Generate a symbolic expression for the byte address
    2071       96633 :     APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0);
    2072       96633 :     cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI);
    2073             : 
    2074      193266 :     const MCExpr *Base = lowerConstant(CE->getOperand(0));
    2075       96633 :     if (!OffsetAI)
    2076             :       return Base;
    2077             : 
    2078             :     int64_t Offset = OffsetAI.getSExtValue();
    2079       48244 :     return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
    2080       48244 :                                    Ctx);
    2081             :   }
    2082             : 
    2083         206 :   case Instruction::Trunc:
    2084             :     // We emit the value and depend on the assembler to truncate the generated
    2085             :     // expression properly.  This is important for differences between
    2086             :     // blockaddress labels.  Since the two labels are in the same function, it
    2087             :     // is reasonable to treat their delta as a 32-bit value.
    2088             :     LLVM_FALLTHROUGH;
    2089             :   case Instruction::BitCast:
    2090         412 :     return lowerConstant(CE->getOperand(0));
    2091             : 
    2092         198 :   case Instruction::IntToPtr: {
    2093         198 :     const DataLayout &DL = getDataLayout();
    2094             : 
    2095             :     // Handle casts to pointers by changing them into casts to the appropriate
    2096             :     // integer type.  This promotes constant folding and simplifies this code.
    2097             :     Constant *Op = CE->getOperand(0);
    2098         198 :     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
    2099             :                                       false/*ZExt*/);
    2100         198 :     return lowerConstant(Op);
    2101             :   }
    2102             : 
    2103          57 :   case Instruction::PtrToInt: {
    2104          57 :     const DataLayout &DL = getDataLayout();
    2105             : 
    2106             :     // Support only foldable casts to/from pointers that can be eliminated by
    2107             :     // changing the pointer to the appropriately sized integer type.
    2108             :     Constant *Op = CE->getOperand(0);
    2109          57 :     Type *Ty = CE->getType();
    2110             : 
    2111          57 :     const MCExpr *OpExpr = lowerConstant(Op);
    2112             : 
    2113             :     // We can emit the pointer value into this slot if the slot is an
    2114             :     // integer slot equal to the size of the pointer.
    2115          57 :     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
    2116             :       return OpExpr;
    2117             : 
    2118             :     // Otherwise the pointer is smaller than the resultant integer, mask off
    2119             :     // the high bits so we are sure to get a proper truncation if the input is
    2120             :     // a constant expr.
    2121           6 :     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
    2122           3 :     const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
    2123           3 :     return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
    2124             :   }
    2125             : 
    2126             :   case Instruction::Sub: {
    2127             :     GlobalValue *LHSGV;
    2128             :     APInt LHSOffset;
    2129         270 :     if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset,
    2130             :                                    getDataLayout())) {
    2131             :       GlobalValue *RHSGV;
    2132             :       APInt RHSOffset;
    2133         244 :       if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset,
    2134             :                                      getDataLayout())) {
    2135             :         const MCExpr *RelocExpr =
    2136         122 :             getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM);
    2137         122 :         if (!RelocExpr)
    2138             :           RelocExpr = MCBinaryExpr::createSub(
    2139          30 :               MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx),
    2140          30 :               MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx);
    2141         122 :         int64_t Addend = (LHSOffset - RHSOffset).getSExtValue();
    2142         122 :         if (Addend != 0)
    2143             :           RelocExpr = MCBinaryExpr::createAdd(
    2144          24 :               RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx);
    2145             :         return RelocExpr;
    2146             :       }
    2147         135 :     }
    2148             :   }
    2149             :   // else fallthrough
    2150             :   LLVM_FALLTHROUGH;
    2151             : 
    2152             :   // The MC library also has a right-shift operator, but it isn't consistently
    2153             :   // signed or unsigned between different targets.
    2154             :   case Instruction::Add:
    2155             :   case Instruction::Mul:
    2156             :   case Instruction::SDiv:
    2157             :   case Instruction::SRem:
    2158             :   case Instruction::Shl:
    2159             :   case Instruction::And:
    2160             :   case Instruction::Or:
    2161             :   case Instruction::Xor: {
    2162          48 :     const MCExpr *LHS = lowerConstant(CE->getOperand(0));
    2163          48 :     const MCExpr *RHS = lowerConstant(CE->getOperand(1));
    2164          24 :     switch (CE->getOpcode()) {
    2165           0 :     default: llvm_unreachable("Unknown binary operator constant cast expr");
    2166          10 :     case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
    2167          13 :     case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx);
    2168           1 :     case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx);
    2169           0 :     case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx);
    2170           0 :     case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx);
    2171           0 :     case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx);
    2172           0 :     case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx);
    2173           0 :     case Instruction::Or:  return MCBinaryExpr::createOr (LHS, RHS, Ctx);
    2174           0 :     case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx);
    2175             :     }
    2176             :   }
    2177             :   }
    2178             : }
    2179             : 
    2180             : static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C,
    2181             :                                    AsmPrinter &AP,
    2182             :                                    const Constant *BaseCV = nullptr,
    2183             :                                    uint64_t Offset = 0);
    2184             : 
    2185             : static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP);
    2186             : static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP);
    2187             : 
    2188             : /// isRepeatedByteSequence - Determine whether the given value is
    2189             : /// composed of a repeated sequence of identical bytes and return the
    2190             : /// byte value.  If it is not a repeated sequence, return -1.
    2191       60270 : static int isRepeatedByteSequence(const ConstantDataSequential *V) {
    2192       60270 :   StringRef Data = V->getRawDataValues();
    2193             :   assert(!Data.empty() && "Empty aggregates should be CAZ node");
    2194             :   char C = Data[0];
    2195      137476 :   for (unsigned i = 1, e = Data.size(); i != e; ++i)
    2196      270082 :     if (Data[i] != C) return -1;
    2197        2435 :   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
    2198             : }
    2199             : 
    2200             : /// isRepeatedByteSequence - Determine whether the given value is
    2201             : /// composed of a repeated sequence of identical bytes and return the
    2202             : /// byte value.  If it is not a repeated sequence, return -1.
    2203       69833 : static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) {
    2204             :   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
    2205           6 :     uint64_t Size = DL.getTypeAllocSizeInBits(V->getType());
    2206             :     assert(Size % 8 == 0);
    2207             : 
    2208             :     // Extend the element to take zero padding into account.
    2209           6 :     APInt Value = CI->getValue().zextOrSelf(Size);
    2210           6 :     if (!Value.isSplat(8))
    2211             :       return -1;
    2212             : 
    2213          15 :     return Value.zextOrTrunc(8).getZExtValue();
    2214             :   }
    2215             :   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
    2216             :     // Make sure all array elements are sequences of the same repeated
    2217             :     // byte.
    2218             :     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
    2219        4815 :     Constant *Op0 = CA->getOperand(0);
    2220        4815 :     int Byte = isRepeatedByteSequence(Op0, DL);
    2221        4815 :     if (Byte == -1)
    2222             :       return -1;
    2223             : 
    2224             :     // All array elements must be equal.
    2225          17 :     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i)
    2226           9 :       if (CA->getOperand(i) != Op0)
    2227             :         return -1;
    2228             :     return Byte;
    2229             :   }
    2230             : 
    2231             :   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
    2232       60270 :     return isRepeatedByteSequence(CDS);
    2233             : 
    2234             :   return -1;
    2235             : }
    2236             : 
    2237       60215 : static void emitGlobalConstantDataSequential(const DataLayout &DL,
    2238             :                                              const ConstantDataSequential *CDS,
    2239             :                                              AsmPrinter &AP) {
    2240             :   // See if we can aggregate this into a .fill, if so, emit it as such.
    2241       60215 :   int Value = isRepeatedByteSequence(CDS, DL);
    2242       60215 :   if (Value != -1) {
    2243        2433 :     uint64_t Bytes = DL.getTypeAllocSize(CDS->getType());
    2244             :     // Don't emit a 1-byte object as a .fill.
    2245        2433 :     if (Bytes > 1)
    2246        2423 :       return AP.OutStreamer->emitFill(Bytes, Value);
    2247             :   }
    2248             : 
    2249             :   // If this can be emitted with .ascii/.asciz, emit it as such.
    2250       57792 :   if (CDS->isString())
    2251       82944 :     return AP.OutStreamer->EmitBytes(CDS->getAsString());
    2252             : 
    2253             :   // Otherwise, emit the values in successive locations.
    2254       16320 :   unsigned ElementByteSize = CDS->getElementByteSize();
    2255       32640 :   if (isa<IntegerType>(CDS->getElementType())) {
    2256      181395 :     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
    2257      166893 :       if (AP.isVerbose())
    2258      319706 :         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
    2259      159853 :                                                  CDS->getElementAsInteger(i));
    2260      166893 :       AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i),
    2261      166893 :                                    ElementByteSize);
    2262             :     }
    2263             :   } else {
    2264        1818 :     Type *ET = CDS->getElementType();
    2265        9766 :     for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I)
    2266       15896 :       emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP);
    2267             :   }
    2268             : 
    2269       16320 :   unsigned Size = DL.getTypeAllocSize(CDS->getType());
    2270       16320 :   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
    2271       16320 :                         CDS->getNumElements();
    2272             :   assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!");
    2273       16320 :   if (unsigned Padding = Size - EmittedSize)
    2274           1 :     AP.OutStreamer->EmitZeros(Padding);
    2275             : }
    2276             : 
    2277        4803 : static void emitGlobalConstantArray(const DataLayout &DL,
    2278             :                                     const ConstantArray *CA, AsmPrinter &AP,
    2279             :                                     const Constant *BaseCV, uint64_t Offset) {
    2280             :   // See if we can aggregate some values.  Make sure it can be
    2281             :   // represented as a series of bytes of the constant value.
    2282        4803 :   int Value = isRepeatedByteSequence(CA, DL);
    2283             : 
    2284        4803 :   if (Value != -1) {
    2285           3 :     uint64_t Bytes = DL.getTypeAllocSize(CA->getType());
    2286           3 :     AP.OutStreamer->emitFill(Bytes, Value);
    2287             :   }
    2288             :   else {
    2289     4548878 :     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
    2290     4544078 :       emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset);
    2291     2272039 :       Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType());
    2292             :     }
    2293             :   }
    2294        4803 : }
    2295             : 
    2296        1552 : static void emitGlobalConstantVector(const DataLayout &DL,
    2297             :                                      const ConstantVector *CV, AsmPrinter &AP) {
    2298       25291 :   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
    2299       47478 :     emitGlobalConstantImpl(DL, CV->getOperand(i), AP);
    2300             : 
    2301        1552 :   unsigned Size = DL.getTypeAllocSize(CV->getType());
    2302        1552 :   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
    2303        3104 :                          CV->getType()->getNumElements();
    2304        1552 :   if (unsigned Padding = Size - EmittedSize)
    2305           0 :     AP.OutStreamer->EmitZeros(Padding);
    2306        1552 : }
    2307             : 
    2308       50549 : static void emitGlobalConstantStruct(const DataLayout &DL,
    2309             :                                      const ConstantStruct *CS, AsmPrinter &AP,
    2310             :                                      const Constant *BaseCV, uint64_t Offset) {
    2311             :   // Print the fields in successive locations. Pad to align if needed!
    2312       50549 :   unsigned Size = DL.getTypeAllocSize(CS->getType());
    2313       50549 :   const StructLayout *Layout = DL.getStructLayout(CS->getType());
    2314             :   uint64_t SizeSoFar = 0;
    2315      396567 :   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
    2316      173009 :     const Constant *Field = CS->getOperand(i);
    2317             : 
    2318             :     // Print the actual field value.
    2319      173009 :     emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar);
    2320             : 
    2321             :     // Check if padding is needed and insert one or more 0s.
    2322      173009 :     uint64_t FieldSize = DL.getTypeAllocSize(Field->getType());
    2323      173009 :     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
    2324      173009 :                         - Layout->getElementOffset(i)) - FieldSize;
    2325      173009 :     SizeSoFar += FieldSize + PadSize;
    2326             : 
    2327             :     // Insert padding - this may include padding to increase the size of the
    2328             :     // current field up to the ABI size (if the struct is not packed) as well
    2329             :     // as padding to ensure that the next field starts at the right offset.
    2330      173009 :     AP.OutStreamer->EmitZeros(PadSize);
    2331             :   }
    2332             :   assert(SizeSoFar == Layout->getSizeInBytes() &&
    2333             :          "Layout of constant struct may be incorrect!");
    2334       50549 : }
    2335             : 
    2336       13132 : static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) {
    2337       13132 :   APInt API = APF.bitcastToAPInt();
    2338             : 
    2339             :   // First print a comment with what we think the original floating-point value
    2340             :   // should have been.
    2341       13132 :   if (AP.isVerbose()) {
    2342             :     SmallString<8> StrVal;
    2343       12272 :     APF.toString(StrVal);
    2344             : 
    2345       12272 :     if (ET)
    2346       12272 :       ET->print(AP.OutStreamer->GetCommentOS());
    2347             :     else
    2348           0 :       AP.OutStreamer->GetCommentOS() << "Printing <null> Type";
    2349       12272 :     AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n';
    2350             :   }
    2351             : 
    2352             :   // Now iterate through the APInt chunks, emitting them in endian-correct
    2353             :   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
    2354             :   // floats).
    2355       13132 :   unsigned NumBytes = API.getBitWidth() / 8;
    2356       13132 :   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
    2357             :   const uint64_t *p = API.getRawData();
    2358             : 
    2359             :   // PPC's long double has odd notions of endianness compared to how LLVM
    2360             :   // handles it: p[0] goes first for *big* endian on PPC.
    2361       14684 :   if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) {
    2362        3098 :     int Chunk = API.getNumWords() - 1;
    2363             : 
    2364        1549 :     if (TrailingBytes)
    2365        1011 :       AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes);
    2366             : 
    2367        2661 :     for (; Chunk >= 0; --Chunk)
    2368         556 :       AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
    2369             :   } else {
    2370             :     unsigned Chunk;
    2371       17745 :     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
    2372        3081 :       AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t));
    2373             : 
    2374       11583 :     if (TrailingBytes)
    2375        8583 :       AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes);
    2376             :   }
    2377             : 
    2378             :   // Emit the tail padding for the long double.
    2379       13132 :   const DataLayout &DL = AP.getDataLayout();
    2380       26264 :   AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET));
    2381       13132 : }
    2382             : 
    2383        5184 : static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
    2384       15552 :   emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP);
    2385        5184 : }
    2386             : 
    2387          38 : static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
    2388          38 :   const DataLayout &DL = AP.getDataLayout();
    2389             :   unsigned BitWidth = CI->getBitWidth();
    2390             : 
    2391             :   // Copy the value as we may massage the layout for constants whose bit width
    2392             :   // is not a multiple of 64-bits.
    2393             :   APInt Realigned(CI->getValue());
    2394             :   uint64_t ExtraBits = 0;
    2395          38 :   unsigned ExtraBitsSize = BitWidth & 63;
    2396             : 
    2397          38 :   if (ExtraBitsSize) {
    2398             :     // The bit width of the data is not a multiple of 64-bits.
    2399             :     // The extra bits are expected to be at the end of the chunk of the memory.
    2400             :     // Little endian:
    2401             :     // * Nothing to be done, just record the extra bits to emit.
    2402             :     // Big endian:
    2403             :     // * Record the extra bits to emit.
    2404             :     // * Realign the raw data to emit the chunks of 64-bits.
    2405           4 :     if (DL.isBigEndian()) {
    2406             :       // Basically the structure of the raw data is a chunk of 64-bits cells:
    2407             :       //    0        1         BitWidth / 64
    2408             :       // [chunk1][chunk2] ... [chunkN].
    2409             :       // The most significant chunk is chunkN and it should be emitted first.
    2410             :       // However, due to the alignment issue chunkN contains useless bits.
    2411             :       // Realign the chunks so that they contain only useless information:
    2412             :       // ExtraBits     0       1       (BitWidth / 64) - 1
    2413             :       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
    2414           2 :       ExtraBits = Realigned.getRawData()[0] &
    2415           1 :         (((uint64_t)-1) >> (64 - ExtraBitsSize));
    2416             :       Realigned.lshrInPlace(ExtraBitsSize);
    2417             :     } else
    2418           3 :       ExtraBits = Realigned.getRawData()[BitWidth / 64];
    2419             :   }
    2420             : 
    2421             :   // We don't expect assemblers to support integer data directives
    2422             :   // for more than 64 bits, so we emit the data in at most 64-bit
    2423             :   // quantities at a time.
    2424             :   const uint64_t *RawData = Realigned.getRawData();
    2425         144 :   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
    2426         106 :     uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i];
    2427         106 :     AP.OutStreamer->EmitIntValue(Val, 8);
    2428             :   }
    2429             : 
    2430          38 :   if (ExtraBitsSize) {
    2431             :     // Emit the extra bits after the 64-bits chunks.
    2432             : 
    2433             :     // Emit a directive that fills the expected size.
    2434           8 :     uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType());
    2435           4 :     Size -= (BitWidth / 64) * 8;
    2436             :     assert(Size && Size * 8 >= ExtraBitsSize &&
    2437             :            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
    2438             :            == ExtraBits && "Directive too small for extra bits.");
    2439           4 :     AP.OutStreamer->EmitIntValue(ExtraBits, Size);
    2440             :   }
    2441          38 : }
    2442             : 
    2443             : /// Transform a not absolute MCExpr containing a reference to a GOT
    2444             : /// equivalent global, by a target specific GOT pc relative access to the
    2445             : /// final symbol.
    2446         498 : static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME,
    2447             :                                          const Constant *BaseCst,
    2448             :                                          uint64_t Offset) {
    2449             :   // The global @foo below illustrates a global that uses a got equivalent.
    2450             :   //
    2451             :   //  @bar = global i32 42
    2452             :   //  @gotequiv = private unnamed_addr constant i32* @bar
    2453             :   //  @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64),
    2454             :   //                             i64 ptrtoint (i32* @foo to i64))
    2455             :   //                        to i32)
    2456             :   //
    2457             :   // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually
    2458             :   // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the
    2459             :   // form:
    2460             :   //
    2461             :   //  foo = cstexpr, where
    2462             :   //    cstexpr := <gotequiv> - "." + <cst>
    2463             :   //    cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst>
    2464             :   //
    2465             :   // After canonicalization by evaluateAsRelocatable `ME` turns into:
    2466             :   //
    2467             :   //  cstexpr := <gotequiv> - <foo> + gotpcrelcst, where
    2468             :   //    gotpcrelcst := <offset from @foo base> + <cst>
    2469         498 :   MCValue MV;
    2470         498 :   if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute())
    2471         480 :     return;
    2472             :   const MCSymbolRefExpr *SymA = MV.getSymA();
    2473         498 :   if (!SymA)
    2474             :     return;
    2475             : 
    2476             :   // Check that GOT equivalent symbol is cached.
    2477         498 :   const MCSymbol *GOTEquivSym = &SymA->getSymbol();
    2478             :   if (!AP.GlobalGOTEquivs.count(GOTEquivSym))
    2479             :     return;
    2480             : 
    2481             :   const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst);
    2482             :   if (!BaseGV)
    2483             :     return;
    2484             : 
    2485             :   // Check for a valid base symbol
    2486          20 :   const MCSymbol *BaseSym = AP.getSymbol(BaseGV);
    2487          20 :   const MCSymbolRefExpr *SymB = MV.getSymB();
    2488             : 
    2489          20 :   if (!SymB || BaseSym != &SymB->getSymbol())
    2490             :     return;
    2491             : 
    2492             :   // Make sure to match:
    2493             :   //
    2494             :   //    gotpcrelcst := <offset from @foo base> + <cst>
    2495             :   //
    2496             :   // If gotpcrelcst is positive it means that we can safely fold the pc rel
    2497             :   // displacement into the GOTPCREL. We can also can have an extra offset <cst>
    2498             :   // if the target knows how to encode it.
    2499          20 :   int64_t GOTPCRelCst = Offset + MV.getConstant();
    2500          20 :   if (GOTPCRelCst < 0)
    2501             :     return;
    2502          20 :   if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0)
    2503             :     return;
    2504             : 
    2505             :   // Emit the GOT PC relative to replace the got equivalent global, i.e.:
    2506             :   //
    2507             :   //  bar:
    2508             :   //    .long 42
    2509             :   //  gotequiv:
    2510             :   //    .quad bar
    2511             :   //  foo:
    2512             :   //    .long gotequiv - "." + <cst>
    2513             :   //
    2514             :   // is replaced by the target specific equivalent to:
    2515             :   //
    2516             :   //  bar:
    2517             :   //    .long 42
    2518             :   //  foo:
    2519             :   //    .long bar@GOTPCREL+<gotpcrelcst>
    2520          18 :   AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym];
    2521             :   const GlobalVariable *GV = Result.first;
    2522          18 :   int NumUses = (int)Result.second;
    2523             :   const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0));
    2524          18 :   const MCSymbol *FinalSym = AP.getSymbol(FinalGV);
    2525          36 :   *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel(
    2526          18 :       FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer);
    2527             : 
    2528             :   // Update GOT equivalent usage information
    2529          18 :   --NumUses;
    2530          18 :   if (NumUses >= 0)
    2531          18 :     AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses);
    2532             : }
    2533             : 
    2534     2583060 : static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV,
    2535             :                                    AsmPrinter &AP, const Constant *BaseCV,
    2536             :                                    uint64_t Offset) {
    2537     2583060 :   uint64_t Size = DL.getTypeAllocSize(CV->getType());
    2538             : 
    2539             :   // Globals with sub-elements such as combinations of arrays and structs
    2540             :   // are handled recursively by emitGlobalConstantImpl. Keep track of the
    2541             :   // constant symbol base and the current position with BaseCV and Offset.
    2542     2705500 :   if (!BaseCV && CV->hasOneUse())
    2543             :     BaseCV = dyn_cast<Constant>(CV->user_back());
    2544             : 
    2545     2583060 :   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
    2546     2517993 :     return AP.OutStreamer->EmitZeros(Size);
    2547             : 
    2548             :   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
    2549             :     switch (Size) {
    2550      140075 :     case 1:
    2551             :     case 2:
    2552             :     case 4:
    2553             :     case 8:
    2554      140075 :       if (AP.isVerbose())
    2555       31206 :         AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n",
    2556             :                                                  CI->getZExtValue());
    2557      280150 :       AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size);
    2558      140075 :       return;
    2559          38 :     default:
    2560          38 :       emitGlobalConstantLargeInt(CI, AP);
    2561          38 :       return;
    2562             :     }
    2563             :   }
    2564             : 
    2565             :   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
    2566        5184 :     return emitGlobalConstantFP(CFP, AP);
    2567             : 
    2568     2398950 :   if (isa<ConstantPointerNull>(CV)) {
    2569     2171929 :     AP.OutStreamer->EmitIntValue(0, Size);
    2570     2171929 :     return;
    2571             :   }
    2572             : 
    2573             :   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
    2574       60215 :     return emitGlobalConstantDataSequential(DL, CDS, AP);
    2575             : 
    2576             :   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
    2577        4803 :     return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset);
    2578             : 
    2579             :   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
    2580       50549 :     return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset);
    2581             : 
    2582             :   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
    2583             :     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
    2584             :     // vectors).
    2585      102981 :     if (CE->getOpcode() == Instruction::BitCast)
    2586        6021 :       return emitGlobalConstantImpl(DL, CE->getOperand(0), AP);
    2587             : 
    2588       96960 :     if (Size > 8) {
    2589             :       // If the constant expression's size is greater than 64-bits, then we have
    2590             :       // to emit the value in chunks. Try to constant fold the value and emit it
    2591             :       // that way.
    2592           1 :       Constant *New = ConstantFoldConstant(CE, DL);
    2593           1 :       if (New && New != CE)
    2594           1 :         return emitGlobalConstantImpl(DL, New, AP);
    2595             :     }
    2596             :   }
    2597             : 
    2598             :   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
    2599        1552 :     return emitGlobalConstantVector(DL, V, AP);
    2600             : 
    2601             :   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
    2602             :   // thread the streamer with EmitValue.
    2603      103880 :   const MCExpr *ME = AP.lowerConstant(CV);
    2604             : 
    2605             :   // Since lowerConstant already folded and got rid of all IR pointer and
    2606             :   // integer casts, detect GOT equivalent accesses by looking into the MCExpr
    2607             :   // directly.
    2608      103878 :   if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel())
    2609         498 :     handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset);
    2610             : 
    2611      103878 :   AP.OutStreamer->EmitValue(ME, Size);
    2612             : }
    2613             : 
    2614             : /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
    2615      108295 : void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) {
    2616      108295 :   uint64_t Size = DL.getTypeAllocSize(CV->getType());
    2617      108295 :   if (Size)
    2618      108251 :     emitGlobalConstantImpl(DL, CV, *this);
    2619          44 :   else if (MAI->hasSubsectionsViaSymbols()) {
    2620             :     // If the global has zero size, emit a single byte so that two labels don't
    2621             :     // look like they are at the same location.
    2622           2 :     OutStreamer->EmitIntValue(0, 1);
    2623             :   }
    2624      108293 : }
    2625             : 
    2626           0 : void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
    2627             :   // Target doesn't support this yet!
    2628           0 :   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
    2629             : }
    2630             : 
    2631          93 : void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
    2632          93 :   if (Offset > 0)
    2633           7 :     OS << '+' << Offset;
    2634          86 :   else if (Offset < 0)
    2635           0 :     OS << Offset;
    2636          93 : }
    2637             : 
    2638             : //===----------------------------------------------------------------------===//
    2639             : // Symbol Lowering Routines.
    2640             : //===----------------------------------------------------------------------===//
    2641             : 
    2642      927628 : MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const {
    2643      927628 :   return OutContext.createTempSymbol(Name, true);
    2644             : }
    2645             : 
    2646         288 : MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
    2647         576 :   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
    2648             : }
    2649             : 
    2650         472 : MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
    2651         944 :   return MMI->getAddrLabelSymbol(BB);
    2652             : }
    2653             : 
    2654             : /// GetCPISymbol - Return the symbol for the specified constant pool entry.
    2655       53097 : MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
    2656       53097 :   const DataLayout &DL = getDataLayout();
    2657      159291 :   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
    2658      159291 :                                       "CPI" + Twine(getFunctionNumber()) + "_" +
    2659      106194 :                                       Twine(CPID));
    2660             : }
    2661             : 
    2662             : /// GetJTISymbol - Return the symbol for the specified jump table entry.
    2663         530 : MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
    2664         530 :   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
    2665             : }
    2666             : 
    2667             : /// GetJTSetSymbol - Return the symbol for the specified jump table .set
    2668             : /// FIXME: privatize to AsmPrinter.
    2669         869 : MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
    2670         869 :   const DataLayout &DL = getDataLayout();
    2671        2607 :   return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) +
    2672        2607 :                                       Twine(getFunctionNumber()) + "_" +
    2673        1738 :                                       Twine(UID) + "_set_" + Twine(MBBID));
    2674             : }
    2675             : 
    2676         921 : MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
    2677             :                                                    StringRef Suffix) const {
    2678         921 :   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM);
    2679             : }
    2680             : 
    2681             : /// Return the MCSymbol for the specified ExternalSymbol.
    2682       12890 : MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
    2683             :   SmallString<60> NameStr;
    2684       25780 :   Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout());
    2685       38670 :   return OutContext.getOrCreateSymbol(NameStr);
    2686             : }
    2687             : 
    2688             : /// PrintParentLoopComment - Print comments about parent loops of this one.
    2689        5431 : static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
    2690             :                                    unsigned FunctionNumber) {
    2691        5431 :   if (!Loop) return;
    2692         349 :   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
    2693         698 :   OS.indent(Loop->getLoopDepth()*2)
    2694         698 :     << "Parent Loop BB" << FunctionNumber << "_"
    2695         349 :     << Loop->getHeader()->getNumber()
    2696         349 :     << " Depth=" << Loop->getLoopDepth() << '\n';
    2697             : }
    2698             : 
    2699             : /// PrintChildLoopComment - Print comments about child loops within
    2700             : /// the loop for this basic block, with nesting.
    2701        5431 : static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
    2702             :                                   unsigned FunctionNumber) {
    2703             :   // Add child loop information
    2704        5780 :   for (const MachineLoop *CL : *Loop) {
    2705         698 :     OS.indent(CL->getLoopDepth()*2)
    2706         698 :       << "Child Loop BB" << FunctionNumber << "_"
    2707         698 :       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
    2708             :       << '\n';
    2709         349 :     PrintChildLoopComment(OS, CL, FunctionNumber);
    2710             :   }
    2711        5431 : }
    2712             : 
    2713             : /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
    2714      209908 : static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
    2715             :                                        const MachineLoopInfo *LI,
    2716             :                                        const AsmPrinter &AP) {
    2717             :   // Add loop depth information
    2718             :   const MachineLoop *Loop = LI->getLoopFor(&MBB);
    2719        7845 :   if (!Loop) return;
    2720             : 
    2721             :   MachineBasicBlock *Header = Loop->getHeader();
    2722             :   assert(Header && "No header for loop");
    2723             : 
    2724             :   // If this block is not a loop header, just print out what is the loop header
    2725             :   // and return.
    2726        7845 :   if (Header != &MBB) {
    2727        5526 :     AP.OutStreamer->AddComment("  in Loop: Header=BB" +
    2728        8289 :                                Twine(AP.getFunctionNumber())+"_" +
    2729        8289 :                                Twine(Loop->getHeader()->getNumber())+
    2730        8289 :                                " Depth="+Twine(Loop->getLoopDepth()));
    2731        2763 :     return;
    2732             :   }
    2733             : 
    2734             :   // Otherwise, it is a loop header.  Print out information about child and
    2735             :   // parent loops.
    2736        5082 :   raw_ostream &OS = AP.OutStreamer->GetCommentOS();
    2737             : 
    2738        5082 :   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
    2739             : 
    2740        5082 :   OS << "=>";
    2741       10164 :   OS.indent(Loop->getLoopDepth()*2-2);
    2742             : 
    2743        5082 :   OS << "This ";
    2744        5082 :   if (Loop->empty())
    2745        4846 :     OS << "Inner ";
    2746       10164 :   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
    2747             : 
    2748        5082 :   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
    2749             : }
    2750             : 
    2751      873236 : void AsmPrinter::setupCodePaddingContext(const MachineBasicBlock &MBB,
    2752             :                                          MCCodePaddingContext &Context) const {
    2753             :   assert(MF != nullptr && "Machine function must be valid");
    2754     2590708 :   Context.IsPaddingActive = !MF->hasInlineAsm() &&
    2755     1709958 :                             !MF->getFunction().optForSize() &&
    2756      836722 :                             TM.getOptLevel() != CodeGenOpt::None;
    2757      873236 :   Context.IsBasicBlockReachableViaFallthrough =
    2758     2619708 :       std::find(MBB.pred_begin(), MBB.pred_end(), MBB.getPrevNode()) !=
    2759             :       MBB.pred_end();
    2760      873236 :   Context.IsBasicBlockReachableViaBranch =
    2761      873236 :       MBB.pred_size() > 0 && !isBlockOnlyReachableByFallthrough(&MBB);
    2762      873236 : }
    2763             : 
    2764             : /// EmitBasicBlockStart - This method prints the label for the specified
    2765             : /// MachineBasicBlock, an alignment (if present) and a comment describing
    2766             : /// it if appropriate.
    2767      436618 : void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
    2768             :   // End the previous funclet and start a new one.
    2769      436618 :   if (MBB.isEHFuncletEntry()) {
    2770         586 :     for (const HandlerInfo &HI : Handlers) {
    2771         234 :       HI.Handler->endFunclet();
    2772         234 :       HI.Handler->beginFunclet(MBB);
    2773             :     }
    2774             :   }
    2775             : 
    2776             :   // Emit an alignment directive for this block, if needed.
    2777      436618 :   if (unsigned Align = MBB.getAlignment())
    2778        7835 :     EmitAlignment(Align);
    2779             :   MCCodePaddingContext Context;
    2780      436618 :   setupCodePaddingContext(MBB, Context);
    2781      436618 :   OutStreamer->EmitCodePaddingBasicBlockStart(Context);
    2782             : 
    2783             :   // If the block has its address taken, emit any labels that were used to
    2784             :   // reference the block.  It is possible that there is more than one label
    2785             :   // here, because multiple LLVM BB's may have been RAUW'd to this block after
    2786             :   // the references were generated.
    2787      436618 :   if (MBB.hasAddressTaken()) {
    2788         441 :     const BasicBlock *BB = MBB.getBasicBlock();
    2789         441 :     if (isVerbose())
    2790         854 :       OutStreamer->AddComment("Block address taken");
    2791             : 
    2792             :     // MBBs can have their address taken as part of CodeGen without having
    2793             :     // their corresponding BB's address taken in IR
    2794         441 :     if (BB->hasAddressTaken())
    2795        1360 :       for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB))
    2796         340 :         OutStreamer->EmitLabel(Sym);
    2797             :   }
    2798             : 
    2799             :   // Print some verbose block comments.
    2800      436618 :   if (isVerbose()) {
    2801      209908 :     if (const BasicBlock *BB = MBB.getBasicBlock()) {
    2802      206281 :       if (BB->hasName()) {
    2803      158454 :         BB->printAsOperand(OutStreamer->GetCommentOS(),
    2804             :                            /*PrintType=*/false, BB->getModule());
    2805       79227 :         OutStreamer->GetCommentOS() << '\n';
    2806             :       }
    2807             :     }
    2808             : 
    2809             :     assert(MLI != nullptr && "MachineLoopInfo should has been computed");
    2810      209908 :     emitBasicBlockLoopComments(MBB, MLI, *this);
    2811             :   }
    2812             : 
    2813             :   // Print the main label for the block.
    2814      643978 :   if (MBB.pred_empty() ||
    2815      284840 :       (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry())) {
    2816      306738 :     if (isVerbose()) {
    2817             :       // NOTE: Want this comment at start of line, don't emit with AddComment.
    2818      378528 :       OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":",
    2819      189264 :                                   false);
    2820             :     }
    2821             :   } else {
    2822      129880 :     OutStreamer->EmitLabel(MBB.getSymbol());
    2823             :   }
    2824      436618 : }
    2825             : 
    2826      436618 : void AsmPrinter::EmitBasicBlockEnd(const MachineBasicBlock &MBB) {
    2827             :   MCCodePaddingContext Context;
    2828      436618 :   setupCodePaddingContext(MBB, Context);
    2829      436618 :   OutStreamer->EmitCodePaddingBasicBlockEnd(Context);
    2830      436618 : }
    2831             : 
    2832      322954 : void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
    2833             :                                 bool IsDefinition) const {
    2834             :   MCSymbolAttr Attr = MCSA_Invalid;
    2835             : 
    2836      322954 :   switch (Visibility) {
    2837             :   default: break;
    2838        4457 :   case GlobalValue::HiddenVisibility:
    2839        4457 :     if (IsDefinition)
    2840        3974 :       Attr = MAI->getHiddenVisibilityAttr();
    2841             :     else
    2842         483 :       Attr = MAI->getHiddenDeclarationVisibilityAttr();
    2843             :     break;
    2844          56 :   case GlobalValue::ProtectedVisibility:
    2845          56 :     Attr = MAI->getProtectedVisibilityAttr();
    2846          56 :     break;
    2847             :   }
    2848             : 
    2849        4513 :   if (Attr != MCSA_Invalid)
    2850        4407 :     OutStreamer->EmitSymbolAttribute(Sym, Attr);
    2851      322954 : }
    2852             : 
    2853             : /// isBlockOnlyReachableByFallthough - Return true if the basic block has
    2854             : /// exactly one predecessor and the control transfer mechanism between
    2855             : /// the predecessor and this block is a fall-through.
    2856      614765 : bool AsmPrinter::
    2857             : isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
    2858             :   // If this is a landing pad, it isn't a fall through.  If it has no preds,
    2859             :   // then nothing falls through to it.
    2860     1144144 :   if (MBB->isEHPad() || MBB->pred_empty())
    2861             :     return false;
    2862             : 
    2863             :   // If there isn't exactly one predecessor, it can't be a fall through.
    2864      529377 :   if (MBB->pred_size() > 1)
    2865             :     return false;
    2866             : 
    2867             :   // The predecessor has to be immediately before this block.
    2868      364140 :   MachineBasicBlock *Pred = *MBB->pred_begin();
    2869      364140 :   if (!Pred->isLayoutSuccessor(MBB))
    2870             :     return false;
    2871             : 
    2872             :   // If the block is completely empty, then it definitely does fall through.
    2873      287883 :   if (Pred->empty())
    2874             :     return true;
    2875             : 
    2876             :   // Check the terminators in the previous blocks
    2877      725592 :   for (const auto &MI : Pred->terminators()) {
    2878             :     // If it is not a simple branch, we are in a table somewhere.
    2879      412341 :     if (!MI.isBranch() || MI.isIndirectBranch())
    2880       57930 :       return false;
    2881             : 
    2882             :     // If we are the operands of one of the branches, this is not a fall
    2883             :     // through. Note that targets with delay slots will usually bundle
    2884             :     // terminators with the delay slot instruction.
    2885      541782 :     for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) {
    2886      391746 :       if (OP->isJTI())
    2887       53403 :         return false;
    2888      391746 :       if (OP->isMBB() && OP->getMBB() == MBB)
    2889             :         return false;
    2890             :     }
    2891             :   }
    2892             : 
    2893      229848 :   return true;
    2894             : }
    2895             : 
    2896          50 : GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
    2897          50 :   if (!S.usesMetadata())
    2898             :     return nullptr;
    2899             : 
    2900             :   assert(!S.useStatepoints() && "statepoints do not currently support custom"
    2901             :          " stackmap formats, please see the documentation for a description of"
    2902             :          " the default format.  If you really need a custom serialized format,"
    2903             :          " please file a bug");
    2904             : 
    2905          12 :   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
    2906          12 :   gcp_map_type::iterator GCPI = GCMap.find(&S);
    2907          12 :   if (GCPI != GCMap.end())
    2908           6 :     return GCPI->second.get();
    2909             : 
    2910             :   auto Name = S.getName();
    2911             : 
    2912             :   for (GCMetadataPrinterRegistry::iterator
    2913           6 :          I = GCMetadataPrinterRegistry::begin(),
    2914           9 :          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
    2915             :     if (Name == I->getName()) {
    2916           6 :       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
    2917           6 :       GMP->S = &S;
    2918           6 :       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
    2919           6 :       return IterBool.first->second.get();
    2920             :     }
    2921             : 
    2922           0 :   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
    2923             : }
    2924             : 
    2925             : /// Pin vtable to this file.
    2926             : AsmPrinterHandler::~AsmPrinterHandler() = default;
    2927             : 
    2928      228883 : void AsmPrinterHandler::markFunctionEnd() {}
    2929             : 
    2930             : // In the binary's "xray_instr_map" section, an array of these function entries
    2931             : // describes each instrumentation point.  When XRay patches your code, the index
    2932             : // into this table will be given to your handler as a patch point identifier.
    2933         152 : void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out,
    2934             :                                          const MCSymbol *CurrentFnSym) const {
    2935         152 :   Out->EmitSymbolValue(Sled, Bytes);
    2936         152 :   Out->EmitSymbolValue(CurrentFnSym, Bytes);
    2937         152 :   auto Kind8 = static_cast<uint8_t>(Kind);
    2938         304 :   Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1));
    2939         152 :   Out->EmitBinaryData(
    2940         152 :       StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1));
    2941         304 :   Out->EmitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1));
    2942         152 :   auto Padding = (4 * Bytes) - ((2 * Bytes) + 3);
    2943             :   assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size");
    2944         152 :   Out->EmitZeros(Padding);
    2945         152 : }
    2946             : 
    2947      190409 : void AsmPrinter::emitXRayTable() {
    2948      190409 :   if (Sleds.empty())
    2949             :     return;
    2950             : 
    2951             :   auto PrevSection = OutStreamer->getCurrentSectionOnly();
    2952          70 :   const Function &F = MF->getFunction();
    2953             :   MCSection *InstMap = nullptr;
    2954             :   MCSection *FnSledIndex = nullptr;
    2955         140 :   if (MF->getSubtarget().getTargetTriple().isOSBinFormatELF()) {
    2956          58 :     auto Associated = dyn_cast<MCSymbolELF>(CurrentFnSym);
    2957             :     assert(Associated != nullptr);
    2958             :     auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER;
    2959             :     std::string GroupName;
    2960          58 :     if (F.hasComdat()) {
    2961             :       Flags |= ELF::SHF_GROUP;
    2962          30 :       GroupName = F.getComdat()->getName();
    2963             :     }
    2964             : 
    2965          58 :     auto UniqueID = ++XRayFnUniqueID;
    2966          58 :     InstMap =
    2967         116 :         OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, Flags, 0,
    2968             :                                  GroupName, UniqueID, Associated);
    2969          58 :     FnSledIndex =
    2970         116 :         OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, Flags, 0,
    2971             :                                  GroupName, UniqueID, Associated);
    2972          12 :   } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) {
    2973          12 :     InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0,
    2974             :                                          SectionKind::getReadOnlyWithRel());
    2975          12 :     FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0,
    2976             :                                              SectionKind::getReadOnlyWithRel());
    2977             :   } else {
    2978           0 :     llvm_unreachable("Unsupported target");
    2979             :   }
    2980             : 
    2981          70 :   auto WordSizeBytes = MAI->getCodePointerSize();
    2982             : 
    2983             :   // Now we switch to the instrumentation map section. Because this is done
    2984             :   // per-function, we are able to create an index entry that will represent the
    2985             :   // range of sleds associated with a function.
    2986         140 :   MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true);
    2987          70 :   OutStreamer->SwitchSection(InstMap);
    2988          70 :   OutStreamer->EmitLabel(SledsStart);
    2989         374 :   for (const auto &Sled : Sleds)
    2990         304 :     Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym);
    2991         140 :   MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true);
    2992          70 :   OutStreamer->EmitLabel(SledsEnd);
    2993             : 
    2994             :   // We then emit a single entry in the index per function. We use the symbols
    2995             :   // that bound the instrumentation map as the range for a specific function.
    2996             :   // Each entry here will be 2 * word size aligned, as we're writing down two
    2997             :   // pointers. This should work for both 32-bit and 64-bit platforms.
    2998          70 :   OutStreamer->SwitchSection(FnSledIndex);
    2999          70 :   OutStreamer->EmitCodeAlignment(2 * WordSizeBytes);
    3000          70 :   OutStreamer->EmitSymbolValue(SledsStart, WordSizeBytes, false);
    3001          70 :   OutStreamer->EmitSymbolValue(SledsEnd, WordSizeBytes, false);
    3002          70 :   OutStreamer->SwitchSection(PrevSection);
    3003             :   Sleds.clear();
    3004             : }
    3005             : 
    3006         152 : void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI,
    3007             :                             SledKind Kind, uint8_t Version) {
    3008         152 :   const Function &F = MI.getMF()->getFunction();
    3009         152 :   auto Attr = F.getFnAttribute("function-instrument");
    3010             :   bool LogArgs = F.hasFnAttribute("xray-log-args");
    3011             :   bool AlwaysInstrument =
    3012         152 :     Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always";
    3013         152 :   if (Kind == SledKind::FUNCTION_ENTER && LogArgs)
    3014             :     Kind = SledKind::LOG_ARGS_ENTER;
    3015         152 :   Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind,
    3016             :                                        AlwaysInstrument, &F, Version});
    3017         152 : }
    3018             : 
    3019     4984667 : uint16_t AsmPrinter::getDwarfVersion() const {
    3020     4984667 :   return OutStreamer->getContext().getDwarfVersion();
    3021             : }
    3022             : 
    3023          65 : void AsmPrinter::setDwarfVersion(uint16_t Version) {
    3024          65 :   OutStreamer->getContext().setDwarfVersion(Version);
    3025      303572 : }

Generated by: LCOV version 1.13