LLVM API Documentation

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