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();
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     } else {
00230       DD = new DwarfDebug(this, &M);
00231       Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName));
00232     }
00233   }
00234 
00235   EHStreamer *ES = nullptr;
00236   switch (MAI->getExceptionHandlingType()) {
00237   case ExceptionHandling::None:
00238     break;
00239   case ExceptionHandling::SjLj:
00240   case ExceptionHandling::DwarfCFI:
00241     ES = new DwarfCFIException(this);
00242     break;
00243   case ExceptionHandling::ARM:
00244     ES = new ARMException(this);
00245     break;
00246   case ExceptionHandling::WinEH:
00247     switch (MAI->getWinEHEncodingType()) {
00248     default: llvm_unreachable("unsupported unwinding information encoding");
00249     case WinEH::EncodingType::Itanium:
00250       ES = new Win64Exception(this);
00251       break;
00252     }
00253     break;
00254   }
00255   if (ES)
00256     Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName));
00257   return false;
00258 }
00259 
00260 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) {
00261   if (!MAI.hasWeakDefCanBeHiddenDirective())
00262     return false;
00263 
00264   return canBeOmittedFromSymbolTable(GV);
00265 }
00266 
00267 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const {
00268   GlobalValue::LinkageTypes Linkage = GV->getLinkage();
00269   switch (Linkage) {
00270   case GlobalValue::CommonLinkage:
00271   case GlobalValue::LinkOnceAnyLinkage:
00272   case GlobalValue::LinkOnceODRLinkage:
00273   case GlobalValue::WeakAnyLinkage:
00274   case GlobalValue::WeakODRLinkage:
00275     if (MAI->hasWeakDefDirective()) {
00276       // .globl _foo
00277       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
00278 
00279       if (!canBeHidden(GV, *MAI))
00280         // .weak_definition _foo
00281         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
00282       else
00283         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
00284     } else if (MAI->hasLinkOnceDirective()) {
00285       // .globl _foo
00286       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
00287       //NOTE: linkonce is handled by the section the symbol was assigned to.
00288     } else {
00289       // .weak _foo
00290       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
00291     }
00292     return;
00293   case GlobalValue::AppendingLinkage:
00294     // FIXME: appending linkage variables should go into a section of
00295     // their name or something.  For now, just emit them as external.
00296   case GlobalValue::ExternalLinkage:
00297     // If external or appending, declare as a global symbol.
00298     // .globl _foo
00299     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
00300     return;
00301   case GlobalValue::PrivateLinkage:
00302   case GlobalValue::InternalLinkage:
00303     return;
00304   case GlobalValue::AvailableExternallyLinkage:
00305     llvm_unreachable("Should never emit this");
00306   case GlobalValue::ExternalWeakLinkage:
00307     llvm_unreachable("Don't know how to emit these");
00308   }
00309   llvm_unreachable("Unknown linkage type!");
00310 }
00311 
00312 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name,
00313                                    const GlobalValue *GV) const {
00314   TM.getNameWithPrefix(Name, GV, *Mang);
00315 }
00316 
00317 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const {
00318   return TM.getSymbol(GV, *Mang);
00319 }
00320 
00321 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
00322 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
00323   if (GV->hasInitializer()) {
00324     // Check to see if this is a special global used by LLVM, if so, emit it.
00325     if (EmitSpecialLLVMGlobal(GV))
00326       return;
00327 
00328     if (isVerbose()) {
00329       GV->printAsOperand(OutStreamer.GetCommentOS(),
00330                      /*PrintType=*/false, GV->getParent());
00331       OutStreamer.GetCommentOS() << '\n';
00332     }
00333   }
00334 
00335   MCSymbol *GVSym = getSymbol(GV);
00336   EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
00337 
00338   if (!GV->hasInitializer())   // External globals require no extra code.
00339     return;
00340 
00341   if (MAI->hasDotTypeDotSizeDirective())
00342     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
00343 
00344   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
00345 
00346   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
00347   uint64_t Size = DL->getTypeAllocSize(GV->getType()->getElementType());
00348 
00349   // If the alignment is specified, we *must* obey it.  Overaligning a global
00350   // with a specified alignment is a prompt way to break globals emitted to
00351   // sections and expected to be contiguous (e.g. ObjC metadata).
00352   unsigned AlignLog = getGVAlignmentLog2(GV, *DL);
00353 
00354   for (const HandlerInfo &HI : Handlers) {
00355     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
00356     HI.Handler->setSymbolSize(GVSym, Size);
00357   }
00358 
00359   // Handle common and BSS local symbols (.lcomm).
00360   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
00361     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
00362     unsigned Align = 1 << AlignLog;
00363 
00364     // Handle common symbols.
00365     if (GVKind.isCommon()) {
00366       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
00367         Align = 0;
00368 
00369       // .comm _foo, 42, 4
00370       OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
00371       return;
00372     }
00373 
00374     // Handle local BSS symbols.
00375     if (MAI->hasMachoZeroFillDirective()) {
00376       const MCSection *TheSection =
00377         getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
00378       // .zerofill __DATA, __bss, _foo, 400, 5
00379       OutStreamer.EmitZerofill(TheSection, GVSym, Size, Align);
00380       return;
00381     }
00382 
00383     // Use .lcomm only if it supports user-specified alignment.
00384     // Otherwise, while it would still be correct to use .lcomm in some
00385     // cases (e.g. when Align == 1), the external assembler might enfore
00386     // some -unknown- default alignment behavior, which could cause
00387     // spurious differences between external and integrated assembler.
00388     // Prefer to simply fall back to .local / .comm in this case.
00389     if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) {
00390       // .lcomm _foo, 42
00391       OutStreamer.EmitLocalCommonSymbol(GVSym, Size, Align);
00392       return;
00393     }
00394 
00395     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
00396       Align = 0;
00397 
00398     // .local _foo
00399     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
00400     // .comm _foo, 42, 4
00401     OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
00402     return;
00403   }
00404 
00405   const MCSection *TheSection =
00406     getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM);
00407 
00408   // Handle the zerofill directive on darwin, which is a special form of BSS
00409   // emission.
00410   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
00411     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
00412 
00413     // .globl _foo
00414     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
00415     // .zerofill __DATA, __common, _foo, 400, 5
00416     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
00417     return;
00418   }
00419 
00420   // Handle thread local data for mach-o which requires us to output an
00421   // additional structure of data and mangle the original symbol so that we
00422   // can reference it later.
00423   //
00424   // TODO: This should become an "emit thread local global" method on TLOF.
00425   // All of this macho specific stuff should be sunk down into TLOFMachO and
00426   // stuff like "TLSExtraDataSection" should no longer be part of the parent
00427   // TLOF class.  This will also make it more obvious that stuff like
00428   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
00429   // specific code.
00430   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
00431     // Emit the .tbss symbol
00432     MCSymbol *MangSym =
00433       OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
00434 
00435     if (GVKind.isThreadBSS()) {
00436       TheSection = getObjFileLowering().getTLSBSSSection();
00437       OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
00438     } else if (GVKind.isThreadData()) {
00439       OutStreamer.SwitchSection(TheSection);
00440 
00441       EmitAlignment(AlignLog, GV);
00442       OutStreamer.EmitLabel(MangSym);
00443 
00444       EmitGlobalConstant(GV->getInitializer());
00445     }
00446 
00447     OutStreamer.AddBlankLine();
00448 
00449     // Emit the variable struct for the runtime.
00450     const MCSection *TLVSect
00451       = getObjFileLowering().getTLSExtraDataSection();
00452 
00453     OutStreamer.SwitchSection(TLVSect);
00454     // Emit the linkage here.
00455     EmitLinkage(GV, GVSym);
00456     OutStreamer.EmitLabel(GVSym);
00457 
00458     // Three pointers in size:
00459     //   - __tlv_bootstrap - used to make sure support exists
00460     //   - spare pointer, used when mapped by the runtime
00461     //   - pointer to mangled symbol above with initializer
00462     unsigned PtrSize = DL->getPointerTypeSize(GV->getType());
00463     OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
00464                                 PtrSize);
00465     OutStreamer.EmitIntValue(0, PtrSize);
00466     OutStreamer.EmitSymbolValue(MangSym, PtrSize);
00467 
00468     OutStreamer.AddBlankLine();
00469     return;
00470   }
00471 
00472   OutStreamer.SwitchSection(TheSection);
00473 
00474   EmitLinkage(GV, GVSym);
00475   EmitAlignment(AlignLog, GV);
00476 
00477   OutStreamer.EmitLabel(GVSym);
00478 
00479   EmitGlobalConstant(GV->getInitializer());
00480 
00481   if (MAI->hasDotTypeDotSizeDirective())
00482     // .size foo, 42
00483     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
00484 
00485   OutStreamer.AddBlankLine();
00486 }
00487 
00488 /// EmitFunctionHeader - This method emits the header for the current
00489 /// function.
00490 void AsmPrinter::EmitFunctionHeader() {
00491   // Print out constants referenced by the function
00492   EmitConstantPool();
00493 
00494   // Print the 'header' of function.
00495   const Function *F = MF->getFunction();
00496 
00497   OutStreamer.SwitchSection(
00498       getObjFileLowering().SectionForGlobal(F, *Mang, TM));
00499   EmitVisibility(CurrentFnSym, F->getVisibility());
00500 
00501   EmitLinkage(F, CurrentFnSym);
00502   EmitAlignment(MF->getAlignment(), F);
00503 
00504   if (MAI->hasDotTypeDotSizeDirective())
00505     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
00506 
00507   if (isVerbose()) {
00508     F->printAsOperand(OutStreamer.GetCommentOS(),
00509                    /*PrintType=*/false, F->getParent());
00510     OutStreamer.GetCommentOS() << '\n';
00511   }
00512 
00513   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
00514   // do their wild and crazy things as required.
00515   EmitFunctionEntryLabel();
00516 
00517   // If the function had address-taken blocks that got deleted, then we have
00518   // references to the dangling symbols.  Emit them at the start of the function
00519   // so that we don't get references to undefined symbols.
00520   std::vector<MCSymbol*> DeadBlockSyms;
00521   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
00522   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
00523     OutStreamer.AddComment("Address taken block that was later removed");
00524     OutStreamer.EmitLabel(DeadBlockSyms[i]);
00525   }
00526 
00527   // Emit pre-function debug and/or EH information.
00528   for (const HandlerInfo &HI : Handlers) {
00529     NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled);
00530     HI.Handler->beginFunction(MF);
00531   }
00532 
00533   // Emit the prefix data.
00534   if (F->hasPrefixData())
00535     EmitGlobalConstant(F->getPrefixData());
00536 }
00537 
00538 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
00539 /// function.  This can be overridden by targets as required to do custom stuff.
00540 void AsmPrinter::EmitFunctionEntryLabel() {
00541   // The function label could have already been emitted if two symbols end up
00542   // conflicting due to asm renaming.  Detect this and emit an error.
00543   if (CurrentFnSym->isUndefined())
00544     return OutStreamer.EmitLabel(CurrentFnSym);
00545 
00546   report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
00547                      "' label emitted multiple times to assembly file");
00548 }
00549 
00550 /// emitComments - Pretty-print comments for instructions.
00551 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
00552   const MachineFunction *MF = MI.getParent()->getParent();
00553   const TargetMachine &TM = MF->getTarget();
00554 
00555   // Check for spills and reloads
00556   int FI;
00557 
00558   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
00559 
00560   // We assume a single instruction only has a spill or reload, not
00561   // both.
00562   const MachineMemOperand *MMO;
00563   if (TM.getSubtargetImpl()->getInstrInfo()->isLoadFromStackSlotPostFE(&MI,
00564                                                                        FI)) {
00565     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
00566       MMO = *MI.memoperands_begin();
00567       CommentOS << MMO->getSize() << "-byte Reload\n";
00568     }
00569   } else if (TM.getSubtargetImpl()->getInstrInfo()->hasLoadFromStackSlot(
00570                  &MI, MMO, FI)) {
00571     if (FrameInfo->isSpillSlotObjectIndex(FI))
00572       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
00573   } else if (TM.getSubtargetImpl()->getInstrInfo()->isStoreToStackSlotPostFE(
00574                  &MI, FI)) {
00575     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
00576       MMO = *MI.memoperands_begin();
00577       CommentOS << MMO->getSize() << "-byte Spill\n";
00578     }
00579   } else if (TM.getSubtargetImpl()->getInstrInfo()->hasStoreToStackSlot(
00580                  &MI, MMO, FI)) {
00581     if (FrameInfo->isSpillSlotObjectIndex(FI))
00582       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
00583   }
00584 
00585   // Check for spill-induced copies
00586   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
00587     CommentOS << " Reload Reuse\n";
00588 }
00589 
00590 /// emitImplicitDef - This method emits the specified machine instruction
00591 /// that is an implicit def.
00592 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
00593   unsigned RegNo = MI->getOperand(0).getReg();
00594   OutStreamer.AddComment(
00595       Twine("implicit-def: ") +
00596       TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
00597   OutStreamer.AddBlankLine();
00598 }
00599 
00600 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) {
00601   std::string Str = "kill:";
00602   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00603     const MachineOperand &Op = MI->getOperand(i);
00604     assert(Op.isReg() && "KILL instruction must have only register operands");
00605     Str += ' ';
00606     Str += AP.TM.getSubtargetImpl()->getRegisterInfo()->getName(Op.getReg());
00607     Str += (Op.isDef() ? "<def>" : "<kill>");
00608   }
00609   AP.OutStreamer.AddComment(Str);
00610   AP.OutStreamer.AddBlankLine();
00611 }
00612 
00613 /// emitDebugValueComment - This method handles the target-independent form
00614 /// of DBG_VALUE, returning true if it was able to do so.  A false return
00615 /// means the target will need to handle MI in EmitInstruction.
00616 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
00617   // This code handles only the 3-operand target-independent form.
00618   if (MI->getNumOperands() != 3)
00619     return false;
00620 
00621   SmallString<128> Str;
00622   raw_svector_ostream OS(Str);
00623   OS << "DEBUG_VALUE: ";
00624 
00625   DIVariable V = MI->getDebugVariable();
00626   if (V.getContext().isSubprogram()) {
00627     StringRef Name = DISubprogram(V.getContext()).getDisplayName();
00628     if (!Name.empty())
00629       OS << Name << ":";
00630   }
00631   OS << V.getName();
00632   if (V.isVariablePiece())
00633     OS << " [piece offset=" << V.getPieceOffset()
00634        << " size="<<V.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::WinEH &&
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     for (const auto &KV : JITI->getTables()) {
00883       uint64_t Count = 0;
00884       for (const auto &FunPair : KV.second) {
00885         // Emit the function labels to make this be a function entry point.
00886         MCSymbol *FunSym =
00887           OutContext.GetOrCreateSymbol(FunPair.second->getName());
00888         OutStreamer.EmitSymbolAttribute(FunSym, MCSA_Global);
00889         // FIXME: JumpTableInstrInfo should store information about the required
00890         // alignment of table entries and the size of the padding instruction.
00891         EmitAlignment(3);
00892         if (IsThumb)
00893           OutStreamer.EmitThumbFunc(FunSym);
00894         if (MAI->hasDotTypeDotSizeDirective())
00895           OutStreamer.EmitSymbolAttribute(FunSym, MCSA_ELF_TypeFunction);
00896         OutStreamer.EmitLabel(FunSym);
00897 
00898         // Emit the jump instruction to transfer control to the original
00899         // function.
00900         MCInst JumpToFun;
00901         MCSymbol *TargetSymbol =
00902           OutContext.GetOrCreateSymbol(FunPair.first->getName());
00903         const MCSymbolRefExpr *TargetSymRef =
00904           MCSymbolRefExpr::Create(TargetSymbol, MCSymbolRefExpr::VK_PLT,
00905                                   OutContext);
00906         TM.getSubtargetImpl()->getInstrInfo()->getUnconditionalBranch(
00907             JumpToFun, TargetSymRef);
00908         OutStreamer.EmitInstruction(JumpToFun, getSubtargetInfo());
00909         ++Count;
00910       }
00911 
00912       // Emit enough padding instructions to fill up to the next power of two.
00913       // This assumes that the trap instruction takes 8 bytes or fewer.
00914       uint64_t Remaining = NextPowerOf2(Count) - Count;
00915       for (uint64_t C = 0; C < Remaining; ++C) {
00916         EmitAlignment(3);
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   if (MAI->hasSetDirective()) {
00964     OutStreamer.AddBlankLine();
00965     for (const auto &Alias : M.aliases()) {
00966       MCSymbol *Name = getSymbol(&Alias);
00967 
00968       if (Alias.hasExternalLinkage() || !MAI->getWeakRefDirective())
00969         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
00970       else if (Alias.hasWeakLinkage() || Alias.hasLinkOnceLinkage())
00971         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
00972       else
00973         assert(Alias.hasLocalLinkage() && "Invalid alias linkage");
00974 
00975       EmitVisibility(Name, Alias.getVisibility());
00976 
00977       // Emit the directives as assignments aka .set:
00978       OutStreamer.EmitAssignment(Name,
00979                                  lowerConstant(Alias.getAliasee(), *this));
00980     }
00981   }
00982 
00983   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
00984   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
00985   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
00986     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I))
00987       MP->finishAssembly(*this);
00988 
00989   // Emit llvm.ident metadata in an '.ident' directive.
00990   EmitModuleIdents(M);
00991 
00992   // If we don't have any trampolines, then we don't require stack memory
00993   // to be executable. Some targets have a directive to declare this.
00994   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
00995   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
00996     if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
00997       OutStreamer.SwitchSection(S);
00998 
00999   // Allow the target to emit any magic that it wants at the end of the file,
01000   // after everything else has gone out.
01001   EmitEndOfAsmFile(M);
01002 
01003   delete Mang; Mang = nullptr;
01004   MMI = nullptr;
01005 
01006   OutStreamer.Finish();
01007   OutStreamer.reset();
01008 
01009   return false;
01010 }
01011 
01012 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
01013   this->MF = &MF;
01014   // Get the function symbol.
01015   CurrentFnSym = getSymbol(MF.getFunction());
01016   CurrentFnSymForSize = CurrentFnSym;
01017 
01018   if (isVerbose())
01019     LI = &getAnalysis<MachineLoopInfo>();
01020 }
01021 
01022 namespace {
01023   // SectionCPs - Keep track the alignment, constpool entries per Section.
01024   struct SectionCPs {
01025     const MCSection *S;
01026     unsigned Alignment;
01027     SmallVector<unsigned, 4> CPEs;
01028     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
01029   };
01030 }
01031 
01032 /// EmitConstantPool - Print to the current output stream assembly
01033 /// representations of the constants in the constant pool MCP. This is
01034 /// used to print out constants which have been "spilled to memory" by
01035 /// the code generator.
01036 ///
01037 void AsmPrinter::EmitConstantPool() {
01038   const MachineConstantPool *MCP = MF->getConstantPool();
01039   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
01040   if (CP.empty()) return;
01041 
01042   // Calculate sections for constant pool entries. We collect entries to go into
01043   // the same section together to reduce amount of section switch statements.
01044   SmallVector<SectionCPs, 4> CPSections;
01045   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
01046     const MachineConstantPoolEntry &CPE = CP[i];
01047     unsigned Align = CPE.getAlignment();
01048 
01049     SectionKind Kind =
01050         CPE.getSectionKind(TM.getSubtargetImpl()->getDataLayout());
01051 
01052     const Constant *C = nullptr;
01053     if (!CPE.isMachineConstantPoolEntry())
01054       C = CPE.Val.ConstVal;
01055 
01056     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind, C);
01057 
01058     // The number of sections are small, just do a linear search from the
01059     // last section to the first.
01060     bool Found = false;
01061     unsigned SecIdx = CPSections.size();
01062     while (SecIdx != 0) {
01063       if (CPSections[--SecIdx].S == S) {
01064         Found = true;
01065         break;
01066       }
01067     }
01068     if (!Found) {
01069       SecIdx = CPSections.size();
01070       CPSections.push_back(SectionCPs(S, Align));
01071     }
01072 
01073     if (Align > CPSections[SecIdx].Alignment)
01074       CPSections[SecIdx].Alignment = Align;
01075     CPSections[SecIdx].CPEs.push_back(i);
01076   }
01077 
01078   // Now print stuff into the calculated sections.
01079   const MCSection *CurSection = nullptr;
01080   unsigned Offset = 0;
01081   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
01082     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
01083       unsigned CPI = CPSections[i].CPEs[j];
01084       MCSymbol *Sym = GetCPISymbol(CPI);
01085       if (!Sym->isUndefined())
01086         continue;
01087 
01088       if (CurSection != CPSections[i].S) {
01089         OutStreamer.SwitchSection(CPSections[i].S);
01090         EmitAlignment(Log2_32(CPSections[i].Alignment));
01091         CurSection = CPSections[i].S;
01092         Offset = 0;
01093       }
01094 
01095       MachineConstantPoolEntry CPE = CP[CPI];
01096 
01097       // Emit inter-object padding for alignment.
01098       unsigned AlignMask = CPE.getAlignment() - 1;
01099       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
01100       OutStreamer.EmitZeros(NewOffset - Offset);
01101 
01102       Type *Ty = CPE.getType();
01103       Offset = NewOffset +
01104                TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(Ty);
01105 
01106       OutStreamer.EmitLabel(Sym);
01107       if (CPE.isMachineConstantPoolEntry())
01108         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
01109       else
01110         EmitGlobalConstant(CPE.Val.ConstVal);
01111     }
01112   }
01113 }
01114 
01115 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
01116 /// by the current function to the current output stream.
01117 ///
01118 void AsmPrinter::EmitJumpTableInfo() {
01119   const DataLayout *DL = MF->getSubtarget().getDataLayout();
01120   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
01121   if (!MJTI) return;
01122   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
01123   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
01124   if (JT.empty()) return;
01125 
01126   // Pick the directive to use to print the jump table entries, and switch to
01127   // the appropriate section.
01128   const Function *F = MF->getFunction();
01129   bool JTInDiffSection = false;
01130   if (// In PIC mode, we need to emit the jump table to the same section as the
01131       // function body itself, otherwise the label differences won't make sense.
01132       // FIXME: Need a better predicate for this: what about custom entries?
01133       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
01134       // We should also do if the section name is NULL or function is declared
01135       // in discardable section
01136       // FIXME: this isn't the right predicate, should be based on the MCSection
01137       // for the function.
01138       F->isWeakForLinker()) {
01139     OutStreamer.SwitchSection(
01140         getObjFileLowering().SectionForGlobal(F, *Mang, TM));
01141   } else {
01142     // Otherwise, drop it in the readonly section.
01143     const MCSection *ReadOnlySection =
01144         getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly(),
01145                                                    /*C=*/nullptr);
01146     OutStreamer.SwitchSection(ReadOnlySection);
01147     JTInDiffSection = true;
01148   }
01149 
01150   EmitAlignment(Log2_32(
01151       MJTI->getEntryAlignment(*TM.getSubtargetImpl()->getDataLayout())));
01152 
01153   // Jump tables in code sections are marked with a data_region directive
01154   // where that's supported.
01155   if (!JTInDiffSection)
01156     OutStreamer.EmitDataRegion(MCDR_DataRegionJT32);
01157 
01158   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
01159     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
01160 
01161     // If this jump table was deleted, ignore it.
01162     if (JTBBs.empty()) continue;
01163 
01164     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
01165     // .set directive for each unique entry.  This reduces the number of
01166     // relocations the assembler will generate for the jump table.
01167     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
01168         MAI->hasSetDirective()) {
01169       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
01170       const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
01171       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
01172       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
01173         const MachineBasicBlock *MBB = JTBBs[ii];
01174         if (!EmittedSets.insert(MBB)) continue;
01175 
01176         // .set LJTSet, LBB32-base
01177         const MCExpr *LHS =
01178           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
01179         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
01180                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
01181       }
01182     }
01183 
01184     // On some targets (e.g. Darwin) we want to emit two consecutive labels
01185     // before each jump table.  The first label is never referenced, but tells
01186     // the assembler and linker the extents of the jump table object.  The
01187     // second label is actually referenced by the code.
01188     if (JTInDiffSection && DL->hasLinkerPrivateGlobalPrefix())
01189       // FIXME: This doesn't have to have any specific name, just any randomly
01190       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
01191       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
01192 
01193     OutStreamer.EmitLabel(GetJTISymbol(JTI));
01194 
01195     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
01196       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
01197   }
01198   if (!JTInDiffSection)
01199     OutStreamer.EmitDataRegion(MCDR_DataRegionEnd);
01200 }
01201 
01202 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
01203 /// current stream.
01204 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
01205                                     const MachineBasicBlock *MBB,
01206                                     unsigned UID) const {
01207   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
01208   const MCExpr *Value = nullptr;
01209   switch (MJTI->getEntryKind()) {
01210   case MachineJumpTableInfo::EK_Inline:
01211     llvm_unreachable("Cannot emit EK_Inline jump table entry");
01212   case MachineJumpTableInfo::EK_Custom32:
01213     Value =
01214         TM.getSubtargetImpl()->getTargetLowering()->LowerCustomJumpTableEntry(
01215             MJTI, MBB, UID, OutContext);
01216     break;
01217   case MachineJumpTableInfo::EK_BlockAddress:
01218     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
01219     //     .word LBB123
01220     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
01221     break;
01222   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
01223     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
01224     // with a relocation as gp-relative, e.g.:
01225     //     .gprel32 LBB123
01226     MCSymbol *MBBSym = MBB->getSymbol();
01227     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
01228     return;
01229   }
01230 
01231   case MachineJumpTableInfo::EK_GPRel64BlockAddress: {
01232     // EK_GPRel64BlockAddress - Each entry is an address of block, encoded
01233     // with a relocation as gp-relative, e.g.:
01234     //     .gpdword LBB123
01235     MCSymbol *MBBSym = MBB->getSymbol();
01236     OutStreamer.EmitGPRel64Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
01237     return;
01238   }
01239 
01240   case MachineJumpTableInfo::EK_LabelDifference32: {
01241     // EK_LabelDifference32 - Each entry is the address of the block minus
01242     // the address of the jump table.  This is used for PIC jump tables where
01243     // gprel32 is not supported.  e.g.:
01244     //      .word LBB123 - LJTI1_2
01245     // If the .set directive is supported, this is emitted as:
01246     //      .set L4_5_set_123, LBB123 - LJTI1_2
01247     //      .word L4_5_set_123
01248 
01249     // If we have emitted set directives for the jump table entries, print
01250     // them rather than the entries themselves.  If we're emitting PIC, then
01251     // emit the table entries as differences between two text section labels.
01252     if (MAI->hasSetDirective()) {
01253       // If we used .set, reference the .set's symbol.
01254       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
01255                                       OutContext);
01256       break;
01257     }
01258     // Otherwise, use the difference as the jump table entry.
01259     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
01260     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
01261     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
01262     break;
01263   }
01264   }
01265 
01266   assert(Value && "Unknown entry kind!");
01267 
01268   unsigned EntrySize =
01269       MJTI->getEntrySize(*TM.getSubtargetImpl()->getDataLayout());
01270   OutStreamer.EmitValue(Value, EntrySize);
01271 }
01272 
01273 
01274 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
01275 /// special global used by LLVM.  If so, emit it and return true, otherwise
01276 /// do nothing and return false.
01277 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
01278   if (GV->getName() == "llvm.used") {
01279     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
01280       EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer()));
01281     return true;
01282   }
01283 
01284   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
01285   if (StringRef(GV->getSection()) == "llvm.metadata" ||
01286       GV->hasAvailableExternallyLinkage())
01287     return true;
01288 
01289   if (!GV->hasAppendingLinkage()) return false;
01290 
01291   assert(GV->hasInitializer() && "Not a special LLVM global!");
01292 
01293   if (GV->getName() == "llvm.global_ctors") {
01294     EmitXXStructorList(GV->getInitializer(), /* isCtor */ true);
01295 
01296     if (TM.getRelocationModel() == Reloc::Static &&
01297         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
01298       StringRef Sym(".constructors_used");
01299       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
01300                                       MCSA_Reference);
01301     }
01302     return true;
01303   }
01304 
01305   if (GV->getName() == "llvm.global_dtors") {
01306     EmitXXStructorList(GV->getInitializer(), /* isCtor */ false);
01307 
01308     if (TM.getRelocationModel() == Reloc::Static &&
01309         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
01310       StringRef Sym(".destructors_used");
01311       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
01312                                       MCSA_Reference);
01313     }
01314     return true;
01315   }
01316 
01317   return false;
01318 }
01319 
01320 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
01321 /// global in the specified llvm.used list for which emitUsedDirectiveFor
01322 /// is true, as being used with this directive.
01323 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) {
01324   // Should be an array of 'i8*'.
01325   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
01326     const GlobalValue *GV =
01327       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
01328     if (GV)
01329       OutStreamer.EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip);
01330   }
01331 }
01332 
01333 namespace {
01334 struct Structor {
01335   Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {}
01336   int Priority;
01337   llvm::Constant *Func;
01338   llvm::GlobalValue *ComdatKey;
01339 };
01340 } // end namespace
01341 
01342 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init
01343 /// priority.
01344 void AsmPrinter::EmitXXStructorList(const Constant *List, bool isCtor) {
01345   // Should be an array of '{ int, void ()* }' structs.  The first value is the
01346   // init priority.
01347   if (!isa<ConstantArray>(List)) return;
01348 
01349   // Sanity check the structors list.
01350   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
01351   if (!InitList) return; // Not an array!
01352   StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType());
01353   // FIXME: Only allow the 3-field form in LLVM 4.0.
01354   if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3)
01355     return; // Not an array of two or three elements!
01356   if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) ||
01357       !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr).
01358   if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U)))
01359     return; // Not (int, ptr, ptr).
01360 
01361   // Gather the structors in a form that's convenient for sorting by priority.
01362   SmallVector<Structor, 8> Structors;
01363   for (Value *O : InitList->operands()) {
01364     ConstantStruct *CS = dyn_cast<ConstantStruct>(O);
01365     if (!CS) continue; // Malformed.
01366     if (CS->getOperand(1)->isNullValue())
01367       break;  // Found a null terminator, skip the rest.
01368     ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0));
01369     if (!Priority) continue; // Malformed.
01370     Structors.push_back(Structor());
01371     Structor &S = Structors.back();
01372     S.Priority = Priority->getLimitedValue(65535);
01373     S.Func = CS->getOperand(1);
01374     if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue())
01375       S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts());
01376   }
01377 
01378   // Emit the function pointers in the target-specific order
01379   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
01380   unsigned Align = Log2_32(DL->getPointerPrefAlignment());
01381   std::stable_sort(Structors.begin(), Structors.end(),
01382                    [](const Structor &L,
01383                       const Structor &R) { return L.Priority < R.Priority; });
01384   for (Structor &S : Structors) {
01385     const TargetLoweringObjectFile &Obj = getObjFileLowering();
01386     const MCSymbol *KeySym = nullptr;
01387     if (GlobalValue *GV = S.ComdatKey) {
01388       if (GV->hasAvailableExternallyLinkage())
01389         // If the associated variable is available_externally, some other TU
01390         // will provide its dynamic initializer.
01391         continue;
01392 
01393       KeySym = getSymbol(GV);
01394     }
01395     const MCSection *OutputSection =
01396         (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym)
01397                 : Obj.getStaticDtorSection(S.Priority, KeySym));
01398     OutStreamer.SwitchSection(OutputSection);
01399     if (OutStreamer.getCurrentSection() != OutStreamer.getPreviousSection())
01400       EmitAlignment(Align);
01401     EmitXXStructor(S.Func);
01402   }
01403 }
01404 
01405 void AsmPrinter::EmitModuleIdents(Module &M) {
01406   if (!MAI->hasIdentDirective())
01407     return;
01408 
01409   if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) {
01410     for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
01411       const MDNode *N = NMD->getOperand(i);
01412       assert(N->getNumOperands() == 1 &&
01413              "llvm.ident metadata entry can have only one operand");
01414       const MDString *S = cast<MDString>(N->getOperand(0));
01415       OutStreamer.EmitIdent(S->getString());
01416     }
01417   }
01418 }
01419 
01420 //===--------------------------------------------------------------------===//
01421 // Emission and print routines
01422 //
01423 
01424 /// EmitInt8 - Emit a byte directive and value.
01425 ///
01426 void AsmPrinter::EmitInt8(int Value) const {
01427   OutStreamer.EmitIntValue(Value, 1);
01428 }
01429 
01430 /// EmitInt16 - Emit a short directive and value.
01431 ///
01432 void AsmPrinter::EmitInt16(int Value) const {
01433   OutStreamer.EmitIntValue(Value, 2);
01434 }
01435 
01436 /// EmitInt32 - Emit a long directive and value.
01437 ///
01438 void AsmPrinter::EmitInt32(int Value) const {
01439   OutStreamer.EmitIntValue(Value, 4);
01440 }
01441 
01442 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
01443 /// in bytes of the directive is specified by Size and Hi/Lo specify the
01444 /// labels.  This implicitly uses .set if it is available.
01445 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
01446                                      unsigned Size) const {
01447   // Get the Hi-Lo expression.
01448   const MCExpr *Diff =
01449     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
01450                             MCSymbolRefExpr::Create(Lo, OutContext),
01451                             OutContext);
01452 
01453   if (!MAI->hasSetDirective()) {
01454     OutStreamer.EmitValue(Diff, Size);
01455     return;
01456   }
01457 
01458   // Otherwise, emit with .set (aka assignment).
01459   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
01460   OutStreamer.EmitAssignment(SetLabel, Diff);
01461   OutStreamer.EmitSymbolValue(SetLabel, Size);
01462 }
01463 
01464 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
01465 /// where the size in bytes of the directive is specified by Size and Hi/Lo
01466 /// specify the labels.  This implicitly uses .set if it is available.
01467 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
01468                                            const MCSymbol *Lo,
01469                                            unsigned Size) const {
01470 
01471   // Emit Hi+Offset - Lo
01472   // Get the Hi+Offset expression.
01473   const MCExpr *Plus =
01474     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
01475                             MCConstantExpr::Create(Offset, OutContext),
01476                             OutContext);
01477 
01478   // Get the Hi+Offset-Lo expression.
01479   const MCExpr *Diff =
01480     MCBinaryExpr::CreateSub(Plus,
01481                             MCSymbolRefExpr::Create(Lo, OutContext),
01482                             OutContext);
01483 
01484   if (!MAI->hasSetDirective())
01485     OutStreamer.EmitValue(Diff, Size);
01486   else {
01487     // Otherwise, emit with .set (aka assignment).
01488     MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
01489     OutStreamer.EmitAssignment(SetLabel, Diff);
01490     OutStreamer.EmitSymbolValue(SetLabel, Size);
01491   }
01492 }
01493 
01494 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
01495 /// where the size in bytes of the directive is specified by Size and Label
01496 /// specifies the label.  This implicitly uses .set if it is available.
01497 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
01498                                      unsigned Size,
01499                                      bool IsSectionRelative) const {
01500   if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) {
01501     OutStreamer.EmitCOFFSecRel32(Label);
01502     return;
01503   }
01504 
01505   // Emit Label+Offset (or just Label if Offset is zero)
01506   const MCExpr *Expr = MCSymbolRefExpr::Create(Label, OutContext);
01507   if (Offset)
01508     Expr = MCBinaryExpr::CreateAdd(
01509         Expr, MCConstantExpr::Create(Offset, OutContext), OutContext);
01510 
01511   OutStreamer.EmitValue(Expr, Size);
01512 }
01513 
01514 //===----------------------------------------------------------------------===//
01515 
01516 // EmitAlignment - Emit an alignment directive to the specified power of
01517 // two boundary.  For example, if you pass in 3 here, you will get an 8
01518 // byte alignment.  If a global value is specified, and if that global has
01519 // an explicit alignment requested, it will override the alignment request
01520 // if required for correctness.
01521 //
01522 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const {
01523   if (GV)
01524     NumBits = getGVAlignmentLog2(GV, *TM.getSubtargetImpl()->getDataLayout(),
01525                                  NumBits);
01526 
01527   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
01528 
01529   if (getCurrentSection()->getKind().isText())
01530     OutStreamer.EmitCodeAlignment(1 << NumBits);
01531   else
01532     OutStreamer.EmitValueToAlignment(1 << NumBits);
01533 }
01534 
01535 //===----------------------------------------------------------------------===//
01536 // Constant emission.
01537 //===----------------------------------------------------------------------===//
01538 
01539 /// lowerConstant - Lower the specified LLVM Constant to an MCExpr.
01540 ///
01541 static const MCExpr *lowerConstant(const Constant *CV, AsmPrinter &AP) {
01542   MCContext &Ctx = AP.OutContext;
01543 
01544   if (CV->isNullValue() || isa<UndefValue>(CV))
01545     return MCConstantExpr::Create(0, Ctx);
01546 
01547   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
01548     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
01549 
01550   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
01551     return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
01552 
01553   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
01554     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
01555 
01556   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
01557   if (!CE) {
01558     llvm_unreachable("Unknown constant value to lower!");
01559   }
01560 
01561   if (const MCExpr *RelocExpr =
01562           AP.getObjFileLowering().getExecutableRelativeSymbol(CE, *AP.Mang,
01563                                                               AP.TM))
01564     return RelocExpr;
01565 
01566   switch (CE->getOpcode()) {
01567   default:
01568     // If the code isn't optimized, there may be outstanding folding
01569     // opportunities. Attempt to fold the expression using DataLayout as a
01570     // last resort before giving up.
01571     if (Constant *C = ConstantFoldConstantExpression(
01572             CE, AP.TM.getSubtargetImpl()->getDataLayout()))
01573       if (C != CE)
01574         return lowerConstant(C, AP);
01575 
01576     // Otherwise report the problem to the user.
01577     {
01578       std::string S;
01579       raw_string_ostream OS(S);
01580       OS << "Unsupported expression in static initializer: ";
01581       CE->printAsOperand(OS, /*PrintType=*/false,
01582                      !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
01583       report_fatal_error(OS.str());
01584     }
01585   case Instruction::GetElementPtr: {
01586     const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
01587     // Generate a symbolic expression for the byte address
01588     APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
01589     cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
01590 
01591     const MCExpr *Base = lowerConstant(CE->getOperand(0), AP);
01592     if (!OffsetAI)
01593       return Base;
01594 
01595     int64_t Offset = OffsetAI.getSExtValue();
01596     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
01597                                    Ctx);
01598   }
01599 
01600   case Instruction::Trunc:
01601     // We emit the value and depend on the assembler to truncate the generated
01602     // expression properly.  This is important for differences between
01603     // blockaddress labels.  Since the two labels are in the same function, it
01604     // is reasonable to treat their delta as a 32-bit value.
01605     // FALL THROUGH.
01606   case Instruction::BitCast:
01607     return lowerConstant(CE->getOperand(0), AP);
01608 
01609   case Instruction::IntToPtr: {
01610     const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
01611     // Handle casts to pointers by changing them into casts to the appropriate
01612     // integer type.  This promotes constant folding and simplifies this code.
01613     Constant *Op = CE->getOperand(0);
01614     Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
01615                                       false/*ZExt*/);
01616     return lowerConstant(Op, AP);
01617   }
01618 
01619   case Instruction::PtrToInt: {
01620     const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
01621     // Support only foldable casts to/from pointers that can be eliminated by
01622     // changing the pointer to the appropriately sized integer type.
01623     Constant *Op = CE->getOperand(0);
01624     Type *Ty = CE->getType();
01625 
01626     const MCExpr *OpExpr = lowerConstant(Op, AP);
01627 
01628     // We can emit the pointer value into this slot if the slot is an
01629     // integer slot equal to the size of the pointer.
01630     if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
01631       return OpExpr;
01632 
01633     // Otherwise the pointer is smaller than the resultant integer, mask off
01634     // the high bits so we are sure to get a proper truncation if the input is
01635     // a constant expr.
01636     unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
01637     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
01638     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
01639   }
01640 
01641   // The MC library also has a right-shift operator, but it isn't consistently
01642   // signed or unsigned between different targets.
01643   case Instruction::Add:
01644   case Instruction::Sub:
01645   case Instruction::Mul:
01646   case Instruction::SDiv:
01647   case Instruction::SRem:
01648   case Instruction::Shl:
01649   case Instruction::And:
01650   case Instruction::Or:
01651   case Instruction::Xor: {
01652     const MCExpr *LHS = lowerConstant(CE->getOperand(0), AP);
01653     const MCExpr *RHS = lowerConstant(CE->getOperand(1), AP);
01654     switch (CE->getOpcode()) {
01655     default: llvm_unreachable("Unknown binary operator constant cast expr");
01656     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
01657     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
01658     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
01659     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
01660     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
01661     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
01662     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
01663     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
01664     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
01665     }
01666   }
01667   }
01668 }
01669 
01670 static void emitGlobalConstantImpl(const Constant *C, AsmPrinter &AP);
01671 
01672 /// isRepeatedByteSequence - Determine whether the given value is
01673 /// composed of a repeated sequence of identical bytes and return the
01674 /// byte value.  If it is not a repeated sequence, return -1.
01675 static int isRepeatedByteSequence(const ConstantDataSequential *V) {
01676   StringRef Data = V->getRawDataValues();
01677   assert(!Data.empty() && "Empty aggregates should be CAZ node");
01678   char C = Data[0];
01679   for (unsigned i = 1, e = Data.size(); i != e; ++i)
01680     if (Data[i] != C) return -1;
01681   return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1.
01682 }
01683 
01684 
01685 /// isRepeatedByteSequence - Determine whether the given value is
01686 /// composed of a repeated sequence of identical bytes and return the
01687 /// byte value.  If it is not a repeated sequence, return -1.
01688 static int isRepeatedByteSequence(const Value *V, TargetMachine &TM) {
01689 
01690   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
01691     if (CI->getBitWidth() > 64) return -1;
01692 
01693     uint64_t Size =
01694         TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(V->getType());
01695     uint64_t Value = CI->getZExtValue();
01696 
01697     // Make sure the constant is at least 8 bits long and has a power
01698     // of 2 bit width.  This guarantees the constant bit width is
01699     // always a multiple of 8 bits, avoiding issues with padding out
01700     // to Size and other such corner cases.
01701     if (CI->getBitWidth() < 8 || !isPowerOf2_64(CI->getBitWidth())) return -1;
01702 
01703     uint8_t Byte = static_cast<uint8_t>(Value);
01704 
01705     for (unsigned i = 1; i < Size; ++i) {
01706       Value >>= 8;
01707       if (static_cast<uint8_t>(Value) != Byte) return -1;
01708     }
01709     return Byte;
01710   }
01711   if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) {
01712     // Make sure all array elements are sequences of the same repeated
01713     // byte.
01714     assert(CA->getNumOperands() != 0 && "Should be a CAZ");
01715     int Byte = isRepeatedByteSequence(CA->getOperand(0), TM);
01716     if (Byte == -1) return -1;
01717 
01718     for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) {
01719       int ThisByte = isRepeatedByteSequence(CA->getOperand(i), TM);
01720       if (ThisByte == -1) return -1;
01721       if (Byte != ThisByte) return -1;
01722     }
01723     return Byte;
01724   }
01725 
01726   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V))
01727     return isRepeatedByteSequence(CDS);
01728 
01729   return -1;
01730 }
01731 
01732 static void emitGlobalConstantDataSequential(const ConstantDataSequential *CDS,
01733                                              AsmPrinter &AP){
01734 
01735   // See if we can aggregate this into a .fill, if so, emit it as such.
01736   int Value = isRepeatedByteSequence(CDS, AP.TM);
01737   if (Value != -1) {
01738     uint64_t Bytes =
01739         AP.TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(
01740             CDS->getType());
01741     // Don't emit a 1-byte object as a .fill.
01742     if (Bytes > 1)
01743       return AP.OutStreamer.EmitFill(Bytes, Value);
01744   }
01745 
01746   // If this can be emitted with .ascii/.asciz, emit it as such.
01747   if (CDS->isString())
01748     return AP.OutStreamer.EmitBytes(CDS->getAsString());
01749 
01750   // Otherwise, emit the values in successive locations.
01751   unsigned ElementByteSize = CDS->getElementByteSize();
01752   if (isa<IntegerType>(CDS->getElementType())) {
01753     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01754       if (AP.isVerbose())
01755         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
01756                                                 CDS->getElementAsInteger(i));
01757       AP.OutStreamer.EmitIntValue(CDS->getElementAsInteger(i),
01758                                   ElementByteSize);
01759     }
01760   } else if (ElementByteSize == 4) {
01761     // FP Constants are printed as integer constants to avoid losing
01762     // precision.
01763     assert(CDS->getElementType()->isFloatTy());
01764     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01765       union {
01766         float F;
01767         uint32_t I;
01768       };
01769 
01770       F = CDS->getElementAsFloat(i);
01771       if (AP.isVerbose())
01772         AP.OutStreamer.GetCommentOS() << "float " << F << '\n';
01773       AP.OutStreamer.EmitIntValue(I, 4);
01774     }
01775   } else {
01776     assert(CDS->getElementType()->isDoubleTy());
01777     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
01778       union {
01779         double F;
01780         uint64_t I;
01781       };
01782 
01783       F = CDS->getElementAsDouble(i);
01784       if (AP.isVerbose())
01785         AP.OutStreamer.GetCommentOS() << "double " << F << '\n';
01786       AP.OutStreamer.EmitIntValue(I, 8);
01787     }
01788   }
01789 
01790   const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
01791   unsigned Size = DL.getTypeAllocSize(CDS->getType());
01792   unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) *
01793                         CDS->getNumElements();
01794   if (unsigned Padding = Size - EmittedSize)
01795     AP.OutStreamer.EmitZeros(Padding);
01796 
01797 }
01798 
01799 static void emitGlobalConstantArray(const ConstantArray *CA, AsmPrinter &AP) {
01800   // See if we can aggregate some values.  Make sure it can be
01801   // represented as a series of bytes of the constant value.
01802   int Value = isRepeatedByteSequence(CA, AP.TM);
01803 
01804   if (Value != -1) {
01805     uint64_t Bytes =
01806         AP.TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(
01807             CA->getType());
01808     AP.OutStreamer.EmitFill(Bytes, Value);
01809   }
01810   else {
01811     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
01812       emitGlobalConstantImpl(CA->getOperand(i), AP);
01813   }
01814 }
01815 
01816 static void emitGlobalConstantVector(const ConstantVector *CV, AsmPrinter &AP) {
01817   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
01818     emitGlobalConstantImpl(CV->getOperand(i), AP);
01819 
01820   const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
01821   unsigned Size = DL.getTypeAllocSize(CV->getType());
01822   unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) *
01823                          CV->getType()->getNumElements();
01824   if (unsigned Padding = Size - EmittedSize)
01825     AP.OutStreamer.EmitZeros(Padding);
01826 }
01827 
01828 static void emitGlobalConstantStruct(const ConstantStruct *CS, AsmPrinter &AP) {
01829   // Print the fields in successive locations. Pad to align if needed!
01830   const DataLayout *DL = AP.TM.getSubtargetImpl()->getDataLayout();
01831   unsigned Size = DL->getTypeAllocSize(CS->getType());
01832   const StructLayout *Layout = DL->getStructLayout(CS->getType());
01833   uint64_t SizeSoFar = 0;
01834   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
01835     const Constant *Field = CS->getOperand(i);
01836 
01837     // Check if padding is needed and insert one or more 0s.
01838     uint64_t FieldSize = DL->getTypeAllocSize(Field->getType());
01839     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
01840                         - Layout->getElementOffset(i)) - FieldSize;
01841     SizeSoFar += FieldSize + PadSize;
01842 
01843     // Now print the actual field value.
01844     emitGlobalConstantImpl(Field, AP);
01845 
01846     // Insert padding - this may include padding to increase the size of the
01847     // current field up to the ABI size (if the struct is not packed) as well
01848     // as padding to ensure that the next field starts at the right offset.
01849     AP.OutStreamer.EmitZeros(PadSize);
01850   }
01851   assert(SizeSoFar == Layout->getSizeInBytes() &&
01852          "Layout of constant struct may be incorrect!");
01853 }
01854 
01855 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) {
01856   APInt API = CFP->getValueAPF().bitcastToAPInt();
01857 
01858   // First print a comment with what we think the original floating-point value
01859   // should have been.
01860   if (AP.isVerbose()) {
01861     SmallString<8> StrVal;
01862     CFP->getValueAPF().toString(StrVal);
01863 
01864     if (CFP->getType())
01865       CFP->getType()->print(AP.OutStreamer.GetCommentOS());
01866     else
01867       AP.OutStreamer.GetCommentOS() << "Printing <null> Type";
01868     AP.OutStreamer.GetCommentOS() << ' ' << StrVal << '\n';
01869   }
01870 
01871   // Now iterate through the APInt chunks, emitting them in endian-correct
01872   // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit
01873   // floats).
01874   unsigned NumBytes = API.getBitWidth() / 8;
01875   unsigned TrailingBytes = NumBytes % sizeof(uint64_t);
01876   const uint64_t *p = API.getRawData();
01877 
01878   // PPC's long double has odd notions of endianness compared to how LLVM
01879   // handles it: p[0] goes first for *big* endian on PPC.
01880   if (AP.TM.getSubtargetImpl()->getDataLayout()->isBigEndian() &&
01881       !CFP->getType()->isPPC_FP128Ty()) {
01882     int Chunk = API.getNumWords() - 1;
01883 
01884     if (TrailingBytes)
01885       AP.OutStreamer.EmitIntValue(p[Chunk--], TrailingBytes);
01886 
01887     for (; Chunk >= 0; --Chunk)
01888       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
01889   } else {
01890     unsigned Chunk;
01891     for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk)
01892       AP.OutStreamer.EmitIntValue(p[Chunk], sizeof(uint64_t));
01893 
01894     if (TrailingBytes)
01895       AP.OutStreamer.EmitIntValue(p[Chunk], TrailingBytes);
01896   }
01897 
01898   // Emit the tail padding for the long double.
01899   const DataLayout &DL = *AP.TM.getSubtargetImpl()->getDataLayout();
01900   AP.OutStreamer.EmitZeros(DL.getTypeAllocSize(CFP->getType()) -
01901                            DL.getTypeStoreSize(CFP->getType()));
01902 }
01903 
01904 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) {
01905   const DataLayout *DL = AP.TM.getSubtargetImpl()->getDataLayout();
01906   unsigned BitWidth = CI->getBitWidth();
01907 
01908   // Copy the value as we may massage the layout for constants whose bit width
01909   // is not a multiple of 64-bits.
01910   APInt Realigned(CI->getValue());
01911   uint64_t ExtraBits = 0;
01912   unsigned ExtraBitsSize = BitWidth & 63;
01913 
01914   if (ExtraBitsSize) {
01915     // The bit width of the data is not a multiple of 64-bits.
01916     // The extra bits are expected to be at the end of the chunk of the memory.
01917     // Little endian:
01918     // * Nothing to be done, just record the extra bits to emit.
01919     // Big endian:
01920     // * Record the extra bits to emit.
01921     // * Realign the raw data to emit the chunks of 64-bits.
01922     if (DL->isBigEndian()) {
01923       // Basically the structure of the raw data is a chunk of 64-bits cells:
01924       //    0        1         BitWidth / 64
01925       // [chunk1][chunk2] ... [chunkN].
01926       // The most significant chunk is chunkN and it should be emitted first.
01927       // However, due to the alignment issue chunkN contains useless bits.
01928       // Realign the chunks so that they contain only useless information:
01929       // ExtraBits     0       1       (BitWidth / 64) - 1
01930       //       chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN]
01931       ExtraBits = Realigned.getRawData()[0] &
01932         (((uint64_t)-1) >> (64 - ExtraBitsSize));
01933       Realigned = Realigned.lshr(ExtraBitsSize);
01934     } else
01935       ExtraBits = Realigned.getRawData()[BitWidth / 64];
01936   }
01937 
01938   // We don't expect assemblers to support integer data directives
01939   // for more than 64 bits, so we emit the data in at most 64-bit
01940   // quantities at a time.
01941   const uint64_t *RawData = Realigned.getRawData();
01942   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
01943     uint64_t Val = DL->isBigEndian() ? RawData[e - i - 1] : RawData[i];
01944     AP.OutStreamer.EmitIntValue(Val, 8);
01945   }
01946 
01947   if (ExtraBitsSize) {
01948     // Emit the extra bits after the 64-bits chunks.
01949 
01950     // Emit a directive that fills the expected size.
01951     uint64_t Size = AP.TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(
01952         CI->getType());
01953     Size -= (BitWidth / 64) * 8;
01954     assert(Size && Size * 8 >= ExtraBitsSize &&
01955            (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize)))
01956            == ExtraBits && "Directive too small for extra bits.");
01957     AP.OutStreamer.EmitIntValue(ExtraBits, Size);
01958   }
01959 }
01960 
01961 static void emitGlobalConstantImpl(const Constant *CV, AsmPrinter &AP) {
01962   const DataLayout *DL = AP.TM.getSubtargetImpl()->getDataLayout();
01963   uint64_t Size = DL->getTypeAllocSize(CV->getType());
01964   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV))
01965     return AP.OutStreamer.EmitZeros(Size);
01966 
01967   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
01968     switch (Size) {
01969     case 1:
01970     case 2:
01971     case 4:
01972     case 8:
01973       if (AP.isVerbose())
01974         AP.OutStreamer.GetCommentOS() << format("0x%" PRIx64 "\n",
01975                                                 CI->getZExtValue());
01976       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size);
01977       return;
01978     default:
01979       emitGlobalConstantLargeInt(CI, AP);
01980       return;
01981     }
01982   }
01983 
01984   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
01985     return emitGlobalConstantFP(CFP, AP);
01986 
01987   if (isa<ConstantPointerNull>(CV)) {
01988     AP.OutStreamer.EmitIntValue(0, Size);
01989     return;
01990   }
01991 
01992   if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV))
01993     return emitGlobalConstantDataSequential(CDS, AP);
01994 
01995   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
01996     return emitGlobalConstantArray(CVA, AP);
01997 
01998   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
01999     return emitGlobalConstantStruct(CVS, AP);
02000 
02001   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
02002     // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of
02003     // vectors).
02004     if (CE->getOpcode() == Instruction::BitCast)
02005       return emitGlobalConstantImpl(CE->getOperand(0), AP);
02006 
02007     if (Size > 8) {
02008       // If the constant expression's size is greater than 64-bits, then we have
02009       // to emit the value in chunks. Try to constant fold the value and emit it
02010       // that way.
02011       Constant *New = ConstantFoldConstantExpression(CE, DL);
02012       if (New && New != CE)
02013         return emitGlobalConstantImpl(New, AP);
02014     }
02015   }
02016 
02017   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
02018     return emitGlobalConstantVector(V, AP);
02019 
02020   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
02021   // thread the streamer with EmitValue.
02022   AP.OutStreamer.EmitValue(lowerConstant(CV, AP), Size);
02023 }
02024 
02025 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
02026 void AsmPrinter::EmitGlobalConstant(const Constant *CV) {
02027   uint64_t Size =
02028       TM.getSubtargetImpl()->getDataLayout()->getTypeAllocSize(CV->getType());
02029   if (Size)
02030     emitGlobalConstantImpl(CV, *this);
02031   else if (MAI->hasSubsectionsViaSymbols()) {
02032     // If the global has zero size, emit a single byte so that two labels don't
02033     // look like they are at the same location.
02034     OutStreamer.EmitIntValue(0, 1);
02035   }
02036 }
02037 
02038 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
02039   // Target doesn't support this yet!
02040   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
02041 }
02042 
02043 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
02044   if (Offset > 0)
02045     OS << '+' << Offset;
02046   else if (Offset < 0)
02047     OS << Offset;
02048 }
02049 
02050 //===----------------------------------------------------------------------===//
02051 // Symbol Lowering Routines.
02052 //===----------------------------------------------------------------------===//
02053 
02054 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
02055 /// temporary label with the specified stem and unique ID.
02056 MCSymbol *AsmPrinter::GetTempSymbol(Twine Name, unsigned ID) const {
02057   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
02058   return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix()) +
02059                                       Name + Twine(ID));
02060 }
02061 
02062 /// GetTempSymbol - Return an assembler temporary label with the specified
02063 /// stem.
02064 MCSymbol *AsmPrinter::GetTempSymbol(Twine Name) const {
02065   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
02066   return OutContext.GetOrCreateSymbol(Twine(DL->getPrivateGlobalPrefix())+
02067                                       Name);
02068 }
02069 
02070 
02071 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
02072   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
02073 }
02074 
02075 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
02076   return MMI->getAddrLabelSymbol(BB);
02077 }
02078 
02079 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
02080 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
02081   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
02082   return OutContext.GetOrCreateSymbol
02083     (Twine(DL->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
02084      + "_" + Twine(CPID));
02085 }
02086 
02087 /// GetJTISymbol - Return the symbol for the specified jump table entry.
02088 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
02089   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
02090 }
02091 
02092 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
02093 /// FIXME: privatize to AsmPrinter.
02094 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
02095   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
02096   return OutContext.GetOrCreateSymbol
02097   (Twine(DL->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
02098    Twine(UID) + "_set_" + Twine(MBBID));
02099 }
02100 
02101 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV,
02102                                                    StringRef Suffix) const {
02103   return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang,
02104                                                            TM);
02105 }
02106 
02107 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
02108 /// ExternalSymbol.
02109 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
02110   SmallString<60> NameStr;
02111   Mang->getNameWithPrefix(NameStr, Sym);
02112   return OutContext.GetOrCreateSymbol(NameStr.str());
02113 }
02114 
02115 
02116 
02117 /// PrintParentLoopComment - Print comments about parent loops of this one.
02118 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
02119                                    unsigned FunctionNumber) {
02120   if (!Loop) return;
02121   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
02122   OS.indent(Loop->getLoopDepth()*2)
02123     << "Parent Loop BB" << FunctionNumber << "_"
02124     << Loop->getHeader()->getNumber()
02125     << " Depth=" << Loop->getLoopDepth() << '\n';
02126 }
02127 
02128 
02129 /// PrintChildLoopComment - Print comments about child loops within
02130 /// the loop for this basic block, with nesting.
02131 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
02132                                   unsigned FunctionNumber) {
02133   // Add child loop information
02134   for (const MachineLoop *CL : *Loop) {
02135     OS.indent(CL->getLoopDepth()*2)
02136       << "Child Loop BB" << FunctionNumber << "_"
02137       << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth()
02138       << '\n';
02139     PrintChildLoopComment(OS, CL, FunctionNumber);
02140   }
02141 }
02142 
02143 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks.
02144 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB,
02145                                        const MachineLoopInfo *LI,
02146                                        const AsmPrinter &AP) {
02147   // Add loop depth information
02148   const MachineLoop *Loop = LI->getLoopFor(&MBB);
02149   if (!Loop) return;
02150 
02151   MachineBasicBlock *Header = Loop->getHeader();
02152   assert(Header && "No header for loop");
02153 
02154   // If this block is not a loop header, just print out what is the loop header
02155   // and return.
02156   if (Header != &MBB) {
02157     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
02158                               Twine(AP.getFunctionNumber())+"_" +
02159                               Twine(Loop->getHeader()->getNumber())+
02160                               " Depth="+Twine(Loop->getLoopDepth()));
02161     return;
02162   }
02163 
02164   // Otherwise, it is a loop header.  Print out information about child and
02165   // parent loops.
02166   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
02167 
02168   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
02169 
02170   OS << "=>";
02171   OS.indent(Loop->getLoopDepth()*2-2);
02172 
02173   OS << "This ";
02174   if (Loop->empty())
02175     OS << "Inner ";
02176   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
02177 
02178   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
02179 }
02180 
02181 
02182 /// EmitBasicBlockStart - This method prints the label for the specified
02183 /// MachineBasicBlock, an alignment (if present) and a comment describing
02184 /// it if appropriate.
02185 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
02186   // Emit an alignment directive for this block, if needed.
02187   if (unsigned Align = MBB.getAlignment())
02188     EmitAlignment(Align);
02189 
02190   // If the block has its address taken, emit any labels that were used to
02191   // reference the block.  It is possible that there is more than one label
02192   // here, because multiple LLVM BB's may have been RAUW'd to this block after
02193   // the references were generated.
02194   if (MBB.hasAddressTaken()) {
02195     const BasicBlock *BB = MBB.getBasicBlock();
02196     if (isVerbose())
02197       OutStreamer.AddComment("Block address taken");
02198 
02199     std::vector<MCSymbol*> Symbols = MMI->getAddrLabelSymbolToEmit(BB);
02200     for (auto *Sym : Symbols)
02201       OutStreamer.EmitLabel(Sym);
02202   }
02203 
02204   // Print some verbose block comments.
02205   if (isVerbose()) {
02206     if (const BasicBlock *BB = MBB.getBasicBlock())
02207       if (BB->hasName())
02208         OutStreamer.AddComment("%" + BB->getName());
02209     emitBasicBlockLoopComments(MBB, LI, *this);
02210   }
02211 
02212   // Print the main label for the block.
02213   if (MBB.pred_empty() || isBlockOnlyReachableByFallthrough(&MBB)) {
02214     if (isVerbose()) {
02215       // NOTE: Want this comment at start of line, don't emit with AddComment.
02216       OutStreamer.emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false);
02217     }
02218   } else {
02219     OutStreamer.EmitLabel(MBB.getSymbol());
02220   }
02221 }
02222 
02223 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
02224                                 bool IsDefinition) const {
02225   MCSymbolAttr Attr = MCSA_Invalid;
02226 
02227   switch (Visibility) {
02228   default: break;
02229   case GlobalValue::HiddenVisibility:
02230     if (IsDefinition)
02231       Attr = MAI->getHiddenVisibilityAttr();
02232     else
02233       Attr = MAI->getHiddenDeclarationVisibilityAttr();
02234     break;
02235   case GlobalValue::ProtectedVisibility:
02236     Attr = MAI->getProtectedVisibilityAttr();
02237     break;
02238   }
02239 
02240   if (Attr != MCSA_Invalid)
02241     OutStreamer.EmitSymbolAttribute(Sym, Attr);
02242 }
02243 
02244 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
02245 /// exactly one predecessor and the control transfer mechanism between
02246 /// the predecessor and this block is a fall-through.
02247 bool AsmPrinter::
02248 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
02249   // If this is a landing pad, it isn't a fall through.  If it has no preds,
02250   // then nothing falls through to it.
02251   if (MBB->isLandingPad() || MBB->pred_empty())
02252     return false;
02253 
02254   // If there isn't exactly one predecessor, it can't be a fall through.
02255   if (MBB->pred_size() > 1)
02256     return false;
02257 
02258   // The predecessor has to be immediately before this block.
02259   MachineBasicBlock *Pred = *MBB->pred_begin();
02260   if (!Pred->isLayoutSuccessor(MBB))
02261     return false;
02262 
02263   // If the block is completely empty, then it definitely does fall through.
02264   if (Pred->empty())
02265     return true;
02266 
02267   // Check the terminators in the previous blocks
02268   for (const auto &MI : Pred->terminators()) {
02269     // If it is not a simple branch, we are in a table somewhere.
02270     if (!MI.isBranch() || MI.isIndirectBranch())
02271       return false;
02272 
02273     // If we are the operands of one of the branches, this is not a fall
02274     // through. Note that targets with delay slots will usually bundle
02275     // terminators with the delay slot instruction.
02276     for (ConstMIBundleOperands OP(&MI); OP.isValid(); ++OP) {
02277       if (OP->isJTI())
02278         return false;
02279       if (OP->isMBB() && OP->getMBB() == MBB)
02280         return false;
02281     }
02282   }
02283 
02284   return true;
02285 }
02286 
02287 
02288 
02289 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) {
02290   if (!S.usesMetadata())
02291     return nullptr;
02292 
02293   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
02294   gcp_map_type::iterator GCPI = GCMap.find(&S);
02295   if (GCPI != GCMap.end())
02296     return GCPI->second.get();
02297 
02298   const char *Name = S.getName().c_str();
02299 
02300   for (GCMetadataPrinterRegistry::iterator
02301          I = GCMetadataPrinterRegistry::begin(),
02302          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
02303     if (strcmp(Name, I->getName()) == 0) {
02304       std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate();
02305       GMP->S = &S;
02306       auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP)));
02307       return IterBool.first->second.get();
02308     }
02309 
02310   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
02311 }
02312 
02313 /// Pin vtable to this file.
02314 AsmPrinterHandler::~AsmPrinterHandler() {}