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