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 "CodeViewDebug.h" 16 #include "DwarfDebug.h" 17 #include "DwarfException.h" 18 #include "WinException.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/Analysis/ConstantFolding.h" 21 #include "llvm/CodeGen/Analysis.h" 22 #include "llvm/CodeGen/GCMetadataPrinter.h" 23 #include "llvm/CodeGen/MachineConstantPool.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBundle.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineLoopInfo.h" 29 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 30 #include "llvm/IR/DataLayout.h" 31 #include "llvm/IR/DebugInfo.h" 32 #include "llvm/IR/Mangler.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/Operator.h" 35 #include "llvm/MC/MCAsmInfo.h" 36 #include "llvm/MC/MCContext.h" 37 #include "llvm/MC/MCExpr.h" 38 #include "llvm/MC/MCInst.h" 39 #include "llvm/MC/MCSection.h" 40 #include "llvm/MC/MCStreamer.h" 41 #include "llvm/MC/MCSymbolELF.h" 42 #include "llvm/MC/MCValue.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/Format.h" 45 #include "llvm/Support/MathExtras.h" 46 #include "llvm/Support/TargetRegistry.h" 47 #include "llvm/Support/Timer.h" 48 #include "llvm/Target/TargetFrameLowering.h" 49 #include "llvm/Target/TargetInstrInfo.h" 50 #include "llvm/Target/TargetLowering.h" 51 #include "llvm/Target/TargetLoweringObjectFile.h" 52 #include "llvm/Target/TargetRegisterInfo.h" 53 #include "llvm/Target/TargetSubtargetInfo.h" 54 using namespace llvm; 55 56 #define DEBUG_TYPE "asm-printer" 57 58 static const char *const DWARFGroupName = "DWARF Emission"; 59 static const char *const DbgTimerName = "Debug Info Emission"; 60 static const char *const EHTimerName = "DWARF Exception Writer"; 61 static const char *const CodeViewLineTablesGroupName = "CodeView Line Tables"; 62 63 STATISTIC(EmittedInsts, "Number of machine instrs printed"); 64 65 char AsmPrinter::ID = 0; 66 67 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type; 68 static gcp_map_type &getGCMap(void *&P) { 69 if (!P) 70 P = new gcp_map_type(); 71 return *(gcp_map_type*)P; 72 } 73 74 75 /// getGVAlignmentLog2 - Return the alignment to use for the specified global 76 /// value in log2 form. This rounds up to the preferred alignment if possible 77 /// and legal. 78 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL, 79 unsigned InBits = 0) { 80 unsigned NumBits = 0; 81 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 82 NumBits = DL.getPreferredAlignmentLog(GVar); 83 84 // If InBits is specified, round it to it. 85 if (InBits > NumBits) 86 NumBits = InBits; 87 88 // If the GV has a specified alignment, take it into account. 89 if (GV->getAlignment() == 0) 90 return NumBits; 91 92 unsigned GVAlign = Log2_32(GV->getAlignment()); 93 94 // If the GVAlign is larger than NumBits, or if we are required to obey 95 // NumBits because the GV has an assigned section, obey it. 96 if (GVAlign > NumBits || GV->hasSection()) 97 NumBits = GVAlign; 98 return NumBits; 99 } 100 101 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer) 102 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()), 103 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)), 104 LastMI(nullptr), LastFn(0), Counter(~0U) { 105 DD = nullptr; 106 MMI = nullptr; 107 LI = nullptr; 108 MF = nullptr; 109 CurExceptionSym = CurrentFnSym = CurrentFnSymForSize = nullptr; 110 CurrentFnBegin = nullptr; 111 CurrentFnEnd = nullptr; 112 GCMetadataPrinters = nullptr; 113 VerboseAsm = OutStreamer->isVerboseAsm(); 114 } 115 116 AsmPrinter::~AsmPrinter() { 117 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized"); 118 119 if (GCMetadataPrinters) { 120 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 121 122 delete &GCMap; 123 GCMetadataPrinters = nullptr; 124 } 125 } 126 127 bool AsmPrinter::isPositionIndependent() const { 128 return TM.isPositionIndependent(); 129 } 130 131 /// getFunctionNumber - Return a unique ID for the current function. 132 /// 133 unsigned AsmPrinter::getFunctionNumber() const { 134 return MF->getFunctionNumber(); 135 } 136 137 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 138 return *TM.getObjFileLowering(); 139 } 140 141 const DataLayout &AsmPrinter::getDataLayout() const { 142 return MMI->getModule()->getDataLayout(); 143 } 144 145 // Do not use the cached DataLayout because some client use it without a Module 146 // (llmv-dsymutil, llvm-dwarfdump). 147 unsigned AsmPrinter::getPointerSize() const { return TM.getPointerSize(); } 148 149 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const { 150 assert(MF && "getSubtargetInfo requires a valid MachineFunction!"); 151 return MF->getSubtarget<MCSubtargetInfo>(); 152 } 153 154 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) { 155 S.EmitInstruction(Inst, getSubtargetInfo()); 156 } 157 158 StringRef AsmPrinter::getTargetTriple() const { 159 return TM.getTargetTriple().str(); 160 } 161 162 /// getCurrentSection() - Return the current section we are emitting to. 163 const MCSection *AsmPrinter::getCurrentSection() const { 164 return OutStreamer->getCurrentSection().first; 165 } 166 167 168 169 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 170 AU.setPreservesAll(); 171 MachineFunctionPass::getAnalysisUsage(AU); 172 AU.addRequired<MachineModuleInfo>(); 173 AU.addRequired<GCModuleInfo>(); 174 if (isVerbose()) 175 AU.addRequired<MachineLoopInfo>(); 176 } 177 178 bool AsmPrinter::doInitialization(Module &M) { 179 MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 180 181 // Initialize TargetLoweringObjectFile. 182 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 183 .Initialize(OutContext, TM); 184 185 OutStreamer->InitSections(false); 186 187 Mang = new Mangler(); 188 189 // Emit the version-min deplyment target directive if needed. 190 // 191 // FIXME: If we end up with a collection of these sorts of Darwin-specific 192 // or ELF-specific things, it may make sense to have a platform helper class 193 // that will work with the target helper class. For now keep it here, as the 194 // alternative is duplicated code in each of the target asm printers that 195 // use the directive, where it would need the same conditionalization 196 // anyway. 197 Triple TT(getTargetTriple()); 198 // If there is a version specified, Major will be non-zero. 199 if (TT.isOSDarwin() && TT.getOSMajorVersion() != 0) { 200 unsigned Major, Minor, Update; 201 MCVersionMinType VersionType; 202 if (TT.isWatchOS()) { 203 VersionType = MCVM_WatchOSVersionMin; 204 TT.getWatchOSVersion(Major, Minor, Update); 205 } else if (TT.isTvOS()) { 206 VersionType = MCVM_TvOSVersionMin; 207 TT.getiOSVersion(Major, Minor, Update); 208 } else if (TT.isMacOSX()) { 209 VersionType = MCVM_OSXVersionMin; 210 if (!TT.getMacOSXVersion(Major, Minor, Update)) 211 Major = 0; 212 } else { 213 VersionType = MCVM_IOSVersionMin; 214 TT.getiOSVersion(Major, Minor, Update); 215 } 216 if (Major != 0) 217 OutStreamer->EmitVersionMin(VersionType, Major, Minor, Update); 218 } 219 220 // Allow the target to emit any magic that it wants at the start of the file. 221 EmitStartOfAsmFile(M); 222 223 // Very minimal debug info. It is ignored if we emit actual debug info. If we 224 // don't, this at least helps the user find where a global came from. 225 if (MAI->hasSingleParameterDotFile()) { 226 // .file "foo.c" 227 OutStreamer->EmitFileDirective(M.getModuleIdentifier()); 228 } 229 230 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 231 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 232 for (auto &I : *MI) 233 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 234 MP->beginAssembly(M, *MI, *this); 235 236 // Emit module-level inline asm if it exists. 237 if (!M.getModuleInlineAsm().empty()) { 238 // We're at the module level. Construct MCSubtarget from the default CPU 239 // and target triple. 240 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo( 241 TM.getTargetTriple().str(), TM.getTargetCPU(), 242 TM.getTargetFeatureString())); 243 OutStreamer->AddComment("Start of file scope inline assembly"); 244 OutStreamer->AddBlankLine(); 245 EmitInlineAsm(M.getModuleInlineAsm()+"\n", 246 OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions); 247 OutStreamer->AddComment("End of file scope inline assembly"); 248 OutStreamer->AddBlankLine(); 249 } 250 251 if (MAI->doesSupportDebugInformation()) { 252 bool EmitCodeView = MMI->getModule()->getCodeViewFlag(); 253 if (EmitCodeView && TM.getTargetTriple().isKnownWindowsMSVCEnvironment()) { 254 Handlers.push_back(HandlerInfo(new CodeViewDebug(this), 255 DbgTimerName, 256 CodeViewLineTablesGroupName)); 257 } 258 if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) { 259 DD = new DwarfDebug(this, &M); 260 DD->beginModule(); 261 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DWARFGroupName)); 262 } 263 } 264 265 EHStreamer *ES = nullptr; 266 switch (MAI->getExceptionHandlingType()) { 267 case ExceptionHandling::None: 268 break; 269 case ExceptionHandling::SjLj: 270 case ExceptionHandling::DwarfCFI: 271 ES = new DwarfCFIException(this); 272 break; 273 case ExceptionHandling::ARM: 274 ES = new ARMException(this); 275 break; 276 case ExceptionHandling::WinEH: 277 switch (MAI->getWinEHEncodingType()) { 278 default: llvm_unreachable("unsupported unwinding information encoding"); 279 case WinEH::EncodingType::Invalid: 280 break; 281 case WinEH::EncodingType::X86: 282 case WinEH::EncodingType::Itanium: 283 ES = new WinException(this); 284 break; 285 } 286 break; 287 } 288 if (ES) 289 Handlers.push_back(HandlerInfo(ES, EHTimerName, DWARFGroupName)); 290 return false; 291 } 292 293 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) { 294 if (!MAI.hasWeakDefCanBeHiddenDirective()) 295 return false; 296 297 return canBeOmittedFromSymbolTable(GV); 298 } 299 300 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const { 301 GlobalValue::LinkageTypes Linkage = GV->getLinkage(); 302 switch (Linkage) { 303 case GlobalValue::CommonLinkage: 304 case GlobalValue::LinkOnceAnyLinkage: 305 case GlobalValue::LinkOnceODRLinkage: 306 case GlobalValue::WeakAnyLinkage: 307 case GlobalValue::WeakODRLinkage: 308 if (MAI->hasWeakDefDirective()) { 309 // .globl _foo 310 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 311 312 if (!canBeHidden(GV, *MAI)) 313 // .weak_definition _foo 314 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition); 315 else 316 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate); 317 } else if (MAI->hasLinkOnceDirective()) { 318 // .globl _foo 319 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 320 //NOTE: linkonce is handled by the section the symbol was assigned to. 321 } else { 322 // .weak _foo 323 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak); 324 } 325 return; 326 case GlobalValue::ExternalLinkage: 327 // If external, declare as a global symbol: .globl _foo 328 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 329 return; 330 case GlobalValue::PrivateLinkage: 331 case GlobalValue::InternalLinkage: 332 return; 333 case GlobalValue::AppendingLinkage: 334 case GlobalValue::AvailableExternallyLinkage: 335 case GlobalValue::ExternalWeakLinkage: 336 llvm_unreachable("Should never emit this"); 337 } 338 llvm_unreachable("Unknown linkage type!"); 339 } 340 341 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name, 342 const GlobalValue *GV) const { 343 TM.getNameWithPrefix(Name, GV, *Mang); 344 } 345 346 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const { 347 return TM.getSymbol(GV, *Mang); 348 } 349 350 /// EmitGlobalVariable - Emit the specified global variable to the .s file. 351 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) { 352 bool IsEmuTLSVar = TM.Options.EmulatedTLS && GV->isThreadLocal(); 353 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) && 354 "No emulated TLS variables in the common section"); 355 356 // Never emit TLS variable xyz in emulated TLS model. 357 // The initialization value is in __emutls_t.xyz instead of xyz. 358 if (IsEmuTLSVar) 359 return; 360 361 if (GV->hasInitializer()) { 362 // Check to see if this is a special global used by LLVM, if so, emit it. 363 if (EmitSpecialLLVMGlobal(GV)) 364 return; 365 366 // Skip the emission of global equivalents. The symbol can be emitted later 367 // on by emitGlobalGOTEquivs in case it turns out to be needed. 368 if (GlobalGOTEquivs.count(getSymbol(GV))) 369 return; 370 371 if (isVerbose()) { 372 // When printing the control variable __emutls_v.*, 373 // we don't need to print the original TLS variable name. 374 GV->printAsOperand(OutStreamer->GetCommentOS(), 375 /*PrintType=*/false, GV->getParent()); 376 OutStreamer->GetCommentOS() << '\n'; 377 } 378 } 379 380 MCSymbol *GVSym = getSymbol(GV); 381 MCSymbol *EmittedSym = GVSym; 382 // getOrCreateEmuTLSControlSym only creates the symbol with name and default attributes. 383 // GV's or GVSym's attributes will be used for the EmittedSym. 384 385 EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration()); 386 387 if (!GV->hasInitializer()) // External globals require no extra code. 388 return; 389 390 GVSym->redefineIfPossible(); 391 if (GVSym->isDefined() || GVSym->isVariable()) 392 report_fatal_error("symbol '" + Twine(GVSym->getName()) + 393 "' is already defined"); 394 395 if (MAI->hasDotTypeDotSizeDirective()) 396 OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject); 397 398 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM); 399 400 const DataLayout &DL = GV->getParent()->getDataLayout(); 401 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType()); 402 403 // If the alignment is specified, we *must* obey it. Overaligning a global 404 // with a specified alignment is a prompt way to break globals emitted to 405 // sections and expected to be contiguous (e.g. ObjC metadata). 406 unsigned AlignLog = getGVAlignmentLog2(GV, DL); 407 408 for (const HandlerInfo &HI : Handlers) { 409 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled); 410 HI.Handler->setSymbolSize(GVSym, Size); 411 } 412 413 // Handle common symbols 414 if (GVKind.isCommon()) { 415 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 416 unsigned Align = 1 << AlignLog; 417 if (!getObjFileLowering().getCommDirectiveSupportsAlignment()) 418 Align = 0; 419 420 // .comm _foo, 42, 4 421 OutStreamer->EmitCommonSymbol(GVSym, Size, Align); 422 return; 423 } 424 425 // Determine to which section this global should be emitted. 426 MCSection *TheSection = 427 getObjFileLowering().SectionForGlobal(GV, GVKind, *Mang, TM); 428 429 // If we have a bss global going to a section that supports the 430 // zerofill directive, do so here. 431 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() && 432 TheSection->isVirtualSection()) { 433 if (Size == 0) 434 Size = 1; // zerofill of 0 bytes is undefined. 435 unsigned Align = 1 << AlignLog; 436 EmitLinkage(GV, GVSym); 437 // .zerofill __DATA, __bss, _foo, 400, 5 438 OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align); 439 return; 440 } 441 442 // If this is a BSS local symbol and we are emitting in the BSS 443 // section use .lcomm/.comm directive. 444 if (GVKind.isBSSLocal() && 445 getObjFileLowering().getBSSSection() == TheSection) { 446 if (Size == 0) 447 Size = 1; // .comm Foo, 0 is undefined, avoid it. 448 unsigned Align = 1 << AlignLog; 449 450 // Use .lcomm only if it supports user-specified alignment. 451 // Otherwise, while it would still be correct to use .lcomm in some 452 // cases (e.g. when Align == 1), the external assembler might enfore 453 // some -unknown- default alignment behavior, which could cause 454 // spurious differences between external and integrated assembler. 455 // Prefer to simply fall back to .local / .comm in this case. 456 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) { 457 // .lcomm _foo, 42 458 OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align); 459 return; 460 } 461 462 if (!getObjFileLowering().getCommDirectiveSupportsAlignment()) 463 Align = 0; 464 465 // .local _foo 466 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local); 467 // .comm _foo, 42, 4 468 OutStreamer->EmitCommonSymbol(GVSym, Size, Align); 469 return; 470 } 471 472 // Handle thread local data for mach-o which requires us to output an 473 // additional structure of data and mangle the original symbol so that we 474 // can reference it later. 475 // 476 // TODO: This should become an "emit thread local global" method on TLOF. 477 // All of this macho specific stuff should be sunk down into TLOFMachO and 478 // stuff like "TLSExtraDataSection" should no longer be part of the parent 479 // TLOF class. This will also make it more obvious that stuff like 480 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho 481 // specific code. 482 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) { 483 // Emit the .tbss symbol 484 MCSymbol *MangSym = 485 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init")); 486 487 if (GVKind.isThreadBSS()) { 488 TheSection = getObjFileLowering().getTLSBSSSection(); 489 OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog); 490 } else if (GVKind.isThreadData()) { 491 OutStreamer->SwitchSection(TheSection); 492 493 EmitAlignment(AlignLog, GV); 494 OutStreamer->EmitLabel(MangSym); 495 496 EmitGlobalConstant(GV->getParent()->getDataLayout(), 497 GV->getInitializer()); 498 } 499 500 OutStreamer->AddBlankLine(); 501 502 // Emit the variable struct for the runtime. 503 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection(); 504 505 OutStreamer->SwitchSection(TLVSect); 506 // Emit the linkage here. 507 EmitLinkage(GV, GVSym); 508 OutStreamer->EmitLabel(GVSym); 509 510 // Three pointers in size: 511 // - __tlv_bootstrap - used to make sure support exists 512 // - spare pointer, used when mapped by the runtime 513 // - pointer to mangled symbol above with initializer 514 unsigned PtrSize = DL.getPointerTypeSize(GV->getType()); 515 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"), 516 PtrSize); 517 OutStreamer->EmitIntValue(0, PtrSize); 518 OutStreamer->EmitSymbolValue(MangSym, PtrSize); 519 520 OutStreamer->AddBlankLine(); 521 return; 522 } 523 524 MCSymbol *EmittedInitSym = GVSym; 525 526 OutStreamer->SwitchSection(TheSection); 527 528 EmitLinkage(GV, EmittedInitSym); 529 EmitAlignment(AlignLog, GV); 530 531 OutStreamer->EmitLabel(EmittedInitSym); 532 533 EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 534 535 if (MAI->hasDotTypeDotSizeDirective()) 536 // .size foo, 42 537 OutStreamer->emitELFSize(cast<MCSymbolELF>(EmittedInitSym), 538 MCConstantExpr::create(Size, OutContext)); 539 540 OutStreamer->AddBlankLine(); 541 } 542 543 /// EmitFunctionHeader - This method emits the header for the current 544 /// function. 545 void AsmPrinter::EmitFunctionHeader() { 546 // Print out constants referenced by the function 547 EmitConstantPool(); 548 549 // Print the 'header' of function. 550 const Function *F = MF->getFunction(); 551 552 OutStreamer->SwitchSection( 553 getObjFileLowering().SectionForGlobal(F, *Mang, TM)); 554 EmitVisibility(CurrentFnSym, F->getVisibility()); 555 556 EmitLinkage(F, CurrentFnSym); 557 if (MAI->hasFunctionAlignment()) 558 EmitAlignment(MF->getAlignment(), F); 559 560 if (MAI->hasDotTypeDotSizeDirective()) 561 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction); 562 563 if (isVerbose()) { 564 F->printAsOperand(OutStreamer->GetCommentOS(), 565 /*PrintType=*/false, F->getParent()); 566 OutStreamer->GetCommentOS() << '\n'; 567 } 568 569 // Emit the prefix data. 570 if (F->hasPrefixData()) 571 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrefixData()); 572 573 // Emit the CurrentFnSym. This is a virtual function to allow targets to 574 // do their wild and crazy things as required. 575 EmitFunctionEntryLabel(); 576 577 // If the function had address-taken blocks that got deleted, then we have 578 // references to the dangling symbols. Emit them at the start of the function 579 // so that we don't get references to undefined symbols. 580 std::vector<MCSymbol*> DeadBlockSyms; 581 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms); 582 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) { 583 OutStreamer->AddComment("Address taken block that was later removed"); 584 OutStreamer->EmitLabel(DeadBlockSyms[i]); 585 } 586 587 if (CurrentFnBegin) { 588 if (MAI->useAssignmentForEHBegin()) { 589 MCSymbol *CurPos = OutContext.createTempSymbol(); 590 OutStreamer->EmitLabel(CurPos); 591 OutStreamer->EmitAssignment(CurrentFnBegin, 592 MCSymbolRefExpr::create(CurPos, OutContext)); 593 } else { 594 OutStreamer->EmitLabel(CurrentFnBegin); 595 } 596 } 597 598 // Emit pre-function debug and/or EH information. 599 for (const HandlerInfo &HI : Handlers) { 600 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled); 601 HI.Handler->beginFunction(MF); 602 } 603 604 // Emit the prologue data. 605 if (F->hasPrologueData()) 606 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrologueData()); 607 } 608 609 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the 610 /// function. This can be overridden by targets as required to do custom stuff. 611 void AsmPrinter::EmitFunctionEntryLabel() { 612 CurrentFnSym->redefineIfPossible(); 613 614 // The function label could have already been emitted if two symbols end up 615 // conflicting due to asm renaming. Detect this and emit an error. 616 if (CurrentFnSym->isVariable()) 617 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 618 "' is a protected alias"); 619 if (CurrentFnSym->isDefined()) 620 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 621 "' label emitted multiple times to assembly file"); 622 623 return OutStreamer->EmitLabel(CurrentFnSym); 624 } 625 626 /// emitComments - Pretty-print comments for instructions. 627 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) { 628 const MachineFunction *MF = MI.getParent()->getParent(); 629 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 630 631 // Check for spills and reloads 632 int FI; 633 634 const MachineFrameInfo *FrameInfo = MF->getFrameInfo(); 635 636 // We assume a single instruction only has a spill or reload, not 637 // both. 638 const MachineMemOperand *MMO; 639 if (TII->isLoadFromStackSlotPostFE(MI, FI)) { 640 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 641 MMO = *MI.memoperands_begin(); 642 CommentOS << MMO->getSize() << "-byte Reload\n"; 643 } 644 } else if (TII->hasLoadFromStackSlot(MI, MMO, FI)) { 645 if (FrameInfo->isSpillSlotObjectIndex(FI)) 646 CommentOS << MMO->getSize() << "-byte Folded Reload\n"; 647 } else if (TII->isStoreToStackSlotPostFE(MI, FI)) { 648 if (FrameInfo->isSpillSlotObjectIndex(FI)) { 649 MMO = *MI.memoperands_begin(); 650 CommentOS << MMO->getSize() << "-byte Spill\n"; 651 } 652 } else if (TII->hasStoreToStackSlot(MI, MMO, FI)) { 653 if (FrameInfo->isSpillSlotObjectIndex(FI)) 654 CommentOS << MMO->getSize() << "-byte Folded Spill\n"; 655 } 656 657 // Check for spill-induced copies 658 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse)) 659 CommentOS << " Reload Reuse\n"; 660 } 661 662 /// emitImplicitDef - This method emits the specified machine instruction 663 /// that is an implicit def. 664 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const { 665 unsigned RegNo = MI->getOperand(0).getReg(); 666 667 SmallString<128> Str; 668 raw_svector_ostream OS(Str); 669 OS << "implicit-def: " 670 << PrintReg(RegNo, MF->getSubtarget().getRegisterInfo()); 671 672 OutStreamer->AddComment(OS.str()); 673 OutStreamer->AddBlankLine(); 674 } 675 676 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) { 677 std::string Str; 678 raw_string_ostream OS(Str); 679 OS << "kill:"; 680 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 681 const MachineOperand &Op = MI->getOperand(i); 682 assert(Op.isReg() && "KILL instruction must have only register operands"); 683 OS << ' ' 684 << PrintReg(Op.getReg(), 685 AP.MF->getSubtarget().getRegisterInfo()) 686 << (Op.isDef() ? "<def>" : "<kill>"); 687 } 688 AP.OutStreamer->AddComment(Str); 689 AP.OutStreamer->AddBlankLine(); 690 } 691 692 /// emitDebugValueComment - This method handles the target-independent form 693 /// of DBG_VALUE, returning true if it was able to do so. A false return 694 /// means the target will need to handle MI in EmitInstruction. 695 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) { 696 // This code handles only the 4-operand target-independent form. 697 if (MI->getNumOperands() != 4) 698 return false; 699 700 SmallString<128> Str; 701 raw_svector_ostream OS(Str); 702 OS << "DEBUG_VALUE: "; 703 704 const DILocalVariable *V = MI->getDebugVariable(); 705 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) { 706 StringRef Name = SP->getDisplayName(); 707 if (!Name.empty()) 708 OS << Name << ":"; 709 } 710 OS << V->getName(); 711 712 const DIExpression *Expr = MI->getDebugExpression(); 713 if (Expr->isBitPiece()) 714 OS << " [bit_piece offset=" << Expr->getBitPieceOffset() 715 << " size=" << Expr->getBitPieceSize() << "]"; 716 OS << " <- "; 717 718 // The second operand is only an offset if it's an immediate. 719 bool Deref = MI->getOperand(0).isReg() && MI->getOperand(1).isImm(); 720 int64_t Offset = Deref ? MI->getOperand(1).getImm() : 0; 721 722 for (unsigned i = 0; i < Expr->getNumElements(); ++i) { 723 if (Deref) { 724 // We currently don't support extra Offsets or derefs after the first 725 // one. Bail out early instead of emitting an incorrect comment 726 OS << " [complex expression]"; 727 AP.OutStreamer->emitRawComment(OS.str()); 728 return true; 729 } 730 uint64_t Op = Expr->getElement(i); 731 if (Op == dwarf::DW_OP_deref) { 732 Deref = true; 733 continue; 734 } else if (Op == dwarf::DW_OP_bit_piece) { 735 // There can't be any operands after this in a valid expression 736 break; 737 } 738 uint64_t ExtraOffset = Expr->getElement(i++); 739 if (Op == dwarf::DW_OP_plus) 740 Offset += ExtraOffset; 741 else { 742 assert(Op == dwarf::DW_OP_minus); 743 Offset -= ExtraOffset; 744 } 745 } 746 747 // Register or immediate value. Register 0 means undef. 748 if (MI->getOperand(0).isFPImm()) { 749 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF()); 750 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) { 751 OS << (double)APF.convertToFloat(); 752 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) { 753 OS << APF.convertToDouble(); 754 } else { 755 // There is no good way to print long double. Convert a copy to 756 // double. Ah well, it's only a comment. 757 bool ignored; 758 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, 759 &ignored); 760 OS << "(long double) " << APF.convertToDouble(); 761 } 762 } else if (MI->getOperand(0).isImm()) { 763 OS << MI->getOperand(0).getImm(); 764 } else if (MI->getOperand(0).isCImm()) { 765 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/); 766 } else { 767 unsigned Reg; 768 if (MI->getOperand(0).isReg()) { 769 Reg = MI->getOperand(0).getReg(); 770 } else { 771 assert(MI->getOperand(0).isFI() && "Unknown operand type"); 772 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering(); 773 Offset += TFI->getFrameIndexReference(*AP.MF, 774 MI->getOperand(0).getIndex(), Reg); 775 Deref = true; 776 } 777 if (Reg == 0) { 778 // Suppress offset, it is not meaningful here. 779 OS << "undef"; 780 // NOTE: Want this comment at start of line, don't emit with AddComment. 781 AP.OutStreamer->emitRawComment(OS.str()); 782 return true; 783 } 784 if (Deref) 785 OS << '['; 786 OS << PrintReg(Reg, AP.MF->getSubtarget().getRegisterInfo()); 787 } 788 789 if (Deref) 790 OS << '+' << Offset << ']'; 791 792 // NOTE: Want this comment at start of line, don't emit with AddComment. 793 AP.OutStreamer->emitRawComment(OS.str()); 794 return true; 795 } 796 797 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() { 798 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI && 799 MF->getFunction()->needsUnwindTableEntry()) 800 return CFI_M_EH; 801 802 if (MMI->hasDebugInfo()) 803 return CFI_M_Debug; 804 805 return CFI_M_None; 806 } 807 808 bool AsmPrinter::needsSEHMoves() { 809 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry(); 810 } 811 812 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) { 813 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType(); 814 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI && 815 ExceptionHandlingType != ExceptionHandling::ARM) 816 return; 817 818 if (needsCFIMoves() == CFI_M_None) 819 return; 820 821 const MachineModuleInfo &MMI = MF->getMMI(); 822 const std::vector<MCCFIInstruction> &Instrs = MMI.getFrameInstructions(); 823 unsigned CFIIndex = MI.getOperand(0).getCFIIndex(); 824 const MCCFIInstruction &CFI = Instrs[CFIIndex]; 825 emitCFIInstruction(CFI); 826 } 827 828 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) { 829 // The operands are the MCSymbol and the frame offset of the allocation. 830 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol(); 831 int FrameOffset = MI.getOperand(1).getImm(); 832 833 // Emit a symbol assignment. 834 OutStreamer->EmitAssignment(FrameAllocSym, 835 MCConstantExpr::create(FrameOffset, OutContext)); 836 } 837 838 /// EmitFunctionBody - This method emits the body and trailer for a 839 /// function. 840 void AsmPrinter::EmitFunctionBody() { 841 EmitFunctionHeader(); 842 843 // Emit target-specific gunk before the function body. 844 EmitFunctionBodyStart(); 845 846 bool ShouldPrintDebugScopes = MMI->hasDebugInfo(); 847 848 // Print out code for the function. 849 bool HasAnyRealCode = false; 850 for (auto &MBB : *MF) { 851 // Print a label for the basic block. 852 EmitBasicBlockStart(MBB); 853 for (auto &MI : MBB) { 854 855 // Print the assembly for the instruction. 856 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() && 857 !MI.isDebugValue()) { 858 HasAnyRealCode = true; 859 ++EmittedInsts; 860 } 861 862 if (ShouldPrintDebugScopes) { 863 for (const HandlerInfo &HI : Handlers) { 864 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, 865 TimePassesIsEnabled); 866 HI.Handler->beginInstruction(&MI); 867 } 868 } 869 870 if (isVerbose()) 871 emitComments(MI, OutStreamer->GetCommentOS()); 872 873 switch (MI.getOpcode()) { 874 case TargetOpcode::CFI_INSTRUCTION: 875 emitCFIInstruction(MI); 876 break; 877 878 case TargetOpcode::LOCAL_ESCAPE: 879 emitFrameAlloc(MI); 880 break; 881 882 case TargetOpcode::EH_LABEL: 883 case TargetOpcode::GC_LABEL: 884 OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol()); 885 break; 886 case TargetOpcode::INLINEASM: 887 EmitInlineAsm(&MI); 888 break; 889 case TargetOpcode::DBG_VALUE: 890 if (isVerbose()) { 891 if (!emitDebugValueComment(&MI, *this)) 892 EmitInstruction(&MI); 893 } 894 break; 895 case TargetOpcode::IMPLICIT_DEF: 896 if (isVerbose()) emitImplicitDef(&MI); 897 break; 898 case TargetOpcode::KILL: 899 if (isVerbose()) emitKill(&MI, *this); 900 break; 901 default: 902 EmitInstruction(&MI); 903 break; 904 } 905 906 if (ShouldPrintDebugScopes) { 907 for (const HandlerInfo &HI : Handlers) { 908 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, 909 TimePassesIsEnabled); 910 HI.Handler->endInstruction(); 911 } 912 } 913 } 914 915 EmitBasicBlockEnd(MBB); 916 } 917 918 // If the function is empty and the object file uses .subsections_via_symbols, 919 // then we need to emit *something* to the function body to prevent the 920 // labels from collapsing together. Just emit a noop. 921 if ((MAI->hasSubsectionsViaSymbols() && !HasAnyRealCode)) { 922 MCInst Noop; 923 MF->getSubtarget().getInstrInfo()->getNoopForMachoTarget(Noop); 924 OutStreamer->AddComment("avoids zero-length function"); 925 926 // Targets can opt-out of emitting the noop here by leaving the opcode 927 // unspecified. 928 if (Noop.getOpcode()) 929 OutStreamer->EmitInstruction(Noop, getSubtargetInfo()); 930 } 931 932 const Function *F = MF->getFunction(); 933 for (const auto &BB : *F) { 934 if (!BB.hasAddressTaken()) 935 continue; 936 MCSymbol *Sym = GetBlockAddressSymbol(&BB); 937 if (Sym->isDefined()) 938 continue; 939 OutStreamer->AddComment("Address of block that was removed by CodeGen"); 940 OutStreamer->EmitLabel(Sym); 941 } 942 943 // Emit target-specific gunk after the function body. 944 EmitFunctionBodyEnd(); 945 946 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() || 947 MMI->hasEHFunclets() || MAI->hasDotTypeDotSizeDirective()) { 948 // Create a symbol for the end of function. 949 CurrentFnEnd = createTempSymbol("func_end"); 950 OutStreamer->EmitLabel(CurrentFnEnd); 951 } 952 953 // If the target wants a .size directive for the size of the function, emit 954 // it. 955 if (MAI->hasDotTypeDotSizeDirective()) { 956 // We can get the size as difference between the function label and the 957 // temp label. 958 const MCExpr *SizeExp = MCBinaryExpr::createSub( 959 MCSymbolRefExpr::create(CurrentFnEnd, OutContext), 960 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext); 961 if (auto Sym = dyn_cast<MCSymbolELF>(CurrentFnSym)) 962 OutStreamer->emitELFSize(Sym, SizeExp); 963 } 964 965 for (const HandlerInfo &HI : Handlers) { 966 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled); 967 HI.Handler->markFunctionEnd(); 968 } 969 970 // Print out jump tables referenced by the function. 971 EmitJumpTableInfo(); 972 973 // Emit post-function debug and/or EH information. 974 for (const HandlerInfo &HI : Handlers) { 975 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, TimePassesIsEnabled); 976 HI.Handler->endFunction(MF); 977 } 978 MMI->EndFunction(); 979 980 OutStreamer->AddBlankLine(); 981 } 982 983 /// \brief Compute the number of Global Variables that uses a Constant. 984 static unsigned getNumGlobalVariableUses(const Constant *C) { 985 if (!C) 986 return 0; 987 988 if (isa<GlobalVariable>(C)) 989 return 1; 990 991 unsigned NumUses = 0; 992 for (auto *CU : C->users()) 993 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU)); 994 995 return NumUses; 996 } 997 998 /// \brief Only consider global GOT equivalents if at least one user is a 999 /// cstexpr inside an initializer of another global variables. Also, don't 1000 /// handle cstexpr inside instructions. During global variable emission, 1001 /// candidates are skipped and are emitted later in case at least one cstexpr 1002 /// isn't replaced by a PC relative GOT entry access. 1003 static bool isGOTEquivalentCandidate(const GlobalVariable *GV, 1004 unsigned &NumGOTEquivUsers) { 1005 // Global GOT equivalents are unnamed private globals with a constant 1006 // pointer initializer to another global symbol. They must point to a 1007 // GlobalVariable or Function, i.e., as GlobalValue. 1008 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() || !GV->isConstant() || 1009 !GV->isDiscardableIfUnused() || !dyn_cast<GlobalValue>(GV->getOperand(0))) 1010 return false; 1011 1012 // To be a got equivalent, at least one of its users need to be a constant 1013 // expression used by another global variable. 1014 for (auto *U : GV->users()) 1015 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U)); 1016 1017 return NumGOTEquivUsers > 0; 1018 } 1019 1020 /// \brief Unnamed constant global variables solely contaning a pointer to 1021 /// another globals variable is equivalent to a GOT table entry; it contains the 1022 /// the address of another symbol. Optimize it and replace accesses to these 1023 /// "GOT equivalents" by using the GOT entry for the final global instead. 1024 /// Compute GOT equivalent candidates among all global variables to avoid 1025 /// emitting them if possible later on, after it use is replaced by a GOT entry 1026 /// access. 1027 void AsmPrinter::computeGlobalGOTEquivs(Module &M) { 1028 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1029 return; 1030 1031 for (const auto &G : M.globals()) { 1032 unsigned NumGOTEquivUsers = 0; 1033 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers)) 1034 continue; 1035 1036 const MCSymbol *GOTEquivSym = getSymbol(&G); 1037 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers); 1038 } 1039 } 1040 1041 /// \brief Constant expressions using GOT equivalent globals may not be eligible 1042 /// for PC relative GOT entry conversion, in such cases we need to emit such 1043 /// globals we previously omitted in EmitGlobalVariable. 1044 void AsmPrinter::emitGlobalGOTEquivs() { 1045 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1046 return; 1047 1048 SmallVector<const GlobalVariable *, 8> FailedCandidates; 1049 for (auto &I : GlobalGOTEquivs) { 1050 const GlobalVariable *GV = I.second.first; 1051 unsigned Cnt = I.second.second; 1052 if (Cnt) 1053 FailedCandidates.push_back(GV); 1054 } 1055 GlobalGOTEquivs.clear(); 1056 1057 for (auto *GV : FailedCandidates) 1058 EmitGlobalVariable(GV); 1059 } 1060 1061 void AsmPrinter::emitGlobalIndirectSymbol(Module &M, 1062 const GlobalIndirectSymbol& GIS) { 1063 MCSymbol *Name = getSymbol(&GIS); 1064 1065 if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective()) 1066 OutStreamer->EmitSymbolAttribute(Name, MCSA_Global); 1067 else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage()) 1068 OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference); 1069 else 1070 assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage"); 1071 1072 // Set the symbol type to function if the alias has a function type. 1073 // This affects codegen when the aliasee is not a function. 1074 if (GIS.getType()->getPointerElementType()->isFunctionTy()) { 1075 OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeFunction); 1076 if (isa<GlobalIFunc>(GIS)) 1077 OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction); 1078 } 1079 1080 EmitVisibility(Name, GIS.getVisibility()); 1081 1082 const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol()); 1083 1084 if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr)) 1085 OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry); 1086 1087 // Emit the directives as assignments aka .set: 1088 OutStreamer->EmitAssignment(Name, Expr); 1089 1090 if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) { 1091 // If the aliasee does not correspond to a symbol in the output, i.e. the 1092 // alias is not of an object or the aliased object is private, then set the 1093 // size of the alias symbol from the type of the alias. We don't do this in 1094 // other situations as the alias and aliasee having differing types but same 1095 // size may be intentional. 1096 const GlobalObject *BaseObject = GA->getBaseObject(); 1097 if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() && 1098 (!BaseObject || BaseObject->hasPrivateLinkage())) { 1099 const DataLayout &DL = M.getDataLayout(); 1100 uint64_t Size = DL.getTypeAllocSize(GA->getValueType()); 1101 OutStreamer->emitELFSize(cast<MCSymbolELF>(Name), 1102 MCConstantExpr::create(Size, OutContext)); 1103 } 1104 } 1105 } 1106 1107 bool AsmPrinter::doFinalization(Module &M) { 1108 // Set the MachineFunction to nullptr so that we can catch attempted 1109 // accesses to MF specific features at the module level and so that 1110 // we can conditionalize accesses based on whether or not it is nullptr. 1111 MF = nullptr; 1112 1113 // Gather all GOT equivalent globals in the module. We really need two 1114 // passes over the globals: one to compute and another to avoid its emission 1115 // in EmitGlobalVariable, otherwise we would not be able to handle cases 1116 // where the got equivalent shows up before its use. 1117 computeGlobalGOTEquivs(M); 1118 1119 // Emit global variables. 1120 for (const auto &G : M.globals()) 1121 EmitGlobalVariable(&G); 1122 1123 // Emit remaining GOT equivalent globals. 1124 emitGlobalGOTEquivs(); 1125 1126 // Emit visibility info for declarations 1127 for (const Function &F : M) { 1128 if (!F.isDeclarationForLinker()) 1129 continue; 1130 GlobalValue::VisibilityTypes V = F.getVisibility(); 1131 if (V == GlobalValue::DefaultVisibility) 1132 continue; 1133 1134 MCSymbol *Name = getSymbol(&F); 1135 EmitVisibility(Name, V, false); 1136 } 1137 1138 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1139 1140 // Emit module flags. 1141 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 1142 M.getModuleFlagsMetadata(ModuleFlags); 1143 if (!ModuleFlags.empty()) 1144 TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, *Mang, TM); 1145 1146 if (TM.getTargetTriple().isOSBinFormatELF()) { 1147 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>(); 1148 1149 // Output stubs for external and common global variables. 1150 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList(); 1151 if (!Stubs.empty()) { 1152 OutStreamer->SwitchSection(TLOF.getDataSection()); 1153 const DataLayout &DL = M.getDataLayout(); 1154 1155 for (const auto &Stub : Stubs) { 1156 OutStreamer->EmitLabel(Stub.first); 1157 OutStreamer->EmitSymbolValue(Stub.second.getPointer(), 1158 DL.getPointerSize()); 1159 } 1160 } 1161 } 1162 1163 // Finalize debug and EH information. 1164 for (const HandlerInfo &HI : Handlers) { 1165 NamedRegionTimer T(HI.TimerName, HI.TimerGroupName, 1166 TimePassesIsEnabled); 1167 HI.Handler->endModule(); 1168 delete HI.Handler; 1169 } 1170 Handlers.clear(); 1171 DD = nullptr; 1172 1173 // If the target wants to know about weak references, print them all. 1174 if (MAI->getWeakRefDirective()) { 1175 // FIXME: This is not lazy, it would be nice to only print weak references 1176 // to stuff that is actually used. Note that doing so would require targets 1177 // to notice uses in operands (due to constant exprs etc). This should 1178 // happen with the MC stuff eventually. 1179 1180 // Print out module-level global objects here. 1181 for (const auto &GO : M.global_objects()) { 1182 if (!GO.hasExternalWeakLinkage()) 1183 continue; 1184 OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference); 1185 } 1186 } 1187 1188 OutStreamer->AddBlankLine(); 1189 1190 // Print aliases in topological order, that is, for each alias a = b, 1191 // b must be printed before a. 1192 // This is because on some targets (e.g. PowerPC) linker expects aliases in 1193 // such an order to generate correct TOC information. 1194 SmallVector<const GlobalAlias *, 16> AliasStack; 1195 SmallPtrSet<const GlobalAlias *, 16> AliasVisited; 1196 for (const auto &Alias : M.aliases()) { 1197 for (const GlobalAlias *Cur = &Alias; Cur; 1198 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) { 1199 if (!AliasVisited.insert(Cur).second) 1200 break; 1201 AliasStack.push_back(Cur); 1202 } 1203 for (const GlobalAlias *AncestorAlias : reverse(AliasStack)) 1204 emitGlobalIndirectSymbol(M, *AncestorAlias); 1205 AliasStack.clear(); 1206 } 1207 for (const auto &IFunc : M.ifuncs()) 1208 emitGlobalIndirectSymbol(M, IFunc); 1209 1210 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 1211 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 1212 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 1213 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I)) 1214 MP->finishAssembly(M, *MI, *this); 1215 1216 // Emit llvm.ident metadata in an '.ident' directive. 1217 EmitModuleIdents(M); 1218 1219 // Emit __morestack address if needed for indirect calls. 1220 if (MMI->usesMorestackAddr()) { 1221 unsigned Align = 1; 1222 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant( 1223 getDataLayout(), SectionKind::getReadOnly(), 1224 /*C=*/nullptr, Align); 1225 OutStreamer->SwitchSection(ReadOnlySection); 1226 1227 MCSymbol *AddrSymbol = 1228 OutContext.getOrCreateSymbol(StringRef("__morestack_addr")); 1229 OutStreamer->EmitLabel(AddrSymbol); 1230 1231 unsigned PtrSize = M.getDataLayout().getPointerSize(0); 1232 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"), 1233 PtrSize); 1234 } 1235 1236 // If we don't have any trampolines, then we don't require stack memory 1237 // to be executable. Some targets have a directive to declare this. 1238 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 1239 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 1240 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext)) 1241 OutStreamer->SwitchSection(S); 1242 1243 // Allow the target to emit any magic that it wants at the end of the file, 1244 // after everything else has gone out. 1245 EmitEndOfAsmFile(M); 1246 1247 delete Mang; Mang = nullptr; 1248 MMI = nullptr; 1249 1250 OutStreamer->Finish(); 1251 OutStreamer->reset(); 1252 1253 return false; 1254 } 1255 1256 MCSymbol *AsmPrinter::getCurExceptionSym() { 1257 if (!CurExceptionSym) 1258 CurExceptionSym = createTempSymbol("exception"); 1259 return CurExceptionSym; 1260 } 1261 1262 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1263 this->MF = &MF; 1264 // Get the function symbol. 1265 CurrentFnSym = getSymbol(MF.getFunction()); 1266 CurrentFnSymForSize = CurrentFnSym; 1267 CurrentFnBegin = nullptr; 1268 CurExceptionSym = nullptr; 1269 bool NeedsLocalForSize = MAI->needsLocalForSize(); 1270 if (!MMI->getLandingPads().empty() || MMI->hasDebugInfo() || 1271 MMI->hasEHFunclets() || NeedsLocalForSize) { 1272 CurrentFnBegin = createTempSymbol("func_begin"); 1273 if (NeedsLocalForSize) 1274 CurrentFnSymForSize = CurrentFnBegin; 1275 } 1276 1277 if (isVerbose()) 1278 LI = &getAnalysis<MachineLoopInfo>(); 1279 } 1280 1281 namespace { 1282 // Keep track the alignment, constpool entries per Section. 1283 struct SectionCPs { 1284 MCSection *S; 1285 unsigned Alignment; 1286 SmallVector<unsigned, 4> CPEs; 1287 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {} 1288 }; 1289 } 1290 1291 /// EmitConstantPool - Print to the current output stream assembly 1292 /// representations of the constants in the constant pool MCP. This is 1293 /// used to print out constants which have been "spilled to memory" by 1294 /// the code generator. 1295 /// 1296 void AsmPrinter::EmitConstantPool() { 1297 const MachineConstantPool *MCP = MF->getConstantPool(); 1298 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 1299 if (CP.empty()) return; 1300 1301 // Calculate sections for constant pool entries. We collect entries to go into 1302 // the same section together to reduce amount of section switch statements. 1303 SmallVector<SectionCPs, 4> CPSections; 1304 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 1305 const MachineConstantPoolEntry &CPE = CP[i]; 1306 unsigned Align = CPE.getAlignment(); 1307 1308 SectionKind Kind = CPE.getSectionKind(&getDataLayout()); 1309 1310 const Constant *C = nullptr; 1311 if (!CPE.isMachineConstantPoolEntry()) 1312 C = CPE.Val.ConstVal; 1313 1314 MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(), 1315 Kind, C, Align); 1316 1317 // The number of sections are small, just do a linear search from the 1318 // last section to the first. 1319 bool Found = false; 1320 unsigned SecIdx = CPSections.size(); 1321 while (SecIdx != 0) { 1322 if (CPSections[--SecIdx].S == S) { 1323 Found = true; 1324 break; 1325 } 1326 } 1327 if (!Found) { 1328 SecIdx = CPSections.size(); 1329 CPSections.push_back(SectionCPs(S, Align)); 1330 } 1331 1332 if (Align > CPSections[SecIdx].Alignment) 1333 CPSections[SecIdx].Alignment = Align; 1334 CPSections[SecIdx].CPEs.push_back(i); 1335 } 1336 1337 // Now print stuff into the calculated sections. 1338 const MCSection *CurSection = nullptr; 1339 unsigned Offset = 0; 1340 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 1341 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 1342 unsigned CPI = CPSections[i].CPEs[j]; 1343 MCSymbol *Sym = GetCPISymbol(CPI); 1344 if (!Sym->isUndefined()) 1345 continue; 1346 1347 if (CurSection != CPSections[i].S) { 1348 OutStreamer->SwitchSection(CPSections[i].S); 1349 EmitAlignment(Log2_32(CPSections[i].Alignment)); 1350 CurSection = CPSections[i].S; 1351 Offset = 0; 1352 } 1353 1354 MachineConstantPoolEntry CPE = CP[CPI]; 1355 1356 // Emit inter-object padding for alignment. 1357 unsigned AlignMask = CPE.getAlignment() - 1; 1358 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 1359 OutStreamer->EmitZeros(NewOffset - Offset); 1360 1361 Type *Ty = CPE.getType(); 1362 Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty); 1363 1364 OutStreamer->EmitLabel(Sym); 1365 if (CPE.isMachineConstantPoolEntry()) 1366 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 1367 else 1368 EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal); 1369 } 1370 } 1371 } 1372 1373 /// EmitJumpTableInfo - Print assembly representations of the jump tables used 1374 /// by the current function to the current output stream. 1375 /// 1376 void AsmPrinter::EmitJumpTableInfo() { 1377 const DataLayout &DL = MF->getDataLayout(); 1378 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 1379 if (!MJTI) return; 1380 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 1381 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 1382 if (JT.empty()) return; 1383 1384 // Pick the directive to use to print the jump table entries, and switch to 1385 // the appropriate section. 1386 const Function *F = MF->getFunction(); 1387 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1388 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection( 1389 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32, 1390 *F); 1391 if (JTInDiffSection) { 1392 // Drop it in the readonly section. 1393 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, *Mang, TM); 1394 OutStreamer->SwitchSection(ReadOnlySection); 1395 } 1396 1397 EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL))); 1398 1399 // Jump tables in code sections are marked with a data_region directive 1400 // where that's supported. 1401 if (!JTInDiffSection) 1402 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32); 1403 1404 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 1405 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 1406 1407 // If this jump table was deleted, ignore it. 1408 if (JTBBs.empty()) continue; 1409 1410 // For the EK_LabelDifference32 entry, if using .set avoids a relocation, 1411 /// emit a .set directive for each unique entry. 1412 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 1413 MAI->doesSetDirectiveSuppressReloc()) { 1414 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 1415 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1416 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 1417 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 1418 const MachineBasicBlock *MBB = JTBBs[ii]; 1419 if (!EmittedSets.insert(MBB).second) 1420 continue; 1421 1422 // .set LJTSet, LBB32-base 1423 const MCExpr *LHS = 1424 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1425 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 1426 MCBinaryExpr::createSub(LHS, Base, 1427 OutContext)); 1428 } 1429 } 1430 1431 // On some targets (e.g. Darwin) we want to emit two consecutive labels 1432 // before each jump table. The first label is never referenced, but tells 1433 // the assembler and linker the extents of the jump table object. The 1434 // second label is actually referenced by the code. 1435 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix()) 1436 // FIXME: This doesn't have to have any specific name, just any randomly 1437 // named and numbered 'l' label would work. Simplify GetJTISymbol. 1438 OutStreamer->EmitLabel(GetJTISymbol(JTI, true)); 1439 1440 OutStreamer->EmitLabel(GetJTISymbol(JTI)); 1441 1442 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 1443 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI); 1444 } 1445 if (!JTInDiffSection) 1446 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd); 1447 } 1448 1449 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 1450 /// current stream. 1451 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI, 1452 const MachineBasicBlock *MBB, 1453 unsigned UID) const { 1454 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block"); 1455 const MCExpr *Value = nullptr; 1456 switch (MJTI->getEntryKind()) { 1457 case MachineJumpTableInfo::EK_Inline: 1458 llvm_unreachable("Cannot emit EK_Inline jump table entry"); 1459 case MachineJumpTableInfo::EK_Custom32: 1460 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry( 1461 MJTI, MBB, UID, OutContext); 1462 break; 1463 case MachineJumpTableInfo::EK_BlockAddress: 1464 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 1465 // .word LBB123 1466 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1467 break; 1468 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 1469 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 1470 // with a relocation as gp-relative, e.g.: 1471 // .gprel32 LBB123 1472 MCSymbol *MBBSym = MBB->getSymbol(); 1473 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 1474 return; 1475 } 1476 1477 case MachineJumpTableInfo::EK_GPRel64BlockAddress: { 1478 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded 1479 // with a relocation as gp-relative, e.g.: 1480 // .gpdword LBB123 1481 MCSymbol *MBBSym = MBB->getSymbol(); 1482 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 1483 return; 1484 } 1485 1486 case MachineJumpTableInfo::EK_LabelDifference32: { 1487 // Each entry is the address of the block minus the address of the jump 1488 // table. This is used for PIC jump tables where gprel32 is not supported. 1489 // e.g.: 1490 // .word LBB123 - LJTI1_2 1491 // If the .set directive avoids relocations, this is emitted as: 1492 // .set L4_5_set_123, LBB123 - LJTI1_2 1493 // .word L4_5_set_123 1494 if (MAI->doesSetDirectiveSuppressReloc()) { 1495 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()), 1496 OutContext); 1497 break; 1498 } 1499 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1500 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1501 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext); 1502 Value = MCBinaryExpr::createSub(Value, Base, OutContext); 1503 break; 1504 } 1505 } 1506 1507 assert(Value && "Unknown entry kind!"); 1508 1509 unsigned EntrySize = MJTI->getEntrySize(getDataLayout()); 1510 OutStreamer->EmitValue(Value, EntrySize); 1511 } 1512 1513 1514 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a 1515 /// special global used by LLVM. If so, emit it and return true, otherwise 1516 /// do nothing and return false. 1517 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 1518 if (GV->getName() == "llvm.used") { 1519 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 1520 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer())); 1521 return true; 1522 } 1523 1524 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 1525 if (GV->getSection() == "llvm.metadata" || 1526 GV->hasAvailableExternallyLinkage()) 1527 return true; 1528 1529 if (!GV->hasAppendingLinkage()) return false; 1530 1531 assert(GV->hasInitializer() && "Not a special LLVM global!"); 1532 1533 if (GV->getName() == "llvm.global_ctors") { 1534 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 1535 /* isCtor */ true); 1536 1537 if (TM.getRelocationModel() == Reloc::Static && 1538 MAI->hasStaticCtorDtorReferenceInStaticMode()) { 1539 StringRef Sym(".constructors_used"); 1540 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym), 1541 MCSA_Reference); 1542 } 1543 return true; 1544 } 1545 1546 if (GV->getName() == "llvm.global_dtors") { 1547 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 1548 /* isCtor */ false); 1549 1550 if (TM.getRelocationModel() == Reloc::Static && 1551 MAI->hasStaticCtorDtorReferenceInStaticMode()) { 1552 StringRef Sym(".destructors_used"); 1553 OutStreamer->EmitSymbolAttribute(OutContext.getOrCreateSymbol(Sym), 1554 MCSA_Reference); 1555 } 1556 return true; 1557 } 1558 1559 report_fatal_error("unknown special variable"); 1560 } 1561 1562 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 1563 /// global in the specified llvm.used list for which emitUsedDirectiveFor 1564 /// is true, as being used with this directive. 1565 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) { 1566 // Should be an array of 'i8*'. 1567 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 1568 const GlobalValue *GV = 1569 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 1570 if (GV) 1571 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip); 1572 } 1573 } 1574 1575 namespace { 1576 struct Structor { 1577 Structor() : Priority(0), Func(nullptr), ComdatKey(nullptr) {} 1578 int Priority; 1579 llvm::Constant *Func; 1580 llvm::GlobalValue *ComdatKey; 1581 }; 1582 } // end namespace 1583 1584 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init 1585 /// priority. 1586 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List, 1587 bool isCtor) { 1588 // Should be an array of '{ int, void ()* }' structs. The first value is the 1589 // init priority. 1590 if (!isa<ConstantArray>(List)) return; 1591 1592 // Sanity check the structors list. 1593 const ConstantArray *InitList = dyn_cast<ConstantArray>(List); 1594 if (!InitList) return; // Not an array! 1595 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType()); 1596 // FIXME: Only allow the 3-field form in LLVM 4.0. 1597 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3) 1598 return; // Not an array of two or three elements! 1599 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) || 1600 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr). 1601 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U))) 1602 return; // Not (int, ptr, ptr). 1603 1604 // Gather the structors in a form that's convenient for sorting by priority. 1605 SmallVector<Structor, 8> Structors; 1606 for (Value *O : InitList->operands()) { 1607 ConstantStruct *CS = dyn_cast<ConstantStruct>(O); 1608 if (!CS) continue; // Malformed. 1609 if (CS->getOperand(1)->isNullValue()) 1610 break; // Found a null terminator, skip the rest. 1611 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); 1612 if (!Priority) continue; // Malformed. 1613 Structors.push_back(Structor()); 1614 Structor &S = Structors.back(); 1615 S.Priority = Priority->getLimitedValue(65535); 1616 S.Func = CS->getOperand(1); 1617 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue()) 1618 S.ComdatKey = dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts()); 1619 } 1620 1621 // Emit the function pointers in the target-specific order 1622 unsigned Align = Log2_32(DL.getPointerPrefAlignment()); 1623 std::stable_sort(Structors.begin(), Structors.end(), 1624 [](const Structor &L, 1625 const Structor &R) { return L.Priority < R.Priority; }); 1626 for (Structor &S : Structors) { 1627 const TargetLoweringObjectFile &Obj = getObjFileLowering(); 1628 const MCSymbol *KeySym = nullptr; 1629 if (GlobalValue *GV = S.ComdatKey) { 1630 if (GV->hasAvailableExternallyLinkage()) 1631 // If the associated variable is available_externally, some other TU 1632 // will provide its dynamic initializer. 1633 continue; 1634 1635 KeySym = getSymbol(GV); 1636 } 1637 MCSection *OutputSection = 1638 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym) 1639 : Obj.getStaticDtorSection(S.Priority, KeySym)); 1640 OutStreamer->SwitchSection(OutputSection); 1641 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection()) 1642 EmitAlignment(Align); 1643 EmitXXStructor(DL, S.Func); 1644 } 1645 } 1646 1647 void AsmPrinter::EmitModuleIdents(Module &M) { 1648 if (!MAI->hasIdentDirective()) 1649 return; 1650 1651 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) { 1652 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1653 const MDNode *N = NMD->getOperand(i); 1654 assert(N->getNumOperands() == 1 && 1655 "llvm.ident metadata entry can have only one operand"); 1656 const MDString *S = cast<MDString>(N->getOperand(0)); 1657 OutStreamer->EmitIdent(S->getString()); 1658 } 1659 } 1660 } 1661 1662 //===--------------------------------------------------------------------===// 1663 // Emission and print routines 1664 // 1665 1666 /// EmitInt8 - Emit a byte directive and value. 1667 /// 1668 void AsmPrinter::EmitInt8(int Value) const { 1669 OutStreamer->EmitIntValue(Value, 1); 1670 } 1671 1672 /// EmitInt16 - Emit a short directive and value. 1673 /// 1674 void AsmPrinter::EmitInt16(int Value) const { 1675 OutStreamer->EmitIntValue(Value, 2); 1676 } 1677 1678 /// EmitInt32 - Emit a long directive and value. 1679 /// 1680 void AsmPrinter::EmitInt32(int Value) const { 1681 OutStreamer->EmitIntValue(Value, 4); 1682 } 1683 1684 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive 1685 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses 1686 /// .set if it avoids relocations. 1687 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 1688 unsigned Size) const { 1689 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size); 1690 } 1691 1692 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset" 1693 /// where the size in bytes of the directive is specified by Size and Label 1694 /// specifies the label. This implicitly uses .set if it is available. 1695 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 1696 unsigned Size, 1697 bool IsSectionRelative) const { 1698 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) { 1699 OutStreamer->EmitCOFFSecRel32(Label); 1700 return; 1701 } 1702 1703 // Emit Label+Offset (or just Label if Offset is zero) 1704 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext); 1705 if (Offset) 1706 Expr = MCBinaryExpr::createAdd( 1707 Expr, MCConstantExpr::create(Offset, OutContext), OutContext); 1708 1709 OutStreamer->EmitValue(Expr, Size); 1710 } 1711 1712 //===----------------------------------------------------------------------===// 1713 1714 // EmitAlignment - Emit an alignment directive to the specified power of 1715 // two boundary. For example, if you pass in 3 here, you will get an 8 1716 // byte alignment. If a global value is specified, and if that global has 1717 // an explicit alignment requested, it will override the alignment request 1718 // if required for correctness. 1719 // 1720 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const { 1721 if (GV) 1722 NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits); 1723 1724 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment. 1725 1726 assert(NumBits < 1727 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 1728 "undefined behavior"); 1729 if (getCurrentSection()->getKind().isText()) 1730 OutStreamer->EmitCodeAlignment(1u << NumBits); 1731 else 1732 OutStreamer->EmitValueToAlignment(1u << NumBits); 1733 } 1734 1735 //===----------------------------------------------------------------------===// 1736 // Constant emission. 1737 //===----------------------------------------------------------------------===// 1738 1739 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) { 1740 MCContext &Ctx = OutContext; 1741 1742 if (CV->isNullValue() || isa<UndefValue>(CV)) 1743 return MCConstantExpr::create(0, Ctx); 1744 1745 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 1746 return MCConstantExpr::create(CI->getZExtValue(), Ctx); 1747 1748 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 1749 return MCSymbolRefExpr::create(getSymbol(GV), Ctx); 1750 1751 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 1752 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx); 1753 1754 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 1755 if (!CE) { 1756 llvm_unreachable("Unknown constant value to lower!"); 1757 } 1758 1759 switch (CE->getOpcode()) { 1760 default: 1761 // If the code isn't optimized, there may be outstanding folding 1762 // opportunities. Attempt to fold the expression using DataLayout as a 1763 // last resort before giving up. 1764 if (Constant *C = ConstantFoldConstantExpression(CE, getDataLayout())) 1765 if (C != CE) 1766 return lowerConstant(C); 1767 1768 // Otherwise report the problem to the user. 1769 { 1770 std::string S; 1771 raw_string_ostream OS(S); 1772 OS << "Unsupported expression in static initializer: "; 1773 CE->printAsOperand(OS, /*PrintType=*/false, 1774 !MF ? nullptr : MF->getFunction()->getParent()); 1775 report_fatal_error(OS.str()); 1776 } 1777 case Instruction::GetElementPtr: { 1778 // Generate a symbolic expression for the byte address 1779 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0); 1780 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI); 1781 1782 const MCExpr *Base = lowerConstant(CE->getOperand(0)); 1783 if (!OffsetAI) 1784 return Base; 1785 1786 int64_t Offset = OffsetAI.getSExtValue(); 1787 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx), 1788 Ctx); 1789 } 1790 1791 case Instruction::Trunc: 1792 // We emit the value and depend on the assembler to truncate the generated 1793 // expression properly. This is important for differences between 1794 // blockaddress labels. Since the two labels are in the same function, it 1795 // is reasonable to treat their delta as a 32-bit value. 1796 // FALL THROUGH. 1797 case Instruction::BitCast: 1798 return lowerConstant(CE->getOperand(0)); 1799 1800 case Instruction::IntToPtr: { 1801 const DataLayout &DL = getDataLayout(); 1802 1803 // Handle casts to pointers by changing them into casts to the appropriate 1804 // integer type. This promotes constant folding and simplifies this code. 1805 Constant *Op = CE->getOperand(0); 1806 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()), 1807 false/*ZExt*/); 1808 return lowerConstant(Op); 1809 } 1810 1811 case Instruction::PtrToInt: { 1812 const DataLayout &DL = getDataLayout(); 1813 1814 // Support only foldable casts to/from pointers that can be eliminated by 1815 // changing the pointer to the appropriately sized integer type. 1816 Constant *Op = CE->getOperand(0); 1817 Type *Ty = CE->getType(); 1818 1819 const MCExpr *OpExpr = lowerConstant(Op); 1820 1821 // We can emit the pointer value into this slot if the slot is an 1822 // integer slot equal to the size of the pointer. 1823 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType())) 1824 return OpExpr; 1825 1826 // Otherwise the pointer is smaller than the resultant integer, mask off 1827 // the high bits so we are sure to get a proper truncation if the input is 1828 // a constant expr. 1829 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType()); 1830 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx); 1831 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx); 1832 } 1833 1834 case Instruction::Sub: { 1835 GlobalValue *LHSGV; 1836 APInt LHSOffset; 1837 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset, 1838 getDataLayout())) { 1839 GlobalValue *RHSGV; 1840 APInt RHSOffset; 1841 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset, 1842 getDataLayout())) { 1843 const MCExpr *RelocExpr = getObjFileLowering().lowerRelativeReference( 1844 LHSGV, RHSGV, *Mang, TM); 1845 if (!RelocExpr) 1846 RelocExpr = MCBinaryExpr::createSub( 1847 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx), 1848 MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx); 1849 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue(); 1850 if (Addend != 0) 1851 RelocExpr = MCBinaryExpr::createAdd( 1852 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx); 1853 return RelocExpr; 1854 } 1855 } 1856 } 1857 // else fallthrough 1858 1859 // The MC library also has a right-shift operator, but it isn't consistently 1860 // signed or unsigned between different targets. 1861 case Instruction::Add: 1862 case Instruction::Mul: 1863 case Instruction::SDiv: 1864 case Instruction::SRem: 1865 case Instruction::Shl: 1866 case Instruction::And: 1867 case Instruction::Or: 1868 case Instruction::Xor: { 1869 const MCExpr *LHS = lowerConstant(CE->getOperand(0)); 1870 const MCExpr *RHS = lowerConstant(CE->getOperand(1)); 1871 switch (CE->getOpcode()) { 1872 default: llvm_unreachable("Unknown binary operator constant cast expr"); 1873 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx); 1874 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx); 1875 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx); 1876 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx); 1877 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx); 1878 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx); 1879 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx); 1880 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx); 1881 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx); 1882 } 1883 } 1884 } 1885 } 1886 1887 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, 1888 AsmPrinter &AP, 1889 const Constant *BaseCV = nullptr, 1890 uint64_t Offset = 0); 1891 1892 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP); 1893 1894 /// isRepeatedByteSequence - Determine whether the given value is 1895 /// composed of a repeated sequence of identical bytes and return the 1896 /// byte value. If it is not a repeated sequence, return -1. 1897 static int isRepeatedByteSequence(const ConstantDataSequential *V) { 1898 StringRef Data = V->getRawDataValues(); 1899 assert(!Data.empty() && "Empty aggregates should be CAZ node"); 1900 char C = Data[0]; 1901 for (unsigned i = 1, e = Data.size(); i != e; ++i) 1902 if (Data[i] != C) return -1; 1903 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1. 1904 } 1905 1906 1907 /// isRepeatedByteSequence - Determine whether the given value is 1908 /// composed of a repeated sequence of identical bytes and return the 1909 /// byte value. If it is not a repeated sequence, return -1. 1910 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) { 1911 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 1912 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType()); 1913 assert(Size % 8 == 0); 1914 1915 // Extend the element to take zero padding into account. 1916 APInt Value = CI->getValue().zextOrSelf(Size); 1917 if (!Value.isSplat(8)) 1918 return -1; 1919 1920 return Value.zextOrTrunc(8).getZExtValue(); 1921 } 1922 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 1923 // Make sure all array elements are sequences of the same repeated 1924 // byte. 1925 assert(CA->getNumOperands() != 0 && "Should be a CAZ"); 1926 Constant *Op0 = CA->getOperand(0); 1927 int Byte = isRepeatedByteSequence(Op0, DL); 1928 if (Byte == -1) 1929 return -1; 1930 1931 // All array elements must be equal. 1932 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) 1933 if (CA->getOperand(i) != Op0) 1934 return -1; 1935 return Byte; 1936 } 1937 1938 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) 1939 return isRepeatedByteSequence(CDS); 1940 1941 return -1; 1942 } 1943 1944 static void emitGlobalConstantDataSequential(const DataLayout &DL, 1945 const ConstantDataSequential *CDS, 1946 AsmPrinter &AP) { 1947 1948 // See if we can aggregate this into a .fill, if so, emit it as such. 1949 int Value = isRepeatedByteSequence(CDS, DL); 1950 if (Value != -1) { 1951 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType()); 1952 // Don't emit a 1-byte object as a .fill. 1953 if (Bytes > 1) 1954 return AP.OutStreamer->emitFill(Bytes, Value); 1955 } 1956 1957 // If this can be emitted with .ascii/.asciz, emit it as such. 1958 if (CDS->isString()) 1959 return AP.OutStreamer->EmitBytes(CDS->getAsString()); 1960 1961 // Otherwise, emit the values in successive locations. 1962 unsigned ElementByteSize = CDS->getElementByteSize(); 1963 if (isa<IntegerType>(CDS->getElementType())) { 1964 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 1965 if (AP.isVerbose()) 1966 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 1967 CDS->getElementAsInteger(i)); 1968 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i), 1969 ElementByteSize); 1970 } 1971 } else { 1972 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) 1973 emitGlobalConstantFP(cast<ConstantFP>(CDS->getElementAsConstant(I)), AP); 1974 } 1975 1976 unsigned Size = DL.getTypeAllocSize(CDS->getType()); 1977 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) * 1978 CDS->getNumElements(); 1979 if (unsigned Padding = Size - EmittedSize) 1980 AP.OutStreamer->EmitZeros(Padding); 1981 1982 } 1983 1984 static void emitGlobalConstantArray(const DataLayout &DL, 1985 const ConstantArray *CA, AsmPrinter &AP, 1986 const Constant *BaseCV, uint64_t Offset) { 1987 // See if we can aggregate some values. Make sure it can be 1988 // represented as a series of bytes of the constant value. 1989 int Value = isRepeatedByteSequence(CA, DL); 1990 1991 if (Value != -1) { 1992 uint64_t Bytes = DL.getTypeAllocSize(CA->getType()); 1993 AP.OutStreamer->emitFill(Bytes, Value); 1994 } 1995 else { 1996 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) { 1997 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset); 1998 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType()); 1999 } 2000 } 2001 } 2002 2003 static void emitGlobalConstantVector(const DataLayout &DL, 2004 const ConstantVector *CV, AsmPrinter &AP) { 2005 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 2006 emitGlobalConstantImpl(DL, CV->getOperand(i), AP); 2007 2008 unsigned Size = DL.getTypeAllocSize(CV->getType()); 2009 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) * 2010 CV->getType()->getNumElements(); 2011 if (unsigned Padding = Size - EmittedSize) 2012 AP.OutStreamer->EmitZeros(Padding); 2013 } 2014 2015 static void emitGlobalConstantStruct(const DataLayout &DL, 2016 const ConstantStruct *CS, AsmPrinter &AP, 2017 const Constant *BaseCV, uint64_t Offset) { 2018 // Print the fields in successive locations. Pad to align if needed! 2019 unsigned Size = DL.getTypeAllocSize(CS->getType()); 2020 const StructLayout *Layout = DL.getStructLayout(CS->getType()); 2021 uint64_t SizeSoFar = 0; 2022 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 2023 const Constant *Field = CS->getOperand(i); 2024 2025 // Print the actual field value. 2026 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar); 2027 2028 // Check if padding is needed and insert one or more 0s. 2029 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType()); 2030 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 2031 - Layout->getElementOffset(i)) - FieldSize; 2032 SizeSoFar += FieldSize + PadSize; 2033 2034 // Insert padding - this may include padding to increase the size of the 2035 // current field up to the ABI size (if the struct is not packed) as well 2036 // as padding to ensure that the next field starts at the right offset. 2037 AP.OutStreamer->EmitZeros(PadSize); 2038 } 2039 assert(SizeSoFar == Layout->getSizeInBytes() && 2040 "Layout of constant struct may be incorrect!"); 2041 } 2042 2043 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) { 2044 APInt API = CFP->getValueAPF().bitcastToAPInt(); 2045 2046 // First print a comment with what we think the original floating-point value 2047 // should have been. 2048 if (AP.isVerbose()) { 2049 SmallString<8> StrVal; 2050 CFP->getValueAPF().toString(StrVal); 2051 2052 if (CFP->getType()) 2053 CFP->getType()->print(AP.OutStreamer->GetCommentOS()); 2054 else 2055 AP.OutStreamer->GetCommentOS() << "Printing <null> Type"; 2056 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n'; 2057 } 2058 2059 // Now iterate through the APInt chunks, emitting them in endian-correct 2060 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit 2061 // floats). 2062 unsigned NumBytes = API.getBitWidth() / 8; 2063 unsigned TrailingBytes = NumBytes % sizeof(uint64_t); 2064 const uint64_t *p = API.getRawData(); 2065 2066 // PPC's long double has odd notions of endianness compared to how LLVM 2067 // handles it: p[0] goes first for *big* endian on PPC. 2068 if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) { 2069 int Chunk = API.getNumWords() - 1; 2070 2071 if (TrailingBytes) 2072 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes); 2073 2074 for (; Chunk >= 0; --Chunk) 2075 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t)); 2076 } else { 2077 unsigned Chunk; 2078 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk) 2079 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t)); 2080 2081 if (TrailingBytes) 2082 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes); 2083 } 2084 2085 // Emit the tail padding for the long double. 2086 const DataLayout &DL = AP.getDataLayout(); 2087 AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) - 2088 DL.getTypeStoreSize(CFP->getType())); 2089 } 2090 2091 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) { 2092 const DataLayout &DL = AP.getDataLayout(); 2093 unsigned BitWidth = CI->getBitWidth(); 2094 2095 // Copy the value as we may massage the layout for constants whose bit width 2096 // is not a multiple of 64-bits. 2097 APInt Realigned(CI->getValue()); 2098 uint64_t ExtraBits = 0; 2099 unsigned ExtraBitsSize = BitWidth & 63; 2100 2101 if (ExtraBitsSize) { 2102 // The bit width of the data is not a multiple of 64-bits. 2103 // The extra bits are expected to be at the end of the chunk of the memory. 2104 // Little endian: 2105 // * Nothing to be done, just record the extra bits to emit. 2106 // Big endian: 2107 // * Record the extra bits to emit. 2108 // * Realign the raw data to emit the chunks of 64-bits. 2109 if (DL.isBigEndian()) { 2110 // Basically the structure of the raw data is a chunk of 64-bits cells: 2111 // 0 1 BitWidth / 64 2112 // [chunk1][chunk2] ... [chunkN]. 2113 // The most significant chunk is chunkN and it should be emitted first. 2114 // However, due to the alignment issue chunkN contains useless bits. 2115 // Realign the chunks so that they contain only useless information: 2116 // ExtraBits 0 1 (BitWidth / 64) - 1 2117 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN] 2118 ExtraBits = Realigned.getRawData()[0] & 2119 (((uint64_t)-1) >> (64 - ExtraBitsSize)); 2120 Realigned = Realigned.lshr(ExtraBitsSize); 2121 } else 2122 ExtraBits = Realigned.getRawData()[BitWidth / 64]; 2123 } 2124 2125 // We don't expect assemblers to support integer data directives 2126 // for more than 64 bits, so we emit the data in at most 64-bit 2127 // quantities at a time. 2128 const uint64_t *RawData = Realigned.getRawData(); 2129 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 2130 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i]; 2131 AP.OutStreamer->EmitIntValue(Val, 8); 2132 } 2133 2134 if (ExtraBitsSize) { 2135 // Emit the extra bits after the 64-bits chunks. 2136 2137 // Emit a directive that fills the expected size. 2138 uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType()); 2139 Size -= (BitWidth / 64) * 8; 2140 assert(Size && Size * 8 >= ExtraBitsSize && 2141 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) 2142 == ExtraBits && "Directive too small for extra bits."); 2143 AP.OutStreamer->EmitIntValue(ExtraBits, Size); 2144 } 2145 } 2146 2147 /// \brief Transform a not absolute MCExpr containing a reference to a GOT 2148 /// equivalent global, by a target specific GOT pc relative access to the 2149 /// final symbol. 2150 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, 2151 const Constant *BaseCst, 2152 uint64_t Offset) { 2153 // The global @foo below illustrates a global that uses a got equivalent. 2154 // 2155 // @bar = global i32 42 2156 // @gotequiv = private unnamed_addr constant i32* @bar 2157 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64), 2158 // i64 ptrtoint (i32* @foo to i64)) 2159 // to i32) 2160 // 2161 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually 2162 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the 2163 // form: 2164 // 2165 // foo = cstexpr, where 2166 // cstexpr := <gotequiv> - "." + <cst> 2167 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst> 2168 // 2169 // After canonicalization by evaluateAsRelocatable `ME` turns into: 2170 // 2171 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where 2172 // gotpcrelcst := <offset from @foo base> + <cst> 2173 // 2174 MCValue MV; 2175 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute()) 2176 return; 2177 const MCSymbolRefExpr *SymA = MV.getSymA(); 2178 if (!SymA) 2179 return; 2180 2181 // Check that GOT equivalent symbol is cached. 2182 const MCSymbol *GOTEquivSym = &SymA->getSymbol(); 2183 if (!AP.GlobalGOTEquivs.count(GOTEquivSym)) 2184 return; 2185 2186 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst); 2187 if (!BaseGV) 2188 return; 2189 2190 // Check for a valid base symbol 2191 const MCSymbol *BaseSym = AP.getSymbol(BaseGV); 2192 const MCSymbolRefExpr *SymB = MV.getSymB(); 2193 2194 if (!SymB || BaseSym != &SymB->getSymbol()) 2195 return; 2196 2197 // Make sure to match: 2198 // 2199 // gotpcrelcst := <offset from @foo base> + <cst> 2200 // 2201 // If gotpcrelcst is positive it means that we can safely fold the pc rel 2202 // displacement into the GOTPCREL. We can also can have an extra offset <cst> 2203 // if the target knows how to encode it. 2204 // 2205 int64_t GOTPCRelCst = Offset + MV.getConstant(); 2206 if (GOTPCRelCst < 0) 2207 return; 2208 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0) 2209 return; 2210 2211 // Emit the GOT PC relative to replace the got equivalent global, i.e.: 2212 // 2213 // bar: 2214 // .long 42 2215 // gotequiv: 2216 // .quad bar 2217 // foo: 2218 // .long gotequiv - "." + <cst> 2219 // 2220 // is replaced by the target specific equivalent to: 2221 // 2222 // bar: 2223 // .long 42 2224 // foo: 2225 // .long bar@GOTPCREL+<gotpcrelcst> 2226 // 2227 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym]; 2228 const GlobalVariable *GV = Result.first; 2229 int NumUses = (int)Result.second; 2230 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0)); 2231 const MCSymbol *FinalSym = AP.getSymbol(FinalGV); 2232 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel( 2233 FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer); 2234 2235 // Update GOT equivalent usage information 2236 --NumUses; 2237 if (NumUses >= 0) 2238 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses); 2239 } 2240 2241 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV, 2242 AsmPrinter &AP, const Constant *BaseCV, 2243 uint64_t Offset) { 2244 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2245 2246 // Globals with sub-elements such as combinations of arrays and structs 2247 // are handled recursively by emitGlobalConstantImpl. Keep track of the 2248 // constant symbol base and the current position with BaseCV and Offset. 2249 if (!BaseCV && CV->hasOneUse()) 2250 BaseCV = dyn_cast<Constant>(CV->user_back()); 2251 2252 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) 2253 return AP.OutStreamer->EmitZeros(Size); 2254 2255 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 2256 switch (Size) { 2257 case 1: 2258 case 2: 2259 case 4: 2260 case 8: 2261 if (AP.isVerbose()) 2262 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2263 CI->getZExtValue()); 2264 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size); 2265 return; 2266 default: 2267 emitGlobalConstantLargeInt(CI, AP); 2268 return; 2269 } 2270 } 2271 2272 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 2273 return emitGlobalConstantFP(CFP, AP); 2274 2275 if (isa<ConstantPointerNull>(CV)) { 2276 AP.OutStreamer->EmitIntValue(0, Size); 2277 return; 2278 } 2279 2280 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV)) 2281 return emitGlobalConstantDataSequential(DL, CDS, AP); 2282 2283 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 2284 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset); 2285 2286 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 2287 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset); 2288 2289 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 2290 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of 2291 // vectors). 2292 if (CE->getOpcode() == Instruction::BitCast) 2293 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP); 2294 2295 if (Size > 8) { 2296 // If the constant expression's size is greater than 64-bits, then we have 2297 // to emit the value in chunks. Try to constant fold the value and emit it 2298 // that way. 2299 Constant *New = ConstantFoldConstantExpression(CE, DL); 2300 if (New && New != CE) 2301 return emitGlobalConstantImpl(DL, New, AP); 2302 } 2303 } 2304 2305 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 2306 return emitGlobalConstantVector(DL, V, AP); 2307 2308 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 2309 // thread the streamer with EmitValue. 2310 const MCExpr *ME = AP.lowerConstant(CV); 2311 2312 // Since lowerConstant already folded and got rid of all IR pointer and 2313 // integer casts, detect GOT equivalent accesses by looking into the MCExpr 2314 // directly. 2315 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel()) 2316 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset); 2317 2318 AP.OutStreamer->EmitValue(ME, Size); 2319 } 2320 2321 /// EmitGlobalConstant - Print a general LLVM constant to the .s file. 2322 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) { 2323 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2324 if (Size) 2325 emitGlobalConstantImpl(DL, CV, *this); 2326 else if (MAI->hasSubsectionsViaSymbols()) { 2327 // If the global has zero size, emit a single byte so that two labels don't 2328 // look like they are at the same location. 2329 OutStreamer->EmitIntValue(0, 1); 2330 } 2331 } 2332 2333 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 2334 // Target doesn't support this yet! 2335 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 2336 } 2337 2338 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 2339 if (Offset > 0) 2340 OS << '+' << Offset; 2341 else if (Offset < 0) 2342 OS << Offset; 2343 } 2344 2345 //===----------------------------------------------------------------------===// 2346 // Symbol Lowering Routines. 2347 //===----------------------------------------------------------------------===// 2348 2349 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const { 2350 return OutContext.createTempSymbol(Name, true); 2351 } 2352 2353 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 2354 return MMI->getAddrLabelSymbol(BA->getBasicBlock()); 2355 } 2356 2357 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 2358 return MMI->getAddrLabelSymbol(BB); 2359 } 2360 2361 /// GetCPISymbol - Return the symbol for the specified constant pool entry. 2362 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 2363 const DataLayout &DL = getDataLayout(); 2364 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2365 "CPI" + Twine(getFunctionNumber()) + "_" + 2366 Twine(CPID)); 2367 } 2368 2369 /// GetJTISymbol - Return the symbol for the specified jump table entry. 2370 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 2371 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 2372 } 2373 2374 /// GetJTSetSymbol - Return the symbol for the specified jump table .set 2375 /// FIXME: privatize to AsmPrinter. 2376 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 2377 const DataLayout &DL = getDataLayout(); 2378 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2379 Twine(getFunctionNumber()) + "_" + 2380 Twine(UID) + "_set_" + Twine(MBBID)); 2381 } 2382 2383 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV, 2384 StringRef Suffix) const { 2385 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, *Mang, 2386 TM); 2387 } 2388 2389 /// Return the MCSymbol for the specified ExternalSymbol. 2390 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 2391 SmallString<60> NameStr; 2392 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout()); 2393 return OutContext.getOrCreateSymbol(NameStr); 2394 } 2395 2396 2397 2398 /// PrintParentLoopComment - Print comments about parent loops of this one. 2399 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2400 unsigned FunctionNumber) { 2401 if (!Loop) return; 2402 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 2403 OS.indent(Loop->getLoopDepth()*2) 2404 << "Parent Loop BB" << FunctionNumber << "_" 2405 << Loop->getHeader()->getNumber() 2406 << " Depth=" << Loop->getLoopDepth() << '\n'; 2407 } 2408 2409 2410 /// PrintChildLoopComment - Print comments about child loops within 2411 /// the loop for this basic block, with nesting. 2412 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2413 unsigned FunctionNumber) { 2414 // Add child loop information 2415 for (const MachineLoop *CL : *Loop) { 2416 OS.indent(CL->getLoopDepth()*2) 2417 << "Child Loop BB" << FunctionNumber << "_" 2418 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth() 2419 << '\n'; 2420 PrintChildLoopComment(OS, CL, FunctionNumber); 2421 } 2422 } 2423 2424 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks. 2425 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, 2426 const MachineLoopInfo *LI, 2427 const AsmPrinter &AP) { 2428 // Add loop depth information 2429 const MachineLoop *Loop = LI->getLoopFor(&MBB); 2430 if (!Loop) return; 2431 2432 MachineBasicBlock *Header = Loop->getHeader(); 2433 assert(Header && "No header for loop"); 2434 2435 // If this block is not a loop header, just print out what is the loop header 2436 // and return. 2437 if (Header != &MBB) { 2438 AP.OutStreamer->AddComment(" in Loop: Header=BB" + 2439 Twine(AP.getFunctionNumber())+"_" + 2440 Twine(Loop->getHeader()->getNumber())+ 2441 " Depth="+Twine(Loop->getLoopDepth())); 2442 return; 2443 } 2444 2445 // Otherwise, it is a loop header. Print out information about child and 2446 // parent loops. 2447 raw_ostream &OS = AP.OutStreamer->GetCommentOS(); 2448 2449 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 2450 2451 OS << "=>"; 2452 OS.indent(Loop->getLoopDepth()*2-2); 2453 2454 OS << "This "; 2455 if (Loop->empty()) 2456 OS << "Inner "; 2457 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 2458 2459 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 2460 } 2461 2462 2463 /// EmitBasicBlockStart - This method prints the label for the specified 2464 /// MachineBasicBlock, an alignment (if present) and a comment describing 2465 /// it if appropriate. 2466 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const { 2467 // End the previous funclet and start a new one. 2468 if (MBB.isEHFuncletEntry()) { 2469 for (const HandlerInfo &HI : Handlers) { 2470 HI.Handler->endFunclet(); 2471 HI.Handler->beginFunclet(MBB); 2472 } 2473 } 2474 2475 // Emit an alignment directive for this block, if needed. 2476 if (unsigned Align = MBB.getAlignment()) 2477 EmitAlignment(Align); 2478 2479 // If the block has its address taken, emit any labels that were used to 2480 // reference the block. It is possible that there is more than one label 2481 // here, because multiple LLVM BB's may have been RAUW'd to this block after 2482 // the references were generated. 2483 if (MBB.hasAddressTaken()) { 2484 const BasicBlock *BB = MBB.getBasicBlock(); 2485 if (isVerbose()) 2486 OutStreamer->AddComment("Block address taken"); 2487 2488 // MBBs can have their address taken as part of CodeGen without having 2489 // their corresponding BB's address taken in IR 2490 if (BB->hasAddressTaken()) 2491 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB)) 2492 OutStreamer->EmitLabel(Sym); 2493 } 2494 2495 // Print some verbose block comments. 2496 if (isVerbose()) { 2497 if (const BasicBlock *BB = MBB.getBasicBlock()) { 2498 if (BB->hasName()) { 2499 BB->printAsOperand(OutStreamer->GetCommentOS(), 2500 /*PrintType=*/false, BB->getModule()); 2501 OutStreamer->GetCommentOS() << '\n'; 2502 } 2503 } 2504 emitBasicBlockLoopComments(MBB, LI, *this); 2505 } 2506 2507 // Print the main label for the block. 2508 if (MBB.pred_empty() || 2509 (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry())) { 2510 if (isVerbose()) { 2511 // NOTE: Want this comment at start of line, don't emit with AddComment. 2512 OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false); 2513 } 2514 } else { 2515 OutStreamer->EmitLabel(MBB.getSymbol()); 2516 } 2517 } 2518 2519 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility, 2520 bool IsDefinition) const { 2521 MCSymbolAttr Attr = MCSA_Invalid; 2522 2523 switch (Visibility) { 2524 default: break; 2525 case GlobalValue::HiddenVisibility: 2526 if (IsDefinition) 2527 Attr = MAI->getHiddenVisibilityAttr(); 2528 else 2529 Attr = MAI->getHiddenDeclarationVisibilityAttr(); 2530 break; 2531 case GlobalValue::ProtectedVisibility: 2532 Attr = MAI->getProtectedVisibilityAttr(); 2533 break; 2534 } 2535 2536 if (Attr != MCSA_Invalid) 2537 OutStreamer->EmitSymbolAttribute(Sym, Attr); 2538 } 2539 2540 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 2541 /// exactly one predecessor and the control transfer mechanism between 2542 /// the predecessor and this block is a fall-through. 2543 bool AsmPrinter:: 2544 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 2545 // If this is a landing pad, it isn't a fall through. If it has no preds, 2546 // then nothing falls through to it. 2547 if (MBB->isEHPad() || MBB->pred_empty()) 2548 return false; 2549 2550 // If there isn't exactly one predecessor, it can't be a fall through. 2551 if (MBB->pred_size() > 1) 2552 return false; 2553 2554 // The predecessor has to be immediately before this block. 2555 MachineBasicBlock *Pred = *MBB->pred_begin(); 2556 if (!Pred->isLayoutSuccessor(MBB)) 2557 return false; 2558 2559 // If the block is completely empty, then it definitely does fall through. 2560 if (Pred->empty()) 2561 return true; 2562 2563 // Check the terminators in the previous blocks 2564 for (const auto &MI : Pred->terminators()) { 2565 // If it is not a simple branch, we are in a table somewhere. 2566 if (!MI.isBranch() || MI.isIndirectBranch()) 2567 return false; 2568 2569 // If we are the operands of one of the branches, this is not a fall 2570 // through. Note that targets with delay slots will usually bundle 2571 // terminators with the delay slot instruction. 2572 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) { 2573 if (OP->isJTI()) 2574 return false; 2575 if (OP->isMBB() && OP->getMBB() == MBB) 2576 return false; 2577 } 2578 } 2579 2580 return true; 2581 } 2582 2583 2584 2585 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) { 2586 if (!S.usesMetadata()) 2587 return nullptr; 2588 2589 assert(!S.useStatepoints() && "statepoints do not currently support custom" 2590 " stackmap formats, please see the documentation for a description of" 2591 " the default format. If you really need a custom serialized format," 2592 " please file a bug"); 2593 2594 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 2595 gcp_map_type::iterator GCPI = GCMap.find(&S); 2596 if (GCPI != GCMap.end()) 2597 return GCPI->second.get(); 2598 2599 const char *Name = S.getName().c_str(); 2600 2601 for (GCMetadataPrinterRegistry::iterator 2602 I = GCMetadataPrinterRegistry::begin(), 2603 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 2604 if (strcmp(Name, I->getName()) == 0) { 2605 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate(); 2606 GMP->S = &S; 2607 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP))); 2608 return IterBool.first->second.get(); 2609 } 2610 2611 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 2612 } 2613 2614 /// Pin vtable to this file. 2615 AsmPrinterHandler::~AsmPrinterHandler() {} 2616 2617 void AsmPrinterHandler::markFunctionEnd() {} 2618