AsmPrinter.cpp revision 8559cf724e8fb6a74ee227709b3a634edb2f46b4
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) const { 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 EmitVisibility(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(); 298 299 // Print the 'header' of function. 300 const Function *F = MF->getFunction(); 301 302 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM)); 303 EmitVisibility(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 EmitVisibility(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() { 444 const MachineConstantPool *MCP = MF->getConstantPool(); 445 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 446 if (CP.empty()) return; 447 448 // Calculate sections for constant pool entries. We collect entries to go into 449 // the same section together to reduce amount of section switch statements. 450 SmallVector<SectionCPs, 4> CPSections; 451 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 452 const MachineConstantPoolEntry &CPE = CP[i]; 453 unsigned Align = CPE.getAlignment(); 454 455 SectionKind Kind; 456 switch (CPE.getRelocationInfo()) { 457 default: llvm_unreachable("Unknown section kind"); 458 case 2: Kind = SectionKind::getReadOnlyWithRel(); break; 459 case 1: 460 Kind = SectionKind::getReadOnlyWithRelLocal(); 461 break; 462 case 0: 463 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) { 464 case 4: Kind = SectionKind::getMergeableConst4(); break; 465 case 8: Kind = SectionKind::getMergeableConst8(); break; 466 case 16: Kind = SectionKind::getMergeableConst16();break; 467 default: Kind = SectionKind::getMergeableConst(); break; 468 } 469 } 470 471 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind); 472 473 // The number of sections are small, just do a linear search from the 474 // last section to the first. 475 bool Found = false; 476 unsigned SecIdx = CPSections.size(); 477 while (SecIdx != 0) { 478 if (CPSections[--SecIdx].S == S) { 479 Found = true; 480 break; 481 } 482 } 483 if (!Found) { 484 SecIdx = CPSections.size(); 485 CPSections.push_back(SectionCPs(S, Align)); 486 } 487 488 if (Align > CPSections[SecIdx].Alignment) 489 CPSections[SecIdx].Alignment = Align; 490 CPSections[SecIdx].CPEs.push_back(i); 491 } 492 493 // Now print stuff into the calculated sections. 494 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 495 OutStreamer.SwitchSection(CPSections[i].S); 496 EmitAlignment(Log2_32(CPSections[i].Alignment)); 497 498 unsigned Offset = 0; 499 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 500 unsigned CPI = CPSections[i].CPEs[j]; 501 MachineConstantPoolEntry CPE = CP[CPI]; 502 503 // Emit inter-object padding for alignment. 504 unsigned AlignMask = CPE.getAlignment() - 1; 505 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 506 OutStreamer.EmitFill(NewOffset - Offset, 0/*fillval*/, 0/*addrspace*/); 507 508 const Type *Ty = CPE.getType(); 509 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty); 510 511 // Emit the label with a comment on it. 512 if (VerboseAsm) { 513 OutStreamer.GetCommentOS() << "constant pool "; 514 WriteTypeSymbolic(OutStreamer.GetCommentOS(), CPE.getType(), 515 MF->getFunction()->getParent()); 516 OutStreamer.GetCommentOS() << '\n'; 517 } 518 OutStreamer.EmitLabel(GetCPISymbol(CPI)); 519 520 if (CPE.isMachineConstantPoolEntry()) 521 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 522 else 523 EmitGlobalConstant(CPE.Val.ConstVal); 524 } 525 } 526} 527 528/// EmitJumpTableInfo - Print assembly representations of the jump tables used 529/// by the current function to the current output stream. 530/// 531void AsmPrinter::EmitJumpTableInfo(MachineFunction &MF) { 532 MachineJumpTableInfo *MJTI = MF.getJumpTableInfo(); 533 if (MJTI == 0) return; 534 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 535 if (JT.empty()) return; 536 537 // Pick the directive to use to print the jump table entries, and switch to 538 // the appropriate section. 539 const Function *F = MF.getFunction(); 540 bool JTInDiffSection = false; 541 if (// In PIC mode, we need to emit the jump table to the same section as the 542 // function body itself, otherwise the label differences won't make sense. 543 // FIXME: Need a better predicate for this: what about custom entries? 544 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 || 545 // We should also do if the section name is NULL or function is declared 546 // in discardable section 547 // FIXME: this isn't the right predicate, should be based on the MCSection 548 // for the function. 549 F->isWeakForLinker()) { 550 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, 551 TM)); 552 } else { 553 // Otherwise, drop it in the readonly section. 554 const MCSection *ReadOnlySection = 555 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly()); 556 OutStreamer.SwitchSection(ReadOnlySection); 557 JTInDiffSection = true; 558 } 559 560 EmitAlignment(Log2_32(MJTI->getEntryAlignment(*TM.getTargetData()))); 561 562 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 563 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 564 565 // If this jump table was deleted, ignore it. 566 if (JTBBs.empty()) continue; 567 568 // For the EK_LabelDifference32 entry, if the target supports .set, emit a 569 // .set directive for each unique entry. This reduces the number of 570 // relocations the assembler will generate for the jump table. 571 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 572 MAI->hasSetDirective()) { 573 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 574 const TargetLowering *TLI = TM.getTargetLowering(); 575 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(&MF, JTI, 576 OutContext); 577 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 578 const MachineBasicBlock *MBB = JTBBs[ii]; 579 if (!EmittedSets.insert(MBB)) continue; 580 581 // .set LJTSet, LBB32-base 582 const MCExpr *LHS = 583 MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext); 584 OutStreamer.EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 585 MCBinaryExpr::CreateSub(LHS, Base, OutContext)); 586 } 587 } 588 589 // On some targets (e.g. Darwin) we want to emit two consequtive labels 590 // before each jump table. The first label is never referenced, but tells 591 // the assembler and linker the extents of the jump table object. The 592 // second label is actually referenced by the code. 593 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) 594 // FIXME: This doesn't have to have any specific name, just any randomly 595 // named and numbered 'l' label would work. Simplify GetJTISymbol. 596 OutStreamer.EmitLabel(GetJTISymbol(JTI, true)); 597 598 OutStreamer.EmitLabel(GetJTISymbol(JTI)); 599 600 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 601 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI); 602 } 603} 604 605/// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 606/// current stream. 607void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI, 608 const MachineBasicBlock *MBB, 609 unsigned UID) const { 610 const MCExpr *Value = 0; 611 switch (MJTI->getEntryKind()) { 612 case MachineJumpTableInfo::EK_Custom32: 613 Value = TM.getTargetLowering()->LowerCustomJumpTableEntry(MJTI, MBB, UID, 614 OutContext); 615 break; 616 case MachineJumpTableInfo::EK_BlockAddress: 617 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 618 // .word LBB123 619 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext); 620 break; 621 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 622 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 623 // with a relocation as gp-relative, e.g.: 624 // .gprel32 LBB123 625 MCSymbol *MBBSym = MBB->getSymbol(OutContext); 626 OutStreamer.EmitGPRel32Value(MCSymbolRefExpr::Create(MBBSym, OutContext)); 627 return; 628 } 629 630 case MachineJumpTableInfo::EK_LabelDifference32: { 631 // EK_LabelDifference32 - Each entry is the address of the block minus 632 // the address of the jump table. This is used for PIC jump tables where 633 // gprel32 is not supported. e.g.: 634 // .word LBB123 - LJTI1_2 635 // If the .set directive is supported, this is emitted as: 636 // .set L4_5_set_123, LBB123 - LJTI1_2 637 // .word L4_5_set_123 638 639 // If we have emitted set directives for the jump table entries, print 640 // them rather than the entries themselves. If we're emitting PIC, then 641 // emit the table entries as differences between two text section labels. 642 if (MAI->hasSetDirective()) { 643 // If we used .set, reference the .set's symbol. 644 Value = MCSymbolRefExpr::Create(GetJTSetSymbol(UID, MBB->getNumber()), 645 OutContext); 646 break; 647 } 648 // Otherwise, use the difference as the jump table entry. 649 Value = MCSymbolRefExpr::Create(MBB->getSymbol(OutContext), OutContext); 650 const MCExpr *JTI = MCSymbolRefExpr::Create(GetJTISymbol(UID), OutContext); 651 Value = MCBinaryExpr::CreateSub(Value, JTI, OutContext); 652 break; 653 } 654 } 655 656 assert(Value && "Unknown entry kind!"); 657 658 unsigned EntrySize = MJTI->getEntrySize(*TM.getTargetData()); 659 OutStreamer.EmitValue(Value, EntrySize, /*addrspace*/0); 660} 661 662 663/// EmitSpecialLLVMGlobal - Check to see if the specified global is a 664/// special global used by LLVM. If so, emit it and return true, otherwise 665/// do nothing and return false. 666bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 667 if (GV->getName() == "llvm.used") { 668 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 669 EmitLLVMUsedList(GV->getInitializer()); 670 return true; 671 } 672 673 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 674 if (GV->getSection() == "llvm.metadata" || 675 GV->hasAvailableExternallyLinkage()) 676 return true; 677 678 if (!GV->hasAppendingLinkage()) return false; 679 680 assert(GV->hasInitializer() && "Not a special LLVM global!"); 681 682 const TargetData *TD = TM.getTargetData(); 683 unsigned Align = Log2_32(TD->getPointerPrefAlignment()); 684 if (GV->getName() == "llvm.global_ctors") { 685 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection()); 686 EmitAlignment(Align, 0); 687 EmitXXStructorList(GV->getInitializer()); 688 689 if (TM.getRelocationModel() == Reloc::Static && 690 MAI->hasStaticCtorDtorReferenceInStaticMode()) { 691 StringRef Sym(".constructors_used"); 692 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym), 693 MCSA_Reference); 694 } 695 return true; 696 } 697 698 if (GV->getName() == "llvm.global_dtors") { 699 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection()); 700 EmitAlignment(Align, 0); 701 EmitXXStructorList(GV->getInitializer()); 702 703 if (TM.getRelocationModel() == Reloc::Static && 704 MAI->hasStaticCtorDtorReferenceInStaticMode()) { 705 StringRef Sym(".destructors_used"); 706 OutStreamer.EmitSymbolAttribute(OutContext.GetOrCreateSymbol(Sym), 707 MCSA_Reference); 708 } 709 return true; 710 } 711 712 return false; 713} 714 715/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 716/// global in the specified llvm.used list for which emitUsedDirectiveFor 717/// is true, as being used with this directive. 718void AsmPrinter::EmitLLVMUsedList(Constant *List) { 719 // Should be an array of 'i8*'. 720 ConstantArray *InitList = dyn_cast<ConstantArray>(List); 721 if (InitList == 0) return; 722 723 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 724 const GlobalValue *GV = 725 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 726 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) 727 OutStreamer.EmitSymbolAttribute(GetGlobalValueSymbol(GV), 728 MCSA_NoDeadStrip); 729 } 730} 731 732/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the 733/// function pointers, ignoring the init priority. 734void AsmPrinter::EmitXXStructorList(Constant *List) { 735 // Should be an array of '{ int, void ()* }' structs. The first value is the 736 // init priority, which we ignore. 737 if (!isa<ConstantArray>(List)) return; 738 ConstantArray *InitList = cast<ConstantArray>(List); 739 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 740 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){ 741 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs. 742 743 if (CS->getOperand(1)->isNullValue()) 744 return; // Found a null terminator, exit printing. 745 // Emit the function pointer. 746 EmitGlobalConstant(CS->getOperand(1)); 747 } 748} 749 750//===--------------------------------------------------------------------===// 751// Emission and print routines 752// 753 754/// EmitInt8 - Emit a byte directive and value. 755/// 756void AsmPrinter::EmitInt8(int Value) const { 757 OutStreamer.EmitIntValue(Value, 1, 0/*addrspace*/); 758} 759 760/// EmitInt16 - Emit a short directive and value. 761/// 762void AsmPrinter::EmitInt16(int Value) const { 763 OutStreamer.EmitIntValue(Value, 2, 0/*addrspace*/); 764} 765 766/// EmitInt32 - Emit a long directive and value. 767/// 768void AsmPrinter::EmitInt32(int Value) const { 769 OutStreamer.EmitIntValue(Value, 4, 0/*addrspace*/); 770} 771 772/// EmitInt64 - Emit a long long directive and value. 773/// 774void AsmPrinter::EmitInt64(uint64_t Value) const { 775 OutStreamer.EmitIntValue(Value, 8, 0/*addrspace*/); 776} 777 778//===----------------------------------------------------------------------===// 779 780// EmitAlignment - Emit an alignment directive to the specified power of 781// two boundary. For example, if you pass in 3 here, you will get an 8 782// byte alignment. If a global value is specified, and if that global has 783// an explicit alignment requested, it will unconditionally override the 784// alignment request. However, if ForcedAlignBits is specified, this value 785// has final say: the ultimate alignment will be the max of ForcedAlignBits 786// and the alignment computed with NumBits and the global. 787// 788// The algorithm is: 789// Align = NumBits; 790// if (GV && GV->hasalignment) Align = GV->getalignment(); 791// Align = std::max(Align, ForcedAlignBits); 792// 793void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV, 794 unsigned ForcedAlignBits, 795 bool UseFillExpr) const { 796 if (GV && GV->getAlignment()) 797 NumBits = Log2_32(GV->getAlignment()); 798 NumBits = std::max(NumBits, ForcedAlignBits); 799 800 if (NumBits == 0) return; // No need to emit alignment. 801 802 unsigned FillValue = 0; 803 if (getCurrentSection()->getKind().isText()) 804 FillValue = MAI->getTextAlignFillValue(); 805 806 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0); 807} 808 809/// LowerConstant - Lower the specified LLVM Constant to an MCExpr. 810/// 811static const MCExpr *LowerConstant(const Constant *CV, AsmPrinter &AP) { 812 MCContext &Ctx = AP.OutContext; 813 814 if (CV->isNullValue() || isa<UndefValue>(CV)) 815 return MCConstantExpr::Create(0, Ctx); 816 817 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 818 return MCConstantExpr::Create(CI->getZExtValue(), Ctx); 819 820 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 821 return MCSymbolRefExpr::Create(AP.GetGlobalValueSymbol(GV), Ctx); 822 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 823 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx); 824 825 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 826 if (CE == 0) { 827 llvm_unreachable("Unknown constant value to lower!"); 828 return MCConstantExpr::Create(0, Ctx); 829 } 830 831 switch (CE->getOpcode()) { 832 case Instruction::ZExt: 833 case Instruction::SExt: 834 case Instruction::FPTrunc: 835 case Instruction::FPExt: 836 case Instruction::UIToFP: 837 case Instruction::SIToFP: 838 case Instruction::FPToUI: 839 case Instruction::FPToSI: 840 default: llvm_unreachable("FIXME: Don't support this constant cast expr"); 841 case Instruction::GetElementPtr: { 842 const TargetData &TD = *AP.TM.getTargetData(); 843 // Generate a symbolic expression for the byte address 844 const Constant *PtrVal = CE->getOperand(0); 845 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end()); 846 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), &IdxVec[0], 847 IdxVec.size()); 848 849 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP); 850 if (Offset == 0) 851 return Base; 852 853 // Truncate/sext the offset to the pointer size. 854 if (TD.getPointerSizeInBits() != 64) { 855 int SExtAmount = 64-TD.getPointerSizeInBits(); 856 Offset = (Offset << SExtAmount) >> SExtAmount; 857 } 858 859 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx), 860 Ctx); 861 } 862 863 case Instruction::Trunc: 864 // We emit the value and depend on the assembler to truncate the generated 865 // expression properly. This is important for differences between 866 // blockaddress labels. Since the two labels are in the same function, it 867 // is reasonable to treat their delta as a 32-bit value. 868 // FALL THROUGH. 869 case Instruction::BitCast: 870 return LowerConstant(CE->getOperand(0), AP); 871 872 case Instruction::IntToPtr: { 873 const TargetData &TD = *AP.TM.getTargetData(); 874 // Handle casts to pointers by changing them into casts to the appropriate 875 // integer type. This promotes constant folding and simplifies this code. 876 Constant *Op = CE->getOperand(0); 877 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()), 878 false/*ZExt*/); 879 return LowerConstant(Op, AP); 880 } 881 882 case Instruction::PtrToInt: { 883 const TargetData &TD = *AP.TM.getTargetData(); 884 // Support only foldable casts to/from pointers that can be eliminated by 885 // changing the pointer to the appropriately sized integer type. 886 Constant *Op = CE->getOperand(0); 887 const Type *Ty = CE->getType(); 888 889 const MCExpr *OpExpr = LowerConstant(Op, AP); 890 891 // We can emit the pointer value into this slot if the slot is an 892 // integer slot equal to the size of the pointer. 893 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType())) 894 return OpExpr; 895 896 // Otherwise the pointer is smaller than the resultant integer, mask off 897 // the high bits so we are sure to get a proper truncation if the input is 898 // a constant expr. 899 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType()); 900 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx); 901 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx); 902 } 903 904 case Instruction::Add: 905 case Instruction::Sub: 906 case Instruction::And: 907 case Instruction::Or: 908 case Instruction::Xor: { 909 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP); 910 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP); 911 switch (CE->getOpcode()) { 912 default: llvm_unreachable("Unknown binary operator constant cast expr"); 913 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx); 914 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx); 915 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx); 916 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx); 917 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx); 918 } 919 } 920 } 921} 922 923static void EmitGlobalConstantArray(const ConstantArray *CA, unsigned AddrSpace, 924 AsmPrinter &AP) { 925 if (AddrSpace != 0 || !CA->isString()) { 926 // Not a string. Print the values in successive locations 927 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) 928 AP.EmitGlobalConstant(CA->getOperand(i), AddrSpace); 929 return; 930 } 931 932 // Otherwise, it can be emitted as .ascii. 933 SmallVector<char, 128> TmpVec; 934 TmpVec.reserve(CA->getNumOperands()); 935 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) 936 TmpVec.push_back(cast<ConstantInt>(CA->getOperand(i))->getZExtValue()); 937 938 AP.OutStreamer.EmitBytes(StringRef(TmpVec.data(), TmpVec.size()), AddrSpace); 939} 940 941static void EmitGlobalConstantVector(const ConstantVector *CV, 942 unsigned AddrSpace, AsmPrinter &AP) { 943 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 944 AP.EmitGlobalConstant(CV->getOperand(i), AddrSpace); 945} 946 947static void EmitGlobalConstantStruct(const ConstantStruct *CS, 948 unsigned AddrSpace, AsmPrinter &AP) { 949 // Print the fields in successive locations. Pad to align if needed! 950 const TargetData *TD = AP.TM.getTargetData(); 951 unsigned Size = TD->getTypeAllocSize(CS->getType()); 952 const StructLayout *Layout = TD->getStructLayout(CS->getType()); 953 uint64_t SizeSoFar = 0; 954 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 955 const Constant *Field = CS->getOperand(i); 956 957 // Check if padding is needed and insert one or more 0s. 958 uint64_t FieldSize = TD->getTypeAllocSize(Field->getType()); 959 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 960 - Layout->getElementOffset(i)) - FieldSize; 961 SizeSoFar += FieldSize + PadSize; 962 963 // Now print the actual field value. 964 AP.EmitGlobalConstant(Field, AddrSpace); 965 966 // Insert padding - this may include padding to increase the size of the 967 // current field up to the ABI size (if the struct is not packed) as well 968 // as padding to ensure that the next field starts at the right offset. 969 AP.OutStreamer.EmitZeros(PadSize, AddrSpace); 970 } 971 assert(SizeSoFar == Layout->getSizeInBytes() && 972 "Layout of constant struct may be incorrect!"); 973} 974 975static void EmitGlobalConstantFP(const ConstantFP *CFP, unsigned AddrSpace, 976 AsmPrinter &AP) { 977 // FP Constants are printed as integer constants to avoid losing 978 // precision. 979 if (CFP->getType()->isDoubleTy()) { 980 if (AP.VerboseAsm) { 981 double Val = CFP->getValueAPF().convertToDouble(); 982 AP.OutStreamer.GetCommentOS() << "double " << Val << '\n'; 983 } 984 985 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 986 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace); 987 return; 988 } 989 990 if (CFP->getType()->isFloatTy()) { 991 if (AP.VerboseAsm) { 992 float Val = CFP->getValueAPF().convertToFloat(); 993 AP.OutStreamer.GetCommentOS() << "float " << Val << '\n'; 994 } 995 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 996 AP.OutStreamer.EmitIntValue(Val, 4, AddrSpace); 997 return; 998 } 999 1000 if (CFP->getType()->isX86_FP80Ty()) { 1001 // all long double variants are printed as hex 1002 // api needed to prevent premature destruction 1003 APInt API = CFP->getValueAPF().bitcastToAPInt(); 1004 const uint64_t *p = API.getRawData(); 1005 if (AP.VerboseAsm) { 1006 // Convert to double so we can print the approximate val as a comment. 1007 APFloat DoubleVal = CFP->getValueAPF(); 1008 bool ignored; 1009 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 1010 &ignored); 1011 AP.OutStreamer.GetCommentOS() << "x86_fp80 ~= " 1012 << DoubleVal.convertToDouble() << '\n'; 1013 } 1014 1015 if (AP.TM.getTargetData()->isBigEndian()) { 1016 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace); 1017 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1018 } else { 1019 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1020 AP.OutStreamer.EmitIntValue(p[1], 2, AddrSpace); 1021 } 1022 1023 // Emit the tail padding for the long double. 1024 const TargetData &TD = *AP.TM.getTargetData(); 1025 AP.OutStreamer.EmitZeros(TD.getTypeAllocSize(CFP->getType()) - 1026 TD.getTypeStoreSize(CFP->getType()), AddrSpace); 1027 return; 1028 } 1029 1030 assert(CFP->getType()->isPPC_FP128Ty() && 1031 "Floating point constant type not handled"); 1032 // All long double variants are printed as hex api needed to prevent 1033 // premature destruction. 1034 APInt API = CFP->getValueAPF().bitcastToAPInt(); 1035 const uint64_t *p = API.getRawData(); 1036 if (AP.TM.getTargetData()->isBigEndian()) { 1037 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1038 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace); 1039 } else { 1040 AP.OutStreamer.EmitIntValue(p[1], 8, AddrSpace); 1041 AP.OutStreamer.EmitIntValue(p[0], 8, AddrSpace); 1042 } 1043} 1044 1045static void EmitGlobalConstantLargeInt(const ConstantInt *CI, 1046 unsigned AddrSpace, AsmPrinter &AP) { 1047 const TargetData *TD = AP.TM.getTargetData(); 1048 unsigned BitWidth = CI->getBitWidth(); 1049 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits"); 1050 1051 // We don't expect assemblers to support integer data directives 1052 // for more than 64 bits, so we emit the data in at most 64-bit 1053 // quantities at a time. 1054 const uint64_t *RawData = CI->getValue().getRawData(); 1055 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 1056 uint64_t Val = TD->isBigEndian() ? RawData[e - i - 1] : RawData[i]; 1057 AP.OutStreamer.EmitIntValue(Val, 8, AddrSpace); 1058 } 1059} 1060 1061/// EmitGlobalConstant - Print a general LLVM constant to the .s file. 1062void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) { 1063 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) { 1064 uint64_t Size = TM.getTargetData()->getTypeAllocSize(CV->getType()); 1065 return OutStreamer.EmitZeros(Size, AddrSpace); 1066 } 1067 1068 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1069 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType()); 1070 switch (Size) { 1071 case 1: 1072 case 2: 1073 case 4: 1074 case 8: 1075 if (VerboseAsm) 1076 OutStreamer.GetCommentOS() << format("0x%llx\n", CI->getZExtValue()); 1077 OutStreamer.EmitIntValue(CI->getZExtValue(), Size, AddrSpace); 1078 return; 1079 default: 1080 EmitGlobalConstantLargeInt(CI, AddrSpace, *this); 1081 return; 1082 } 1083 } 1084 1085 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 1086 return EmitGlobalConstantArray(CVA, AddrSpace, *this); 1087 1088 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 1089 return EmitGlobalConstantStruct(CVS, AddrSpace, *this); 1090 1091 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 1092 return EmitGlobalConstantFP(CFP, AddrSpace, *this); 1093 1094 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 1095 return EmitGlobalConstantVector(V, AddrSpace, *this); 1096 1097 if (isa<ConstantPointerNull>(CV)) { 1098 unsigned Size = TM.getTargetData()->getTypeAllocSize(CV->getType()); 1099 OutStreamer.EmitIntValue(0, Size, AddrSpace); 1100 return; 1101 } 1102 1103 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 1104 // thread the streamer with EmitValue. 1105 OutStreamer.EmitValue(LowerConstant(CV, *this), 1106 TM.getTargetData()->getTypeAllocSize(CV->getType()), 1107 AddrSpace); 1108} 1109 1110void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 1111 // Target doesn't support this yet! 1112 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 1113} 1114 1115/// PrintSpecial - Print information related to the specified machine instr 1116/// that is independent of the operand, and may be independent of the instr 1117/// itself. This can be useful for portably encoding the comment character 1118/// or other bits of target-specific knowledge into the asmstrings. The 1119/// syntax used is ${:comment}. Targets can override this to add support 1120/// for their own strange codes. 1121void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const { 1122 if (!strcmp(Code, "private")) { 1123 O << MAI->getPrivateGlobalPrefix(); 1124 } else if (!strcmp(Code, "comment")) { 1125 if (VerboseAsm) 1126 O << MAI->getCommentString(); 1127 } else if (!strcmp(Code, "uid")) { 1128 // Comparing the address of MI isn't sufficient, because machineinstrs may 1129 // be allocated to the same address across functions. 1130 const Function *ThisF = MI->getParent()->getParent()->getFunction(); 1131 1132 // If this is a new LastFn instruction, bump the counter. 1133 if (LastMI != MI || LastFn != ThisF) { 1134 ++Counter; 1135 LastMI = MI; 1136 LastFn = ThisF; 1137 } 1138 O << Counter; 1139 } else { 1140 std::string msg; 1141 raw_string_ostream Msg(msg); 1142 Msg << "Unknown special formatter '" << Code 1143 << "' for machine instr: " << *MI; 1144 llvm_report_error(Msg.str()); 1145 } 1146} 1147 1148/// processDebugLoc - Processes the debug information of each machine 1149/// instruction's DebugLoc. 1150void AsmPrinter::processDebugLoc(const MachineInstr *MI, 1151 bool BeforePrintingInsn) { 1152 if (!MAI || !DW || !MAI->doesSupportDebugInformation() 1153 || !DW->ShouldEmitDwarfDebug()) 1154 return; 1155 DebugLoc DL = MI->getDebugLoc(); 1156 if (DL.isUnknown()) 1157 return; 1158 DILocation CurDLT = MF->getDILocation(DL); 1159 if (CurDLT.getScope().isNull()) 1160 return; 1161 1162 if (!BeforePrintingInsn) { 1163 // After printing instruction 1164 DW->EndScope(MI); 1165 } else if (CurDLT.getNode() != PrevDLT) { 1166 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(), 1167 CurDLT.getColumnNumber(), 1168 CurDLT.getScope().getNode()); 1169 printLabel(L); 1170 O << '\n'; 1171 DW->BeginScope(MI, L); 1172 PrevDLT = CurDLT.getNode(); 1173 } 1174} 1175 1176 1177/// printInlineAsm - This method formats and prints the specified machine 1178/// instruction that is an inline asm. 1179void AsmPrinter::printInlineAsm(const MachineInstr *MI) const { 1180 unsigned NumOperands = MI->getNumOperands(); 1181 1182 // Count the number of register definitions. 1183 unsigned NumDefs = 0; 1184 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef(); 1185 ++NumDefs) 1186 assert(NumDefs != NumOperands-1 && "No asm string?"); 1187 1188 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?"); 1189 1190 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc. 1191 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName(); 1192 1193 O << '\t'; 1194 1195 // If this asmstr is empty, just print the #APP/#NOAPP markers. 1196 // These are useful to see where empty asm's wound up. 1197 if (AsmStr[0] == 0) { 1198 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t"; 1199 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n'; 1200 return; 1201 } 1202 1203 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t"; 1204 1205 // The variant of the current asmprinter. 1206 int AsmPrinterVariant = MAI->getAssemblerDialect(); 1207 1208 int CurVariant = -1; // The number of the {.|.|.} region we are in. 1209 const char *LastEmitted = AsmStr; // One past the last character emitted. 1210 1211 while (*LastEmitted) { 1212 switch (*LastEmitted) { 1213 default: { 1214 // Not a special case, emit the string section literally. 1215 const char *LiteralEnd = LastEmitted+1; 1216 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' && 1217 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n') 1218 ++LiteralEnd; 1219 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) 1220 O.write(LastEmitted, LiteralEnd-LastEmitted); 1221 LastEmitted = LiteralEnd; 1222 break; 1223 } 1224 case '\n': 1225 ++LastEmitted; // Consume newline character. 1226 O << '\n'; // Indent code with newline. 1227 break; 1228 case '$': { 1229 ++LastEmitted; // Consume '$' character. 1230 bool Done = true; 1231 1232 // Handle escapes. 1233 switch (*LastEmitted) { 1234 default: Done = false; break; 1235 case '$': // $$ -> $ 1236 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) 1237 O << '$'; 1238 ++LastEmitted; // Consume second '$' character. 1239 break; 1240 case '(': // $( -> same as GCC's { character. 1241 ++LastEmitted; // Consume '(' character. 1242 if (CurVariant != -1) { 1243 llvm_report_error("Nested variants found in inline asm string: '" 1244 + std::string(AsmStr) + "'"); 1245 } 1246 CurVariant = 0; // We're in the first variant now. 1247 break; 1248 case '|': 1249 ++LastEmitted; // consume '|' character. 1250 if (CurVariant == -1) 1251 O << '|'; // this is gcc's behavior for | outside a variant 1252 else 1253 ++CurVariant; // We're in the next variant. 1254 break; 1255 case ')': // $) -> same as GCC's } char. 1256 ++LastEmitted; // consume ')' character. 1257 if (CurVariant == -1) 1258 O << '}'; // this is gcc's behavior for } outside a variant 1259 else 1260 CurVariant = -1; 1261 break; 1262 } 1263 if (Done) break; 1264 1265 bool HasCurlyBraces = false; 1266 if (*LastEmitted == '{') { // ${variable} 1267 ++LastEmitted; // Consume '{' character. 1268 HasCurlyBraces = true; 1269 } 1270 1271 // If we have ${:foo}, then this is not a real operand reference, it is a 1272 // "magic" string reference, just like in .td files. Arrange to call 1273 // PrintSpecial. 1274 if (HasCurlyBraces && *LastEmitted == ':') { 1275 ++LastEmitted; 1276 const char *StrStart = LastEmitted; 1277 const char *StrEnd = strchr(StrStart, '}'); 1278 if (StrEnd == 0) { 1279 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 1280 + std::string(AsmStr) + "'"); 1281 } 1282 1283 std::string Val(StrStart, StrEnd); 1284 PrintSpecial(MI, Val.c_str()); 1285 LastEmitted = StrEnd+1; 1286 break; 1287 } 1288 1289 const char *IDStart = LastEmitted; 1290 char *IDEnd; 1291 errno = 0; 1292 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs. 1293 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) { 1294 llvm_report_error("Bad $ operand number in inline asm string: '" 1295 + std::string(AsmStr) + "'"); 1296 } 1297 LastEmitted = IDEnd; 1298 1299 char Modifier[2] = { 0, 0 }; 1300 1301 if (HasCurlyBraces) { 1302 // If we have curly braces, check for a modifier character. This 1303 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm. 1304 if (*LastEmitted == ':') { 1305 ++LastEmitted; // Consume ':' character. 1306 if (*LastEmitted == 0) { 1307 llvm_report_error("Bad ${:} expression in inline asm string: '" 1308 + std::string(AsmStr) + "'"); 1309 } 1310 1311 Modifier[0] = *LastEmitted; 1312 ++LastEmitted; // Consume modifier character. 1313 } 1314 1315 if (*LastEmitted != '}') { 1316 llvm_report_error("Bad ${} expression in inline asm string: '" 1317 + std::string(AsmStr) + "'"); 1318 } 1319 ++LastEmitted; // Consume '}' character. 1320 } 1321 1322 if ((unsigned)Val >= NumOperands-1) { 1323 llvm_report_error("Invalid $ operand number in inline asm string: '" 1324 + std::string(AsmStr) + "'"); 1325 } 1326 1327 // Okay, we finally have a value number. Ask the target to print this 1328 // operand! 1329 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) { 1330 unsigned OpNo = 1; 1331 1332 bool Error = false; 1333 1334 // Scan to find the machine operand number for the operand. 1335 for (; Val; --Val) { 1336 if (OpNo >= MI->getNumOperands()) break; 1337 unsigned OpFlags = MI->getOperand(OpNo).getImm(); 1338 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1; 1339 } 1340 1341 if (OpNo >= MI->getNumOperands()) { 1342 Error = true; 1343 } else { 1344 unsigned OpFlags = MI->getOperand(OpNo).getImm(); 1345 ++OpNo; // Skip over the ID number. 1346 1347 if (Modifier[0] == 'l') // labels are target independent 1348 O << *MI->getOperand(OpNo).getMBB()->getSymbol(OutContext); 1349 else { 1350 AsmPrinter *AP = const_cast<AsmPrinter*>(this); 1351 if ((OpFlags & 7) == 4) { 1352 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant, 1353 Modifier[0] ? Modifier : 0); 1354 } else { 1355 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant, 1356 Modifier[0] ? Modifier : 0); 1357 } 1358 } 1359 } 1360 if (Error) { 1361 std::string msg; 1362 raw_string_ostream Msg(msg); 1363 Msg << "Invalid operand found in inline asm: '" << AsmStr << "'\n"; 1364 MI->print(Msg); 1365 llvm_report_error(Msg.str()); 1366 } 1367 } 1368 break; 1369 } 1370 } 1371 } 1372 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd(); 1373} 1374 1375/// printImplicitDef - This method prints the specified machine instruction 1376/// that is an implicit def. 1377void AsmPrinter::printImplicitDef(const MachineInstr *MI) const { 1378 if (!VerboseAsm) return; 1379 O.PadToColumn(MAI->getCommentColumn()); 1380 O << MAI->getCommentString() << " implicit-def: " 1381 << TRI->getName(MI->getOperand(0).getReg()); 1382} 1383 1384void AsmPrinter::printKill(const MachineInstr *MI) const { 1385 if (!VerboseAsm) return; 1386 O.PadToColumn(MAI->getCommentColumn()); 1387 O << MAI->getCommentString() << " kill:"; 1388 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) { 1389 const MachineOperand &op = MI->getOperand(n); 1390 assert(op.isReg() && "KILL instruction must have only register operands"); 1391 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>"); 1392 } 1393} 1394 1395/// printLabel - This method prints a local label used by debug and 1396/// exception handling tables. 1397void AsmPrinter::printLabel(const MachineInstr *MI) const { 1398 printLabel(MI->getOperand(0).getImm()); 1399} 1400 1401void AsmPrinter::printLabel(unsigned Id) const { 1402 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':'; 1403} 1404 1405/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM 1406/// instruction, using the specified assembler variant. Targets should 1407/// override this to format as appropriate. 1408bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1409 unsigned AsmVariant, const char *ExtraCode) { 1410 // Target doesn't support this yet! 1411 return true; 1412} 1413 1414bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 1415 unsigned AsmVariant, 1416 const char *ExtraCode) { 1417 // Target doesn't support this yet! 1418 return true; 1419} 1420 1421MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA, 1422 const char *Suffix) const { 1423 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix); 1424} 1425 1426MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F, 1427 const BasicBlock *BB, 1428 const char *Suffix) const { 1429 assert(BB->hasName() && 1430 "Address of anonymous basic block not supported yet!"); 1431 1432 // This code must use the function name itself, and not the function number, 1433 // since it must be possible to generate the label name from within other 1434 // functions. 1435 SmallString<60> FnName; 1436 Mang->getNameWithPrefix(FnName, F, false); 1437 1438 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME! 1439 SmallString<60> NameResult; 1440 Mang->getNameWithPrefix(NameResult, 1441 StringRef("BA") + Twine((unsigned)FnName.size()) + 1442 "_" + FnName.str() + "_" + BB->getName() + Suffix, 1443 Mangler::Private); 1444 1445 return OutContext.GetOrCreateSymbol(NameResult.str()); 1446} 1447 1448/// GetCPISymbol - Return the symbol for the specified constant pool entry. 1449MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 1450 SmallString<60> Name; 1451 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI" 1452 << getFunctionNumber() << '_' << CPID; 1453 return OutContext.GetOrCreateSymbol(Name.str()); 1454} 1455 1456/// GetJTISymbol - Return the symbol for the specified jump table entry. 1457MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 1458 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 1459} 1460 1461/// GetJTSetSymbol - Return the symbol for the specified jump table .set 1462/// FIXME: privatize to AsmPrinter. 1463MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 1464 SmallString<60> Name; 1465 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() 1466 << getFunctionNumber() << '_' << UID << "_set_" << MBBID; 1467 return OutContext.GetOrCreateSymbol(Name.str()); 1468} 1469 1470/// GetGlobalValueSymbol - Return the MCSymbol for the specified global 1471/// value. 1472MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const { 1473 SmallString<60> NameStr; 1474 Mang->getNameWithPrefix(NameStr, GV, false); 1475 return OutContext.GetOrCreateSymbol(NameStr.str()); 1476} 1477 1478/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with 1479/// global value name as its base, with the specified suffix, and where the 1480/// symbol is forced to have private linkage if ForcePrivate is true. 1481MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV, 1482 StringRef Suffix, 1483 bool ForcePrivate) const { 1484 SmallString<60> NameStr; 1485 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate); 1486 NameStr.append(Suffix.begin(), Suffix.end()); 1487 return OutContext.GetOrCreateSymbol(NameStr.str()); 1488} 1489 1490/// GetExternalSymbolSymbol - Return the MCSymbol for the specified 1491/// ExternalSymbol. 1492MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 1493 SmallString<60> NameStr; 1494 Mang->getNameWithPrefix(NameStr, Sym); 1495 return OutContext.GetOrCreateSymbol(NameStr.str()); 1496} 1497 1498 1499 1500/// PrintParentLoopComment - Print comments about parent loops of this one. 1501static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 1502 unsigned FunctionNumber) { 1503 if (Loop == 0) return; 1504 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 1505 OS.indent(Loop->getLoopDepth()*2) 1506 << "Parent Loop BB" << FunctionNumber << "_" 1507 << Loop->getHeader()->getNumber() 1508 << " Depth=" << Loop->getLoopDepth() << '\n'; 1509} 1510 1511 1512/// PrintChildLoopComment - Print comments about child loops within 1513/// the loop for this basic block, with nesting. 1514static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 1515 unsigned FunctionNumber) { 1516 // Add child loop information 1517 for (MachineLoop::iterator CL = Loop->begin(), E = Loop->end();CL != E; ++CL){ 1518 OS.indent((*CL)->getLoopDepth()*2) 1519 << "Child Loop BB" << FunctionNumber << "_" 1520 << (*CL)->getHeader()->getNumber() << " Depth " << (*CL)->getLoopDepth() 1521 << '\n'; 1522 PrintChildLoopComment(OS, *CL, FunctionNumber); 1523 } 1524} 1525 1526/// EmitComments - Pretty-print comments for basic blocks. 1527static void PrintBasicBlockLoopComments(const MachineBasicBlock &MBB, 1528 const MachineLoopInfo *LI, 1529 const AsmPrinter &AP) { 1530 // Add loop depth information 1531 const MachineLoop *Loop = LI->getLoopFor(&MBB); 1532 if (Loop == 0) return; 1533 1534 MachineBasicBlock *Header = Loop->getHeader(); 1535 assert(Header && "No header for loop"); 1536 1537 // If this block is not a loop header, just print out what is the loop header 1538 // and return. 1539 if (Header != &MBB) { 1540 AP.OutStreamer.AddComment(" in Loop: Header=BB" + 1541 Twine(AP.getFunctionNumber())+"_" + 1542 Twine(Loop->getHeader()->getNumber())+ 1543 " Depth="+Twine(Loop->getLoopDepth())); 1544 return; 1545 } 1546 1547 // Otherwise, it is a loop header. Print out information about child and 1548 // parent loops. 1549 raw_ostream &OS = AP.OutStreamer.GetCommentOS(); 1550 1551 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 1552 1553 OS << "=>"; 1554 OS.indent(Loop->getLoopDepth()*2-2); 1555 1556 OS << "This "; 1557 if (Loop->empty()) 1558 OS << "Inner "; 1559 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 1560 1561 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 1562} 1563 1564 1565/// EmitBasicBlockStart - This method prints the label for the specified 1566/// MachineBasicBlock, an alignment (if present) and a comment describing 1567/// it if appropriate. 1568void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const { 1569 // Emit an alignment directive for this block, if needed. 1570 if (unsigned Align = MBB->getAlignment()) 1571 EmitAlignment(Log2_32(Align)); 1572 1573 // If the block has its address taken, emit a special label to satisfy 1574 // references to the block. This is done so that we don't need to 1575 // remember the number of this label, and so that we can make 1576 // forward references to labels without knowing what their numbers 1577 // will be. 1578 if (MBB->hasAddressTaken()) { 1579 const BasicBlock *BB = MBB->getBasicBlock(); 1580 if (VerboseAsm) 1581 OutStreamer.AddComment("Address Taken"); 1582 OutStreamer.EmitLabel(GetBlockAddressSymbol(BB->getParent(), BB)); 1583 } 1584 1585 // Print the main label for the block. 1586 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) { 1587 if (VerboseAsm) { 1588 // NOTE: Want this comment at start of line. 1589 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':'; 1590 if (const BasicBlock *BB = MBB->getBasicBlock()) 1591 if (BB->hasName()) 1592 OutStreamer.AddComment("%" + BB->getName()); 1593 1594 PrintBasicBlockLoopComments(*MBB, LI, *this); 1595 OutStreamer.AddBlankLine(); 1596 } 1597 } else { 1598 if (VerboseAsm) { 1599 if (const BasicBlock *BB = MBB->getBasicBlock()) 1600 if (BB->hasName()) 1601 OutStreamer.AddComment("%" + BB->getName()); 1602 PrintBasicBlockLoopComments(*MBB, LI, *this); 1603 } 1604 1605 OutStreamer.EmitLabel(MBB->getSymbol(OutContext)); 1606 } 1607} 1608 1609void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility) const { 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