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