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