Home | History | Annotate | Download | only in AsmPrinter
      1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements the AsmPrinter class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #define DEBUG_TYPE "asm-printer"
     15 #include "llvm/CodeGen/AsmPrinter.h"
     16 #ifndef ANDROID_TARGET_BUILD
     17 #   include "DwarfDebug.h"
     18 #   include "DwarfException.h"
     19 #endif // ANDROID_TARGET_BUILD
     20 #include "llvm/Module.h"
     21 #include "llvm/CodeGen/GCMetadataPrinter.h"
     22 #include "llvm/CodeGen/MachineConstantPool.h"
     23 #include "llvm/CodeGen/MachineFrameInfo.h"
     24 #include "llvm/CodeGen/MachineFunction.h"
     25 #include "llvm/CodeGen/MachineJumpTableInfo.h"
     26 #include "llvm/CodeGen/MachineLoopInfo.h"
     27 #include "llvm/CodeGen/MachineModuleInfo.h"
     28 #include "llvm/Analysis/ConstantFolding.h"
     29 #include "llvm/Analysis/DebugInfo.h"
     30 #include "llvm/MC/MCAsmInfo.h"
     31 #include "llvm/MC/MCContext.h"
     32 #include "llvm/MC/MCExpr.h"
     33 #include "llvm/MC/MCInst.h"
     34 #include "llvm/MC/MCSection.h"
     35 #include "llvm/MC/MCStreamer.h"
     36 #include "llvm/MC/MCSymbol.h"
     37 #include "llvm/Target/Mangler.h"
     38 #include "llvm/Target/TargetAsmInfo.h"
     39 #include "llvm/Target/TargetData.h"
     40 #include "llvm/Target/TargetInstrInfo.h"
     41 #include "llvm/Target/TargetLowering.h"
     42 #include "llvm/Target/TargetLoweringObjectFile.h"
     43 #include "llvm/Target/TargetOptions.h"
     44 #include "llvm/Target/TargetRegisterInfo.h"
     45 #include "llvm/Assembly/Writer.h"
     46 #include "llvm/ADT/SmallString.h"
     47 #include "llvm/ADT/Statistic.h"
     48 #include "llvm/Support/ErrorHandling.h"
     49 #include "llvm/Support/Format.h"
     50 #include "llvm/Support/Timer.h"
     51 #include <ctype.h>
     52 using namespace llvm;
     53 
     54 static const char *DWARFGroupName = "DWARF Emission";
     55 static const char *DbgTimerName = "DWARF Debug Writer";
     56 static const char *EHTimerName = "DWARF Exception Writer";
     57 
     58 STATISTIC(EmittedInsts, "Number of machine instrs printed");
     59 
     60 char AsmPrinter::ID = 0;
     61 
     62 typedef DenseMap<GCStrategy*,GCMetadataPrinter*> gcp_map_type;
     63 static gcp_map_type &getGCMap(void *&P) {
     64   if (P == 0)
     65     P = new gcp_map_type();
     66   return *(gcp_map_type*)P;
     67 }
     68 
     69 
     70 /// getGVAlignmentLog2 - Return the alignment to use for the specified global
     71 /// value in log2 form.  This rounds up to the preferred alignment if possible
     72 /// and legal.
     73 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const TargetData &TD,
     74                                    unsigned InBits = 0) {
     75   unsigned NumBits = 0;
     76   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
     77     NumBits = TD.getPreferredAlignmentLog(GVar);
     78 
     79   // If InBits is specified, round it to it.
     80   if (InBits > NumBits)
     81     NumBits = InBits;
     82 
     83   // If the GV has a specified alignment, take it into account.
     84   if (GV->getAlignment() == 0)
     85     return NumBits;
     86 
     87   unsigned GVAlign = Log2_32(GV->getAlignment());
     88 
     89   // If the GVAlign is larger than NumBits, or if we are required to obey
     90   // NumBits because the GV has an assigned section, obey it.
     91   if (GVAlign > NumBits || GV->hasSection())
     92     NumBits = GVAlign;
     93   return NumBits;
     94 }
     95 
     96 
     97 
     98 
     99 AsmPrinter::AsmPrinter(TargetMachine &tm, MCStreamer &Streamer)
    100   : MachineFunctionPass(ID),
    101     TM(tm), MAI(tm.getMCAsmInfo()),
    102     OutContext(Streamer.getContext()),
    103     OutStreamer(Streamer),
    104     LastMI(0), LastFn(0), Counter(~0U), SetCounter(0) {
    105   DD = 0; DE = 0; MMI = 0; LI = 0;
    106   GCMetadataPrinters = 0;
    107   VerboseAsm = Streamer.isVerboseAsm();
    108 }
    109 
    110 AsmPrinter::~AsmPrinter() {
    111   assert(DD == 0 && DE == 0 && "Debug/EH info didn't get finalized");
    112 
    113   if (GCMetadataPrinters != 0) {
    114     gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
    115 
    116     for (gcp_map_type::iterator I = GCMap.begin(), E = GCMap.end(); I != E; ++I)
    117       delete I->second;
    118     delete &GCMap;
    119     GCMetadataPrinters = 0;
    120   }
    121 
    122   delete &OutStreamer;
    123 }
    124 
    125 /// getFunctionNumber - Return a unique ID for the current function.
    126 ///
    127 unsigned AsmPrinter::getFunctionNumber() const {
    128   return MF->getFunctionNumber();
    129 }
    130 
    131 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const {
    132   return TM.getTargetLowering()->getObjFileLowering();
    133 }
    134 
    135 
    136 /// getTargetData - Return information about data layout.
    137 const TargetData &AsmPrinter::getTargetData() const {
    138   return *TM.getTargetData();
    139 }
    140 
    141 /// getCurrentSection() - Return the current section we are emitting to.
    142 const MCSection *AsmPrinter::getCurrentSection() const {
    143   return OutStreamer.getCurrentSection();
    144 }
    145 
    146 
    147 
    148 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
    149   AU.setPreservesAll();
    150   MachineFunctionPass::getAnalysisUsage(AU);
    151   AU.addRequired<MachineModuleInfo>();
    152   AU.addRequired<GCModuleInfo>();
    153   if (isVerbose())
    154     AU.addRequired<MachineLoopInfo>();
    155 }
    156 
    157 bool AsmPrinter::doInitialization(Module &M) {
    158   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
    159   MMI->AnalyzeModule(M);
    160 
    161   // Initialize TargetLoweringObjectFile.
    162   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
    163     .Initialize(OutContext, TM);
    164 
    165   Mang = new Mangler(OutContext, *TM.getTargetData());
    166 
    167   // Allow the target to emit any magic that it wants at the start of the file.
    168   EmitStartOfAsmFile(M);
    169 
    170   // Very minimal debug info. It is ignored if we emit actual debug info. If we
    171   // don't, this at least helps the user find where a global came from.
    172   if (MAI->hasSingleParameterDotFile()) {
    173     // .file "foo.c"
    174     OutStreamer.EmitFileDirective(M.getModuleIdentifier());
    175   }
    176 
    177   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
    178   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
    179   for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I)
    180     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I))
    181       MP->beginAssembly(*this);
    182 
    183   // Emit module-level inline asm if it exists.
    184   if (!M.getModuleInlineAsm().empty()) {
    185     OutStreamer.AddComment("Start of file scope inline assembly");
    186     OutStreamer.AddBlankLine();
    187     EmitInlineAsm(M.getModuleInlineAsm()+"\n");
    188     OutStreamer.AddComment("End of file scope inline assembly");
    189     OutStreamer.AddBlankLine();
    190   }
    191 
    192 #ifndef ANDROID_TARGET_BUILD
    193   if (MAI->doesSupportDebugInformation())
    194     DD = new DwarfDebug(this, &M);
    195 
    196   switch (MAI->getExceptionHandlingType()) {
    197   case ExceptionHandling::None:
    198     return false;
    199   case ExceptionHandling::SjLj:
    200   case ExceptionHandling::DwarfCFI:
    201     DE = new DwarfCFIException(this);
    202     return false;
    203   case ExceptionHandling::ARM:
    204     DE = new ARMException(this);
    205     return false;
    206   case ExceptionHandling::Win64:
    207     DE = new Win64Exception(this);
    208     return false;
    209   }
    210 #else
    211   return false;
    212 #endif // ANDROID_TARGET_BUILD
    213 
    214   llvm_unreachable("Unknown exception type.");
    215 }
    216 
    217 void AsmPrinter::EmitLinkage(unsigned Linkage, MCSymbol *GVSym) const {
    218   switch ((GlobalValue::LinkageTypes)Linkage) {
    219   case GlobalValue::CommonLinkage:
    220   case GlobalValue::LinkOnceAnyLinkage:
    221   case GlobalValue::LinkOnceODRLinkage:
    222   case GlobalValue::WeakAnyLinkage:
    223   case GlobalValue::WeakODRLinkage:
    224   case GlobalValue::LinkerPrivateWeakLinkage:
    225   case GlobalValue::LinkerPrivateWeakDefAutoLinkage:
    226     if (MAI->getWeakDefDirective() != 0) {
    227       // .globl _foo
    228       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
    229 
    230       if ((GlobalValue::LinkageTypes)Linkage !=
    231           GlobalValue::LinkerPrivateWeakDefAutoLinkage)
    232         // .weak_definition _foo
    233         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefinition);
    234       else
    235         OutStreamer.EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate);
    236     } else if (MAI->getLinkOnceDirective() != 0) {
    237       // .globl _foo
    238       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
    239       //NOTE: linkonce is handled by the section the symbol was assigned to.
    240     } else {
    241       // .weak _foo
    242       OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Weak);
    243     }
    244     break;
    245   case GlobalValue::DLLExportLinkage:
    246   case GlobalValue::AppendingLinkage:
    247     // FIXME: appending linkage variables should go into a section of
    248     // their name or something.  For now, just emit them as external.
    249   case GlobalValue::ExternalLinkage:
    250     // If external or appending, declare as a global symbol.
    251     // .globl _foo
    252     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
    253     break;
    254   case GlobalValue::PrivateLinkage:
    255   case GlobalValue::InternalLinkage:
    256   case GlobalValue::LinkerPrivateLinkage:
    257     break;
    258   default:
    259     llvm_unreachable("Unknown linkage type!");
    260   }
    261 }
    262 
    263 
    264 /// EmitGlobalVariable - Emit the specified global variable to the .s file.
    265 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
    266   if (GV->hasInitializer()) {
    267     // Check to see if this is a special global used by LLVM, if so, emit it.
    268     if (EmitSpecialLLVMGlobal(GV))
    269       return;
    270 
    271     if (isVerbose()) {
    272       WriteAsOperand(OutStreamer.GetCommentOS(), GV,
    273                      /*PrintType=*/false, GV->getParent());
    274       OutStreamer.GetCommentOS() << '\n';
    275     }
    276   }
    277 
    278   MCSymbol *GVSym = Mang->getSymbol(GV);
    279   EmitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
    280 
    281   if (!GV->hasInitializer())   // External globals require no extra code.
    282     return;
    283 
    284   if (MAI->hasDotTypeDotSizeDirective())
    285     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_ELF_TypeObject);
    286 
    287   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
    288 
    289   const TargetData *TD = TM.getTargetData();
    290   uint64_t Size = TD->getTypeAllocSize(GV->getType()->getElementType());
    291 
    292   // If the alignment is specified, we *must* obey it.  Overaligning a global
    293   // with a specified alignment is a prompt way to break globals emitted to
    294   // sections and expected to be contiguous (e.g. ObjC metadata).
    295   unsigned AlignLog = getGVAlignmentLog2(GV, *TD);
    296 
    297   // Handle common and BSS local symbols (.lcomm).
    298   if (GVKind.isCommon() || GVKind.isBSSLocal()) {
    299     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
    300 
    301     // Handle common symbols.
    302     if (GVKind.isCommon()) {
    303       unsigned Align = 1 << AlignLog;
    304       if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
    305         Align = 0;
    306 
    307       // .comm _foo, 42, 4
    308       OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
    309       return;
    310     }
    311 
    312     // Handle local BSS symbols.
    313     if (MAI->hasMachoZeroFillDirective()) {
    314       const MCSection *TheSection =
    315         getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
    316       // .zerofill __DATA, __bss, _foo, 400, 5
    317       OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
    318       return;
    319     }
    320 
    321     if (MAI->hasLCOMMDirective()) {
    322       // .lcomm _foo, 42
    323       OutStreamer.EmitLocalCommonSymbol(GVSym, Size);
    324       return;
    325     }
    326 
    327     unsigned Align = 1 << AlignLog;
    328     if (!getObjFileLowering().getCommDirectiveSupportsAlignment())
    329       Align = 0;
    330 
    331     // .local _foo
    332     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Local);
    333     // .comm _foo, 42, 4
    334     OutStreamer.EmitCommonSymbol(GVSym, Size, Align);
    335     return;
    336   }
    337 
    338   const MCSection *TheSection =
    339     getObjFileLowering().SectionForGlobal(GV, GVKind, Mang, TM);
    340 
    341   // Handle the zerofill directive on darwin, which is a special form of BSS
    342   // emission.
    343   if (GVKind.isBSSExtern() && MAI->hasMachoZeroFillDirective()) {
    344     if (Size == 0) Size = 1;  // zerofill of 0 bytes is undefined.
    345 
    346     // .globl _foo
    347     OutStreamer.EmitSymbolAttribute(GVSym, MCSA_Global);
    348     // .zerofill __DATA, __common, _foo, 400, 5
    349     OutStreamer.EmitZerofill(TheSection, GVSym, Size, 1 << AlignLog);
    350     return;
    351   }
    352 
    353   // Handle thread local data for mach-o which requires us to output an
    354   // additional structure of data and mangle the original symbol so that we
    355   // can reference it later.
    356   //
    357   // TODO: This should become an "emit thread local global" method on TLOF.
    358   // All of this macho specific stuff should be sunk down into TLOFMachO and
    359   // stuff like "TLSExtraDataSection" should no longer be part of the parent
    360   // TLOF class.  This will also make it more obvious that stuff like
    361   // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho
    362   // specific code.
    363   if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) {
    364     // Emit the .tbss symbol
    365     MCSymbol *MangSym =
    366       OutContext.GetOrCreateSymbol(GVSym->getName() + Twine("$tlv$init"));
    367 
    368     if (GVKind.isThreadBSS())
    369       OutStreamer.EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog);
    370     else if (GVKind.isThreadData()) {
    371       OutStreamer.SwitchSection(TheSection);
    372 
    373       EmitAlignment(AlignLog, GV);
    374       OutStreamer.EmitLabel(MangSym);
    375 
    376       EmitGlobalConstant(GV->getInitializer());
    377     }
    378 
    379     OutStreamer.AddBlankLine();
    380 
    381     // Emit the variable struct for the runtime.
    382     const MCSection *TLVSect
    383       = getObjFileLowering().getTLSExtraDataSection();
    384 
    385     OutStreamer.SwitchSection(TLVSect);
    386     // Emit the linkage here.
    387     EmitLinkage(GV->getLinkage(), GVSym);
    388     OutStreamer.EmitLabel(GVSym);
    389 
    390     // Three pointers in size:
    391     //   - __tlv_bootstrap - used to make sure support exists
    392     //   - spare pointer, used when mapped by the runtime
    393     //   - pointer to mangled symbol above with initializer
    394     unsigned PtrSize = TD->getPointerSizeInBits()/8;
    395     OutStreamer.EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"),
    396                           PtrSize, 0);
    397     OutStreamer.EmitIntValue(0, PtrSize, 0);
    398     OutStreamer.EmitSymbolValue(MangSym, PtrSize, 0);
    399 
    400     OutStreamer.AddBlankLine();
    401     return;
    402   }
    403 
    404   OutStreamer.SwitchSection(TheSection);
    405 
    406   EmitLinkage(GV->getLinkage(), GVSym);
    407   EmitAlignment(AlignLog, GV);
    408 
    409   OutStreamer.EmitLabel(GVSym);
    410 
    411   EmitGlobalConstant(GV->getInitializer());
    412 
    413   if (MAI->hasDotTypeDotSizeDirective())
    414     // .size foo, 42
    415     OutStreamer.EmitELFSize(GVSym, MCConstantExpr::Create(Size, OutContext));
    416 
    417   OutStreamer.AddBlankLine();
    418 }
    419 
    420 /// EmitFunctionHeader - This method emits the header for the current
    421 /// function.
    422 void AsmPrinter::EmitFunctionHeader() {
    423   // Print out constants referenced by the function
    424   EmitConstantPool();
    425 
    426   // Print the 'header' of function.
    427   const Function *F = MF->getFunction();
    428 
    429   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
    430   EmitVisibility(CurrentFnSym, F->getVisibility());
    431 
    432   EmitLinkage(F->getLinkage(), CurrentFnSym);
    433   EmitAlignment(MF->getAlignment(), F);
    434 
    435   if (MAI->hasDotTypeDotSizeDirective())
    436     OutStreamer.EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction);
    437 
    438   if (isVerbose()) {
    439     WriteAsOperand(OutStreamer.GetCommentOS(), F,
    440                    /*PrintType=*/false, F->getParent());
    441     OutStreamer.GetCommentOS() << '\n';
    442   }
    443 
    444   // Emit the CurrentFnSym.  This is a virtual function to allow targets to
    445   // do their wild and crazy things as required.
    446   EmitFunctionEntryLabel();
    447 
    448   // If the function had address-taken blocks that got deleted, then we have
    449   // references to the dangling symbols.  Emit them at the start of the function
    450   // so that we don't get references to undefined symbols.
    451   std::vector<MCSymbol*> DeadBlockSyms;
    452   MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms);
    453   for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) {
    454     OutStreamer.AddComment("Address taken block that was later removed");
    455     OutStreamer.EmitLabel(DeadBlockSyms[i]);
    456   }
    457 
    458   // Add some workaround for linkonce linkage on Cygwin\MinGW.
    459   if (MAI->getLinkOnceDirective() != 0 &&
    460       (F->hasLinkOnceLinkage() || F->hasWeakLinkage())) {
    461     // FIXME: What is this?
    462     MCSymbol *FakeStub =
    463       OutContext.GetOrCreateSymbol(Twine("Lllvm$workaround$fake$stub$")+
    464                                    CurrentFnSym->getName());
    465     OutStreamer.EmitLabel(FakeStub);
    466   }
    467 
    468   // Emit pre-function debug and/or EH information.
    469 #ifndef ANDROID_TARGET_BUILD
    470   if (DE) {
    471     NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
    472     DE->BeginFunction(MF);
    473   }
    474   if (DD) {
    475     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
    476     DD->beginFunction(MF);
    477   }
    478 #endif // ANDROID_TARGET_BUILD
    479 }
    480 
    481 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the
    482 /// function.  This can be overridden by targets as required to do custom stuff.
    483 void AsmPrinter::EmitFunctionEntryLabel() {
    484   // The function label could have already been emitted if two symbols end up
    485   // conflicting due to asm renaming.  Detect this and emit an error.
    486   if (CurrentFnSym->isUndefined())
    487     return OutStreamer.EmitLabel(CurrentFnSym);
    488 
    489   report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
    490                      "' label emitted multiple times to assembly file");
    491 }
    492 
    493 
    494 /// EmitComments - Pretty-print comments for instructions.
    495 static void EmitComments(const MachineInstr &MI, raw_ostream &CommentOS) {
    496   const MachineFunction *MF = MI.getParent()->getParent();
    497   const TargetMachine &TM = MF->getTarget();
    498 
    499   // Check for spills and reloads
    500   int FI;
    501 
    502   const MachineFrameInfo *FrameInfo = MF->getFrameInfo();
    503 
    504   // We assume a single instruction only has a spill or reload, not
    505   // both.
    506   const MachineMemOperand *MMO;
    507   if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) {
    508     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
    509       MMO = *MI.memoperands_begin();
    510       CommentOS << MMO->getSize() << "-byte Reload\n";
    511     }
    512   } else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) {
    513     if (FrameInfo->isSpillSlotObjectIndex(FI))
    514       CommentOS << MMO->getSize() << "-byte Folded Reload\n";
    515   } else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) {
    516     if (FrameInfo->isSpillSlotObjectIndex(FI)) {
    517       MMO = *MI.memoperands_begin();
    518       CommentOS << MMO->getSize() << "-byte Spill\n";
    519     }
    520   } else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) {
    521     if (FrameInfo->isSpillSlotObjectIndex(FI))
    522       CommentOS << MMO->getSize() << "-byte Folded Spill\n";
    523   }
    524 
    525   // Check for spill-induced copies
    526   if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse))
    527     CommentOS << " Reload Reuse\n";
    528 }
    529 
    530 /// EmitImplicitDef - This method emits the specified machine instruction
    531 /// that is an implicit def.
    532 static void EmitImplicitDef(const MachineInstr *MI, AsmPrinter &AP) {
    533   unsigned RegNo = MI->getOperand(0).getReg();
    534   AP.OutStreamer.AddComment(Twine("implicit-def: ") +
    535                             AP.TM.getRegisterInfo()->getName(RegNo));
    536   AP.OutStreamer.AddBlankLine();
    537 }
    538 
    539 static void EmitKill(const MachineInstr *MI, AsmPrinter &AP) {
    540   std::string Str = "kill:";
    541   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    542     const MachineOperand &Op = MI->getOperand(i);
    543     assert(Op.isReg() && "KILL instruction must have only register operands");
    544     Str += ' ';
    545     Str += AP.TM.getRegisterInfo()->getName(Op.getReg());
    546     Str += (Op.isDef() ? "<def>" : "<kill>");
    547   }
    548   AP.OutStreamer.AddComment(Str);
    549   AP.OutStreamer.AddBlankLine();
    550 }
    551 
    552 /// EmitDebugValueComment - This method handles the target-independent form
    553 /// of DBG_VALUE, returning true if it was able to do so.  A false return
    554 /// means the target will need to handle MI in EmitInstruction.
    555 static bool EmitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) {
    556   // This code handles only the 3-operand target-independent form.
    557   if (MI->getNumOperands() != 3)
    558     return false;
    559 
    560   SmallString<128> Str;
    561   raw_svector_ostream OS(Str);
    562   OS << '\t' << AP.MAI->getCommentString() << "DEBUG_VALUE: ";
    563 
    564   // cast away const; DIetc do not take const operands for some reason.
    565   DIVariable V(const_cast<MDNode*>(MI->getOperand(2).getMetadata()));
    566   if (V.getContext().isSubprogram())
    567     OS << DISubprogram(V.getContext()).getDisplayName() << ":";
    568   OS << V.getName() << " <- ";
    569 
    570   // Register or immediate value. Register 0 means undef.
    571   if (MI->getOperand(0).isFPImm()) {
    572     APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF());
    573     if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) {
    574       OS << (double)APF.convertToFloat();
    575     } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) {
    576       OS << APF.convertToDouble();
    577     } else {
    578       // There is no good way to print long double.  Convert a copy to
    579       // double.  Ah well, it's only a comment.
    580       bool ignored;
    581       APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
    582                   &ignored);
    583       OS << "(long double) " << APF.convertToDouble();
    584     }
    585   } else if (MI->getOperand(0).isImm()) {
    586     OS << MI->getOperand(0).getImm();
    587   } else if (MI->getOperand(0).isCImm()) {
    588     MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/);
    589   } else {
    590     assert(MI->getOperand(0).isReg() && "Unknown operand type");
    591     if (MI->getOperand(0).getReg() == 0) {
    592       // Suppress offset, it is not meaningful here.
    593       OS << "undef";
    594       // NOTE: Want this comment at start of line, don't emit with AddComment.
    595       AP.OutStreamer.EmitRawText(OS.str());
    596       return true;
    597     }
    598     OS << AP.TM.getRegisterInfo()->getName(MI->getOperand(0).getReg());
    599   }
    600 
    601   OS << '+' << MI->getOperand(1).getImm();
    602   // NOTE: Want this comment at start of line, don't emit with AddComment.
    603   AP.OutStreamer.EmitRawText(OS.str());
    604   return true;
    605 }
    606 
    607 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() {
    608   if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI &&
    609       MF->getFunction()->needsUnwindTableEntry())
    610     return CFI_M_EH;
    611 
    612   if (MMI->hasDebugInfo())
    613     return CFI_M_Debug;
    614 
    615   return CFI_M_None;
    616 }
    617 
    618 bool AsmPrinter::needsSEHMoves() {
    619   return MAI->getExceptionHandlingType() == ExceptionHandling::Win64 &&
    620     MF->getFunction()->needsUnwindTableEntry();
    621 }
    622 
    623 void AsmPrinter::emitPrologLabel(const MachineInstr &MI) {
    624   MCSymbol *Label = MI.getOperand(0).getMCSymbol();
    625 
    626   if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI)
    627     return;
    628 
    629   if (needsCFIMoves() == CFI_M_None)
    630     return;
    631 
    632   if (MMI->getCompactUnwindEncoding() != 0)
    633     OutStreamer.EmitCompactUnwindEncoding(MMI->getCompactUnwindEncoding());
    634 
    635   MachineModuleInfo &MMI = MF->getMMI();
    636   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
    637   bool FoundOne = false;
    638   (void)FoundOne;
    639   for (std::vector<MachineMove>::iterator I = Moves.begin(),
    640          E = Moves.end(); I != E; ++I) {
    641     if (I->getLabel() == Label) {
    642       EmitCFIFrameMove(*I);
    643       FoundOne = true;
    644     }
    645   }
    646   assert(FoundOne);
    647 }
    648 
    649 /// EmitFunctionBody - This method emits the body and trailer for a
    650 /// function.
    651 void AsmPrinter::EmitFunctionBody() {
    652   // Emit target-specific gunk before the function body.
    653   EmitFunctionBodyStart();
    654 
    655   bool ShouldPrintDebugScopes = DD && MMI->hasDebugInfo();
    656 
    657   // Print out code for the function.
    658   bool HasAnyRealCode = false;
    659   const MachineInstr *LastMI = 0;
    660   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
    661        I != E; ++I) {
    662     // Print a label for the basic block.
    663     EmitBasicBlockStart(I);
    664     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
    665          II != IE; ++II) {
    666       LastMI = II;
    667 
    668       // Print the assembly for the instruction.
    669       if (!II->isLabel() && !II->isImplicitDef() && !II->isKill() &&
    670           !II->isDebugValue()) {
    671         HasAnyRealCode = true;
    672 
    673         ++EmittedInsts;
    674       }
    675 #ifndef ANDROID_TARGET_BUILD
    676       if (ShouldPrintDebugScopes) {
    677         NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
    678         DD->beginInstruction(II);
    679       }
    680 #endif // ANDROID_TARGET_BUILD
    681 
    682       if (isVerbose())
    683         EmitComments(*II, OutStreamer.GetCommentOS());
    684 
    685       switch (II->getOpcode()) {
    686       case TargetOpcode::PROLOG_LABEL:
    687         emitPrologLabel(*II);
    688         break;
    689 
    690       case TargetOpcode::EH_LABEL:
    691       case TargetOpcode::GC_LABEL:
    692         OutStreamer.EmitLabel(II->getOperand(0).getMCSymbol());
    693         break;
    694       case TargetOpcode::INLINEASM:
    695         EmitInlineAsm(II);
    696         break;
    697       case TargetOpcode::DBG_VALUE:
    698         if (isVerbose()) {
    699           if (!EmitDebugValueComment(II, *this))
    700             EmitInstruction(II);
    701         }
    702         break;
    703       case TargetOpcode::IMPLICIT_DEF:
    704         if (isVerbose()) EmitImplicitDef(II, *this);
    705         break;
    706       case TargetOpcode::KILL:
    707         if (isVerbose()) EmitKill(II, *this);
    708         break;
    709       default:
    710         if (!TM.hasMCUseLoc())
    711           MCLineEntry::Make(&OutStreamer, getCurrentSection());
    712 
    713         EmitInstruction(II);
    714         break;
    715       }
    716 
    717 #ifndef ANDROID_TARGET_BUILD
    718       if (ShouldPrintDebugScopes) {
    719         NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
    720         DD->endInstruction(II);
    721       }
    722 #endif // ANDROID_TARGET_BUILD
    723     }
    724   }
    725 
    726   // If the last instruction was a prolog label, then we have a situation where
    727   // we emitted a prolog but no function body. This results in the ending prolog
    728   // label equaling the end of function label and an invalid "row" in the
    729   // FDE. We need to emit a noop in this situation so that the FDE's rows are
    730   // valid.
    731   bool RequiresNoop = LastMI && LastMI->isPrologLabel();
    732 
    733   // If the function is empty and the object file uses .subsections_via_symbols,
    734   // then we need to emit *something* to the function body to prevent the
    735   // labels from collapsing together.  Just emit a noop.
    736   if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode) || RequiresNoop) {
    737     MCInst Noop;
    738     TM.getInstrInfo()->getNoopForMachoTarget(Noop);
    739     if (Noop.getOpcode()) {
    740       OutStreamer.AddComment("avoids zero-length function");
    741       OutStreamer.EmitInstruction(Noop);
    742     } else  // Target not mc-ized yet.
    743       OutStreamer.EmitRawText(StringRef("\tnop\n"));
    744   }
    745 
    746   // Emit target-specific gunk after the function body.
    747   EmitFunctionBodyEnd();
    748 
    749   // If the target wants a .size directive for the size of the function, emit
    750   // it.
    751   if (MAI->hasDotTypeDotSizeDirective()) {
    752     // Create a symbol for the end of function, so we can get the size as
    753     // difference between the function label and the temp label.
    754     MCSymbol *FnEndLabel = OutContext.CreateTempSymbol();
    755     OutStreamer.EmitLabel(FnEndLabel);
    756 
    757     const MCExpr *SizeExp =
    758       MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(FnEndLabel, OutContext),
    759                               MCSymbolRefExpr::Create(CurrentFnSym, OutContext),
    760                               OutContext);
    761     OutStreamer.EmitELFSize(CurrentFnSym, SizeExp);
    762   }
    763 
    764   // Emit post-function debug information.
    765 #ifndef ANDROID_TARGET_BUILD
    766   if (DD) {
    767     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
    768     DD->endFunction(MF);
    769   }
    770   if (DE) {
    771     NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
    772     DE->EndFunction();
    773   }
    774 #endif // ANDROID_TARGET_BUILD
    775   MMI->EndFunction();
    776 
    777   // Print out jump tables referenced by the function.
    778   EmitJumpTableInfo();
    779 
    780   OutStreamer.AddBlankLine();
    781 }
    782 
    783 /// getDebugValueLocation - Get location information encoded by DBG_VALUE
    784 /// operands.
    785 MachineLocation AsmPrinter::
    786 getDebugValueLocation(const MachineInstr *MI) const {
    787   // Target specific DBG_VALUE instructions are handled by each target.
    788   return MachineLocation();
    789 }
    790 
    791 /// EmitDwarfRegOp - Emit dwarf register operation.
    792 void AsmPrinter::EmitDwarfRegOp(const MachineLocation &MLoc) const {
    793   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
    794   int Reg = TRI->getDwarfRegNum(MLoc.getReg(), false);
    795 
    796   for (const unsigned *SR = TRI->getSuperRegisters(MLoc.getReg());
    797        *SR && Reg < 0; ++SR) {
    798     Reg = TRI->getDwarfRegNum(*SR, false);
    799     // FIXME: Get the bit range this register uses of the superregister
    800     // so that we can produce a DW_OP_bit_piece
    801   }
    802 
    803   // FIXME: Handle cases like a super register being encoded as
    804   // DW_OP_reg 32 DW_OP_piece 4 DW_OP_reg 33
    805 
    806   // FIXME: We have no reasonable way of handling errors in here. The
    807   // caller might be in the middle of an dwarf expression. We should
    808   // probably assert that Reg >= 0 once debug info generation is more mature.
    809 
    810   if (int Offset =  MLoc.getOffset()) {
    811     if (Reg < 32) {
    812       OutStreamer.AddComment(
    813         dwarf::OperationEncodingString(dwarf::DW_OP_breg0 + Reg));
    814       EmitInt8(dwarf::DW_OP_breg0 + Reg);
    815     } else {
    816       OutStreamer.AddComment("DW_OP_bregx");
    817       EmitInt8(dwarf::DW_OP_bregx);
    818       OutStreamer.AddComment(Twine(Reg));
    819       EmitULEB128(Reg);
    820     }
    821     EmitSLEB128(Offset);
    822   } else {
    823     if (Reg < 32) {
    824       OutStreamer.AddComment(
    825         dwarf::OperationEncodingString(dwarf::DW_OP_reg0 + Reg));
    826       EmitInt8(dwarf::DW_OP_reg0 + Reg);
    827     } else {
    828       OutStreamer.AddComment("DW_OP_regx");
    829       EmitInt8(dwarf::DW_OP_regx);
    830       OutStreamer.AddComment(Twine(Reg));
    831       EmitULEB128(Reg);
    832     }
    833   }
    834 
    835   // FIXME: Produce a DW_OP_bit_piece if we used a superregister
    836 }
    837 
    838 bool AsmPrinter::doFinalization(Module &M) {
    839   // Emit global variables.
    840   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
    841        I != E; ++I)
    842     EmitGlobalVariable(I);
    843 
    844   // Emit visibility info for declarations
    845   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
    846     const Function &F = *I;
    847     if (!F.isDeclaration())
    848       continue;
    849     GlobalValue::VisibilityTypes V = F.getVisibility();
    850     if (V == GlobalValue::DefaultVisibility)
    851       continue;
    852 
    853     MCSymbol *Name = Mang->getSymbol(&F);
    854     EmitVisibility(Name, V, false);
    855   }
    856 
    857   // Finalize debug and EH information.
    858 #ifndef ANDROID_TARGET_BUILD
    859   if (DE) {
    860     {
    861       NamedRegionTimer T(EHTimerName, DWARFGroupName, TimePassesIsEnabled);
    862       DE->EndModule();
    863     }
    864     delete DE; DE = 0;
    865   }
    866   if (DD) {
    867     {
    868       NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
    869       DD->endModule();
    870     }
    871     delete DD; DD = 0;
    872   }
    873 #endif // ANDROID_TARGET_BUILD
    874 
    875   // If the target wants to know about weak references, print them all.
    876   if (MAI->getWeakRefDirective()) {
    877     // FIXME: This is not lazy, it would be nice to only print weak references
    878     // to stuff that is actually used.  Note that doing so would require targets
    879     // to notice uses in operands (due to constant exprs etc).  This should
    880     // happen with the MC stuff eventually.
    881 
    882     // Print out module-level global variables here.
    883     for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
    884          I != E; ++I) {
    885       if (!I->hasExternalWeakLinkage()) continue;
    886       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
    887     }
    888 
    889     for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
    890       if (!I->hasExternalWeakLinkage()) continue;
    891       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(I), MCSA_WeakReference);
    892     }
    893   }
    894 
    895   if (MAI->hasSetDirective()) {
    896     OutStreamer.AddBlankLine();
    897     for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
    898          I != E; ++I) {
    899       MCSymbol *Name = Mang->getSymbol(I);
    900 
    901       const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal());
    902       MCSymbol *Target = Mang->getSymbol(GV);
    903 
    904       if (I->hasExternalLinkage() || !MAI->getWeakRefDirective())
    905         OutStreamer.EmitSymbolAttribute(Name, MCSA_Global);
    906       else if (I->hasWeakLinkage())
    907         OutStreamer.EmitSymbolAttribute(Name, MCSA_WeakReference);
    908       else
    909         assert(I->hasLocalLinkage() && "Invalid alias linkage");
    910 
    911       EmitVisibility(Name, I->getVisibility());
    912 
    913       // Emit the directives as assignments aka .set:
    914       OutStreamer.EmitAssignment(Name,
    915                                  MCSymbolRefExpr::Create(Target, OutContext));
    916     }
    917   }
    918 
    919   GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>();
    920   assert(MI && "AsmPrinter didn't require GCModuleInfo?");
    921   for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; )
    922     if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I))
    923       MP->finishAssembly(*this);
    924 
    925   // If we don't have any trampolines, then we don't require stack memory
    926   // to be executable. Some targets have a directive to declare this.
    927   Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline");
    928   if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty())
    929     if (const MCSection *S = MAI->getNonexecutableStackSection(OutContext))
    930       OutStreamer.SwitchSection(S);
    931 
    932   // Allow the target to emit any magic that it wants at the end of the file,
    933   // after everything else has gone out.
    934   EmitEndOfAsmFile(M);
    935 
    936   delete Mang; Mang = 0;
    937   MMI = 0;
    938 
    939   OutStreamer.Finish();
    940   return false;
    941 }
    942 
    943 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) {
    944   this->MF = &MF;
    945   // Get the function symbol.
    946   CurrentFnSym = Mang->getSymbol(MF.getFunction());
    947 
    948   if (isVerbose())
    949     LI = &getAnalysis<MachineLoopInfo>();
    950 }
    951 
    952 namespace {
    953   // SectionCPs - Keep track the alignment, constpool entries per Section.
    954   struct SectionCPs {
    955     const MCSection *S;
    956     unsigned Alignment;
    957     SmallVector<unsigned, 4> CPEs;
    958     SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {}
    959   };
    960 }
    961 
    962 /// EmitConstantPool - Print to the current output stream assembly
    963 /// representations of the constants in the constant pool MCP. This is
    964 /// used to print out constants which have been "spilled to memory" by
    965 /// the code generator.
    966 ///
    967 void AsmPrinter::EmitConstantPool() {
    968   const MachineConstantPool *MCP = MF->getConstantPool();
    969   const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants();
    970   if (CP.empty()) return;
    971 
    972   // Calculate sections for constant pool entries. We collect entries to go into
    973   // the same section together to reduce amount of section switch statements.
    974   SmallVector<SectionCPs, 4> CPSections;
    975   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
    976     const MachineConstantPoolEntry &CPE = CP[i];
    977     unsigned Align = CPE.getAlignment();
    978 
    979     SectionKind Kind;
    980     switch (CPE.getRelocationInfo()) {
    981     default: llvm_unreachable("Unknown section kind");
    982     case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
    983     case 1:
    984       Kind = SectionKind::getReadOnlyWithRelLocal();
    985       break;
    986     case 0:
    987     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
    988     case 4:  Kind = SectionKind::getMergeableConst4(); break;
    989     case 8:  Kind = SectionKind::getMergeableConst8(); break;
    990     case 16: Kind = SectionKind::getMergeableConst16();break;
    991     default: Kind = SectionKind::getMergeableConst(); break;
    992     }
    993     }
    994 
    995     const MCSection *S = getObjFileLowering().getSectionForConstant(Kind);
    996 
    997     // The number of sections are small, just do a linear search from the
    998     // last section to the first.
    999     bool Found = false;
   1000     unsigned SecIdx = CPSections.size();
   1001     while (SecIdx != 0) {
   1002       if (CPSections[--SecIdx].S == S) {
   1003         Found = true;
   1004         break;
   1005       }
   1006     }
   1007     if (!Found) {
   1008       SecIdx = CPSections.size();
   1009       CPSections.push_back(SectionCPs(S, Align));
   1010     }
   1011 
   1012     if (Align > CPSections[SecIdx].Alignment)
   1013       CPSections[SecIdx].Alignment = Align;
   1014     CPSections[SecIdx].CPEs.push_back(i);
   1015   }
   1016 
   1017   // Now print stuff into the calculated sections.
   1018   for (unsigned i = 0, e = CPSections.size(); i != e; ++i) {
   1019     OutStreamer.SwitchSection(CPSections[i].S);
   1020     EmitAlignment(Log2_32(CPSections[i].Alignment));
   1021 
   1022     unsigned Offset = 0;
   1023     for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) {
   1024       unsigned CPI = CPSections[i].CPEs[j];
   1025       MachineConstantPoolEntry CPE = CP[CPI];
   1026 
   1027       // Emit inter-object padding for alignment.
   1028       unsigned AlignMask = CPE.getAlignment() - 1;
   1029       unsigned NewOffset = (Offset + AlignMask) & ~AlignMask;
   1030       OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/);
   1031 
   1032       Type *Ty = CPE.getType();
   1033       Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty);
   1034       OutStreamer.EmitLabel(GetCPISymbol(CPI));
   1035 
   1036       if (CPE.isMachineConstantPoolEntry())
   1037         EmitMachineConstantPoolValue(CPE.Val.MachineCPVal);
   1038       else
   1039         EmitGlobalConstant(CPE.Val.ConstVal);
   1040     }
   1041   }
   1042 }
   1043 
   1044 /// EmitJumpTableInfo - Print assembly representations of the jump tables used
   1045 /// by the current function to the current output stream.
   1046 ///
   1047 void AsmPrinter::EmitJumpTableInfo() {
   1048   const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
   1049   if (MJTI == 0) return;
   1050   if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return;
   1051   const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
   1052   if (JT.empty()) return;
   1053 
   1054   // Pick the directive to use to print the jump table entries, and switch to
   1055   // the appropriate section.
   1056   const Function *F = MF->getFunction();
   1057   bool JTInDiffSection = false;
   1058   if (// In PIC mode, we need to emit the jump table to the same section as the
   1059       // function body itself, otherwise the label differences won't make sense.
   1060       // FIXME: Need a better predicate for this: what about custom entries?
   1061       MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 ||
   1062       // We should also do if the section name is NULL or function is declared
   1063       // in discardable section
   1064       // FIXME: this isn't the right predicate, should be based on the MCSection
   1065       // for the function.
   1066       F->isWeakForLinker()) {
   1067     OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F,Mang,TM));
   1068   } else {
   1069     // Otherwise, drop it in the readonly section.
   1070     const MCSection *ReadOnlySection =
   1071       getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly());
   1072     OutStreamer.SwitchSection(ReadOnlySection);
   1073     JTInDiffSection = true;
   1074   }
   1075 
   1076   EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData())));
   1077 
   1078   for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) {
   1079     const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs;
   1080 
   1081     // If this jump table was deleted, ignore it.
   1082     if (JTBBs.empty()) continue;
   1083 
   1084     // For the EK_LabelDifference32 entry, if the target supports .set, emit a
   1085     // .set directive for each unique entry.  This reduces the number of
   1086     // relocations the assembler will generate for the jump table.
   1087     if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 &&
   1088         MAI->hasSetDirective()) {
   1089       SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets;
   1090       const TargetLowering *TLI = TM.getTargetLowering();
   1091       const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext);
   1092       for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) {
   1093         const MachineBasicBlock *MBB = JTBBs[ii];
   1094         if (!EmittedSets.insert(MBB)) continue;
   1095 
   1096         // .set LJTSet, LBB32-base
   1097         const MCExpr *LHS =
   1098           MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
   1099         OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()),
   1100                                 MCBinaryExpr::CreateSub(LHS, Base, OutContext));
   1101       }
   1102     }
   1103 
   1104     // On some targets (e.g. Darwin) we want to emit two consecutive labels
   1105     // before each jump table.  The first label is never referenced, but tells
   1106     // the assembler and linker the extents of the jump table object.  The
   1107     // second label is actually referenced by the code.
   1108     if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0])
   1109       // FIXME: This doesn't have to have any specific name, just any randomly
   1110       // named and numbered 'l' label would work.  Simplify GetJTISymbol.
   1111       OutStreamer.EmitLabel(GetJTISymbol(JTI, true));
   1112 
   1113     OutStreamer.EmitLabel(GetJTISymbol(JTI));
   1114 
   1115     for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii)
   1116       EmitJumpTableEntry(MJTI, JTBBs[ii], JTI);
   1117   }
   1118 }
   1119 
   1120 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the
   1121 /// current stream.
   1122 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI,
   1123                                     const MachineBasicBlock *MBB,
   1124                                     unsigned UID) const {
   1125   assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block");
   1126   const MCExpr *Value = 0;
   1127   switch (MJTI->getEntryKind()) {
   1128   case MachineJumpTableInfo::EK_Inline:
   1129     llvm_unreachable("Cannot emit EK_Inline jump table entry"); break;
   1130   case MachineJumpTableInfo::EK_Custom32:
   1131     Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID,
   1132                                                               OutContext);
   1133     break;
   1134   case MachineJumpTableInfo::EK_BlockAddress:
   1135     // EK_BlockAddress - Each entry is a plain address of block, e.g.:
   1136     //     .word LBB123
   1137     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
   1138     break;
   1139   case MachineJumpTableInfo::EK_GPRel32BlockAddress: {
   1140     // EK_GPRel32BlockAddress - Each entry is an address of block, encoded
   1141     // with a relocation as gp-relative, e.g.:
   1142     //     .gprel32 LBB123
   1143     MCSymbol *MBBSym = MBB->getSymbol();
   1144     OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext));
   1145     return;
   1146   }
   1147 
   1148   case MachineJumpTableInfo::EK_LabelDifference32: {
   1149     // EK_LabelDifference32 - Each entry is the address of the block minus
   1150     // the address of the jump table.  This is used for PIC jump tables where
   1151     // gprel32 is not supported.  e.g.:
   1152     //      .word LBB123 - LJTI1_2
   1153     // If the .set directive is supported, this is emitted as:
   1154     //      .set L4_5_set_123, LBB123 - LJTI1_2
   1155     //      .word L4_5_set_123
   1156 
   1157     // If we have emitted set directives for the jump table entries, print
   1158     // them rather than the entries themselves.  If we're emitting PIC, then
   1159     // emit the table entries as differences between two text section labels.
   1160     if (MAI->hasSetDirective()) {
   1161       // If we used .set, reference the .set's symbol.
   1162       Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()),
   1163                                       OutContext);
   1164       break;
   1165     }
   1166     // Otherwise, use the difference as the jump table entry.
   1167     Value = MCSymbolRefExpr::Create(MBB->getSymbol(), OutContext);
   1168     const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext);
   1169     Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext);
   1170     break;
   1171   }
   1172   }
   1173 
   1174   assert(Value && "Unknown entry kind!");
   1175 
   1176   unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData());
   1177   OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0);
   1178 }
   1179 
   1180 
   1181 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
   1182 /// special global used by LLVM.  If so, emit it and return true, otherwise
   1183 /// do nothing and return false.
   1184 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
   1185   if (GV->getName() == "llvm.used") {
   1186     if (MAI->hasNoDeadStrip())    // No need to emit this at all.
   1187       EmitLLVMUsedList(GV->getInitializer());
   1188     return true;
   1189   }
   1190 
   1191   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
   1192   if (GV->getSection() == "llvm.metadata" ||
   1193       GV->hasAvailableExternallyLinkage())
   1194     return true;
   1195 
   1196   if (!GV->hasAppendingLinkage()) return false;
   1197 
   1198   assert(GV->hasInitializer() && "Not a special LLVM global!");
   1199 
   1200   const TargetData *TD = TM.getTargetData();
   1201   unsigned Align = Log2_32(TD->getPointerPrefAlignment());
   1202   if (GV->getName() == "llvm.global_ctors") {
   1203     OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection());
   1204     EmitAlignment(Align);
   1205     EmitXXStructorList(GV->getInitializer());
   1206 
   1207     if (TM.getRelocationModel() == Reloc::Static &&
   1208         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
   1209       StringRef Sym(".constructors_used");
   1210       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
   1211                                       MCSA_Reference);
   1212     }
   1213     return true;
   1214   }
   1215 
   1216   if (GV->getName() == "llvm.global_dtors") {
   1217     OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection());
   1218     EmitAlignment(Align);
   1219     EmitXXStructorList(GV->getInitializer());
   1220 
   1221     if (TM.getRelocationModel() == Reloc::Static &&
   1222         MAI->hasStaticCtorDtorReferenceInStaticMode()) {
   1223       StringRef Sym(".destructors_used");
   1224       OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym),
   1225                                       MCSA_Reference);
   1226     }
   1227     return true;
   1228   }
   1229 
   1230   return false;
   1231 }
   1232 
   1233 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each
   1234 /// global in the specified llvm.used list for which emitUsedDirectiveFor
   1235 /// is true, as being used with this directive.
   1236 void AsmPrinter::EmitLLVMUsedList(const Constant *List) {
   1237   // Should be an array of 'i8*'.
   1238   const ConstantArray *InitList = dyn_cast<ConstantArray>(List);
   1239   if (InitList == 0) return;
   1240 
   1241   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
   1242     const GlobalValue *GV =
   1243       dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts());
   1244     if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang))
   1245       OutStreamer.EmitSymbolAttribute(Mang->getSymbol(GV), MCSA_NoDeadStrip);
   1246   }
   1247 }
   1248 
   1249 /// EmitXXStructorList - Emit the ctor or dtor list.  This just prints out the
   1250 /// function pointers, ignoring the init priority.
   1251 void AsmPrinter::EmitXXStructorList(const Constant *List) {
   1252   // Should be an array of '{ int, void ()* }' structs.  The first value is the
   1253   // init priority, which we ignore.
   1254   if (!isa<ConstantArray>(List)) return;
   1255   const ConstantArray *InitList = cast<ConstantArray>(List);
   1256   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
   1257     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
   1258       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
   1259 
   1260       if (CS->getOperand(1)->isNullValue())
   1261         return;  // Found a null terminator, exit printing.
   1262       // Emit the function pointer.
   1263       EmitGlobalConstant(CS->getOperand(1));
   1264     }
   1265 }
   1266 
   1267 //===--------------------------------------------------------------------===//
   1268 // Emission and print routines
   1269 //
   1270 
   1271 /// EmitInt8 - Emit a byte directive and value.
   1272 ///
   1273 void AsmPrinter::EmitInt8(int Value) const {
   1274   OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/);
   1275 }
   1276 
   1277 /// EmitInt16 - Emit a short directive and value.
   1278 ///
   1279 void AsmPrinter::EmitInt16(int Value) const {
   1280   OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/);
   1281 }
   1282 
   1283 /// EmitInt32 - Emit a long directive and value.
   1284 ///
   1285 void AsmPrinter::EmitInt32(int Value) const {
   1286   OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/);
   1287 }
   1288 
   1289 /// EmitLabelDifference - Emit something like ".long Hi-Lo" where the size
   1290 /// in bytes of the directive is specified by Size and Hi/Lo specify the
   1291 /// labels.  This implicitly uses .set if it is available.
   1292 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo,
   1293                                      unsigned Size) const {
   1294   // Get the Hi-Lo expression.
   1295   const MCExpr *Diff =
   1296     MCBinaryExpr::CreateSub(MCSymbolRefExpr::Create(Hi, OutContext),
   1297                             MCSymbolRefExpr::Create(Lo, OutContext),
   1298                             OutContext);
   1299 
   1300   if (!MAI->hasSetDirective()) {
   1301     OutStreamer.EmitValue(Diff, Size, 0/*AddrSpace*/);
   1302     return;
   1303   }
   1304 
   1305   // Otherwise, emit with .set (aka assignment).
   1306   MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
   1307   OutStreamer.EmitAssignment(SetLabel, Diff);
   1308   OutStreamer.EmitSymbolValue(SetLabel, Size, 0/*AddrSpace*/);
   1309 }
   1310 
   1311 /// EmitLabelOffsetDifference - Emit something like ".long Hi+Offset-Lo"
   1312 /// where the size in bytes of the directive is specified by Size and Hi/Lo
   1313 /// specify the labels.  This implicitly uses .set if it is available.
   1314 void AsmPrinter::EmitLabelOffsetDifference(const MCSymbol *Hi, uint64_t Offset,
   1315                                            const MCSymbol *Lo, unsigned Size)
   1316   const {
   1317 
   1318   // Emit Hi+Offset - Lo
   1319   // Get the Hi+Offset expression.
   1320   const MCExpr *Plus =
   1321     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Hi, OutContext),
   1322                             MCConstantExpr::Create(Offset, OutContext),
   1323                             OutContext);
   1324 
   1325   // Get the Hi+Offset-Lo expression.
   1326   const MCExpr *Diff =
   1327     MCBinaryExpr::CreateSub(Plus,
   1328                             MCSymbolRefExpr::Create(Lo, OutContext),
   1329                             OutContext);
   1330 
   1331   if (!MAI->hasSetDirective())
   1332     OutStreamer.EmitValue(Diff, 4, 0/*AddrSpace*/);
   1333   else {
   1334     // Otherwise, emit with .set (aka assignment).
   1335     MCSymbol *SetLabel = GetTempSymbol("set", SetCounter++);
   1336     OutStreamer.EmitAssignment(SetLabel, Diff);
   1337     OutStreamer.EmitSymbolValue(SetLabel, 4, 0/*AddrSpace*/);
   1338   }
   1339 }
   1340 
   1341 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset"
   1342 /// where the size in bytes of the directive is specified by Size and Label
   1343 /// specifies the label.  This implicitly uses .set if it is available.
   1344 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset,
   1345                                       unsigned Size)
   1346   const {
   1347 
   1348   // Emit Label+Offset
   1349   const MCExpr *Plus =
   1350     MCBinaryExpr::CreateAdd(MCSymbolRefExpr::Create(Label, OutContext),
   1351                             MCConstantExpr::Create(Offset, OutContext),
   1352                             OutContext);
   1353 
   1354   OutStreamer.EmitValue(Plus, 4, 0/*AddrSpace*/);
   1355 }
   1356 
   1357 
   1358 //===----------------------------------------------------------------------===//
   1359 
   1360 // EmitAlignment - Emit an alignment directive to the specified power of
   1361 // two boundary.  For example, if you pass in 3 here, you will get an 8
   1362 // byte alignment.  If a global value is specified, and if that global has
   1363 // an explicit alignment requested, it will override the alignment request
   1364 // if required for correctness.
   1365 //
   1366 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV) const {
   1367   if (GV) NumBits = getGVAlignmentLog2(GV, *TM.getTargetData(), NumBits);
   1368 
   1369   if (NumBits == 0) return;   // 1-byte aligned: no need to emit alignment.
   1370 
   1371   if (getCurrentSection()->getKind().isText())
   1372     OutStreamer.EmitCodeAlignment(1 << NumBits);
   1373   else
   1374     OutStreamer.EmitValueToAlignment(1 << NumBits, 0, 1, 0);
   1375 }
   1376 
   1377 //===----------------------------------------------------------------------===//
   1378 // Constant emission.
   1379 //===----------------------------------------------------------------------===//
   1380 
   1381 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
   1382 ///
   1383 static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) {
   1384   MCContext &Ctx = AP.OutContext;
   1385 
   1386   if (CV->isNullValue() || isa<UndefValue>(CV))
   1387     return MCConstantExpr::Create(0, Ctx);
   1388 
   1389   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
   1390     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
   1391 
   1392   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
   1393     return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
   1394 
   1395   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
   1396     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
   1397 
   1398   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
   1399   if (CE == 0) {
   1400     llvm_unreachable("Unknown constant value to lower!");
   1401     return MCConstantExpr::Create(0, Ctx);
   1402   }
   1403 
   1404   switch (CE->getOpcode()) {
   1405   default:
   1406     // If the code isn't optimized, there may be outstanding folding
   1407     // opportunities. Attempt to fold the expression using TargetData as a
   1408     // last resort before giving up.
   1409     if (Constant *C =
   1410           ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
   1411       if (C != CE)
   1412         return LowerConstant(C, AP);
   1413 
   1414     // Otherwise report the problem to the user.
   1415     {
   1416       std::string S;
   1417       raw_string_ostream OS(S);
   1418       OS << "Unsupported expression in static initializer: ";
   1419       WriteAsOperand(OS, CE, /*PrintType=*/false,
   1420                      !AP.MF ? 0 : AP.MF->getFunction()->getParent());
   1421       report_fatal_error(OS.str());
   1422     }
   1423     return MCConstantExpr::Create(0, Ctx);
   1424   case Instruction::GetElementPtr: {
   1425     const TargetData &TD = *AP.TM.getTargetData();
   1426     // Generate a symbolic expression for the byte address
   1427     const Constant *PtrVal = CE->getOperand(0);
   1428     SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
   1429     int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
   1430 
   1431     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
   1432     if (Offset == 0)
   1433       return Base;
   1434 
   1435     // Truncate/sext the offset to the pointer size.
   1436     if (TD.getPointerSizeInBits() != 64) {
   1437       int SExtAmount = 64-TD.getPointerSizeInBits();
   1438       Offset = (Offset << SExtAmount) >> SExtAmount;
   1439     }
   1440 
   1441     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
   1442                                    Ctx);
   1443   }
   1444 
   1445   case Instruction::Trunc:
   1446     // We emit the value and depend on the assembler to truncate the generated
   1447     // expression properly.  This is important for differences between
   1448     // blockaddress labels.  Since the two labels are in the same function, it
   1449     // is reasonable to treat their delta as a 32-bit value.
   1450     // FALL THROUGH.
   1451   case Instruction::BitCast:
   1452     return LowerConstant(CE->getOperand(0), AP);
   1453 
   1454   case Instruction::IntToPtr: {
   1455     const TargetData &TD = *AP.TM.getTargetData();
   1456     // Handle casts to pointers by changing them into casts to the appropriate
   1457     // integer type.  This promotes constant folding and simplifies this code.
   1458     Constant *Op = CE->getOperand(0);
   1459     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
   1460                                       false/*ZExt*/);
   1461     return LowerConstant(Op, AP);
   1462   }
   1463 
   1464   case Instruction::PtrToInt: {
   1465     const TargetData &TD = *AP.TM.getTargetData();
   1466     // Support only foldable casts to/from pointers that can be eliminated by
   1467     // changing the pointer to the appropriately sized integer type.
   1468     Constant *Op = CE->getOperand(0);
   1469     Type *Ty = CE->getType();
   1470 
   1471     const MCExpr *OpExpr = LowerConstant(Op, AP);
   1472 
   1473     // We can emit the pointer value into this slot if the slot is an
   1474     // integer slot equal to the size of the pointer.
   1475     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
   1476       return OpExpr;
   1477 
   1478     // Otherwise the pointer is smaller than the resultant integer, mask off
   1479     // the high bits so we are sure to get a proper truncation if the input is
   1480     // a constant expr.
   1481     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
   1482     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
   1483     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
   1484   }
   1485 
   1486   // The MC library also has a right-shift operator, but it isn't consistently
   1487   // signed or unsigned between different targets.
   1488   case Instruction::Add:
   1489   case Instruction::Sub:
   1490   case Instruction::Mul:
   1491   case Instruction::SDiv:
   1492   case Instruction::SRem:
   1493   case Instruction::Shl:
   1494   case Instruction::And:
   1495   case Instruction::Or:
   1496   case Instruction::Xor: {
   1497     const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
   1498     const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
   1499     switch (CE->getOpcode()) {
   1500     default: llvm_unreachable("Unknown binary operator constant cast expr");
   1501     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
   1502     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
   1503     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
   1504     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
   1505     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
   1506     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
   1507     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
   1508     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
   1509     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
   1510     }
   1511   }
   1512   }
   1513 }
   1514 
   1515 static void EmitGlobalConstantImpl(const Constant *C, unsigned AddrSpace,
   1516                                    AsmPrinter &AP);
   1517 
   1518 static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace,
   1519                                     AsmPrinter &AP) {
   1520   if (AddrSpace != 0 || !CA->isString()) {
   1521     // Not a string.  Print the values in successive locations
   1522     for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
   1523       EmitGlobalConstantImpl(CA->getOperand(i), AddrSpace, AP);
   1524     return;
   1525   }
   1526 
   1527   // Otherwise, it can be emitted as .ascii.
   1528   SmallVector<char, 128> TmpVec;
   1529   TmpVec.reserve(CA->getNumOperands());
   1530   for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
   1531     TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
   1532 
   1533   AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace);
   1534 }
   1535 
   1536 static void EmitGlobalConstantVector(const ConstantVector *CV,
   1537                                      unsigned AddrSpace, AsmPrinter &AP) {
   1538   for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i)
   1539     EmitGlobalConstantImpl(CV->getOperand(i), AddrSpace, AP);
   1540 
   1541   const TargetData &TD = *AP.TM.getTargetData();
   1542   unsigned Size = TD.getTypeAllocSize(CV->getType());
   1543   unsigned EmittedSize = TD.getTypeAllocSize(CV->getType()->getElementType()) *
   1544                          CV->getType()->getNumElements();
   1545   if (unsigned Padding = Size - EmittedSize)
   1546     AP.OutStreamer.EmitZeros(Padding, AddrSpace);
   1547 }
   1548 
   1549 static void EmitGlobalConstantStruct(const ConstantStruct *CS,
   1550                                      unsigned AddrSpace, AsmPrinter &AP) {
   1551   // Print the fields in successive locations. Pad to align if needed!
   1552   const TargetData *TD = AP.TM.getTargetData();
   1553   unsigned Size = TD->getTypeAllocSize(CS->getType());
   1554   const StructLayout *Layout = TD->getStructLayout(CS->getType());
   1555   uint64_t SizeSoFar = 0;
   1556   for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) {
   1557     const Constant *Field = CS->getOperand(i);
   1558 
   1559     // Check if padding is needed and insert one or more 0s.
   1560     uint64_t FieldSize = TD->getTypeAllocSize(Field->getType());
   1561     uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1))
   1562                         - Layout->getElementOffset(i)) - FieldSize;
   1563     SizeSoFar += FieldSize + PadSize;
   1564 
   1565     // Now print the actual field value.
   1566     EmitGlobalConstantImpl(Field, AddrSpace, AP);
   1567 
   1568     // Insert padding - this may include padding to increase the size of the
   1569     // current field up to the ABI size (if the struct is not packed) as well
   1570     // as padding to ensure that the next field starts at the right offset.
   1571     AP.OutStreamer.EmitZeros(PadSize, AddrSpace);
   1572   }
   1573   assert(SizeSoFar == Layout->getSizeInBytes() &&
   1574          "Layout of constant struct may be incorrect!");
   1575 }
   1576 
   1577 static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace,
   1578                                  AsmPrinter &AP) {
   1579   // FP Constants are printed as integer constants to avoid losing
   1580   // precision.
   1581   if (CFP->getType()->isDoubleTy()) {
   1582     if (AP.isVerbose()) {
   1583       double Val = CFP->getValueAPF().convertToDouble();
   1584       AP.OutStreamer.GetCommentOS() << "double " << Val << '\n';
   1585     }
   1586 
   1587     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
   1588     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
   1589     return;
   1590   }
   1591 
   1592   if (CFP->getType()->isFloatTy()) {
   1593     if (AP.isVerbose()) {
   1594       float Val = CFP->getValueAPF().convertToFloat();
   1595       AP.OutStreamer.GetCommentOS() << "float " << Val << '\n';
   1596     }
   1597     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
   1598     AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace);
   1599     return;
   1600   }
   1601 
   1602   if (CFP->getType()->isX86_FP80Ty()) {
   1603     // all long double variants are printed as hex
   1604     // API needed to prevent premature destruction
   1605     APInt API = CFP->getValueAPF().bitcastToAPInt();
   1606     const uint64_t *p = API.getRawData();
   1607     if (AP.isVerbose()) {
   1608       // Convert to double so we can print the approximate val as a comment.
   1609       APFloat DoubleVal = CFP->getValueAPF();
   1610       bool ignored;
   1611       DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
   1612                         &ignored);
   1613       AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= "
   1614         << DoubleVal.convertToDouble() << '\n';
   1615     }
   1616 
   1617     if (AP.TM.getTargetData()->isBigEndian()) {
   1618       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
   1619       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
   1620     } else {
   1621       AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
   1622       AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace);
   1623     }
   1624 
   1625     // Emit the tail padding for the long double.
   1626     const TargetData &TD = *AP.TM.getTargetData();
   1627     AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) -
   1628                              TD.getTypeStoreSize(CFP->getType()), AddrSpace);
   1629     return;
   1630   }
   1631 
   1632   assert(CFP->getType()->isPPC_FP128Ty() &&
   1633          "Floating point constant type not handled");
   1634   // All long double variants are printed as hex
   1635   // API needed to prevent premature destruction.
   1636   APInt API = CFP->getValueAPF().bitcastToAPInt();
   1637   const uint64_t *p = API.getRawData();
   1638   if (AP.TM.getTargetData()->isBigEndian()) {
   1639     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
   1640     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
   1641   } else {
   1642     AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace);
   1643     AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace);
   1644   }
   1645 }
   1646 
   1647 static void EmitGlobalConstantLargeInt(const ConstantInt *CI,
   1648                                        unsigned AddrSpace, AsmPrinter &AP) {
   1649   const TargetData *TD = AP.TM.getTargetData();
   1650   unsigned BitWidth = CI->getBitWidth();
   1651   assert((BitWidth & 63) == 0 && "only support multiples of 64-bits");
   1652 
   1653   // We don't expect assemblers to support integer data directives
   1654   // for more than 64 bits, so we emit the data in at most 64-bit
   1655   // quantities at a time.
   1656   const uint64_t *RawData = CI->getValue().getRawData();
   1657   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
   1658     uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i];
   1659     AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace);
   1660   }
   1661 }
   1662 
   1663 static void EmitGlobalConstantImpl(const Constant *CV, unsigned AddrSpace,
   1664                                    AsmPrinter &AP) {
   1665   if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) {
   1666     uint64_t Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
   1667     return AP.OutStreamer.EmitZeros(Size, AddrSpace);
   1668   }
   1669 
   1670   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
   1671     unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
   1672     switch (Size) {
   1673     case 1:
   1674     case 2:
   1675     case 4:
   1676     case 8:
   1677       if (AP.isVerbose())
   1678         AP.OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue());
   1679       AP.OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace);
   1680       return;
   1681     default:
   1682       EmitGlobalConstantLargeInt(CI, AddrSpace, AP);
   1683       return;
   1684     }
   1685   }
   1686 
   1687   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV))
   1688     return EmitGlobalConstantArray(CVA, AddrSpace, AP);
   1689 
   1690   if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV))
   1691     return EmitGlobalConstantStruct(CVS, AddrSpace, AP);
   1692 
   1693   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV))
   1694     return EmitGlobalConstantFP(CFP, AddrSpace, AP);
   1695 
   1696   if (isa<ConstantPointerNull>(CV)) {
   1697     unsigned Size = AP.TM.getTargetData()->getTypeAllocSize(CV->getType());
   1698     AP.OutStreamer.EmitIntValue(0, Size, AddrSpace);
   1699     return;
   1700   }
   1701 
   1702   if (const ConstantVector *V = dyn_cast<ConstantVector>(CV))
   1703     return EmitGlobalConstantVector(V, AddrSpace, AP);
   1704 
   1705   // Otherwise, it must be a ConstantExpr.  Lower it to an MCExpr, then emit it
   1706   // thread the streamer with EmitValue.
   1707   AP.OutStreamer.EmitValue(LowerConstant(CV, AP),
   1708                          AP.TM.getTargetData()->getTypeAllocSize(CV->getType()),
   1709                            AddrSpace);
   1710 }
   1711 
   1712 /// EmitGlobalConstant - Print a general LLVM constant to the .s file.
   1713 void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) {
   1714   uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType());
   1715   if (Size)
   1716     EmitGlobalConstantImpl(CV, AddrSpace, *this);
   1717   else if (MAI->hasSubsectionsViaSymbols()) {
   1718     // If the global has zero size, emit a single byte so that two labels don't
   1719     // look like they are at the same location.
   1720     OutStreamer.EmitIntValue(0, 1, AddrSpace);
   1721   }
   1722 }
   1723 
   1724 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) {
   1725   // Target doesn't support this yet!
   1726   llvm_unreachable("Target does not support EmitMachineConstantPoolValue");
   1727 }
   1728 
   1729 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const {
   1730   if (Offset > 0)
   1731     OS << '+' << Offset;
   1732   else if (Offset < 0)
   1733     OS << Offset;
   1734 }
   1735 
   1736 //===----------------------------------------------------------------------===//
   1737 // Symbol Lowering Routines.
   1738 //===----------------------------------------------------------------------===//
   1739 
   1740 /// GetTempSymbol - Return the MCSymbol corresponding to the assembler
   1741 /// temporary label with the specified stem and unique ID.
   1742 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name, unsigned ID) const {
   1743   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix()) +
   1744                                       Name + Twine(ID));
   1745 }
   1746 
   1747 /// GetTempSymbol - Return an assembler temporary label with the specified
   1748 /// stem.
   1749 MCSymbol *AsmPrinter::GetTempSymbol(StringRef Name) const {
   1750   return OutContext.GetOrCreateSymbol(Twine(MAI->getPrivateGlobalPrefix())+
   1751                                       Name);
   1752 }
   1753 
   1754 
   1755 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const {
   1756   return MMI->getAddrLabelSymbol(BA->getBasicBlock());
   1757 }
   1758 
   1759 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const {
   1760   return MMI->getAddrLabelSymbol(BB);
   1761 }
   1762 
   1763 /// GetCPISymbol - Return the symbol for the specified constant pool entry.
   1764 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const {
   1765   return OutContext.GetOrCreateSymbol
   1766     (Twine(MAI->getPrivateGlobalPrefix()) + "CPI" + Twine(getFunctionNumber())
   1767      + "_" + Twine(CPID));
   1768 }
   1769 
   1770 /// GetJTISymbol - Return the symbol for the specified jump table entry.
   1771 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const {
   1772   return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate);
   1773 }
   1774 
   1775 /// GetJTSetSymbol - Return the symbol for the specified jump table .set
   1776 /// FIXME: privatize to AsmPrinter.
   1777 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const {
   1778   return OutContext.GetOrCreateSymbol
   1779   (Twine(MAI->getPrivateGlobalPrefix()) + Twine(getFunctionNumber()) + "_" +
   1780    Twine(UID) + "_set_" + Twine(MBBID));
   1781 }
   1782 
   1783 /// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with
   1784 /// global value name as its base, with the specified suffix, and where the
   1785 /// symbol is forced to have private linkage if ForcePrivate is true.
   1786 MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV,
   1787                                                    StringRef Suffix,
   1788                                                    bool ForcePrivate) const {
   1789   SmallString<60> NameStr;
   1790   Mang->getNameWithPrefix(NameStr, GV, ForcePrivate);
   1791   NameStr.append(Suffix.begin(), Suffix.end());
   1792   return OutContext.GetOrCreateSymbol(NameStr.str());
   1793 }
   1794 
   1795 /// GetExternalSymbolSymbol - Return the MCSymbol for the specified
   1796 /// ExternalSymbol.
   1797 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const {
   1798   SmallString<60> NameStr;
   1799   Mang->getNameWithPrefix(NameStr, Sym);
   1800   return OutContext.GetOrCreateSymbol(NameStr.str());
   1801 }
   1802 
   1803 
   1804 
   1805 /// PrintParentLoopComment - Print comments about parent loops of this one.
   1806 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop,
   1807                                    unsigned FunctionNumber) {
   1808   if (Loop == 0) return;
   1809   PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber);
   1810   OS.indent(Loop->getLoopDepth()*2)
   1811     << "Parent Loop BB" << FunctionNumber << "_"
   1812     << Loop->getHeader()->getNumber()
   1813     << " Depth=" << Loop->getLoopDepth() << '\n';
   1814 }
   1815 
   1816 
   1817 /// PrintChildLoopComment - Print comments about child loops within
   1818 /// the loop for this basic block, with nesting.
   1819 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop,
   1820                                   unsigned FunctionNumber) {
   1821   // Add child loop information
   1822   for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){
   1823     OS.indent((*CL)->getLoopDepth()*2)
   1824       << "Child Loop BB" << FunctionNumber << "_"
   1825       << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth()
   1826       << '\n';
   1827     PrintChildLoopComment(OS, *CL, FunctionNumber);
   1828   }
   1829 }
   1830 
   1831 /// EmitBasicBlockLoopComments - Pretty-print comments for basic blocks.
   1832 static void EmitBasicBlockLoopComments(const MachineBasicBlock &MBB,
   1833                                        const MachineLoopInfo *LI,
   1834                                        const AsmPrinter &AP) {
   1835   // Add loop depth information
   1836   const MachineLoop *Loop = LI->getLoopFor(&MBB);
   1837   if (Loop == 0) return;
   1838 
   1839   MachineBasicBlock *Header = Loop->getHeader();
   1840   assert(Header && "No header for loop");
   1841 
   1842   // If this block is not a loop header, just print out what is the loop header
   1843   // and return.
   1844   if (Header != &MBB) {
   1845     AP.OutStreamer.AddComment("  in Loop: Header=BB" +
   1846                               Twine(AP.getFunctionNumber())+"_" +
   1847                               Twine(Loop->getHeader()->getNumber())+
   1848                               " Depth="+Twine(Loop->getLoopDepth()));
   1849     return;
   1850   }
   1851 
   1852   // Otherwise, it is a loop header.  Print out information about child and
   1853   // parent loops.
   1854   raw_ostream &OS = AP.OutStreamer.GetCommentOS();
   1855 
   1856   PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber());
   1857 
   1858   OS << "=>";
   1859   OS.indent(Loop->getLoopDepth()*2-2);
   1860 
   1861   OS << "This ";
   1862   if (Loop->empty())
   1863     OS << "Inner ";
   1864   OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n';
   1865 
   1866   PrintChildLoopComment(OS, Loop, AP.getFunctionNumber());
   1867 }
   1868 
   1869 
   1870 /// EmitBasicBlockStart - This method prints the label for the specified
   1871 /// MachineBasicBlock, an alignment (if present) and a comment describing
   1872 /// it if appropriate.
   1873 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const {
   1874   // Emit an alignment directive for this block, if needed.
   1875   if (unsigned Align = MBB->getAlignment())
   1876     EmitAlignment(Log2_32(Align));
   1877 
   1878   // If the block has its address taken, emit any labels that were used to
   1879   // reference the block.  It is possible that there is more than one label
   1880   // here, because multiple LLVM BB's may have been RAUW'd to this block after
   1881   // the references were generated.
   1882   if (MBB->hasAddressTaken()) {
   1883     const BasicBlock *BB = MBB->getBasicBlock();
   1884     if (isVerbose())
   1885       OutStreamer.AddComment("Block address taken");
   1886 
   1887     std::vector<MCSymbol*> Syms = MMI->getAddrLabelSymbolToEmit(BB);
   1888 
   1889     for (unsigned i = 0, e = Syms.size(); i != e; ++i)
   1890       OutStreamer.EmitLabel(Syms[i]);
   1891   }
   1892 
   1893   // Print the main label for the block.
   1894   if (MBB->pred_empty() || isBlockOnlyReachableByFallthrough(MBB)) {
   1895     if (isVerbose() && OutStreamer.hasRawTextSupport()) {
   1896       if (const BasicBlock *BB = MBB->getBasicBlock())
   1897         if (BB->hasName())
   1898           OutStreamer.AddComment("%" + BB->getName());
   1899 
   1900       EmitBasicBlockLoopComments(*MBB, LI, *this);
   1901 
   1902       // NOTE: Want this comment at start of line, don't emit with AddComment.
   1903       OutStreamer.EmitRawText(Twine(MAI->getCommentString()) + " BB#" +
   1904                               Twine(MBB->getNumber()) + ":");
   1905     }
   1906   } else {
   1907     if (isVerbose()) {
   1908       if (const BasicBlock *BB = MBB->getBasicBlock())
   1909         if (BB->hasName())
   1910           OutStreamer.AddComment("%" + BB->getName());
   1911       EmitBasicBlockLoopComments(*MBB, LI, *this);
   1912     }
   1913 
   1914     OutStreamer.EmitLabel(MBB->getSymbol());
   1915   }
   1916 }
   1917 
   1918 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility,
   1919                                 bool IsDefinition) const {
   1920   MCSymbolAttr Attr = MCSA_Invalid;
   1921 
   1922   switch (Visibility) {
   1923   default: break;
   1924   case GlobalValue::HiddenVisibility:
   1925     if (IsDefinition)
   1926       Attr = MAI->getHiddenVisibilityAttr();
   1927     else
   1928       Attr = MAI->getHiddenDeclarationVisibilityAttr();
   1929     break;
   1930   case GlobalValue::ProtectedVisibility:
   1931     Attr = MAI->getProtectedVisibilityAttr();
   1932     break;
   1933   }
   1934 
   1935   if (Attr != MCSA_Invalid)
   1936     OutStreamer.EmitSymbolAttribute(Sym, Attr);
   1937 }
   1938 
   1939 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
   1940 /// exactly one predecessor and the control transfer mechanism between
   1941 /// the predecessor and this block is a fall-through.
   1942 bool AsmPrinter::
   1943 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const {
   1944   // If this is a landing pad, it isn't a fall through.  If it has no preds,
   1945   // then nothing falls through to it.
   1946   if (MBB->isLandingPad() || MBB->pred_empty())
   1947     return false;
   1948 
   1949   // If there isn't exactly one predecessor, it can't be a fall through.
   1950   MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
   1951   ++PI2;
   1952   if (PI2 != MBB->pred_end())
   1953     return false;
   1954 
   1955   // The predecessor has to be immediately before this block.
   1956   MachineBasicBlock *Pred = *PI;
   1957 
   1958   if (!Pred->isLayoutSuccessor(MBB))
   1959     return false;
   1960 
   1961   // If the block is completely empty, then it definitely does fall through.
   1962   if (Pred->empty())
   1963     return true;
   1964 
   1965   // Check the terminators in the previous blocks
   1966   for (MachineBasicBlock::iterator II = Pred->getFirstTerminator(),
   1967          IE = Pred->end(); II != IE; ++II) {
   1968     MachineInstr &MI = *II;
   1969 
   1970     // If it is not a simple branch, we are in a table somewhere.
   1971     if (!MI.getDesc().isBranch() || MI.getDesc().isIndirectBranch())
   1972       return false;
   1973 
   1974     // If we are the operands of one of the branches, this is not
   1975     // a fall through.
   1976     for (MachineInstr::mop_iterator OI = MI.operands_begin(),
   1977            OE = MI.operands_end(); OI != OE; ++OI) {
   1978       const MachineOperand& OP = *OI;
   1979       if (OP.isJTI())
   1980         return false;
   1981       if (OP.isMBB() && OP.getMBB() == MBB)
   1982         return false;
   1983     }
   1984   }
   1985 
   1986   return true;
   1987 }
   1988 
   1989 
   1990 
   1991 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) {
   1992   if (!S->usesMetadata())
   1993     return 0;
   1994 
   1995   gcp_map_type &GCMap = getGCMap(GCMetadataPrinters);
   1996   gcp_map_type::iterator GCPI = GCMap.find(S);
   1997   if (GCPI != GCMap.end())
   1998     return GCPI->second;
   1999 
   2000   const char *Name = S->getName().c_str();
   2001 
   2002   for (GCMetadataPrinterRegistry::iterator
   2003          I = GCMetadataPrinterRegistry::begin(),
   2004          E = GCMetadataPrinterRegistry::end(); I != E; ++I)
   2005     if (strcmp(Name, I->getName()) == 0) {
   2006       GCMetadataPrinter *GMP = I->instantiate();
   2007       GMP->S = S;
   2008       GCMap.insert(std::make_pair(S, GMP));
   2009       return GMP;
   2010     }
   2011 
   2012   report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name));
   2013   return 0;
   2014 }
   2015 
   2016