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