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