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