AsmPrinter.cpp revision 45111d160cf0910030eeb6a949c69273502e5ad5
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/MCInst.h" 30#include "llvm/MC/MCSection.h" 31#include "llvm/MC/MCStreamer.h" 32#include "llvm/MC/MCSymbol.h" 33#include "llvm/Support/CommandLine.h" 34#include "llvm/Support/ErrorHandling.h" 35#include "llvm/Support/FormattedStream.h" 36#include "llvm/MC/MCAsmInfo.h" 37#include "llvm/Target/Mangler.h" 38#include "llvm/Target/TargetData.h" 39#include "llvm/Target/TargetInstrInfo.h" 40#include "llvm/Target/TargetLowering.h" 41#include "llvm/Target/TargetLoweringObjectFile.h" 42#include "llvm/Target/TargetOptions.h" 43#include "llvm/Target/TargetRegisterInfo.h" 44#include "llvm/ADT/SmallPtrSet.h" 45#include "llvm/ADT/SmallString.h" 46#include "llvm/ADT/StringExtras.h" 47#include <cerrno> 48using namespace llvm; 49 50static cl::opt<cl::boolOrDefault> 51AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), 52 cl::init(cl::BOU_UNSET)); 53 54char AsmPrinter::ID = 0; 55AsmPrinter::AsmPrinter(formatted_raw_ostream &o, TargetMachine &tm, 56 const MCAsmInfo *T, bool VDef) 57 : MachineFunctionPass(&ID), FunctionNumber(0), O(o), 58 TM(tm), MAI(T), TRI(tm.getRegisterInfo()), 59 60 OutContext(*new MCContext()), 61 // FIXME: Pass instprinter to streamer. 62 OutStreamer(*createAsmStreamer(OutContext, O, *T, 0)), 63 64 LastMI(0), LastFn(0), Counter(~0U), PrevDLT(NULL) { 65 DW = 0; MMI = 0; 66 switch (AsmVerbose) { 67 case cl::BOU_UNSET: VerboseAsm = VDef; break; 68 case cl::BOU_TRUE: VerboseAsm = true; break; 69 case cl::BOU_FALSE: VerboseAsm = false; break; 70 } 71} 72 73AsmPrinter::~AsmPrinter() { 74 for (gcp_iterator I = GCMetadataPrinters.begin(), 75 E = GCMetadataPrinters.end(); I != E; ++I) 76 delete I->second; 77 78 delete &OutStreamer; 79 delete &OutContext; 80} 81 82TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 83 return TM.getTargetLowering()->getObjFileLowering(); 84} 85 86/// getCurrentSection() - Return the current section we are emitting to. 87const MCSection *AsmPrinter::getCurrentSection() const { 88 return OutStreamer.getCurrentSection(); 89} 90 91 92void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 93 AU.setPreservesAll(); 94 MachineFunctionPass::getAnalysisUsage(AU); 95 AU.addRequired<GCModuleInfo>(); 96 if (VerboseAsm) 97 AU.addRequired<MachineLoopInfo>(); 98} 99 100bool AsmPrinter::doInitialization(Module &M) { 101 // Initialize TargetLoweringObjectFile. 102 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 103 .Initialize(OutContext, TM); 104 105 Mang = new Mangler(M, MAI->getGlobalPrefix(), MAI->getPrivateGlobalPrefix(), 106 MAI->getLinkerPrivateGlobalPrefix()); 107 108 // Allow the target to emit any magic that it wants at the start of the file. 109 EmitStartOfAsmFile(M); 110 111 if (MAI->hasSingleParameterDotFile()) { 112 /* Very minimal debug info. It is ignored if we emit actual 113 debug info. If we don't, this at least helps the user find where 114 a function came from. */ 115 O << "\t.file\t\"" << M.getModuleIdentifier() << "\"\n"; 116 } 117 118 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 119 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 120 for (GCModuleInfo::iterator I = MI->begin(), E = MI->end(); I != E; ++I) 121 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 122 MP->beginAssembly(O, *this, *MAI); 123 124 if (!M.getModuleInlineAsm().empty()) 125 O << MAI->getCommentString() << " Start of file scope inline assembly\n" 126 << M.getModuleInlineAsm() 127 << '\n' << MAI->getCommentString() 128 << " End of file scope inline assembly\n"; 129 130 MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 131 if (MMI) 132 MMI->AnalyzeModule(M); 133 DW = getAnalysisIfAvailable<DwarfWriter>(); 134 if (DW) 135 DW->BeginModule(&M, MMI, O, this, MAI); 136 137 return false; 138} 139 140bool AsmPrinter::doFinalization(Module &M) { 141 // Emit global variables. 142 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 143 I != E; ++I) 144 PrintGlobalVariable(I); 145 146 // Emit final debug information. 147 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling()) 148 DW->EndModule(); 149 150 // If the target wants to know about weak references, print them all. 151 if (MAI->getWeakRefDirective()) { 152 // FIXME: This is not lazy, it would be nice to only print weak references 153 // to stuff that is actually used. Note that doing so would require targets 154 // to notice uses in operands (due to constant exprs etc). This should 155 // happen with the MC stuff eventually. 156 157 // Print out module-level global variables here. 158 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 159 I != E; ++I) { 160 if (!I->hasExternalWeakLinkage()) continue; 161 O << MAI->getWeakRefDirective(); 162 GetGlobalValueSymbol(I)->print(O, MAI); 163 O << '\n'; 164 } 165 166 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) { 167 if (!I->hasExternalWeakLinkage()) continue; 168 O << MAI->getWeakRefDirective(); 169 GetGlobalValueSymbol(I)->print(O, MAI); 170 O << '\n'; 171 } 172 } 173 174 if (MAI->getSetDirective()) { 175 O << '\n'; 176 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); 177 I != E; ++I) { 178 MCSymbol *Name = GetGlobalValueSymbol(I); 179 180 const GlobalValue *GV = cast<GlobalValue>(I->getAliasedGlobal()); 181 MCSymbol *Target = GetGlobalValueSymbol(GV); 182 183 if (I->hasExternalLinkage() || !MAI->getWeakRefDirective()) { 184 O << "\t.globl\t"; 185 Name->print(O, MAI); 186 O << '\n'; 187 } else if (I->hasWeakLinkage()) { 188 O << MAI->getWeakRefDirective(); 189 Name->print(O, MAI); 190 O << '\n'; 191 } else { 192 assert(I->hasLocalLinkage() && "Invalid alias linkage"); 193 } 194 195 printVisibility(Name, I->getVisibility()); 196 197 O << MAI->getSetDirective() << ' '; 198 Name->print(O, MAI); 199 O << ", "; 200 Target->print(O, MAI); 201 O << '\n'; 202 } 203 } 204 205 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 206 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 207 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 208 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*--I)) 209 MP->finishAssembly(O, *this, *MAI); 210 211 // If we don't have any trampolines, then we don't require stack memory 212 // to be executable. Some targets have a directive to declare this. 213 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 214 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 215 if (MAI->getNonexecutableStackDirective()) 216 O << MAI->getNonexecutableStackDirective() << '\n'; 217 218 219 // Allow the target to emit any magic that it wants at the end of the file, 220 // after everything else has gone out. 221 EmitEndOfAsmFile(M); 222 223 delete Mang; Mang = 0; 224 DW = 0; MMI = 0; 225 226 OutStreamer.Finish(); 227 return false; 228} 229 230void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 231 // Get the function symbol. 232 CurrentFnSym = GetGlobalValueSymbol(MF.getFunction()); 233 IncrementFunctionNumber(); 234 235 if (VerboseAsm) 236 LI = &getAnalysis<MachineLoopInfo>(); 237} 238 239namespace { 240 // SectionCPs - Keep track the alignment, constpool entries per Section. 241 struct SectionCPs { 242 const MCSection *S; 243 unsigned Alignment; 244 SmallVector<unsigned, 4> CPEs; 245 SectionCPs(const MCSection *s, unsigned a) : S(s), Alignment(a) {} 246 }; 247} 248 249/// EmitConstantPool - Print to the current output stream assembly 250/// representations of the constants in the constant pool MCP. This is 251/// used to print out constants which have been "spilled to memory" by 252/// the code generator. 253/// 254void AsmPrinter::EmitConstantPool(MachineConstantPool *MCP) { 255 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 256 if (CP.empty()) return; 257 258 // Calculate sections for constant pool entries. We collect entries to go into 259 // the same section together to reduce amount of section switch statements. 260 SmallVector<SectionCPs, 4> CPSections; 261 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 262 const MachineConstantPoolEntry &CPE = CP[i]; 263 unsigned Align = CPE.getAlignment(); 264 265 SectionKind Kind; 266 switch (CPE.getRelocationInfo()) { 267 default: llvm_unreachable("Unknown section kind"); 268 case 2: Kind = SectionKind::getReadOnlyWithRel(); break; 269 case 1: 270 Kind = SectionKind::getReadOnlyWithRelLocal(); 271 break; 272 case 0: 273 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) { 274 case 4: Kind = SectionKind::getMergeableConst4(); break; 275 case 8: Kind = SectionKind::getMergeableConst8(); break; 276 case 16: Kind = SectionKind::getMergeableConst16();break; 277 default: Kind = SectionKind::getMergeableConst(); break; 278 } 279 } 280 281 const MCSection *S = getObjFileLowering().getSectionForConstant(Kind); 282 283 // The number of sections are small, just do a linear search from the 284 // last section to the first. 285 bool Found = false; 286 unsigned SecIdx = CPSections.size(); 287 while (SecIdx != 0) { 288 if (CPSections[--SecIdx].S == S) { 289 Found = true; 290 break; 291 } 292 } 293 if (!Found) { 294 SecIdx = CPSections.size(); 295 CPSections.push_back(SectionCPs(S, Align)); 296 } 297 298 if (Align > CPSections[SecIdx].Alignment) 299 CPSections[SecIdx].Alignment = Align; 300 CPSections[SecIdx].CPEs.push_back(i); 301 } 302 303 // Now print stuff into the calculated sections. 304 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 305 OutStreamer.SwitchSection(CPSections[i].S); 306 EmitAlignment(Log2_32(CPSections[i].Alignment)); 307 308 unsigned Offset = 0; 309 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 310 unsigned CPI = CPSections[i].CPEs[j]; 311 MachineConstantPoolEntry CPE = CP[CPI]; 312 313 // Emit inter-object padding for alignment. 314 unsigned AlignMask = CPE.getAlignment() - 1; 315 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 316 EmitZeros(NewOffset - Offset); 317 318 const Type *Ty = CPE.getType(); 319 Offset = NewOffset + TM.getTargetData()->getTypeAllocSize(Ty); 320 321 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_' 322 << CPI << ':'; 323 if (VerboseAsm) { 324 O.PadToColumn(MAI->getCommentColumn()); 325 O << MAI->getCommentString() << " constant "; 326 WriteTypeSymbolic(O, CPE.getType(), MF->getFunction()->getParent()); 327 } 328 O << '\n'; 329 if (CPE.isMachineConstantPoolEntry()) 330 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 331 else 332 EmitGlobalConstant(CPE.Val.ConstVal); 333 } 334 } 335} 336 337/// EmitJumpTableInfo - Print assembly representations of the jump tables used 338/// by the current function to the current output stream. 339/// 340void AsmPrinter::EmitJumpTableInfo(MachineJumpTableInfo *MJTI, 341 MachineFunction &MF) { 342 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 343 if (JT.empty()) return; 344 345 bool IsPic = TM.getRelocationModel() == Reloc::PIC_; 346 347 // Pick the directive to use to print the jump table entries, and switch to 348 // the appropriate section. 349 TargetLowering *LoweringInfo = TM.getTargetLowering(); 350 351 const Function *F = MF.getFunction(); 352 bool JTInDiffSection = false; 353 if (F->isWeakForLinker() || 354 (IsPic && !LoweringInfo->usesGlobalOffsetTable())) { 355 // In PIC mode, we need to emit the jump table to the same section as the 356 // function body itself, otherwise the label differences won't make sense. 357 // We should also do if the section name is NULL or function is declared in 358 // discardable section. 359 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, 360 TM)); 361 } else { 362 // Otherwise, drop it in the readonly section. 363 const MCSection *ReadOnlySection = 364 getObjFileLowering().getSectionForConstant(SectionKind::getReadOnly()); 365 OutStreamer.SwitchSection(ReadOnlySection); 366 JTInDiffSection = true; 367 } 368 369 EmitAlignment(Log2_32(MJTI->getAlignment())); 370 371 for (unsigned i = 0, e = JT.size(); i != e; ++i) { 372 const std::vector<MachineBasicBlock*> &JTBBs = JT[i].MBBs; 373 374 // If this jump table was deleted, ignore it. 375 if (JTBBs.empty()) continue; 376 377 // For PIC codegen, if possible we want to use the SetDirective to reduce 378 // the number of relocations the assembler will generate for the jump table. 379 // Set directives are all printed before the jump table itself. 380 SmallPtrSet<MachineBasicBlock*, 16> EmittedSets; 381 if (MAI->getSetDirective() && IsPic) 382 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 383 if (EmittedSets.insert(JTBBs[ii])) 384 printPICJumpTableSetLabel(i, JTBBs[ii]); 385 386 // On some targets (e.g. Darwin) we want to emit two consequtive labels 387 // before each jump table. The first label is never referenced, but tells 388 // the assembler and linker the extents of the jump table object. The 389 // second label is actually referenced by the code. 390 if (JTInDiffSection && MAI->getLinkerPrivateGlobalPrefix()[0]) { 391 O << MAI->getLinkerPrivateGlobalPrefix() 392 << "JTI" << getFunctionNumber() << '_' << i << ":\n"; 393 } 394 395 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 396 << '_' << i << ":\n"; 397 398 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 399 printPICJumpTableEntry(MJTI, JTBBs[ii], i); 400 O << '\n'; 401 } 402 } 403} 404 405void AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI, 406 const MachineBasicBlock *MBB, 407 unsigned uid) const { 408 bool isPIC = TM.getRelocationModel() == Reloc::PIC_; 409 410 // Use JumpTableDirective otherwise honor the entry size from the jump table 411 // info. 412 const char *JTEntryDirective = MAI->getJumpTableDirective(isPIC); 413 bool HadJTEntryDirective = JTEntryDirective != NULL; 414 if (!HadJTEntryDirective) { 415 JTEntryDirective = MJTI->getEntrySize() == 4 ? 416 MAI->getData32bitsDirective() : MAI->getData64bitsDirective(); 417 } 418 419 O << JTEntryDirective << ' '; 420 421 // If we have emitted set directives for the jump table entries, print 422 // them rather than the entries themselves. If we're emitting PIC, then 423 // emit the table entries as differences between two text section labels. 424 // If we're emitting non-PIC code, then emit the entries as direct 425 // references to the target basic blocks. 426 if (!isPIC) { 427 GetMBBSymbol(MBB->getNumber())->print(O, MAI); 428 } else if (MAI->getSetDirective()) { 429 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber() 430 << '_' << uid << "_set_" << MBB->getNumber(); 431 } else { 432 GetMBBSymbol(MBB->getNumber())->print(O, MAI); 433 // If the arch uses custom Jump Table directives, don't calc relative to 434 // JT 435 if (!HadJTEntryDirective) 436 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" 437 << getFunctionNumber() << '_' << uid; 438 } 439} 440 441 442/// EmitSpecialLLVMGlobal - Check to see if the specified global is a 443/// special global used by LLVM. If so, emit it and return true, otherwise 444/// do nothing and return false. 445bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 446 if (GV->getName() == "llvm.used") { 447 if (MAI->getUsedDirective() != 0) // No need to emit this at all. 448 EmitLLVMUsedList(GV->getInitializer()); 449 return true; 450 } 451 452 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 453 if (GV->getSection() == "llvm.metadata" || 454 GV->hasAvailableExternallyLinkage()) 455 return true; 456 457 if (!GV->hasAppendingLinkage()) return false; 458 459 assert(GV->hasInitializer() && "Not a special LLVM global!"); 460 461 const TargetData *TD = TM.getTargetData(); 462 unsigned Align = Log2_32(TD->getPointerPrefAlignment()); 463 if (GV->getName() == "llvm.global_ctors") { 464 OutStreamer.SwitchSection(getObjFileLowering().getStaticCtorSection()); 465 EmitAlignment(Align, 0); 466 EmitXXStructorList(GV->getInitializer()); 467 return true; 468 } 469 470 if (GV->getName() == "llvm.global_dtors") { 471 OutStreamer.SwitchSection(getObjFileLowering().getStaticDtorSection()); 472 EmitAlignment(Align, 0); 473 EmitXXStructorList(GV->getInitializer()); 474 return true; 475 } 476 477 return false; 478} 479 480/// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 481/// global in the specified llvm.used list for which emitUsedDirectiveFor 482/// is true, as being used with this directive. 483void AsmPrinter::EmitLLVMUsedList(Constant *List) { 484 const char *Directive = MAI->getUsedDirective(); 485 486 // Should be an array of 'i8*'. 487 ConstantArray *InitList = dyn_cast<ConstantArray>(List); 488 if (InitList == 0) return; 489 490 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 491 const GlobalValue *GV = 492 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 493 if (GV && getObjFileLowering().shouldEmitUsedDirectiveFor(GV, Mang)) { 494 O << Directive; 495 EmitConstantValueOnly(InitList->getOperand(i)); 496 O << '\n'; 497 } 498 } 499} 500 501/// EmitXXStructorList - Emit the ctor or dtor list. This just prints out the 502/// function pointers, ignoring the init priority. 503void AsmPrinter::EmitXXStructorList(Constant *List) { 504 // Should be an array of '{ int, void ()* }' structs. The first value is the 505 // init priority, which we ignore. 506 if (!isa<ConstantArray>(List)) return; 507 ConstantArray *InitList = cast<ConstantArray>(List); 508 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) 509 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){ 510 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs. 511 512 if (CS->getOperand(1)->isNullValue()) 513 return; // Found a null terminator, exit printing. 514 // Emit the function pointer. 515 EmitGlobalConstant(CS->getOperand(1)); 516 } 517} 518 519 520//===----------------------------------------------------------------------===// 521/// LEB 128 number encoding. 522 523/// PrintULEB128 - Print a series of hexadecimal values (separated by commas) 524/// representing an unsigned leb128 value. 525void AsmPrinter::PrintULEB128(unsigned Value) const { 526 char Buffer[20]; 527 do { 528 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); 529 Value >>= 7; 530 if (Value) Byte |= 0x80; 531 O << "0x" << utohex_buffer(Byte, Buffer+20); 532 if (Value) O << ", "; 533 } while (Value); 534} 535 536/// PrintSLEB128 - Print a series of hexadecimal values (separated by commas) 537/// representing a signed leb128 value. 538void AsmPrinter::PrintSLEB128(int Value) const { 539 int Sign = Value >> (8 * sizeof(Value) - 1); 540 bool IsMore; 541 char Buffer[20]; 542 543 do { 544 unsigned char Byte = static_cast<unsigned char>(Value & 0x7f); 545 Value >>= 7; 546 IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0; 547 if (IsMore) Byte |= 0x80; 548 O << "0x" << utohex_buffer(Byte, Buffer+20); 549 if (IsMore) O << ", "; 550 } while (IsMore); 551} 552 553//===--------------------------------------------------------------------===// 554// Emission and print routines 555// 556 557/// PrintHex - Print a value as a hexadecimal value. 558/// 559void AsmPrinter::PrintHex(int Value) const { 560 char Buffer[20]; 561 O << "0x" << utohex_buffer(static_cast<unsigned>(Value), Buffer+20); 562} 563 564/// EOL - Print a newline character to asm stream. If a comment is present 565/// then it will be printed first. Comments should not contain '\n'. 566void AsmPrinter::EOL() const { 567 O << '\n'; 568} 569 570void AsmPrinter::EOL(const std::string &Comment) const { 571 if (VerboseAsm && !Comment.empty()) { 572 O.PadToColumn(MAI->getCommentColumn()); 573 O << MAI->getCommentString() 574 << ' ' 575 << Comment; 576 } 577 O << '\n'; 578} 579 580void AsmPrinter::EOL(const char* Comment) const { 581 if (VerboseAsm && *Comment) { 582 O.PadToColumn(MAI->getCommentColumn()); 583 O << MAI->getCommentString() 584 << ' ' 585 << Comment; 586 } 587 O << '\n'; 588} 589 590static const char *DecodeDWARFEncoding(unsigned Encoding) { 591 switch (Encoding) { 592 case dwarf::DW_EH_PE_absptr: 593 return "absptr"; 594 case dwarf::DW_EH_PE_omit: 595 return "omit"; 596 case dwarf::DW_EH_PE_pcrel: 597 return "pcrel"; 598 case dwarf::DW_EH_PE_udata4: 599 return "udata4"; 600 case dwarf::DW_EH_PE_udata8: 601 return "udata8"; 602 case dwarf::DW_EH_PE_sdata4: 603 return "sdata4"; 604 case dwarf::DW_EH_PE_sdata8: 605 return "sdata8"; 606 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata4: 607 return "pcrel udata4"; 608 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4: 609 return "pcrel sdata4"; 610 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8: 611 return "pcrel udata8"; 612 case dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8: 613 return "pcrel sdata8"; 614 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata4: 615 return "indirect pcrel udata4"; 616 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata4: 617 return "indirect pcrel sdata4"; 618 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_udata8: 619 return "indirect pcrel udata8"; 620 case dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |dwarf::DW_EH_PE_sdata8: 621 return "indirect pcrel sdata8"; 622 } 623 624 return 0; 625} 626 627void AsmPrinter::EOL(const char *Comment, unsigned Encoding) const { 628 if (VerboseAsm && *Comment) { 629 O.PadToColumn(MAI->getCommentColumn()); 630 O << MAI->getCommentString() 631 << ' ' 632 << Comment; 633 634 if (const char *EncStr = DecodeDWARFEncoding(Encoding)) 635 O << " (" << EncStr << ')'; 636 } 637 O << '\n'; 638} 639 640/// EmitULEB128Bytes - Emit an assembler byte data directive to compose an 641/// unsigned leb128 value. 642void AsmPrinter::EmitULEB128Bytes(unsigned Value) const { 643 if (MAI->hasLEB128()) { 644 O << "\t.uleb128\t" 645 << Value; 646 } else { 647 O << MAI->getData8bitsDirective(); 648 PrintULEB128(Value); 649 } 650} 651 652/// EmitSLEB128Bytes - print an assembler byte data directive to compose a 653/// signed leb128 value. 654void AsmPrinter::EmitSLEB128Bytes(int Value) const { 655 if (MAI->hasLEB128()) { 656 O << "\t.sleb128\t" 657 << Value; 658 } else { 659 O << MAI->getData8bitsDirective(); 660 PrintSLEB128(Value); 661 } 662} 663 664/// EmitInt8 - Emit a byte directive and value. 665/// 666void AsmPrinter::EmitInt8(int Value) const { 667 O << MAI->getData8bitsDirective(); 668 PrintHex(Value & 0xFF); 669} 670 671/// EmitInt16 - Emit a short directive and value. 672/// 673void AsmPrinter::EmitInt16(int Value) const { 674 O << MAI->getData16bitsDirective(); 675 PrintHex(Value & 0xFFFF); 676} 677 678/// EmitInt32 - Emit a long directive and value. 679/// 680void AsmPrinter::EmitInt32(int Value) const { 681 O << MAI->getData32bitsDirective(); 682 PrintHex(Value); 683} 684 685/// EmitInt64 - Emit a long long directive and value. 686/// 687void AsmPrinter::EmitInt64(uint64_t Value) const { 688 if (MAI->getData64bitsDirective()) { 689 O << MAI->getData64bitsDirective(); 690 PrintHex(Value); 691 } else { 692 if (TM.getTargetData()->isBigEndian()) { 693 EmitInt32(unsigned(Value >> 32)); O << '\n'; 694 EmitInt32(unsigned(Value)); 695 } else { 696 EmitInt32(unsigned(Value)); O << '\n'; 697 EmitInt32(unsigned(Value >> 32)); 698 } 699 } 700} 701 702/// toOctal - Convert the low order bits of X into an octal digit. 703/// 704static inline char toOctal(int X) { 705 return (X&7)+'0'; 706} 707 708/// printStringChar - Print a char, escaped if necessary. 709/// 710static void printStringChar(formatted_raw_ostream &O, unsigned char C) { 711 if (C == '"') { 712 O << "\\\""; 713 } else if (C == '\\') { 714 O << "\\\\"; 715 } else if (isprint((unsigned char)C)) { 716 O << C; 717 } else { 718 switch(C) { 719 case '\b': O << "\\b"; break; 720 case '\f': O << "\\f"; break; 721 case '\n': O << "\\n"; break; 722 case '\r': O << "\\r"; break; 723 case '\t': O << "\\t"; break; 724 default: 725 O << '\\'; 726 O << toOctal(C >> 6); 727 O << toOctal(C >> 3); 728 O << toOctal(C >> 0); 729 break; 730 } 731 } 732} 733 734/// EmitString - Emit a string with quotes and a null terminator. 735/// Special characters are emitted properly. 736/// \literal (Eg. '\t') \endliteral 737void AsmPrinter::EmitString(const StringRef String) const { 738 EmitString(String.data(), String.size()); 739} 740 741void AsmPrinter::EmitString(const char *String, unsigned Size) const { 742 const char* AscizDirective = MAI->getAscizDirective(); 743 if (AscizDirective) 744 O << AscizDirective; 745 else 746 O << MAI->getAsciiDirective(); 747 O << '\"'; 748 for (unsigned i = 0; i < Size; ++i) 749 printStringChar(O, String[i]); 750 if (AscizDirective) 751 O << '\"'; 752 else 753 O << "\\0\""; 754} 755 756 757/// EmitFile - Emit a .file directive. 758void AsmPrinter::EmitFile(unsigned Number, const std::string &Name) const { 759 O << "\t.file\t" << Number << " \""; 760 for (unsigned i = 0, N = Name.size(); i < N; ++i) 761 printStringChar(O, Name[i]); 762 O << '\"'; 763} 764 765 766//===----------------------------------------------------------------------===// 767 768// EmitAlignment - Emit an alignment directive to the specified power of 769// two boundary. For example, if you pass in 3 here, you will get an 8 770// byte alignment. If a global value is specified, and if that global has 771// an explicit alignment requested, it will unconditionally override the 772// alignment request. However, if ForcedAlignBits is specified, this value 773// has final say: the ultimate alignment will be the max of ForcedAlignBits 774// and the alignment computed with NumBits and the global. 775// 776// The algorithm is: 777// Align = NumBits; 778// if (GV && GV->hasalignment) Align = GV->getalignment(); 779// Align = std::max(Align, ForcedAlignBits); 780// 781void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalValue *GV, 782 unsigned ForcedAlignBits, 783 bool UseFillExpr) const { 784 if (GV && GV->getAlignment()) 785 NumBits = Log2_32(GV->getAlignment()); 786 NumBits = std::max(NumBits, ForcedAlignBits); 787 788 if (NumBits == 0) return; // No need to emit alignment. 789 790 unsigned FillValue = 0; 791 if (getCurrentSection()->getKind().isText()) 792 FillValue = MAI->getTextAlignFillValue(); 793 794 OutStreamer.EmitValueToAlignment(1 << NumBits, FillValue, 1, 0); 795} 796 797/// EmitZeros - Emit a block of zeros. 798/// 799void AsmPrinter::EmitZeros(uint64_t NumZeros, unsigned AddrSpace) const { 800 if (NumZeros) { 801 if (MAI->getZeroDirective()) { 802 O << MAI->getZeroDirective() << NumZeros; 803 if (MAI->getZeroDirectiveSuffix()) 804 O << MAI->getZeroDirectiveSuffix(); 805 O << '\n'; 806 } else { 807 for (; NumZeros; --NumZeros) 808 O << MAI->getData8bitsDirective(AddrSpace) << "0\n"; 809 } 810 } 811} 812 813// Print out the specified constant, without a storage class. Only the 814// constants valid in constant expressions can occur here. 815void AsmPrinter::EmitConstantValueOnly(const Constant *CV) { 816 if (CV->isNullValue() || isa<UndefValue>(CV)) { 817 O << '0'; 818 return; 819 } 820 821 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 822 O << CI->getZExtValue(); 823 return; 824 } 825 826 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) { 827 // This is a constant address for a global variable or function. Use the 828 // name of the variable or function as the address value. 829 GetGlobalValueSymbol(GV)->print(O, MAI); 830 return; 831 } 832 833 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) { 834 GetBlockAddressSymbol(BA)->print(O, MAI); 835 return; 836 } 837 838 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 839 if (CE == 0) { 840 llvm_unreachable("Unknown constant value!"); 841 O << '0'; 842 return; 843 } 844 845 switch (CE->getOpcode()) { 846 case Instruction::ZExt: 847 case Instruction::SExt: 848 case Instruction::FPTrunc: 849 case Instruction::FPExt: 850 case Instruction::UIToFP: 851 case Instruction::SIToFP: 852 case Instruction::FPToUI: 853 case Instruction::FPToSI: 854 default: 855 llvm_unreachable("FIXME: Don't support this constant cast expr"); 856 case Instruction::GetElementPtr: { 857 // generate a symbolic expression for the byte address 858 const TargetData *TD = TM.getTargetData(); 859 const Constant *ptrVal = CE->getOperand(0); 860 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end()); 861 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0], 862 idxVec.size()); 863 if (Offset == 0) 864 return EmitConstantValueOnly(ptrVal); 865 866 // Truncate/sext the offset to the pointer size. 867 if (TD->getPointerSizeInBits() != 64) { 868 int SExtAmount = 64-TD->getPointerSizeInBits(); 869 Offset = (Offset << SExtAmount) >> SExtAmount; 870 } 871 872 if (Offset) 873 O << '('; 874 EmitConstantValueOnly(ptrVal); 875 if (Offset > 0) 876 O << ") + " << Offset; 877 else 878 O << ") - " << -Offset; 879 return; 880 } 881 case Instruction::BitCast: 882 return EmitConstantValueOnly(CE->getOperand(0)); 883 884 case Instruction::IntToPtr: { 885 // Handle casts to pointers by changing them into casts to the appropriate 886 // integer type. This promotes constant folding and simplifies this code. 887 const TargetData *TD = TM.getTargetData(); 888 Constant *Op = CE->getOperand(0); 889 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()), 890 false/*ZExt*/); 891 return EmitConstantValueOnly(Op); 892 } 893 894 case Instruction::PtrToInt: { 895 // Support only foldable casts to/from pointers that can be eliminated by 896 // changing the pointer to the appropriately sized integer type. 897 Constant *Op = CE->getOperand(0); 898 const Type *Ty = CE->getType(); 899 const TargetData *TD = TM.getTargetData(); 900 901 // We can emit the pointer value into this slot if the slot is an 902 // integer slot greater or equal to the size of the pointer. 903 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType())) 904 return EmitConstantValueOnly(Op); 905 906 O << "(("; 907 EmitConstantValueOnly(Op); 908 APInt ptrMask = 909 APInt::getAllOnesValue(TD->getTypeAllocSizeInBits(Op->getType())); 910 911 SmallString<40> S; 912 ptrMask.toStringUnsigned(S); 913 O << ") & " << S.str() << ')'; 914 return; 915 } 916 917 case Instruction::Trunc: 918 // We emit the value and depend on the assembler to truncate the generated 919 // expression properly. This is important for differences between 920 // blockaddress labels. Since the two labels are in the same function, it 921 // is reasonable to treat their delta as a 32-bit value. 922 return EmitConstantValueOnly(CE->getOperand(0)); 923 924 case Instruction::Add: 925 case Instruction::Sub: 926 case Instruction::And: 927 case Instruction::Or: 928 case Instruction::Xor: 929 O << '('; 930 EmitConstantValueOnly(CE->getOperand(0)); 931 O << ')'; 932 switch (CE->getOpcode()) { 933 case Instruction::Add: 934 O << " + "; 935 break; 936 case Instruction::Sub: 937 O << " - "; 938 break; 939 case Instruction::And: 940 O << " & "; 941 break; 942 case Instruction::Or: 943 O << " | "; 944 break; 945 case Instruction::Xor: 946 O << " ^ "; 947 break; 948 default: 949 break; 950 } 951 O << '('; 952 EmitConstantValueOnly(CE->getOperand(1)); 953 O << ')'; 954 break; 955 } 956} 957 958/// printAsCString - Print the specified array as a C compatible string, only if 959/// the predicate isString is true. 960/// 961static void printAsCString(formatted_raw_ostream &O, const ConstantArray *CVA, 962 unsigned LastElt) { 963 assert(CVA->isString() && "Array is not string compatible!"); 964 965 O << '\"'; 966 for (unsigned i = 0; i != LastElt; ++i) { 967 unsigned char C = 968 (unsigned char)cast<ConstantInt>(CVA->getOperand(i))->getZExtValue(); 969 printStringChar(O, C); 970 } 971 O << '\"'; 972} 973 974/// EmitString - Emit a zero-byte-terminated string constant. 975/// 976void AsmPrinter::EmitString(const ConstantArray *CVA) const { 977 unsigned NumElts = CVA->getNumOperands(); 978 if (MAI->getAscizDirective() && NumElts && 979 cast<ConstantInt>(CVA->getOperand(NumElts-1))->getZExtValue() == 0) { 980 O << MAI->getAscizDirective(); 981 printAsCString(O, CVA, NumElts-1); 982 } else { 983 O << MAI->getAsciiDirective(); 984 printAsCString(O, CVA, NumElts); 985 } 986 O << '\n'; 987} 988 989void AsmPrinter::EmitGlobalConstantArray(const ConstantArray *CVA, 990 unsigned AddrSpace) { 991 if (CVA->isString()) { 992 EmitString(CVA); 993 } else { // Not a string. Print the values in successive locations 994 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i) 995 EmitGlobalConstant(CVA->getOperand(i), AddrSpace); 996 } 997} 998 999void AsmPrinter::EmitGlobalConstantVector(const ConstantVector *CP) { 1000 const VectorType *PTy = CP->getType(); 1001 1002 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I) 1003 EmitGlobalConstant(CP->getOperand(I)); 1004} 1005 1006void AsmPrinter::EmitGlobalConstantStruct(const ConstantStruct *CVS, 1007 unsigned AddrSpace) { 1008 // Print the fields in successive locations. Pad to align if needed! 1009 const TargetData *TD = TM.getTargetData(); 1010 unsigned Size = TD->getTypeAllocSize(CVS->getType()); 1011 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType()); 1012 uint64_t sizeSoFar = 0; 1013 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) { 1014 const Constant* field = CVS->getOperand(i); 1015 1016 // Check if padding is needed and insert one or more 0s. 1017 uint64_t fieldSize = TD->getTypeAllocSize(field->getType()); 1018 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1)) 1019 - cvsLayout->getElementOffset(i)) - fieldSize; 1020 sizeSoFar += fieldSize + padSize; 1021 1022 // Now print the actual field value. 1023 EmitGlobalConstant(field, AddrSpace); 1024 1025 // Insert padding - this may include padding to increase the size of the 1026 // current field up to the ABI size (if the struct is not packed) as well 1027 // as padding to ensure that the next field starts at the right offset. 1028 EmitZeros(padSize, AddrSpace); 1029 } 1030 assert(sizeSoFar == cvsLayout->getSizeInBytes() && 1031 "Layout of constant struct may be incorrect!"); 1032} 1033 1034void AsmPrinter::EmitGlobalConstantFP(const ConstantFP *CFP, 1035 unsigned AddrSpace) { 1036 // FP Constants are printed as integer constants to avoid losing 1037 // precision... 1038 LLVMContext &Context = CFP->getContext(); 1039 const TargetData *TD = TM.getTargetData(); 1040 if (CFP->getType()->isDoubleTy()) { 1041 double Val = CFP->getValueAPF().convertToDouble(); // for comment only 1042 uint64_t i = CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 1043 if (MAI->getData64bitsDirective(AddrSpace)) { 1044 O << MAI->getData64bitsDirective(AddrSpace) << i; 1045 if (VerboseAsm) { 1046 O.PadToColumn(MAI->getCommentColumn()); 1047 O << MAI->getCommentString() << " double " << Val; 1048 } 1049 O << '\n'; 1050 } else if (TD->isBigEndian()) { 1051 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32); 1052 if (VerboseAsm) { 1053 O.PadToColumn(MAI->getCommentColumn()); 1054 O << MAI->getCommentString() 1055 << " most significant word of double " << Val; 1056 } 1057 O << '\n'; 1058 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i); 1059 if (VerboseAsm) { 1060 O.PadToColumn(MAI->getCommentColumn()); 1061 O << MAI->getCommentString() 1062 << " least significant word of double " << Val; 1063 } 1064 O << '\n'; 1065 } else { 1066 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i); 1067 if (VerboseAsm) { 1068 O.PadToColumn(MAI->getCommentColumn()); 1069 O << MAI->getCommentString() 1070 << " least significant word of double " << Val; 1071 } 1072 O << '\n'; 1073 O << MAI->getData32bitsDirective(AddrSpace) << unsigned(i >> 32); 1074 if (VerboseAsm) { 1075 O.PadToColumn(MAI->getCommentColumn()); 1076 O << MAI->getCommentString() 1077 << " most significant word of double " << Val; 1078 } 1079 O << '\n'; 1080 } 1081 return; 1082 } 1083 1084 if (CFP->getType()->isFloatTy()) { 1085 float Val = CFP->getValueAPF().convertToFloat(); // for comment only 1086 O << MAI->getData32bitsDirective(AddrSpace) 1087 << CFP->getValueAPF().bitcastToAPInt().getZExtValue(); 1088 if (VerboseAsm) { 1089 O.PadToColumn(MAI->getCommentColumn()); 1090 O << MAI->getCommentString() << " float " << Val; 1091 } 1092 O << '\n'; 1093 return; 1094 } 1095 1096 if (CFP->getType()->isX86_FP80Ty()) { 1097 // all long double variants are printed as hex 1098 // api needed to prevent premature destruction 1099 APInt api = CFP->getValueAPF().bitcastToAPInt(); 1100 const uint64_t *p = api.getRawData(); 1101 // Convert to double so we can print the approximate val as a comment. 1102 APFloat DoubleVal = CFP->getValueAPF(); 1103 bool ignored; 1104 DoubleVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 1105 &ignored); 1106 if (TD->isBigEndian()) { 1107 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]); 1108 if (VerboseAsm) { 1109 O.PadToColumn(MAI->getCommentColumn()); 1110 O << MAI->getCommentString() 1111 << " most significant halfword of x86_fp80 ~" 1112 << DoubleVal.convertToDouble(); 1113 } 1114 O << '\n'; 1115 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48); 1116 if (VerboseAsm) { 1117 O.PadToColumn(MAI->getCommentColumn()); 1118 O << MAI->getCommentString() << " next halfword"; 1119 } 1120 O << '\n'; 1121 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32); 1122 if (VerboseAsm) { 1123 O.PadToColumn(MAI->getCommentColumn()); 1124 O << MAI->getCommentString() << " next halfword"; 1125 } 1126 O << '\n'; 1127 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16); 1128 if (VerboseAsm) { 1129 O.PadToColumn(MAI->getCommentColumn()); 1130 O << MAI->getCommentString() << " next halfword"; 1131 } 1132 O << '\n'; 1133 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]); 1134 if (VerboseAsm) { 1135 O.PadToColumn(MAI->getCommentColumn()); 1136 O << MAI->getCommentString() 1137 << " least significant halfword"; 1138 } 1139 O << '\n'; 1140 } else { 1141 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0]); 1142 if (VerboseAsm) { 1143 O.PadToColumn(MAI->getCommentColumn()); 1144 O << MAI->getCommentString() 1145 << " least significant halfword of x86_fp80 ~" 1146 << DoubleVal.convertToDouble(); 1147 } 1148 O << '\n'; 1149 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 16); 1150 if (VerboseAsm) { 1151 O.PadToColumn(MAI->getCommentColumn()); 1152 O << MAI->getCommentString() 1153 << " next halfword"; 1154 } 1155 O << '\n'; 1156 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 32); 1157 if (VerboseAsm) { 1158 O.PadToColumn(MAI->getCommentColumn()); 1159 O << MAI->getCommentString() 1160 << " next halfword"; 1161 } 1162 O << '\n'; 1163 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[0] >> 48); 1164 if (VerboseAsm) { 1165 O.PadToColumn(MAI->getCommentColumn()); 1166 O << MAI->getCommentString() 1167 << " next halfword"; 1168 } 1169 O << '\n'; 1170 O << MAI->getData16bitsDirective(AddrSpace) << uint16_t(p[1]); 1171 if (VerboseAsm) { 1172 O.PadToColumn(MAI->getCommentColumn()); 1173 O << MAI->getCommentString() 1174 << " most significant halfword"; 1175 } 1176 O << '\n'; 1177 } 1178 EmitZeros(TD->getTypeAllocSize(Type::getX86_FP80Ty(Context)) - 1179 TD->getTypeStoreSize(Type::getX86_FP80Ty(Context)), AddrSpace); 1180 return; 1181 } 1182 1183 if (CFP->getType()->isPPC_FP128Ty()) { 1184 // all long double variants are printed as hex 1185 // api needed to prevent premature destruction 1186 APInt api = CFP->getValueAPF().bitcastToAPInt(); 1187 const uint64_t *p = api.getRawData(); 1188 if (TD->isBigEndian()) { 1189 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32); 1190 if (VerboseAsm) { 1191 O.PadToColumn(MAI->getCommentColumn()); 1192 O << MAI->getCommentString() 1193 << " most significant word of ppc_fp128"; 1194 } 1195 O << '\n'; 1196 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]); 1197 if (VerboseAsm) { 1198 O.PadToColumn(MAI->getCommentColumn()); 1199 O << MAI->getCommentString() 1200 << " next word"; 1201 } 1202 O << '\n'; 1203 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32); 1204 if (VerboseAsm) { 1205 O.PadToColumn(MAI->getCommentColumn()); 1206 O << MAI->getCommentString() 1207 << " next word"; 1208 } 1209 O << '\n'; 1210 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]); 1211 if (VerboseAsm) { 1212 O.PadToColumn(MAI->getCommentColumn()); 1213 O << MAI->getCommentString() 1214 << " least significant word"; 1215 } 1216 O << '\n'; 1217 } else { 1218 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1]); 1219 if (VerboseAsm) { 1220 O.PadToColumn(MAI->getCommentColumn()); 1221 O << MAI->getCommentString() 1222 << " least significant word of ppc_fp128"; 1223 } 1224 O << '\n'; 1225 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[1] >> 32); 1226 if (VerboseAsm) { 1227 O.PadToColumn(MAI->getCommentColumn()); 1228 O << MAI->getCommentString() 1229 << " next word"; 1230 } 1231 O << '\n'; 1232 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0]); 1233 if (VerboseAsm) { 1234 O.PadToColumn(MAI->getCommentColumn()); 1235 O << MAI->getCommentString() 1236 << " next word"; 1237 } 1238 O << '\n'; 1239 O << MAI->getData32bitsDirective(AddrSpace) << uint32_t(p[0] >> 32); 1240 if (VerboseAsm) { 1241 O.PadToColumn(MAI->getCommentColumn()); 1242 O << MAI->getCommentString() 1243 << " most significant word"; 1244 } 1245 O << '\n'; 1246 } 1247 return; 1248 } else llvm_unreachable("Floating point constant type not handled"); 1249} 1250 1251void AsmPrinter::EmitGlobalConstantLargeInt(const ConstantInt *CI, 1252 unsigned AddrSpace) { 1253 const TargetData *TD = TM.getTargetData(); 1254 unsigned BitWidth = CI->getBitWidth(); 1255 assert((BitWidth & 63) == 0 && "only support multiples of 64-bits"); 1256 1257 // We don't expect assemblers to support integer data directives 1258 // for more than 64 bits, so we emit the data in at most 64-bit 1259 // quantities at a time. 1260 const uint64_t *RawData = CI->getValue().getRawData(); 1261 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 1262 uint64_t Val; 1263 if (TD->isBigEndian()) 1264 Val = RawData[e - i - 1]; 1265 else 1266 Val = RawData[i]; 1267 1268 if (MAI->getData64bitsDirective(AddrSpace)) { 1269 O << MAI->getData64bitsDirective(AddrSpace) << Val << '\n'; 1270 continue; 1271 } 1272 1273 // Emit two 32-bit chunks, order depends on endianness. 1274 unsigned FirstChunk = unsigned(Val), SecondChunk = unsigned(Val >> 32); 1275 const char *FirstName = " least", *SecondName = " most"; 1276 if (TD->isBigEndian()) { 1277 std::swap(FirstChunk, SecondChunk); 1278 std::swap(FirstName, SecondName); 1279 } 1280 1281 O << MAI->getData32bitsDirective(AddrSpace) << FirstChunk; 1282 if (VerboseAsm) { 1283 O.PadToColumn(MAI->getCommentColumn()); 1284 O << MAI->getCommentString() 1285 << FirstName << " significant half of i64 " << Val; 1286 } 1287 O << '\n'; 1288 1289 O << MAI->getData32bitsDirective(AddrSpace) << SecondChunk; 1290 if (VerboseAsm) { 1291 O.PadToColumn(MAI->getCommentColumn()); 1292 O << MAI->getCommentString() 1293 << SecondName << " significant half of i64 " << Val; 1294 } 1295 O << '\n'; 1296 } 1297} 1298 1299/// EmitGlobalConstant - Print a general LLVM constant to the .s file. 1300void AsmPrinter::EmitGlobalConstant(const Constant *CV, unsigned AddrSpace) { 1301 const TargetData *TD = TM.getTargetData(); 1302 const Type *type = CV->getType(); 1303 unsigned Size = TD->getTypeAllocSize(type); 1304 1305 if (CV->isNullValue() || isa<UndefValue>(CV)) { 1306 EmitZeros(Size, AddrSpace); 1307 return; 1308 } 1309 1310 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) { 1311 EmitGlobalConstantArray(CVA , AddrSpace); 1312 return; 1313 } 1314 1315 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) { 1316 EmitGlobalConstantStruct(CVS, AddrSpace); 1317 return; 1318 } 1319 1320 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) { 1321 EmitGlobalConstantFP(CFP, AddrSpace); 1322 return; 1323 } 1324 1325 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1326 // If we can directly emit an 8-byte constant, do it. 1327 if (Size == 8) 1328 if (const char *Data64Dir = MAI->getData64bitsDirective(AddrSpace)) { 1329 O << Data64Dir << CI->getZExtValue() << '\n'; 1330 return; 1331 } 1332 1333 // Small integers are handled below; large integers are handled here. 1334 if (Size > 4) { 1335 EmitGlobalConstantLargeInt(CI, AddrSpace); 1336 return; 1337 } 1338 } 1339 1340 if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) { 1341 EmitGlobalConstantVector(CP); 1342 return; 1343 } 1344 1345 printDataDirective(type, AddrSpace); 1346 EmitConstantValueOnly(CV); 1347 if (VerboseAsm) { 1348 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 1349 SmallString<40> S; 1350 CI->getValue().toStringUnsigned(S, 16); 1351 O.PadToColumn(MAI->getCommentColumn()); 1352 O << MAI->getCommentString() << " 0x" << S.str(); 1353 } 1354 } 1355 O << '\n'; 1356} 1357 1358void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 1359 // Target doesn't support this yet! 1360 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 1361} 1362 1363/// PrintSpecial - Print information related to the specified machine instr 1364/// that is independent of the operand, and may be independent of the instr 1365/// itself. This can be useful for portably encoding the comment character 1366/// or other bits of target-specific knowledge into the asmstrings. The 1367/// syntax used is ${:comment}. Targets can override this to add support 1368/// for their own strange codes. 1369void AsmPrinter::PrintSpecial(const MachineInstr *MI, const char *Code) const { 1370 if (!strcmp(Code, "private")) { 1371 O << MAI->getPrivateGlobalPrefix(); 1372 } else if (!strcmp(Code, "comment")) { 1373 if (VerboseAsm) 1374 O << MAI->getCommentString(); 1375 } else if (!strcmp(Code, "uid")) { 1376 // Comparing the address of MI isn't sufficient, because machineinstrs may 1377 // be allocated to the same address across functions. 1378 const Function *ThisF = MI->getParent()->getParent()->getFunction(); 1379 1380 // If this is a new LastFn instruction, bump the counter. 1381 if (LastMI != MI || LastFn != ThisF) { 1382 ++Counter; 1383 LastMI = MI; 1384 LastFn = ThisF; 1385 } 1386 O << Counter; 1387 } else { 1388 std::string msg; 1389 raw_string_ostream Msg(msg); 1390 Msg << "Unknown special formatter '" << Code 1391 << "' for machine instr: " << *MI; 1392 llvm_report_error(Msg.str()); 1393 } 1394} 1395 1396/// processDebugLoc - Processes the debug information of each machine 1397/// instruction's DebugLoc. 1398void AsmPrinter::processDebugLoc(const MachineInstr *MI, 1399 bool BeforePrintingInsn) { 1400 if (!MAI || !DW || !MAI->doesSupportDebugInformation() 1401 || !DW->ShouldEmitDwarfDebug()) 1402 return; 1403 DebugLoc DL = MI->getDebugLoc(); 1404 if (DL.isUnknown()) 1405 return; 1406 DILocation CurDLT = MF->getDILocation(DL); 1407 if (CurDLT.getScope().isNull()) 1408 return; 1409 1410 if (BeforePrintingInsn) { 1411 if (CurDLT.getNode() != PrevDLT.getNode()) { 1412 unsigned L = DW->RecordSourceLine(CurDLT.getLineNumber(), 1413 CurDLT.getColumnNumber(), 1414 CurDLT.getScope().getNode()); 1415 printLabel(L); 1416 O << '\n'; 1417 DW->BeginScope(MI, L); 1418 PrevDLT = CurDLT; 1419 } 1420 } else { 1421 // After printing instruction 1422 DW->EndScope(MI); 1423 } 1424} 1425 1426 1427/// printInlineAsm - This method formats and prints the specified machine 1428/// instruction that is an inline asm. 1429void AsmPrinter::printInlineAsm(const MachineInstr *MI) const { 1430 unsigned NumOperands = MI->getNumOperands(); 1431 1432 // Count the number of register definitions. 1433 unsigned NumDefs = 0; 1434 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef(); 1435 ++NumDefs) 1436 assert(NumDefs != NumOperands-1 && "No asm string?"); 1437 1438 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?"); 1439 1440 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc. 1441 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName(); 1442 1443 O << '\t'; 1444 1445 // If this asmstr is empty, just print the #APP/#NOAPP markers. 1446 // These are useful to see where empty asm's wound up. 1447 if (AsmStr[0] == 0) { 1448 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t"; 1449 O << MAI->getCommentString() << MAI->getInlineAsmEnd() << '\n'; 1450 return; 1451 } 1452 1453 O << MAI->getCommentString() << MAI->getInlineAsmStart() << "\n\t"; 1454 1455 // The variant of the current asmprinter. 1456 int AsmPrinterVariant = MAI->getAssemblerDialect(); 1457 1458 int CurVariant = -1; // The number of the {.|.|.} region we are in. 1459 const char *LastEmitted = AsmStr; // One past the last character emitted. 1460 1461 while (*LastEmitted) { 1462 switch (*LastEmitted) { 1463 default: { 1464 // Not a special case, emit the string section literally. 1465 const char *LiteralEnd = LastEmitted+1; 1466 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' && 1467 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n') 1468 ++LiteralEnd; 1469 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) 1470 O.write(LastEmitted, LiteralEnd-LastEmitted); 1471 LastEmitted = LiteralEnd; 1472 break; 1473 } 1474 case '\n': 1475 ++LastEmitted; // Consume newline character. 1476 O << '\n'; // Indent code with newline. 1477 break; 1478 case '$': { 1479 ++LastEmitted; // Consume '$' character. 1480 bool Done = true; 1481 1482 // Handle escapes. 1483 switch (*LastEmitted) { 1484 default: Done = false; break; 1485 case '$': // $$ -> $ 1486 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) 1487 O << '$'; 1488 ++LastEmitted; // Consume second '$' character. 1489 break; 1490 case '(': // $( -> same as GCC's { character. 1491 ++LastEmitted; // Consume '(' character. 1492 if (CurVariant != -1) { 1493 llvm_report_error("Nested variants found in inline asm string: '" 1494 + std::string(AsmStr) + "'"); 1495 } 1496 CurVariant = 0; // We're in the first variant now. 1497 break; 1498 case '|': 1499 ++LastEmitted; // consume '|' character. 1500 if (CurVariant == -1) 1501 O << '|'; // this is gcc's behavior for | outside a variant 1502 else 1503 ++CurVariant; // We're in the next variant. 1504 break; 1505 case ')': // $) -> same as GCC's } char. 1506 ++LastEmitted; // consume ')' character. 1507 if (CurVariant == -1) 1508 O << '}'; // this is gcc's behavior for } outside a variant 1509 else 1510 CurVariant = -1; 1511 break; 1512 } 1513 if (Done) break; 1514 1515 bool HasCurlyBraces = false; 1516 if (*LastEmitted == '{') { // ${variable} 1517 ++LastEmitted; // Consume '{' character. 1518 HasCurlyBraces = true; 1519 } 1520 1521 // If we have ${:foo}, then this is not a real operand reference, it is a 1522 // "magic" string reference, just like in .td files. Arrange to call 1523 // PrintSpecial. 1524 if (HasCurlyBraces && *LastEmitted == ':') { 1525 ++LastEmitted; 1526 const char *StrStart = LastEmitted; 1527 const char *StrEnd = strchr(StrStart, '}'); 1528 if (StrEnd == 0) { 1529 llvm_report_error("Unterminated ${:foo} operand in inline asm string: '" 1530 + std::string(AsmStr) + "'"); 1531 } 1532 1533 std::string Val(StrStart, StrEnd); 1534 PrintSpecial(MI, Val.c_str()); 1535 LastEmitted = StrEnd+1; 1536 break; 1537 } 1538 1539 const char *IDStart = LastEmitted; 1540 char *IDEnd; 1541 errno = 0; 1542 long Val = strtol(IDStart, &IDEnd, 10); // We only accept numbers for IDs. 1543 if (!isdigit(*IDStart) || (Val == 0 && errno == EINVAL)) { 1544 llvm_report_error("Bad $ operand number in inline asm string: '" 1545 + std::string(AsmStr) + "'"); 1546 } 1547 LastEmitted = IDEnd; 1548 1549 char Modifier[2] = { 0, 0 }; 1550 1551 if (HasCurlyBraces) { 1552 // If we have curly braces, check for a modifier character. This 1553 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm. 1554 if (*LastEmitted == ':') { 1555 ++LastEmitted; // Consume ':' character. 1556 if (*LastEmitted == 0) { 1557 llvm_report_error("Bad ${:} expression in inline asm string: '" 1558 + std::string(AsmStr) + "'"); 1559 } 1560 1561 Modifier[0] = *LastEmitted; 1562 ++LastEmitted; // Consume modifier character. 1563 } 1564 1565 if (*LastEmitted != '}') { 1566 llvm_report_error("Bad ${} expression in inline asm string: '" 1567 + std::string(AsmStr) + "'"); 1568 } 1569 ++LastEmitted; // Consume '}' character. 1570 } 1571 1572 if ((unsigned)Val >= NumOperands-1) { 1573 llvm_report_error("Invalid $ operand number in inline asm string: '" 1574 + std::string(AsmStr) + "'"); 1575 } 1576 1577 // Okay, we finally have a value number. Ask the target to print this 1578 // operand! 1579 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) { 1580 unsigned OpNo = 1; 1581 1582 bool Error = false; 1583 1584 // Scan to find the machine operand number for the operand. 1585 for (; Val; --Val) { 1586 if (OpNo >= MI->getNumOperands()) break; 1587 unsigned OpFlags = MI->getOperand(OpNo).getImm(); 1588 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1; 1589 } 1590 1591 if (OpNo >= MI->getNumOperands()) { 1592 Error = true; 1593 } else { 1594 unsigned OpFlags = MI->getOperand(OpNo).getImm(); 1595 ++OpNo; // Skip over the ID number. 1596 1597 if (Modifier[0]=='l') // labels are target independent 1598 GetMBBSymbol(MI->getOperand(OpNo).getMBB() 1599 ->getNumber())->print(O, MAI); 1600 else { 1601 AsmPrinter *AP = const_cast<AsmPrinter*>(this); 1602 if ((OpFlags & 7) == 4) { 1603 Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant, 1604 Modifier[0] ? Modifier : 0); 1605 } else { 1606 Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant, 1607 Modifier[0] ? Modifier : 0); 1608 } 1609 } 1610 } 1611 if (Error) { 1612 std::string msg; 1613 raw_string_ostream Msg(msg); 1614 Msg << "Invalid operand found in inline asm: '" 1615 << AsmStr << "'\n"; 1616 MI->print(Msg); 1617 llvm_report_error(Msg.str()); 1618 } 1619 } 1620 break; 1621 } 1622 } 1623 } 1624 O << "\n\t" << MAI->getCommentString() << MAI->getInlineAsmEnd(); 1625} 1626 1627/// printImplicitDef - This method prints the specified machine instruction 1628/// that is an implicit def. 1629void AsmPrinter::printImplicitDef(const MachineInstr *MI) const { 1630 if (!VerboseAsm) return; 1631 O.PadToColumn(MAI->getCommentColumn()); 1632 O << MAI->getCommentString() << " implicit-def: " 1633 << TRI->getName(MI->getOperand(0).getReg()); 1634} 1635 1636void AsmPrinter::printKill(const MachineInstr *MI) const { 1637 if (!VerboseAsm) return; 1638 O.PadToColumn(MAI->getCommentColumn()); 1639 O << MAI->getCommentString() << " kill:"; 1640 for (unsigned n = 0, e = MI->getNumOperands(); n != e; ++n) { 1641 const MachineOperand &op = MI->getOperand(n); 1642 assert(op.isReg() && "KILL instruction must have only register operands"); 1643 O << ' ' << TRI->getName(op.getReg()) << (op.isDef() ? "<def>" : "<kill>"); 1644 } 1645} 1646 1647/// printLabel - This method prints a local label used by debug and 1648/// exception handling tables. 1649void AsmPrinter::printLabel(const MachineInstr *MI) const { 1650 printLabel(MI->getOperand(0).getImm()); 1651} 1652 1653void AsmPrinter::printLabel(unsigned Id) const { 1654 O << MAI->getPrivateGlobalPrefix() << "label" << Id << ':'; 1655} 1656 1657/// PrintAsmOperand - Print the specified operand of MI, an INLINEASM 1658/// instruction, using the specified assembler variant. Targets should 1659/// override this to format as appropriate. 1660bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1661 unsigned AsmVariant, const char *ExtraCode) { 1662 // Target doesn't support this yet! 1663 return true; 1664} 1665 1666bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo, 1667 unsigned AsmVariant, 1668 const char *ExtraCode) { 1669 // Target doesn't support this yet! 1670 return true; 1671} 1672 1673MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA, 1674 const char *Suffix) const { 1675 return GetBlockAddressSymbol(BA->getFunction(), BA->getBasicBlock(), Suffix); 1676} 1677 1678MCSymbol *AsmPrinter::GetBlockAddressSymbol(const Function *F, 1679 const BasicBlock *BB, 1680 const char *Suffix) const { 1681 assert(BB->hasName() && 1682 "Address of anonymous basic block not supported yet!"); 1683 1684 // This code must use the function name itself, and not the function number, 1685 // since it must be possible to generate the label name from within other 1686 // functions. 1687 SmallString<60> FnName; 1688 Mang->getNameWithPrefix(FnName, F, false); 1689 1690 // FIXME: THIS IS BROKEN IF THE LLVM BASIC BLOCK DOESN'T HAVE A NAME! 1691 SmallString<60> NameResult; 1692 Mang->getNameWithPrefix(NameResult, 1693 StringRef("BA") + Twine((unsigned)FnName.size()) + 1694 "_" + FnName.str() + "_" + BB->getName() + Suffix, 1695 Mangler::Private); 1696 1697 return OutContext.GetOrCreateSymbol(NameResult.str()); 1698} 1699 1700MCSymbol *AsmPrinter::GetMBBSymbol(unsigned MBBID) const { 1701 SmallString<60> Name; 1702 raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "BB" 1703 << getFunctionNumber() << '_' << MBBID; 1704 1705 return OutContext.GetOrCreateSymbol(Name.str()); 1706} 1707 1708/// GetGlobalValueSymbol - Return the MCSymbol for the specified global 1709/// value. 1710MCSymbol *AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const { 1711 SmallString<60> NameStr; 1712 Mang->getNameWithPrefix(NameStr, GV, false); 1713 return OutContext.GetOrCreateSymbol(NameStr.str()); 1714} 1715 1716/// GetSymbolWithGlobalValueBase - Return the MCSymbol for a symbol with 1717/// global value name as its base, with the specified suffix, and where the 1718/// symbol is forced to have private linkage if ForcePrivate is true. 1719MCSymbol *AsmPrinter::GetSymbolWithGlobalValueBase(const GlobalValue *GV, 1720 StringRef Suffix, 1721 bool ForcePrivate) const { 1722 SmallString<60> NameStr; 1723 Mang->getNameWithPrefix(NameStr, GV, ForcePrivate); 1724 NameStr.append(Suffix.begin(), Suffix.end()); 1725 return OutContext.GetOrCreateSymbol(NameStr.str()); 1726} 1727 1728/// GetExternalSymbolSymbol - Return the MCSymbol for the specified 1729/// ExternalSymbol. 1730MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 1731 SmallString<60> NameStr; 1732 Mang->getNameWithPrefix(NameStr, Sym); 1733 return OutContext.GetOrCreateSymbol(NameStr.str()); 1734} 1735 1736 1737/// EmitBasicBlockStart - This method prints the label for the specified 1738/// MachineBasicBlock, an alignment (if present) and a comment describing 1739/// it if appropriate. 1740void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock *MBB) const { 1741 // Emit an alignment directive for this block, if needed. 1742 if (unsigned Align = MBB->getAlignment()) 1743 EmitAlignment(Log2_32(Align)); 1744 1745 // If the block has its address taken, emit a special label to satisfy 1746 // references to the block. This is done so that we don't need to 1747 // remember the number of this label, and so that we can make 1748 // forward references to labels without knowing what their numbers 1749 // will be. 1750 if (MBB->hasAddressTaken()) { 1751 GetBlockAddressSymbol(MBB->getBasicBlock()->getParent(), 1752 MBB->getBasicBlock())->print(O, MAI); 1753 O << ':'; 1754 if (VerboseAsm) { 1755 O.PadToColumn(MAI->getCommentColumn()); 1756 O << MAI->getCommentString() << " Address Taken"; 1757 } 1758 O << '\n'; 1759 } 1760 1761 // Print the main label for the block. 1762 if (MBB->pred_empty() || MBB->isOnlyReachableByFallthrough()) { 1763 if (VerboseAsm) 1764 O << MAI->getCommentString() << " BB#" << MBB->getNumber() << ':'; 1765 } else { 1766 GetMBBSymbol(MBB->getNumber())->print(O, MAI); 1767 O << ':'; 1768 if (!VerboseAsm) 1769 O << '\n'; 1770 } 1771 1772 // Print some comments to accompany the label. 1773 if (VerboseAsm) { 1774 if (const BasicBlock *BB = MBB->getBasicBlock()) 1775 if (BB->hasName()) { 1776 O.PadToColumn(MAI->getCommentColumn()); 1777 O << MAI->getCommentString() << ' '; 1778 WriteAsOperand(O, BB, /*PrintType=*/false); 1779 } 1780 1781 EmitComments(*MBB); 1782 O << '\n'; 1783 } 1784} 1785 1786/// printPICJumpTableSetLabel - This method prints a set label for the 1787/// specified MachineBasicBlock for a jumptable entry. 1788void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, 1789 const MachineBasicBlock *MBB) const { 1790 if (!MAI->getSetDirective()) 1791 return; 1792 1793 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix() 1794 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ','; 1795 GetMBBSymbol(MBB->getNumber())->print(O, MAI); 1796 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 1797 << '_' << uid << '\n'; 1798} 1799 1800void AsmPrinter::printPICJumpTableSetLabel(unsigned uid, unsigned uid2, 1801 const MachineBasicBlock *MBB) const { 1802 if (!MAI->getSetDirective()) 1803 return; 1804 1805 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix() 1806 << getFunctionNumber() << '_' << uid << '_' << uid2 1807 << "_set_" << MBB->getNumber() << ','; 1808 GetMBBSymbol(MBB->getNumber())->print(O, MAI); 1809 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() 1810 << '_' << uid << '_' << uid2 << '\n'; 1811} 1812 1813/// printDataDirective - This method prints the asm directive for the 1814/// specified type. 1815void AsmPrinter::printDataDirective(const Type *type, unsigned AddrSpace) { 1816 const TargetData *TD = TM.getTargetData(); 1817 switch (type->getTypeID()) { 1818 case Type::FloatTyID: case Type::DoubleTyID: 1819 case Type::X86_FP80TyID: case Type::FP128TyID: case Type::PPC_FP128TyID: 1820 assert(0 && "Should have already output floating point constant."); 1821 default: 1822 assert(0 && "Can't handle printing this type of thing"); 1823 case Type::IntegerTyID: { 1824 unsigned BitWidth = cast<IntegerType>(type)->getBitWidth(); 1825 if (BitWidth <= 8) 1826 O << MAI->getData8bitsDirective(AddrSpace); 1827 else if (BitWidth <= 16) 1828 O << MAI->getData16bitsDirective(AddrSpace); 1829 else if (BitWidth <= 32) 1830 O << MAI->getData32bitsDirective(AddrSpace); 1831 else if (BitWidth <= 64) { 1832 assert(MAI->getData64bitsDirective(AddrSpace) && 1833 "Target cannot handle 64-bit constant exprs!"); 1834 O << MAI->getData64bitsDirective(AddrSpace); 1835 } else { 1836 llvm_unreachable("Target cannot handle given data directive width!"); 1837 } 1838 break; 1839 } 1840 case Type::PointerTyID: 1841 if (TD->getPointerSize() == 8) { 1842 assert(MAI->getData64bitsDirective(AddrSpace) && 1843 "Target cannot handle 64-bit pointer exprs!"); 1844 O << MAI->getData64bitsDirective(AddrSpace); 1845 } else if (TD->getPointerSize() == 2) { 1846 O << MAI->getData16bitsDirective(AddrSpace); 1847 } else if (TD->getPointerSize() == 1) { 1848 O << MAI->getData8bitsDirective(AddrSpace); 1849 } else { 1850 O << MAI->getData32bitsDirective(AddrSpace); 1851 } 1852 break; 1853 } 1854} 1855 1856void AsmPrinter::printVisibility(const MCSymbol *Sym, 1857 unsigned Visibility) const { 1858 if (Visibility == GlobalValue::HiddenVisibility) { 1859 if (const char *Directive = MAI->getHiddenDirective()) { 1860 O << Directive; 1861 Sym->print(O, MAI); 1862 O << '\n'; 1863 } 1864 } else if (Visibility == GlobalValue::ProtectedVisibility) { 1865 if (const char *Directive = MAI->getProtectedDirective()) { 1866 O << Directive; 1867 Sym->print(O, MAI); 1868 O << '\n'; 1869 } 1870 } 1871} 1872 1873void AsmPrinter::printOffset(int64_t Offset) const { 1874 if (Offset > 0) 1875 O << '+' << Offset; 1876 else if (Offset < 0) 1877 O << Offset; 1878} 1879 1880GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy *S) { 1881 if (!S->usesMetadata()) 1882 return 0; 1883 1884 gcp_iterator GCPI = GCMetadataPrinters.find(S); 1885 if (GCPI != GCMetadataPrinters.end()) 1886 return GCPI->second; 1887 1888 const char *Name = S->getName().c_str(); 1889 1890 for (GCMetadataPrinterRegistry::iterator 1891 I = GCMetadataPrinterRegistry::begin(), 1892 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 1893 if (strcmp(Name, I->getName()) == 0) { 1894 GCMetadataPrinter *GMP = I->instantiate(); 1895 GMP->S = S; 1896 GCMetadataPrinters.insert(std::make_pair(S, GMP)); 1897 return GMP; 1898 } 1899 1900 errs() << "no GCMetadataPrinter registered for GC: " << Name << "\n"; 1901 llvm_unreachable(0); 1902} 1903 1904/// EmitComments - Pretty-print comments for instructions 1905void AsmPrinter::EmitComments(const MachineInstr &MI) const { 1906 if (!VerboseAsm) 1907 return; 1908 1909 bool Newline = false; 1910 1911 if (!MI.getDebugLoc().isUnknown()) { 1912 DILocation DLT = MF->getDILocation(MI.getDebugLoc()); 1913 1914 // Print source line info. 1915 O.PadToColumn(MAI->getCommentColumn()); 1916 O << MAI->getCommentString() << ' '; 1917 DIScope Scope = DLT.getScope(); 1918 // Omit the directory, because it's likely to be long and uninteresting. 1919 if (!Scope.isNull()) 1920 O << Scope.getFilename(); 1921 else 1922 O << "<unknown>"; 1923 O << ':' << DLT.getLineNumber(); 1924 if (DLT.getColumnNumber() != 0) 1925 O << ':' << DLT.getColumnNumber(); 1926 Newline = true; 1927 } 1928 1929 // Check for spills and reloads 1930 int FI; 1931 1932 const MachineFrameInfo *FrameInfo = 1933 MI.getParent()->getParent()->getFrameInfo(); 1934 1935 // We assume a single instruction only has a spill or reload, not 1936 // both. 1937 const MachineMemOperand *MMO; 1938 if (TM.getInstrInfo()->isLoadFromStackSlotPostFE(&MI, FI)) { 1939 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1940 MMO = *MI.memoperands_begin(); 1941 if (Newline) O << '\n'; 1942 O.PadToColumn(MAI->getCommentColumn()); 1943 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Reload"; 1944 Newline = true; 1945 } 1946 } 1947 else if (TM.getInstrInfo()->hasLoadFromStackSlot(&MI, MMO, FI)) { 1948 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1949 if (Newline) O << '\n'; 1950 O.PadToColumn(MAI->getCommentColumn()); 1951 O << MAI->getCommentString() << ' ' 1952 << MMO->getSize() << "-byte Folded Reload"; 1953 Newline = true; 1954 } 1955 } 1956 else if (TM.getInstrInfo()->isStoreToStackSlotPostFE(&MI, FI)) { 1957 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1958 MMO = *MI.memoperands_begin(); 1959 if (Newline) O << '\n'; 1960 O.PadToColumn(MAI->getCommentColumn()); 1961 O << MAI->getCommentString() << ' ' << MMO->getSize() << "-byte Spill"; 1962 Newline = true; 1963 } 1964 } 1965 else if (TM.getInstrInfo()->hasStoreToStackSlot(&MI, MMO, FI)) { 1966 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 1967 if (Newline) O << '\n'; 1968 O.PadToColumn(MAI->getCommentColumn()); 1969 O << MAI->getCommentString() << ' ' 1970 << MMO->getSize() << "-byte Folded Spill"; 1971 Newline = true; 1972 } 1973 } 1974 1975 // Check for spill-induced copies 1976 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx; 1977 if (TM.getInstrInfo()->isMoveInstr(MI, SrcReg, DstReg, 1978 SrcSubIdx, DstSubIdx)) { 1979 if (MI.getAsmPrinterFlag(ReloadReuse)) { 1980 if (Newline) O << '\n'; 1981 O.PadToColumn(MAI->getCommentColumn()); 1982 O << MAI->getCommentString() << " Reload Reuse"; 1983 } 1984 } 1985} 1986 1987/// PrintChildLoopComment - Print comments about child loops within 1988/// the loop for this basic block, with nesting. 1989/// 1990static void PrintChildLoopComment(formatted_raw_ostream &O, 1991 const MachineLoop *loop, 1992 const MCAsmInfo *MAI, 1993 int FunctionNumber) { 1994 // Add child loop information 1995 for(MachineLoop::iterator cl = loop->begin(), 1996 clend = loop->end(); 1997 cl != clend; 1998 ++cl) { 1999 MachineBasicBlock *Header = (*cl)->getHeader(); 2000 assert(Header && "No header for loop"); 2001 2002 O << '\n'; 2003 O.PadToColumn(MAI->getCommentColumn()); 2004 2005 O << MAI->getCommentString(); 2006 O.indent(((*cl)->getLoopDepth()-1)*2) 2007 << " Child Loop BB" << FunctionNumber << "_" 2008 << Header->getNumber() << " Depth " << (*cl)->getLoopDepth(); 2009 2010 PrintChildLoopComment(O, *cl, MAI, FunctionNumber); 2011 } 2012} 2013 2014/// EmitComments - Pretty-print comments for basic blocks 2015void AsmPrinter::EmitComments(const MachineBasicBlock &MBB) const { 2016 if (VerboseAsm) { 2017 // Add loop depth information 2018 const MachineLoop *loop = LI->getLoopFor(&MBB); 2019 2020 if (loop) { 2021 // Print a newline after bb# annotation. 2022 O << "\n"; 2023 O.PadToColumn(MAI->getCommentColumn()); 2024 O << MAI->getCommentString() << " Loop Depth " << loop->getLoopDepth() 2025 << '\n'; 2026 2027 O.PadToColumn(MAI->getCommentColumn()); 2028 2029 MachineBasicBlock *Header = loop->getHeader(); 2030 assert(Header && "No header for loop"); 2031 2032 if (Header == &MBB) { 2033 O << MAI->getCommentString() << " Loop Header"; 2034 PrintChildLoopComment(O, loop, MAI, getFunctionNumber()); 2035 } 2036 else { 2037 O << MAI->getCommentString() << " Loop Header is BB" 2038 << getFunctionNumber() << "_" << loop->getHeader()->getNumber(); 2039 } 2040 2041 if (loop->empty()) { 2042 O << '\n'; 2043 O.PadToColumn(MAI->getCommentColumn()); 2044 O << MAI->getCommentString() << " Inner Loop"; 2045 } 2046 2047 // Add parent loop information 2048 for (const MachineLoop *CurLoop = loop->getParentLoop(); 2049 CurLoop; 2050 CurLoop = CurLoop->getParentLoop()) { 2051 MachineBasicBlock *Header = CurLoop->getHeader(); 2052 assert(Header && "No header for loop"); 2053 2054 O << '\n'; 2055 O.PadToColumn(MAI->getCommentColumn()); 2056 O << MAI->getCommentString(); 2057 O.indent((CurLoop->getLoopDepth()-1)*2) 2058 << " Inside Loop BB" << getFunctionNumber() << "_" 2059 << Header->getNumber() << " Depth " << CurLoop->getLoopDepth(); 2060 } 2061 } 2062 } 2063} 2064