1 //===- AsmPrinter.cpp - Common AsmPrinter code ----------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the AsmPrinter class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/AsmPrinter.h" 14 #include "CodeViewDebug.h" 15 #include "DwarfDebug.h" 16 #include "DwarfException.h" 17 #include "WasmException.h" 18 #include "WinCFGuard.h" 19 #include "WinException.h" 20 #include "llvm/ADT/APFloat.h" 21 #include "llvm/ADT/APInt.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/ADT/SmallPtrSet.h" 25 #include "llvm/ADT/SmallString.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/Triple.h" 30 #include "llvm/ADT/Twine.h" 31 #include "llvm/Analysis/ConstantFolding.h" 32 #include "llvm/Analysis/EHPersonalities.h" 33 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 34 #include "llvm/BinaryFormat/COFF.h" 35 #include "llvm/BinaryFormat/Dwarf.h" 36 #include "llvm/BinaryFormat/ELF.h" 37 #include "llvm/CodeGen/GCMetadata.h" 38 #include "llvm/CodeGen/GCMetadataPrinter.h" 39 #include "llvm/CodeGen/GCStrategy.h" 40 #include "llvm/CodeGen/MachineBasicBlock.h" 41 #include "llvm/CodeGen/MachineConstantPool.h" 42 #include "llvm/CodeGen/MachineDominators.h" 43 #include "llvm/CodeGen/MachineFrameInfo.h" 44 #include "llvm/CodeGen/MachineFunction.h" 45 #include "llvm/CodeGen/MachineFunctionPass.h" 46 #include "llvm/CodeGen/MachineInstr.h" 47 #include "llvm/CodeGen/MachineInstrBundle.h" 48 #include "llvm/CodeGen/MachineJumpTableInfo.h" 49 #include "llvm/CodeGen/MachineLoopInfo.h" 50 #include "llvm/CodeGen/MachineMemOperand.h" 51 #include "llvm/CodeGen/MachineModuleInfo.h" 52 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 53 #include "llvm/CodeGen/MachineOperand.h" 54 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 55 #include "llvm/CodeGen/StackMaps.h" 56 #include "llvm/CodeGen/TargetFrameLowering.h" 57 #include "llvm/CodeGen/TargetInstrInfo.h" 58 #include "llvm/CodeGen/TargetLowering.h" 59 #include "llvm/CodeGen/TargetOpcodes.h" 60 #include "llvm/CodeGen/TargetRegisterInfo.h" 61 #include "llvm/IR/BasicBlock.h" 62 #include "llvm/IR/Comdat.h" 63 #include "llvm/IR/Constant.h" 64 #include "llvm/IR/Constants.h" 65 #include "llvm/IR/DataLayout.h" 66 #include "llvm/IR/DebugInfoMetadata.h" 67 #include "llvm/IR/DerivedTypes.h" 68 #include "llvm/IR/Function.h" 69 #include "llvm/IR/GlobalAlias.h" 70 #include "llvm/IR/GlobalIFunc.h" 71 #include "llvm/IR/GlobalIndirectSymbol.h" 72 #include "llvm/IR/GlobalObject.h" 73 #include "llvm/IR/GlobalValue.h" 74 #include "llvm/IR/GlobalVariable.h" 75 #include "llvm/IR/Instruction.h" 76 #include "llvm/IR/Mangler.h" 77 #include "llvm/IR/Metadata.h" 78 #include "llvm/IR/Module.h" 79 #include "llvm/IR/Operator.h" 80 #include "llvm/IR/Type.h" 81 #include "llvm/IR/Value.h" 82 #include "llvm/MC/MCAsmInfo.h" 83 #include "llvm/MC/MCContext.h" 84 #include "llvm/MC/MCDirectives.h" 85 #include "llvm/MC/MCDwarf.h" 86 #include "llvm/MC/MCExpr.h" 87 #include "llvm/MC/MCInst.h" 88 #include "llvm/MC/MCSection.h" 89 #include "llvm/MC/MCSectionCOFF.h" 90 #include "llvm/MC/MCSectionELF.h" 91 #include "llvm/MC/MCSectionMachO.h" 92 #include "llvm/MC/MCSectionXCOFF.h" 93 #include "llvm/MC/MCStreamer.h" 94 #include "llvm/MC/MCSubtargetInfo.h" 95 #include "llvm/MC/MCSymbol.h" 96 #include "llvm/MC/MCSymbolELF.h" 97 #include "llvm/MC/MCSymbolXCOFF.h" 98 #include "llvm/MC/MCTargetOptions.h" 99 #include "llvm/MC/MCValue.h" 100 #include "llvm/MC/SectionKind.h" 101 #include "llvm/Pass.h" 102 #include "llvm/Remarks/Remark.h" 103 #include "llvm/Remarks/RemarkFormat.h" 104 #include "llvm/Remarks/RemarkStreamer.h" 105 #include "llvm/Remarks/RemarkStringTable.h" 106 #include "llvm/Support/Casting.h" 107 #include "llvm/Support/CommandLine.h" 108 #include "llvm/Support/Compiler.h" 109 #include "llvm/Support/ErrorHandling.h" 110 #include "llvm/Support/Format.h" 111 #include "llvm/Support/MathExtras.h" 112 #include "llvm/Support/Path.h" 113 #include "llvm/Support/TargetRegistry.h" 114 #include "llvm/Support/Timer.h" 115 #include "llvm/Support/raw_ostream.h" 116 #include "llvm/Target/TargetLoweringObjectFile.h" 117 #include "llvm/Target/TargetMachine.h" 118 #include "llvm/Target/TargetOptions.h" 119 #include <algorithm> 120 #include <cassert> 121 #include <cinttypes> 122 #include <cstdint> 123 #include <iterator> 124 #include <limits> 125 #include <memory> 126 #include <string> 127 #include <utility> 128 #include <vector> 129 130 using namespace llvm; 131 132 #define DEBUG_TYPE "asm-printer" 133 134 static const char *const DWARFGroupName = "dwarf"; 135 static const char *const DWARFGroupDescription = "DWARF Emission"; 136 static const char *const DbgTimerName = "emit"; 137 static const char *const DbgTimerDescription = "Debug Info Emission"; 138 static const char *const EHTimerName = "write_exception"; 139 static const char *const EHTimerDescription = "DWARF Exception Writer"; 140 static const char *const CFGuardName = "Control Flow Guard"; 141 static const char *const CFGuardDescription = "Control Flow Guard"; 142 static const char *const CodeViewLineTablesGroupName = "linetables"; 143 static const char *const CodeViewLineTablesGroupDescription = 144 "CodeView Line Tables"; 145 146 STATISTIC(EmittedInsts, "Number of machine instrs printed"); 147 148 char AsmPrinter::ID = 0; 149 150 using gcp_map_type = DenseMap<GCStrategy *, std::unique_ptr<GCMetadataPrinter>>; 151 152 static gcp_map_type &getGCMap(void *&P) { 153 if (!P) 154 P = new gcp_map_type(); 155 return *(gcp_map_type*)P; 156 } 157 158 /// getGVAlignment - Return the alignment to use for the specified global 159 /// value. This rounds up to the preferred alignment if possible and legal. 160 Align AsmPrinter::getGVAlignment(const GlobalObject *GV, const DataLayout &DL, 161 Align InAlign) { 162 Align Alignment; 163 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 164 Alignment = DL.getPreferredAlign(GVar); 165 166 // If InAlign is specified, round it to it. 167 if (InAlign > Alignment) 168 Alignment = InAlign; 169 170 // If the GV has a specified alignment, take it into account. 171 const MaybeAlign GVAlign(GV->getAlignment()); 172 if (!GVAlign) 173 return Alignment; 174 175 assert(GVAlign && "GVAlign must be set"); 176 177 // If the GVAlign is larger than NumBits, or if we are required to obey 178 // NumBits because the GV has an assigned section, obey it. 179 if (*GVAlign > Alignment || GV->hasSection()) 180 Alignment = *GVAlign; 181 return Alignment; 182 } 183 184 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer) 185 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()), 186 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) { 187 VerboseAsm = OutStreamer->isVerboseAsm(); 188 } 189 190 AsmPrinter::~AsmPrinter() { 191 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized"); 192 193 if (GCMetadataPrinters) { 194 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 195 196 delete &GCMap; 197 GCMetadataPrinters = nullptr; 198 } 199 } 200 201 bool AsmPrinter::isPositionIndependent() const { 202 return TM.isPositionIndependent(); 203 } 204 205 /// getFunctionNumber - Return a unique ID for the current function. 206 unsigned AsmPrinter::getFunctionNumber() const { 207 return MF->getFunctionNumber(); 208 } 209 210 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 211 return *TM.getObjFileLowering(); 212 } 213 214 const DataLayout &AsmPrinter::getDataLayout() const { 215 return MMI->getModule()->getDataLayout(); 216 } 217 218 // Do not use the cached DataLayout because some client use it without a Module 219 // (dsymutil, llvm-dwarfdump). 220 unsigned AsmPrinter::getPointerSize() const { 221 return TM.getPointerSize(0); // FIXME: Default address space 222 } 223 224 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const { 225 assert(MF && "getSubtargetInfo requires a valid MachineFunction!"); 226 return MF->getSubtarget<MCSubtargetInfo>(); 227 } 228 229 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) { 230 S.emitInstruction(Inst, getSubtargetInfo()); 231 } 232 233 void AsmPrinter::emitInitialRawDwarfLocDirective(const MachineFunction &MF) { 234 assert(DD && "Dwarf debug file is not defined."); 235 assert(OutStreamer->hasRawTextSupport() && "Expected assembly output mode."); 236 (void)DD->emitInitialLocDirective(MF, /*CUID=*/0); 237 } 238 239 /// getCurrentSection() - Return the current section we are emitting to. 240 const MCSection *AsmPrinter::getCurrentSection() const { 241 return OutStreamer->getCurrentSectionOnly(); 242 } 243 244 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 245 AU.setPreservesAll(); 246 MachineFunctionPass::getAnalysisUsage(AU); 247 AU.addRequired<MachineOptimizationRemarkEmitterPass>(); 248 AU.addRequired<GCModuleInfo>(); 249 } 250 251 bool AsmPrinter::doInitialization(Module &M) { 252 auto *MMIWP = getAnalysisIfAvailable<MachineModuleInfoWrapperPass>(); 253 MMI = MMIWP ? &MMIWP->getMMI() : nullptr; 254 255 // Initialize TargetLoweringObjectFile. 256 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 257 .Initialize(OutContext, TM); 258 259 const_cast<TargetLoweringObjectFile &>(getObjFileLowering()) 260 .getModuleMetadata(M); 261 262 OutStreamer->InitSections(false); 263 264 // Emit the version-min deployment target directive if needed. 265 // 266 // FIXME: If we end up with a collection of these sorts of Darwin-specific 267 // or ELF-specific things, it may make sense to have a platform helper class 268 // that will work with the target helper class. For now keep it here, as the 269 // alternative is duplicated code in each of the target asm printers that 270 // use the directive, where it would need the same conditionalization 271 // anyway. 272 const Triple &Target = TM.getTargetTriple(); 273 OutStreamer->emitVersionForTarget(Target, M.getSDKVersion()); 274 275 // Allow the target to emit any magic that it wants at the start of the file. 276 emitStartOfAsmFile(M); 277 278 // Very minimal debug info. It is ignored if we emit actual debug info. If we 279 // don't, this at least helps the user find where a global came from. 280 if (MAI->hasSingleParameterDotFile()) { 281 // .file "foo.c" 282 OutStreamer->emitFileDirective( 283 llvm::sys::path::filename(M.getSourceFileName())); 284 } 285 286 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 287 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 288 for (auto &I : *MI) 289 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 290 MP->beginAssembly(M, *MI, *this); 291 292 // Emit module-level inline asm if it exists. 293 if (!M.getModuleInlineAsm().empty()) { 294 // We're at the module level. Construct MCSubtarget from the default CPU 295 // and target triple. 296 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo( 297 TM.getTargetTriple().str(), TM.getTargetCPU(), 298 TM.getTargetFeatureString())); 299 OutStreamer->AddComment("Start of file scope inline assembly"); 300 OutStreamer->AddBlankLine(); 301 emitInlineAsm(M.getModuleInlineAsm() + "\n", 302 OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions); 303 OutStreamer->AddComment("End of file scope inline assembly"); 304 OutStreamer->AddBlankLine(); 305 } 306 307 if (MAI->doesSupportDebugInformation()) { 308 bool EmitCodeView = M.getCodeViewFlag(); 309 if (EmitCodeView && TM.getTargetTriple().isOSWindows()) { 310 Handlers.emplace_back(std::make_unique<CodeViewDebug>(this), 311 DbgTimerName, DbgTimerDescription, 312 CodeViewLineTablesGroupName, 313 CodeViewLineTablesGroupDescription); 314 } 315 if (!EmitCodeView || M.getDwarfVersion()) { 316 DD = new DwarfDebug(this, &M); 317 DD->beginModule(); 318 Handlers.emplace_back(std::unique_ptr<DwarfDebug>(DD), DbgTimerName, 319 DbgTimerDescription, DWARFGroupName, 320 DWARFGroupDescription); 321 } 322 } 323 324 switch (MAI->getExceptionHandlingType()) { 325 case ExceptionHandling::SjLj: 326 case ExceptionHandling::DwarfCFI: 327 case ExceptionHandling::ARM: 328 isCFIMoveForDebugging = true; 329 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI) 330 break; 331 for (auto &F: M.getFunctionList()) { 332 // If the module contains any function with unwind data, 333 // .eh_frame has to be emitted. 334 // Ignore functions that won't get emitted. 335 if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) { 336 isCFIMoveForDebugging = false; 337 break; 338 } 339 } 340 break; 341 default: 342 isCFIMoveForDebugging = false; 343 break; 344 } 345 346 EHStreamer *ES = nullptr; 347 switch (MAI->getExceptionHandlingType()) { 348 case ExceptionHandling::None: 349 break; 350 case ExceptionHandling::SjLj: 351 case ExceptionHandling::DwarfCFI: 352 ES = new DwarfCFIException(this); 353 break; 354 case ExceptionHandling::ARM: 355 ES = new ARMException(this); 356 break; 357 case ExceptionHandling::WinEH: 358 switch (MAI->getWinEHEncodingType()) { 359 default: llvm_unreachable("unsupported unwinding information encoding"); 360 case WinEH::EncodingType::Invalid: 361 break; 362 case WinEH::EncodingType::X86: 363 case WinEH::EncodingType::Itanium: 364 ES = new WinException(this); 365 break; 366 } 367 break; 368 case ExceptionHandling::Wasm: 369 ES = new WasmException(this); 370 break; 371 } 372 if (ES) 373 Handlers.emplace_back(std::unique_ptr<EHStreamer>(ES), EHTimerName, 374 EHTimerDescription, DWARFGroupName, 375 DWARFGroupDescription); 376 377 // Emit tables for any value of cfguard flag (i.e. cfguard=1 or cfguard=2). 378 if (mdconst::extract_or_null<ConstantInt>(M.getModuleFlag("cfguard"))) 379 Handlers.emplace_back(std::make_unique<WinCFGuard>(this), CFGuardName, 380 CFGuardDescription, DWARFGroupName, 381 DWARFGroupDescription); 382 return false; 383 } 384 385 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) { 386 if (!MAI.hasWeakDefCanBeHiddenDirective()) 387 return false; 388 389 return GV->canBeOmittedFromSymbolTable(); 390 } 391 392 void AsmPrinter::emitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const { 393 GlobalValue::LinkageTypes Linkage = GV->getLinkage(); 394 switch (Linkage) { 395 case GlobalValue::CommonLinkage: 396 case GlobalValue::LinkOnceAnyLinkage: 397 case GlobalValue::LinkOnceODRLinkage: 398 case GlobalValue::WeakAnyLinkage: 399 case GlobalValue::WeakODRLinkage: 400 if (MAI->hasWeakDefDirective()) { 401 // .globl _foo 402 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global); 403 404 if (!canBeHidden(GV, *MAI)) 405 // .weak_definition _foo 406 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefinition); 407 else 408 OutStreamer->emitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate); 409 } else if (MAI->avoidWeakIfComdat() && GV->hasComdat()) { 410 // .globl _foo 411 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global); 412 //NOTE: linkonce is handled by the section the symbol was assigned to. 413 } else { 414 // .weak _foo 415 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Weak); 416 } 417 return; 418 case GlobalValue::ExternalLinkage: 419 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Global); 420 return; 421 case GlobalValue::PrivateLinkage: 422 case GlobalValue::InternalLinkage: 423 return; 424 case GlobalValue::ExternalWeakLinkage: 425 case GlobalValue::AvailableExternallyLinkage: 426 case GlobalValue::AppendingLinkage: 427 llvm_unreachable("Should never emit this"); 428 } 429 llvm_unreachable("Unknown linkage type!"); 430 } 431 432 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name, 433 const GlobalValue *GV) const { 434 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler()); 435 } 436 437 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const { 438 return TM.getSymbol(GV); 439 } 440 441 MCSymbol *AsmPrinter::getSymbolPreferLocal(const GlobalValue &GV) const { 442 // On ELF, use .Lfoo$local if GV is a non-interposable GlobalObject with an 443 // exact definion (intersection of GlobalValue::hasExactDefinition() and 444 // !isInterposable()). These linkages include: external, appending, internal, 445 // private. It may be profitable to use a local alias for external. The 446 // assembler would otherwise be conservative and assume a global default 447 // visibility symbol can be interposable, even if the code generator already 448 // assumed it. 449 if (TM.getTargetTriple().isOSBinFormatELF() && GV.canBenefitFromLocalAlias()) { 450 const Module &M = *GV.getParent(); 451 if (TM.getRelocationModel() != Reloc::Static && 452 M.getPIELevel() == PIELevel::Default) 453 if (GV.isDSOLocal() || (TM.getTargetTriple().isX86() && 454 GV.getParent()->noSemanticInterposition())) 455 return getSymbolWithGlobalValueBase(&GV, "$local"); 456 } 457 return TM.getSymbol(&GV); 458 } 459 460 /// EmitGlobalVariable - Emit the specified global variable to the .s file. 461 void AsmPrinter::emitGlobalVariable(const GlobalVariable *GV) { 462 bool IsEmuTLSVar = TM.useEmulatedTLS() && GV->isThreadLocal(); 463 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) && 464 "No emulated TLS variables in the common section"); 465 466 // Never emit TLS variable xyz in emulated TLS model. 467 // The initialization value is in __emutls_t.xyz instead of xyz. 468 if (IsEmuTLSVar) 469 return; 470 471 if (GV->hasInitializer()) { 472 // Check to see if this is a special global used by LLVM, if so, emit it. 473 if (emitSpecialLLVMGlobal(GV)) 474 return; 475 476 // Skip the emission of global equivalents. The symbol can be emitted later 477 // on by emitGlobalGOTEquivs in case it turns out to be needed. 478 if (GlobalGOTEquivs.count(getSymbol(GV))) 479 return; 480 481 if (isVerbose()) { 482 // When printing the control variable __emutls_v.*, 483 // we don't need to print the original TLS variable name. 484 GV->printAsOperand(OutStreamer->GetCommentOS(), 485 /*PrintType=*/false, GV->getParent()); 486 OutStreamer->GetCommentOS() << '\n'; 487 } 488 } 489 490 MCSymbol *GVSym = getSymbol(GV); 491 MCSymbol *EmittedSym = GVSym; 492 493 // getOrCreateEmuTLSControlSym only creates the symbol with name and default 494 // attributes. 495 // GV's or GVSym's attributes will be used for the EmittedSym. 496 emitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration()); 497 498 if (!GV->hasInitializer()) // External globals require no extra code. 499 return; 500 501 GVSym->redefineIfPossible(); 502 if (GVSym->isDefined() || GVSym->isVariable()) 503 report_fatal_error("symbol '" + Twine(GVSym->getName()) + 504 "' is already defined"); 505 506 if (MAI->hasDotTypeDotSizeDirective()) 507 OutStreamer->emitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject); 508 509 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM); 510 511 const DataLayout &DL = GV->getParent()->getDataLayout(); 512 uint64_t Size = DL.getTypeAllocSize(GV->getValueType()); 513 514 // If the alignment is specified, we *must* obey it. Overaligning a global 515 // with a specified alignment is a prompt way to break globals emitted to 516 // sections and expected to be contiguous (e.g. ObjC metadata). 517 const Align Alignment = getGVAlignment(GV, DL); 518 519 for (const HandlerInfo &HI : Handlers) { 520 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 521 HI.TimerGroupName, HI.TimerGroupDescription, 522 TimePassesIsEnabled); 523 HI.Handler->setSymbolSize(GVSym, Size); 524 } 525 526 // Handle common symbols 527 if (GVKind.isCommon()) { 528 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 529 // .comm _foo, 42, 4 530 const bool SupportsAlignment = 531 getObjFileLowering().getCommDirectiveSupportsAlignment(); 532 OutStreamer->emitCommonSymbol(GVSym, Size, 533 SupportsAlignment ? Alignment.value() : 0); 534 return; 535 } 536 537 // Determine to which section this global should be emitted. 538 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM); 539 540 // If we have a bss global going to a section that supports the 541 // zerofill directive, do so here. 542 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() && 543 TheSection->isVirtualSection()) { 544 if (Size == 0) 545 Size = 1; // zerofill of 0 bytes is undefined. 546 emitLinkage(GV, GVSym); 547 // .zerofill __DATA, __bss, _foo, 400, 5 548 OutStreamer->emitZerofill(TheSection, GVSym, Size, Alignment.value()); 549 return; 550 } 551 552 // If this is a BSS local symbol and we are emitting in the BSS 553 // section use .lcomm/.comm directive. 554 if (GVKind.isBSSLocal() && 555 getObjFileLowering().getBSSSection() == TheSection) { 556 if (Size == 0) 557 Size = 1; // .comm Foo, 0 is undefined, avoid it. 558 559 // Use .lcomm only if it supports user-specified alignment. 560 // Otherwise, while it would still be correct to use .lcomm in some 561 // cases (e.g. when Align == 1), the external assembler might enfore 562 // some -unknown- default alignment behavior, which could cause 563 // spurious differences between external and integrated assembler. 564 // Prefer to simply fall back to .local / .comm in this case. 565 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) { 566 // .lcomm _foo, 42 567 OutStreamer->emitLocalCommonSymbol(GVSym, Size, Alignment.value()); 568 return; 569 } 570 571 // .local _foo 572 OutStreamer->emitSymbolAttribute(GVSym, MCSA_Local); 573 // .comm _foo, 42, 4 574 const bool SupportsAlignment = 575 getObjFileLowering().getCommDirectiveSupportsAlignment(); 576 OutStreamer->emitCommonSymbol(GVSym, Size, 577 SupportsAlignment ? Alignment.value() : 0); 578 return; 579 } 580 581 // Handle thread local data for mach-o which requires us to output an 582 // additional structure of data and mangle the original symbol so that we 583 // can reference it later. 584 // 585 // TODO: This should become an "emit thread local global" method on TLOF. 586 // All of this macho specific stuff should be sunk down into TLOFMachO and 587 // stuff like "TLSExtraDataSection" should no longer be part of the parent 588 // TLOF class. This will also make it more obvious that stuff like 589 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho 590 // specific code. 591 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) { 592 // Emit the .tbss symbol 593 MCSymbol *MangSym = 594 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init")); 595 596 if (GVKind.isThreadBSS()) { 597 TheSection = getObjFileLowering().getTLSBSSSection(); 598 OutStreamer->emitTBSSSymbol(TheSection, MangSym, Size, Alignment.value()); 599 } else if (GVKind.isThreadData()) { 600 OutStreamer->SwitchSection(TheSection); 601 602 emitAlignment(Alignment, GV); 603 OutStreamer->emitLabel(MangSym); 604 605 emitGlobalConstant(GV->getParent()->getDataLayout(), 606 GV->getInitializer()); 607 } 608 609 OutStreamer->AddBlankLine(); 610 611 // Emit the variable struct for the runtime. 612 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection(); 613 614 OutStreamer->SwitchSection(TLVSect); 615 // Emit the linkage here. 616 emitLinkage(GV, GVSym); 617 OutStreamer->emitLabel(GVSym); 618 619 // Three pointers in size: 620 // - __tlv_bootstrap - used to make sure support exists 621 // - spare pointer, used when mapped by the runtime 622 // - pointer to mangled symbol above with initializer 623 unsigned PtrSize = DL.getPointerTypeSize(GV->getType()); 624 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"), 625 PtrSize); 626 OutStreamer->emitIntValue(0, PtrSize); 627 OutStreamer->emitSymbolValue(MangSym, PtrSize); 628 629 OutStreamer->AddBlankLine(); 630 return; 631 } 632 633 MCSymbol *EmittedInitSym = GVSym; 634 635 OutStreamer->SwitchSection(TheSection); 636 637 emitLinkage(GV, EmittedInitSym); 638 emitAlignment(Alignment, GV); 639 640 OutStreamer->emitLabel(EmittedInitSym); 641 MCSymbol *LocalAlias = getSymbolPreferLocal(*GV); 642 if (LocalAlias != EmittedInitSym) 643 OutStreamer->emitLabel(LocalAlias); 644 645 emitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 646 647 if (MAI->hasDotTypeDotSizeDirective()) 648 // .size foo, 42 649 OutStreamer->emitELFSize(EmittedInitSym, 650 MCConstantExpr::create(Size, OutContext)); 651 652 OutStreamer->AddBlankLine(); 653 } 654 655 /// Emit the directive and value for debug thread local expression 656 /// 657 /// \p Value - The value to emit. 658 /// \p Size - The size of the integer (in bytes) to emit. 659 void AsmPrinter::emitDebugValue(const MCExpr *Value, unsigned Size) const { 660 OutStreamer->emitValue(Value, Size); 661 } 662 663 void AsmPrinter::emitFunctionHeaderComment() {} 664 665 /// EmitFunctionHeader - This method emits the header for the current 666 /// function. 667 void AsmPrinter::emitFunctionHeader() { 668 const Function &F = MF->getFunction(); 669 670 if (isVerbose()) 671 OutStreamer->GetCommentOS() 672 << "-- Begin function " 673 << GlobalValue::dropLLVMManglingEscape(F.getName()) << '\n'; 674 675 // Print out constants referenced by the function 676 emitConstantPool(); 677 678 // Print the 'header' of function. 679 MF->setSection(getObjFileLowering().SectionForGlobal(&F, TM)); 680 OutStreamer->SwitchSection(MF->getSection()); 681 682 if (!MAI->hasVisibilityOnlyWithLinkage()) 683 emitVisibility(CurrentFnSym, F.getVisibility()); 684 685 if (MAI->needsFunctionDescriptors() && 686 F.getLinkage() != GlobalValue::InternalLinkage) 687 emitLinkage(&F, CurrentFnDescSym); 688 689 emitLinkage(&F, CurrentFnSym); 690 if (MAI->hasFunctionAlignment()) 691 emitAlignment(MF->getAlignment(), &F); 692 693 if (MAI->hasDotTypeDotSizeDirective()) 694 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction); 695 696 if (F.hasFnAttribute(Attribute::Cold)) 697 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_Cold); 698 699 if (isVerbose()) { 700 F.printAsOperand(OutStreamer->GetCommentOS(), 701 /*PrintType=*/false, F.getParent()); 702 emitFunctionHeaderComment(); 703 OutStreamer->GetCommentOS() << '\n'; 704 } 705 706 // Emit the prefix data. 707 if (F.hasPrefixData()) { 708 if (MAI->hasSubsectionsViaSymbols()) { 709 // Preserving prefix data on platforms which use subsections-via-symbols 710 // is a bit tricky. Here we introduce a symbol for the prefix data 711 // and use the .alt_entry attribute to mark the function's real entry point 712 // as an alternative entry point to the prefix-data symbol. 713 MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol(); 714 OutStreamer->emitLabel(PrefixSym); 715 716 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData()); 717 718 // Emit an .alt_entry directive for the actual function symbol. 719 OutStreamer->emitSymbolAttribute(CurrentFnSym, MCSA_AltEntry); 720 } else { 721 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrefixData()); 722 } 723 } 724 725 // Emit M NOPs for -fpatchable-function-entry=N,M where M>0. We arbitrarily 726 // place prefix data before NOPs. 727 unsigned PatchableFunctionPrefix = 0; 728 unsigned PatchableFunctionEntry = 0; 729 (void)F.getFnAttribute("patchable-function-prefix") 730 .getValueAsString() 731 .getAsInteger(10, PatchableFunctionPrefix); 732 (void)F.getFnAttribute("patchable-function-entry") 733 .getValueAsString() 734 .getAsInteger(10, PatchableFunctionEntry); 735 if (PatchableFunctionPrefix) { 736 CurrentPatchableFunctionEntrySym = 737 OutContext.createLinkerPrivateTempSymbol(); 738 OutStreamer->emitLabel(CurrentPatchableFunctionEntrySym); 739 emitNops(PatchableFunctionPrefix); 740 } else if (PatchableFunctionEntry) { 741 // May be reassigned when emitting the body, to reference the label after 742 // the initial BTI (AArch64) or endbr32/endbr64 (x86). 743 CurrentPatchableFunctionEntrySym = CurrentFnBegin; 744 } 745 746 // Emit the function descriptor. This is a virtual function to allow targets 747 // to emit their specific function descriptor. Right now it is only used by 748 // the AIX target. The PowerPC 64-bit V1 ELF target also uses function 749 // descriptors and should be converted to use this hook as well. 750 if (MAI->needsFunctionDescriptors()) 751 emitFunctionDescriptor(); 752 753 // Emit the CurrentFnSym. This is a virtual function to allow targets to do 754 // their wild and crazy things as required. 755 emitFunctionEntryLabel(); 756 757 if (CurrentFnBegin) { 758 if (MAI->useAssignmentForEHBegin()) { 759 MCSymbol *CurPos = OutContext.createTempSymbol(); 760 OutStreamer->emitLabel(CurPos); 761 OutStreamer->emitAssignment(CurrentFnBegin, 762 MCSymbolRefExpr::create(CurPos, OutContext)); 763 } else { 764 OutStreamer->emitLabel(CurrentFnBegin); 765 } 766 } 767 768 // Emit pre-function debug and/or EH information. 769 for (const HandlerInfo &HI : Handlers) { 770 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 771 HI.TimerGroupDescription, TimePassesIsEnabled); 772 HI.Handler->beginFunction(MF); 773 } 774 775 // Emit the prologue data. 776 if (F.hasPrologueData()) 777 emitGlobalConstant(F.getParent()->getDataLayout(), F.getPrologueData()); 778 } 779 780 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the 781 /// function. This can be overridden by targets as required to do custom stuff. 782 void AsmPrinter::emitFunctionEntryLabel() { 783 CurrentFnSym->redefineIfPossible(); 784 785 // The function label could have already been emitted if two symbols end up 786 // conflicting due to asm renaming. Detect this and emit an error. 787 if (CurrentFnSym->isVariable()) 788 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 789 "' is a protected alias"); 790 if (CurrentFnSym->isDefined()) 791 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 792 "' label emitted multiple times to assembly file"); 793 794 OutStreamer->emitLabel(CurrentFnSym); 795 796 if (TM.getTargetTriple().isOSBinFormatELF()) { 797 MCSymbol *Sym = getSymbolPreferLocal(MF->getFunction()); 798 if (Sym != CurrentFnSym) 799 OutStreamer->emitLabel(Sym); 800 } 801 } 802 803 /// emitComments - Pretty-print comments for instructions. 804 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS) { 805 const MachineFunction *MF = MI.getMF(); 806 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 807 808 // Check for spills and reloads 809 810 // We assume a single instruction only has a spill or reload, not 811 // both. 812 Optional<unsigned> Size; 813 if ((Size = MI.getRestoreSize(TII))) { 814 CommentOS << *Size << "-byte Reload\n"; 815 } else if ((Size = MI.getFoldedRestoreSize(TII))) { 816 if (*Size) 817 CommentOS << *Size << "-byte Folded Reload\n"; 818 } else if ((Size = MI.getSpillSize(TII))) { 819 CommentOS << *Size << "-byte Spill\n"; 820 } else if ((Size = MI.getFoldedSpillSize(TII))) { 821 if (*Size) 822 CommentOS << *Size << "-byte Folded Spill\n"; 823 } 824 825 // Check for spill-induced copies 826 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse)) 827 CommentOS << " Reload Reuse\n"; 828 } 829 830 /// emitImplicitDef - This method emits the specified machine instruction 831 /// that is an implicit def. 832 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const { 833 Register RegNo = MI->getOperand(0).getReg(); 834 835 SmallString<128> Str; 836 raw_svector_ostream OS(Str); 837 OS << "implicit-def: " 838 << printReg(RegNo, MF->getSubtarget().getRegisterInfo()); 839 840 OutStreamer->AddComment(OS.str()); 841 OutStreamer->AddBlankLine(); 842 } 843 844 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) { 845 std::string Str; 846 raw_string_ostream OS(Str); 847 OS << "kill:"; 848 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 849 const MachineOperand &Op = MI->getOperand(i); 850 assert(Op.isReg() && "KILL instruction must have only register operands"); 851 OS << ' ' << (Op.isDef() ? "def " : "killed ") 852 << printReg(Op.getReg(), AP.MF->getSubtarget().getRegisterInfo()); 853 } 854 AP.OutStreamer->AddComment(OS.str()); 855 AP.OutStreamer->AddBlankLine(); 856 } 857 858 /// emitDebugValueComment - This method handles the target-independent form 859 /// of DBG_VALUE, returning true if it was able to do so. A false return 860 /// means the target will need to handle MI in EmitInstruction. 861 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) { 862 // This code handles only the 4-operand target-independent form. 863 if (MI->getNumOperands() != 4) 864 return false; 865 866 SmallString<128> Str; 867 raw_svector_ostream OS(Str); 868 OS << "DEBUG_VALUE: "; 869 870 const DILocalVariable *V = MI->getDebugVariable(); 871 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) { 872 StringRef Name = SP->getName(); 873 if (!Name.empty()) 874 OS << Name << ":"; 875 } 876 OS << V->getName(); 877 OS << " <- "; 878 879 // The second operand is only an offset if it's an immediate. 880 bool MemLoc = MI->isIndirectDebugValue(); 881 int64_t Offset = MemLoc ? MI->getOperand(1).getImm() : 0; 882 const DIExpression *Expr = MI->getDebugExpression(); 883 if (Expr->getNumElements()) { 884 OS << '['; 885 bool NeedSep = false; 886 for (auto Op : Expr->expr_ops()) { 887 if (NeedSep) 888 OS << ", "; 889 else 890 NeedSep = true; 891 OS << dwarf::OperationEncodingString(Op.getOp()); 892 for (unsigned I = 0; I < Op.getNumArgs(); ++I) 893 OS << ' ' << Op.getArg(I); 894 } 895 OS << "] "; 896 } 897 898 // Register or immediate value. Register 0 means undef. 899 if (MI->getDebugOperand(0).isFPImm()) { 900 APFloat APF = APFloat(MI->getDebugOperand(0).getFPImm()->getValueAPF()); 901 if (MI->getDebugOperand(0).getFPImm()->getType()->isFloatTy()) { 902 OS << (double)APF.convertToFloat(); 903 } else if (MI->getDebugOperand(0).getFPImm()->getType()->isDoubleTy()) { 904 OS << APF.convertToDouble(); 905 } else { 906 // There is no good way to print long double. Convert a copy to 907 // double. Ah well, it's only a comment. 908 bool ignored; 909 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, 910 &ignored); 911 OS << "(long double) " << APF.convertToDouble(); 912 } 913 } else if (MI->getDebugOperand(0).isImm()) { 914 OS << MI->getDebugOperand(0).getImm(); 915 } else if (MI->getDebugOperand(0).isCImm()) { 916 MI->getDebugOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/); 917 } else if (MI->getDebugOperand(0).isTargetIndex()) { 918 auto Op = MI->getDebugOperand(0); 919 OS << "!target-index(" << Op.getIndex() << "," << Op.getOffset() << ")"; 920 return true; 921 } else { 922 Register Reg; 923 if (MI->getDebugOperand(0).isReg()) { 924 Reg = MI->getDebugOperand(0).getReg(); 925 } else { 926 assert(MI->getDebugOperand(0).isFI() && "Unknown operand type"); 927 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering(); 928 Offset += TFI->getFrameIndexReference( 929 *AP.MF, MI->getDebugOperand(0).getIndex(), Reg); 930 MemLoc = true; 931 } 932 if (Reg == 0) { 933 // Suppress offset, it is not meaningful here. 934 OS << "undef"; 935 // NOTE: Want this comment at start of line, don't emit with AddComment. 936 AP.OutStreamer->emitRawComment(OS.str()); 937 return true; 938 } 939 if (MemLoc) 940 OS << '['; 941 OS << printReg(Reg, AP.MF->getSubtarget().getRegisterInfo()); 942 } 943 944 if (MemLoc) 945 OS << '+' << Offset << ']'; 946 947 // NOTE: Want this comment at start of line, don't emit with AddComment. 948 AP.OutStreamer->emitRawComment(OS.str()); 949 return true; 950 } 951 952 /// This method handles the target-independent form of DBG_LABEL, returning 953 /// true if it was able to do so. A false return means the target will need 954 /// to handle MI in EmitInstruction. 955 static bool emitDebugLabelComment(const MachineInstr *MI, AsmPrinter &AP) { 956 if (MI->getNumOperands() != 1) 957 return false; 958 959 SmallString<128> Str; 960 raw_svector_ostream OS(Str); 961 OS << "DEBUG_LABEL: "; 962 963 const DILabel *V = MI->getDebugLabel(); 964 if (auto *SP = dyn_cast<DISubprogram>( 965 V->getScope()->getNonLexicalBlockFileScope())) { 966 StringRef Name = SP->getName(); 967 if (!Name.empty()) 968 OS << Name << ":"; 969 } 970 OS << V->getName(); 971 972 // NOTE: Want this comment at start of line, don't emit with AddComment. 973 AP.OutStreamer->emitRawComment(OS.str()); 974 return true; 975 } 976 977 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() const { 978 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI && 979 MF->getFunction().needsUnwindTableEntry()) 980 return CFI_M_EH; 981 982 if (MMI->hasDebugInfo() || MF->getTarget().Options.ForceDwarfFrameSection) 983 return CFI_M_Debug; 984 985 return CFI_M_None; 986 } 987 988 bool AsmPrinter::needsSEHMoves() { 989 return MAI->usesWindowsCFI() && MF->getFunction().needsUnwindTableEntry(); 990 } 991 992 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) { 993 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType(); 994 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI && 995 ExceptionHandlingType != ExceptionHandling::ARM) 996 return; 997 998 if (needsCFIMoves() == CFI_M_None) 999 return; 1000 1001 // If there is no "real" instruction following this CFI instruction, skip 1002 // emitting it; it would be beyond the end of the function's FDE range. 1003 auto *MBB = MI.getParent(); 1004 auto I = std::next(MI.getIterator()); 1005 while (I != MBB->end() && I->isTransient()) 1006 ++I; 1007 if (I == MBB->instr_end() && 1008 MBB->getReverseIterator() == MBB->getParent()->rbegin()) 1009 return; 1010 1011 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions(); 1012 unsigned CFIIndex = MI.getOperand(0).getCFIIndex(); 1013 const MCCFIInstruction &CFI = Instrs[CFIIndex]; 1014 emitCFIInstruction(CFI); 1015 } 1016 1017 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) { 1018 // The operands are the MCSymbol and the frame offset of the allocation. 1019 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol(); 1020 int FrameOffset = MI.getOperand(1).getImm(); 1021 1022 // Emit a symbol assignment. 1023 OutStreamer->emitAssignment(FrameAllocSym, 1024 MCConstantExpr::create(FrameOffset, OutContext)); 1025 } 1026 1027 void AsmPrinter::emitStackSizeSection(const MachineFunction &MF) { 1028 if (!MF.getTarget().Options.EmitStackSizeSection) 1029 return; 1030 1031 MCSection *StackSizeSection = 1032 getObjFileLowering().getStackSizesSection(*getCurrentSection()); 1033 if (!StackSizeSection) 1034 return; 1035 1036 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 1037 // Don't emit functions with dynamic stack allocations. 1038 if (FrameInfo.hasVarSizedObjects()) 1039 return; 1040 1041 OutStreamer->PushSection(); 1042 OutStreamer->SwitchSection(StackSizeSection); 1043 1044 const MCSymbol *FunctionSymbol = getFunctionBegin(); 1045 uint64_t StackSize = FrameInfo.getStackSize(); 1046 OutStreamer->emitSymbolValue(FunctionSymbol, TM.getProgramPointerSize()); 1047 OutStreamer->emitULEB128IntValue(StackSize); 1048 1049 OutStreamer->PopSection(); 1050 } 1051 1052 static bool needFuncLabelsForEHOrDebugInfo(const MachineFunction &MF) { 1053 MachineModuleInfo &MMI = MF.getMMI(); 1054 if (!MF.getLandingPads().empty() || MF.hasEHFunclets() || MMI.hasDebugInfo()) 1055 return true; 1056 1057 // We might emit an EH table that uses function begin and end labels even if 1058 // we don't have any landingpads. 1059 if (!MF.getFunction().hasPersonalityFn()) 1060 return false; 1061 return !isNoOpWithoutInvoke( 1062 classifyEHPersonality(MF.getFunction().getPersonalityFn())); 1063 } 1064 1065 /// EmitFunctionBody - This method emits the body and trailer for a 1066 /// function. 1067 void AsmPrinter::emitFunctionBody() { 1068 emitFunctionHeader(); 1069 1070 // Emit target-specific gunk before the function body. 1071 emitFunctionBodyStart(); 1072 1073 bool ShouldPrintDebugScopes = MMI->hasDebugInfo(); 1074 1075 if (isVerbose()) { 1076 // Get MachineDominatorTree or compute it on the fly if it's unavailable 1077 MDT = getAnalysisIfAvailable<MachineDominatorTree>(); 1078 if (!MDT) { 1079 OwnedMDT = std::make_unique<MachineDominatorTree>(); 1080 OwnedMDT->getBase().recalculate(*MF); 1081 MDT = OwnedMDT.get(); 1082 } 1083 1084 // Get MachineLoopInfo or compute it on the fly if it's unavailable 1085 MLI = getAnalysisIfAvailable<MachineLoopInfo>(); 1086 if (!MLI) { 1087 OwnedMLI = std::make_unique<MachineLoopInfo>(); 1088 OwnedMLI->getBase().analyze(MDT->getBase()); 1089 MLI = OwnedMLI.get(); 1090 } 1091 } 1092 1093 // Print out code for the function. 1094 bool HasAnyRealCode = false; 1095 int NumInstsInFunction = 0; 1096 1097 for (auto &MBB : *MF) { 1098 // Print a label for the basic block. 1099 emitBasicBlockStart(MBB); 1100 for (auto &MI : MBB) { 1101 // Print the assembly for the instruction. 1102 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() && 1103 !MI.isDebugInstr()) { 1104 HasAnyRealCode = true; 1105 ++NumInstsInFunction; 1106 } 1107 1108 // If there is a pre-instruction symbol, emit a label for it here. 1109 if (MCSymbol *S = MI.getPreInstrSymbol()) 1110 OutStreamer->emitLabel(S); 1111 1112 if (ShouldPrintDebugScopes) { 1113 for (const HandlerInfo &HI : Handlers) { 1114 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 1115 HI.TimerGroupName, HI.TimerGroupDescription, 1116 TimePassesIsEnabled); 1117 HI.Handler->beginInstruction(&MI); 1118 } 1119 } 1120 1121 if (isVerbose()) 1122 emitComments(MI, OutStreamer->GetCommentOS()); 1123 1124 switch (MI.getOpcode()) { 1125 case TargetOpcode::CFI_INSTRUCTION: 1126 emitCFIInstruction(MI); 1127 break; 1128 case TargetOpcode::LOCAL_ESCAPE: 1129 emitFrameAlloc(MI); 1130 break; 1131 case TargetOpcode::ANNOTATION_LABEL: 1132 case TargetOpcode::EH_LABEL: 1133 case TargetOpcode::GC_LABEL: 1134 OutStreamer->emitLabel(MI.getOperand(0).getMCSymbol()); 1135 break; 1136 case TargetOpcode::INLINEASM: 1137 case TargetOpcode::INLINEASM_BR: 1138 emitInlineAsm(&MI); 1139 break; 1140 case TargetOpcode::DBG_VALUE: 1141 if (isVerbose()) { 1142 if (!emitDebugValueComment(&MI, *this)) 1143 emitInstruction(&MI); 1144 } 1145 break; 1146 case TargetOpcode::DBG_LABEL: 1147 if (isVerbose()) { 1148 if (!emitDebugLabelComment(&MI, *this)) 1149 emitInstruction(&MI); 1150 } 1151 break; 1152 case TargetOpcode::IMPLICIT_DEF: 1153 if (isVerbose()) emitImplicitDef(&MI); 1154 break; 1155 case TargetOpcode::KILL: 1156 if (isVerbose()) emitKill(&MI, *this); 1157 break; 1158 default: 1159 emitInstruction(&MI); 1160 break; 1161 } 1162 1163 // If there is a post-instruction symbol, emit a label for it here. 1164 if (MCSymbol *S = MI.getPostInstrSymbol()) 1165 OutStreamer->emitLabel(S); 1166 1167 if (ShouldPrintDebugScopes) { 1168 for (const HandlerInfo &HI : Handlers) { 1169 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 1170 HI.TimerGroupName, HI.TimerGroupDescription, 1171 TimePassesIsEnabled); 1172 HI.Handler->endInstruction(); 1173 } 1174 } 1175 } 1176 1177 // We need a temporary symbol for the end of this basic block, if either we 1178 // have BBLabels enabled and we want to emit size directive for the BBs, or 1179 // if this basic blocks marks the end of a section (except the section 1180 // containing the entry basic block as the end symbol for that section is 1181 // CurrentFnEnd). 1182 MCSymbol *CurrentBBEnd = nullptr; 1183 if ((MAI->hasDotTypeDotSizeDirective() && MF->hasBBLabels()) || 1184 (MBB.isEndSection() && !MBB.sameSection(&MF->front()))) { 1185 CurrentBBEnd = OutContext.createTempSymbol(); 1186 OutStreamer->emitLabel(CurrentBBEnd); 1187 } 1188 1189 // Helper for emitting the size directive associated with a basic block 1190 // symbol. 1191 auto emitELFSizeDirective = [&](MCSymbol *SymForSize) { 1192 assert(CurrentBBEnd && "Basicblock end symbol not set!"); 1193 const MCExpr *SizeExp = MCBinaryExpr::createSub( 1194 MCSymbolRefExpr::create(CurrentBBEnd, OutContext), 1195 MCSymbolRefExpr::create(SymForSize, OutContext), OutContext); 1196 OutStreamer->emitELFSize(SymForSize, SizeExp); 1197 }; 1198 1199 // Emit size directive for the size of each basic block, if BBLabels is 1200 // enabled. 1201 if (MAI->hasDotTypeDotSizeDirective() && MF->hasBBLabels()) 1202 emitELFSizeDirective(MBB.getSymbol()); 1203 1204 // Emit size directive for the size of each basic block section once we 1205 // get to the end of that section. 1206 if (MBB.isEndSection()) { 1207 if (!MBB.sameSection(&MF->front())) { 1208 if (MAI->hasDotTypeDotSizeDirective()) 1209 emitELFSizeDirective(CurrentSectionBeginSym); 1210 MBBSectionRanges[MBB.getSectionIDNum()] = 1211 MBBSectionRange{CurrentSectionBeginSym, CurrentBBEnd}; 1212 } 1213 } 1214 emitBasicBlockEnd(MBB); 1215 } 1216 1217 EmittedInsts += NumInstsInFunction; 1218 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount", 1219 MF->getFunction().getSubprogram(), 1220 &MF->front()); 1221 R << ore::NV("NumInstructions", NumInstsInFunction) 1222 << " instructions in function"; 1223 ORE->emit(R); 1224 1225 // If the function is empty and the object file uses .subsections_via_symbols, 1226 // then we need to emit *something* to the function body to prevent the 1227 // labels from collapsing together. Just emit a noop. 1228 // Similarly, don't emit empty functions on Windows either. It can lead to 1229 // duplicate entries (two functions with the same RVA) in the Guard CF Table 1230 // after linking, causing the kernel not to load the binary: 1231 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html 1232 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer. 1233 const Triple &TT = TM.getTargetTriple(); 1234 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() || 1235 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) { 1236 MCInst Noop; 1237 MF->getSubtarget().getInstrInfo()->getNoop(Noop); 1238 1239 // Targets can opt-out of emitting the noop here by leaving the opcode 1240 // unspecified. 1241 if (Noop.getOpcode()) { 1242 OutStreamer->AddComment("avoids zero-length function"); 1243 emitNops(1); 1244 } 1245 } 1246 1247 // Switch to the original section in case basic block sections was used. 1248 OutStreamer->SwitchSection(MF->getSection()); 1249 1250 const Function &F = MF->getFunction(); 1251 for (const auto &BB : F) { 1252 if (!BB.hasAddressTaken()) 1253 continue; 1254 MCSymbol *Sym = GetBlockAddressSymbol(&BB); 1255 if (Sym->isDefined()) 1256 continue; 1257 OutStreamer->AddComment("Address of block that was removed by CodeGen"); 1258 OutStreamer->emitLabel(Sym); 1259 } 1260 1261 // Emit target-specific gunk after the function body. 1262 emitFunctionBodyEnd(); 1263 1264 if (needFuncLabelsForEHOrDebugInfo(*MF) || 1265 MAI->hasDotTypeDotSizeDirective()) { 1266 // Create a symbol for the end of function. 1267 CurrentFnEnd = createTempSymbol("func_end"); 1268 OutStreamer->emitLabel(CurrentFnEnd); 1269 } 1270 1271 // If the target wants a .size directive for the size of the function, emit 1272 // it. 1273 if (MAI->hasDotTypeDotSizeDirective()) { 1274 // We can get the size as difference between the function label and the 1275 // temp label. 1276 const MCExpr *SizeExp = MCBinaryExpr::createSub( 1277 MCSymbolRefExpr::create(CurrentFnEnd, OutContext), 1278 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext); 1279 OutStreamer->emitELFSize(CurrentFnSym, SizeExp); 1280 } 1281 1282 for (const HandlerInfo &HI : Handlers) { 1283 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1284 HI.TimerGroupDescription, TimePassesIsEnabled); 1285 HI.Handler->markFunctionEnd(); 1286 } 1287 1288 MBBSectionRanges[MF->front().getSectionIDNum()] = 1289 MBBSectionRange{CurrentFnBegin, CurrentFnEnd}; 1290 1291 // Print out jump tables referenced by the function. 1292 emitJumpTableInfo(); 1293 1294 // Emit post-function debug and/or EH information. 1295 for (const HandlerInfo &HI : Handlers) { 1296 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1297 HI.TimerGroupDescription, TimePassesIsEnabled); 1298 HI.Handler->endFunction(MF); 1299 } 1300 1301 // Emit section containing stack size metadata. 1302 emitStackSizeSection(*MF); 1303 1304 emitPatchableFunctionEntries(); 1305 1306 if (isVerbose()) 1307 OutStreamer->GetCommentOS() << "-- End function\n"; 1308 1309 OutStreamer->AddBlankLine(); 1310 } 1311 1312 /// Compute the number of Global Variables that uses a Constant. 1313 static unsigned getNumGlobalVariableUses(const Constant *C) { 1314 if (!C) 1315 return 0; 1316 1317 if (isa<GlobalVariable>(C)) 1318 return 1; 1319 1320 unsigned NumUses = 0; 1321 for (auto *CU : C->users()) 1322 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU)); 1323 1324 return NumUses; 1325 } 1326 1327 /// Only consider global GOT equivalents if at least one user is a 1328 /// cstexpr inside an initializer of another global variables. Also, don't 1329 /// handle cstexpr inside instructions. During global variable emission, 1330 /// candidates are skipped and are emitted later in case at least one cstexpr 1331 /// isn't replaced by a PC relative GOT entry access. 1332 static bool isGOTEquivalentCandidate(const GlobalVariable *GV, 1333 unsigned &NumGOTEquivUsers) { 1334 // Global GOT equivalents are unnamed private globals with a constant 1335 // pointer initializer to another global symbol. They must point to a 1336 // GlobalVariable or Function, i.e., as GlobalValue. 1337 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() || 1338 !GV->isConstant() || !GV->isDiscardableIfUnused() || 1339 !isa<GlobalValue>(GV->getOperand(0))) 1340 return false; 1341 1342 // To be a got equivalent, at least one of its users need to be a constant 1343 // expression used by another global variable. 1344 for (auto *U : GV->users()) 1345 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U)); 1346 1347 return NumGOTEquivUsers > 0; 1348 } 1349 1350 /// Unnamed constant global variables solely contaning a pointer to 1351 /// another globals variable is equivalent to a GOT table entry; it contains the 1352 /// the address of another symbol. Optimize it and replace accesses to these 1353 /// "GOT equivalents" by using the GOT entry for the final global instead. 1354 /// Compute GOT equivalent candidates among all global variables to avoid 1355 /// emitting them if possible later on, after it use is replaced by a GOT entry 1356 /// access. 1357 void AsmPrinter::computeGlobalGOTEquivs(Module &M) { 1358 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1359 return; 1360 1361 for (const auto &G : M.globals()) { 1362 unsigned NumGOTEquivUsers = 0; 1363 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers)) 1364 continue; 1365 1366 const MCSymbol *GOTEquivSym = getSymbol(&G); 1367 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers); 1368 } 1369 } 1370 1371 /// Constant expressions using GOT equivalent globals may not be eligible 1372 /// for PC relative GOT entry conversion, in such cases we need to emit such 1373 /// globals we previously omitted in EmitGlobalVariable. 1374 void AsmPrinter::emitGlobalGOTEquivs() { 1375 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1376 return; 1377 1378 SmallVector<const GlobalVariable *, 8> FailedCandidates; 1379 for (auto &I : GlobalGOTEquivs) { 1380 const GlobalVariable *GV = I.second.first; 1381 unsigned Cnt = I.second.second; 1382 if (Cnt) 1383 FailedCandidates.push_back(GV); 1384 } 1385 GlobalGOTEquivs.clear(); 1386 1387 for (auto *GV : FailedCandidates) 1388 emitGlobalVariable(GV); 1389 } 1390 1391 void AsmPrinter::emitGlobalIndirectSymbol(Module &M, 1392 const GlobalIndirectSymbol& GIS) { 1393 MCSymbol *Name = getSymbol(&GIS); 1394 1395 if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective()) 1396 OutStreamer->emitSymbolAttribute(Name, MCSA_Global); 1397 else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage()) 1398 OutStreamer->emitSymbolAttribute(Name, MCSA_WeakReference); 1399 else 1400 assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage"); 1401 1402 bool IsFunction = GIS.getValueType()->isFunctionTy(); 1403 1404 // Treat bitcasts of functions as functions also. This is important at least 1405 // on WebAssembly where object and function addresses can't alias each other. 1406 if (!IsFunction) 1407 if (auto *CE = dyn_cast<ConstantExpr>(GIS.getIndirectSymbol())) 1408 if (CE->getOpcode() == Instruction::BitCast) 1409 IsFunction = 1410 CE->getOperand(0)->getType()->getPointerElementType()->isFunctionTy(); 1411 1412 // Set the symbol type to function if the alias has a function type. 1413 // This affects codegen when the aliasee is not a function. 1414 if (IsFunction) 1415 OutStreamer->emitSymbolAttribute(Name, isa<GlobalIFunc>(GIS) 1416 ? MCSA_ELF_TypeIndFunction 1417 : MCSA_ELF_TypeFunction); 1418 1419 emitVisibility(Name, GIS.getVisibility()); 1420 1421 const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol()); 1422 1423 if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr)) 1424 OutStreamer->emitSymbolAttribute(Name, MCSA_AltEntry); 1425 1426 // Emit the directives as assignments aka .set: 1427 OutStreamer->emitAssignment(Name, Expr); 1428 MCSymbol *LocalAlias = getSymbolPreferLocal(GIS); 1429 if (LocalAlias != Name) 1430 OutStreamer->emitAssignment(LocalAlias, Expr); 1431 1432 if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) { 1433 // If the aliasee does not correspond to a symbol in the output, i.e. the 1434 // alias is not of an object or the aliased object is private, then set the 1435 // size of the alias symbol from the type of the alias. We don't do this in 1436 // other situations as the alias and aliasee having differing types but same 1437 // size may be intentional. 1438 const GlobalObject *BaseObject = GA->getBaseObject(); 1439 if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() && 1440 (!BaseObject || BaseObject->hasPrivateLinkage())) { 1441 const DataLayout &DL = M.getDataLayout(); 1442 uint64_t Size = DL.getTypeAllocSize(GA->getValueType()); 1443 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext)); 1444 } 1445 } 1446 } 1447 1448 void AsmPrinter::emitRemarksSection(remarks::RemarkStreamer &RS) { 1449 if (!RS.needsSection()) 1450 return; 1451 1452 remarks::RemarkSerializer &RemarkSerializer = RS.getSerializer(); 1453 1454 Optional<SmallString<128>> Filename; 1455 if (Optional<StringRef> FilenameRef = RS.getFilename()) { 1456 Filename = *FilenameRef; 1457 sys::fs::make_absolute(*Filename); 1458 assert(!Filename->empty() && "The filename can't be empty."); 1459 } 1460 1461 std::string Buf; 1462 raw_string_ostream OS(Buf); 1463 std::unique_ptr<remarks::MetaSerializer> MetaSerializer = 1464 Filename ? RemarkSerializer.metaSerializer(OS, StringRef(*Filename)) 1465 : RemarkSerializer.metaSerializer(OS); 1466 MetaSerializer->emit(); 1467 1468 // Switch to the remarks section. 1469 MCSection *RemarksSection = 1470 OutContext.getObjectFileInfo()->getRemarksSection(); 1471 OutStreamer->SwitchSection(RemarksSection); 1472 1473 OutStreamer->emitBinaryData(OS.str()); 1474 } 1475 1476 bool AsmPrinter::doFinalization(Module &M) { 1477 // Set the MachineFunction to nullptr so that we can catch attempted 1478 // accesses to MF specific features at the module level and so that 1479 // we can conditionalize accesses based on whether or not it is nullptr. 1480 MF = nullptr; 1481 1482 // Gather all GOT equivalent globals in the module. We really need two 1483 // passes over the globals: one to compute and another to avoid its emission 1484 // in EmitGlobalVariable, otherwise we would not be able to handle cases 1485 // where the got equivalent shows up before its use. 1486 computeGlobalGOTEquivs(M); 1487 1488 // Emit global variables. 1489 for (const auto &G : M.globals()) 1490 emitGlobalVariable(&G); 1491 1492 // Emit remaining GOT equivalent globals. 1493 emitGlobalGOTEquivs(); 1494 1495 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1496 1497 // Emit linkage(XCOFF) and visibility info for declarations 1498 for (const Function &F : M) { 1499 if (!F.isDeclarationForLinker()) 1500 continue; 1501 1502 MCSymbol *Name = getSymbol(&F); 1503 // Function getSymbol gives us the function descriptor symbol for XCOFF. 1504 1505 if (!TM.getTargetTriple().isOSBinFormatXCOFF()) { 1506 GlobalValue::VisibilityTypes V = F.getVisibility(); 1507 if (V == GlobalValue::DefaultVisibility) 1508 continue; 1509 1510 emitVisibility(Name, V, false); 1511 continue; 1512 } 1513 1514 if (F.isIntrinsic()) 1515 continue; 1516 1517 // Handle the XCOFF case. 1518 // Variable `Name` is the function descriptor symbol (see above). Get the 1519 // function entry point symbol. 1520 MCSymbol *FnEntryPointSym = TLOF.getFunctionEntryPointSymbol(&F, TM); 1521 if (cast<MCSymbolXCOFF>(FnEntryPointSym)->hasRepresentedCsectSet()) 1522 // Emit linkage for the function entry point. 1523 emitLinkage(&F, FnEntryPointSym); 1524 1525 // Emit linkage for the function descriptor. 1526 emitLinkage(&F, Name); 1527 } 1528 1529 // Emit the remarks section contents. 1530 // FIXME: Figure out when is the safest time to emit this section. It should 1531 // not come after debug info. 1532 if (remarks::RemarkStreamer *RS = M.getContext().getMainRemarkStreamer()) 1533 emitRemarksSection(*RS); 1534 1535 TLOF.emitModuleMetadata(*OutStreamer, M); 1536 1537 if (TM.getTargetTriple().isOSBinFormatELF()) { 1538 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>(); 1539 1540 // Output stubs for external and common global variables. 1541 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList(); 1542 if (!Stubs.empty()) { 1543 OutStreamer->SwitchSection(TLOF.getDataSection()); 1544 const DataLayout &DL = M.getDataLayout(); 1545 1546 emitAlignment(Align(DL.getPointerSize())); 1547 for (const auto &Stub : Stubs) { 1548 OutStreamer->emitLabel(Stub.first); 1549 OutStreamer->emitSymbolValue(Stub.second.getPointer(), 1550 DL.getPointerSize()); 1551 } 1552 } 1553 } 1554 1555 if (TM.getTargetTriple().isOSBinFormatCOFF()) { 1556 MachineModuleInfoCOFF &MMICOFF = 1557 MMI->getObjFileInfo<MachineModuleInfoCOFF>(); 1558 1559 // Output stubs for external and common global variables. 1560 MachineModuleInfoCOFF::SymbolListTy Stubs = MMICOFF.GetGVStubList(); 1561 if (!Stubs.empty()) { 1562 const DataLayout &DL = M.getDataLayout(); 1563 1564 for (const auto &Stub : Stubs) { 1565 SmallString<256> SectionName = StringRef(".rdata$"); 1566 SectionName += Stub.first->getName(); 1567 OutStreamer->SwitchSection(OutContext.getCOFFSection( 1568 SectionName, 1569 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ | 1570 COFF::IMAGE_SCN_LNK_COMDAT, 1571 SectionKind::getReadOnly(), Stub.first->getName(), 1572 COFF::IMAGE_COMDAT_SELECT_ANY)); 1573 emitAlignment(Align(DL.getPointerSize())); 1574 OutStreamer->emitSymbolAttribute(Stub.first, MCSA_Global); 1575 OutStreamer->emitLabel(Stub.first); 1576 OutStreamer->emitSymbolValue(Stub.second.getPointer(), 1577 DL.getPointerSize()); 1578 } 1579 } 1580 } 1581 1582 // Finalize debug and EH information. 1583 for (const HandlerInfo &HI : Handlers) { 1584 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1585 HI.TimerGroupDescription, TimePassesIsEnabled); 1586 HI.Handler->endModule(); 1587 } 1588 Handlers.clear(); 1589 DD = nullptr; 1590 1591 // If the target wants to know about weak references, print them all. 1592 if (MAI->getWeakRefDirective()) { 1593 // FIXME: This is not lazy, it would be nice to only print weak references 1594 // to stuff that is actually used. Note that doing so would require targets 1595 // to notice uses in operands (due to constant exprs etc). This should 1596 // happen with the MC stuff eventually. 1597 1598 // Print out module-level global objects here. 1599 for (const auto &GO : M.global_objects()) { 1600 if (!GO.hasExternalWeakLinkage()) 1601 continue; 1602 OutStreamer->emitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference); 1603 } 1604 } 1605 1606 // Print aliases in topological order, that is, for each alias a = b, 1607 // b must be printed before a. 1608 // This is because on some targets (e.g. PowerPC) linker expects aliases in 1609 // such an order to generate correct TOC information. 1610 SmallVector<const GlobalAlias *, 16> AliasStack; 1611 SmallPtrSet<const GlobalAlias *, 16> AliasVisited; 1612 for (const auto &Alias : M.aliases()) { 1613 for (const GlobalAlias *Cur = &Alias; Cur; 1614 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) { 1615 if (!AliasVisited.insert(Cur).second) 1616 break; 1617 AliasStack.push_back(Cur); 1618 } 1619 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack)) 1620 emitGlobalIndirectSymbol(M, *AncestorAlias); 1621 AliasStack.clear(); 1622 } 1623 for (const auto &IFunc : M.ifuncs()) 1624 emitGlobalIndirectSymbol(M, IFunc); 1625 1626 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 1627 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 1628 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 1629 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I)) 1630 MP->finishAssembly(M, *MI, *this); 1631 1632 // Emit llvm.ident metadata in an '.ident' directive. 1633 emitModuleIdents(M); 1634 1635 // Emit bytes for llvm.commandline metadata. 1636 emitModuleCommandLines(M); 1637 1638 // Emit __morestack address if needed for indirect calls. 1639 if (MMI->usesMorestackAddr()) { 1640 Align Alignment(1); 1641 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant( 1642 getDataLayout(), SectionKind::getReadOnly(), 1643 /*C=*/nullptr, Alignment); 1644 OutStreamer->SwitchSection(ReadOnlySection); 1645 1646 MCSymbol *AddrSymbol = 1647 OutContext.getOrCreateSymbol(StringRef("__morestack_addr")); 1648 OutStreamer->emitLabel(AddrSymbol); 1649 1650 unsigned PtrSize = MAI->getCodePointerSize(); 1651 OutStreamer->emitSymbolValue(GetExternalSymbolSymbol("__morestack"), 1652 PtrSize); 1653 } 1654 1655 // Emit .note.GNU-split-stack and .note.GNU-no-split-stack sections if 1656 // split-stack is used. 1657 if (TM.getTargetTriple().isOSBinFormatELF() && MMI->hasSplitStack()) { 1658 OutStreamer->SwitchSection( 1659 OutContext.getELFSection(".note.GNU-split-stack", ELF::SHT_PROGBITS, 0)); 1660 if (MMI->hasNosplitStack()) 1661 OutStreamer->SwitchSection( 1662 OutContext.getELFSection(".note.GNU-no-split-stack", ELF::SHT_PROGBITS, 0)); 1663 } 1664 1665 // If we don't have any trampolines, then we don't require stack memory 1666 // to be executable. Some targets have a directive to declare this. 1667 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 1668 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 1669 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext)) 1670 OutStreamer->SwitchSection(S); 1671 1672 if (TM.getTargetTriple().isOSBinFormatCOFF()) { 1673 // Emit /EXPORT: flags for each exported global as necessary. 1674 const auto &TLOF = getObjFileLowering(); 1675 std::string Flags; 1676 1677 for (const GlobalValue &GV : M.global_values()) { 1678 raw_string_ostream OS(Flags); 1679 TLOF.emitLinkerFlagsForGlobal(OS, &GV); 1680 OS.flush(); 1681 if (!Flags.empty()) { 1682 OutStreamer->SwitchSection(TLOF.getDrectveSection()); 1683 OutStreamer->emitBytes(Flags); 1684 } 1685 Flags.clear(); 1686 } 1687 1688 // Emit /INCLUDE: flags for each used global as necessary. 1689 if (const auto *LU = M.getNamedGlobal("llvm.used")) { 1690 assert(LU->hasInitializer() && 1691 "expected llvm.used to have an initializer"); 1692 assert(isa<ArrayType>(LU->getValueType()) && 1693 "expected llvm.used to be an array type"); 1694 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) { 1695 for (const Value *Op : A->operands()) { 1696 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts()); 1697 // Global symbols with internal or private linkage are not visible to 1698 // the linker, and thus would cause an error when the linker tried to 1699 // preserve the symbol due to the `/include:` directive. 1700 if (GV->hasLocalLinkage()) 1701 continue; 1702 1703 raw_string_ostream OS(Flags); 1704 TLOF.emitLinkerFlagsForUsed(OS, GV); 1705 OS.flush(); 1706 1707 if (!Flags.empty()) { 1708 OutStreamer->SwitchSection(TLOF.getDrectveSection()); 1709 OutStreamer->emitBytes(Flags); 1710 } 1711 Flags.clear(); 1712 } 1713 } 1714 } 1715 } 1716 1717 if (TM.Options.EmitAddrsig) { 1718 // Emit address-significance attributes for all globals. 1719 OutStreamer->emitAddrsig(); 1720 for (const GlobalValue &GV : M.global_values()) 1721 if (!GV.use_empty() && !GV.isThreadLocal() && 1722 !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") && 1723 !GV.hasAtLeastLocalUnnamedAddr()) 1724 OutStreamer->emitAddrsigSym(getSymbol(&GV)); 1725 } 1726 1727 // Emit symbol partition specifications (ELF only). 1728 if (TM.getTargetTriple().isOSBinFormatELF()) { 1729 unsigned UniqueID = 0; 1730 for (const GlobalValue &GV : M.global_values()) { 1731 if (!GV.hasPartition() || GV.isDeclarationForLinker() || 1732 GV.getVisibility() != GlobalValue::DefaultVisibility) 1733 continue; 1734 1735 OutStreamer->SwitchSection( 1736 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0, 1737 "", ++UniqueID, nullptr)); 1738 OutStreamer->emitBytes(GV.getPartition()); 1739 OutStreamer->emitZeros(1); 1740 OutStreamer->emitValue( 1741 MCSymbolRefExpr::create(getSymbol(&GV), OutContext), 1742 MAI->getCodePointerSize()); 1743 } 1744 } 1745 1746 // Allow the target to emit any magic that it wants at the end of the file, 1747 // after everything else has gone out. 1748 emitEndOfAsmFile(M); 1749 1750 MMI = nullptr; 1751 1752 OutStreamer->Finish(); 1753 OutStreamer->reset(); 1754 OwnedMLI.reset(); 1755 OwnedMDT.reset(); 1756 1757 return false; 1758 } 1759 1760 MCSymbol *AsmPrinter::getCurExceptionSym() { 1761 if (!CurExceptionSym) 1762 CurExceptionSym = createTempSymbol("exception"); 1763 return CurExceptionSym; 1764 } 1765 1766 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1767 this->MF = &MF; 1768 const Function &F = MF.getFunction(); 1769 1770 // Get the function symbol. 1771 if (!MAI->needsFunctionDescriptors()) { 1772 CurrentFnSym = getSymbol(&MF.getFunction()); 1773 } else { 1774 assert(TM.getTargetTriple().isOSAIX() && 1775 "Only AIX uses the function descriptor hooks."); 1776 // AIX is unique here in that the name of the symbol emitted for the 1777 // function body does not have the same name as the source function's 1778 // C-linkage name. 1779 assert(CurrentFnDescSym && "The function descriptor symbol needs to be" 1780 " initalized first."); 1781 1782 // Get the function entry point symbol. 1783 CurrentFnSym = getObjFileLowering().getFunctionEntryPointSymbol(&F, TM); 1784 } 1785 1786 CurrentFnSymForSize = CurrentFnSym; 1787 CurrentFnBegin = nullptr; 1788 CurrentSectionBeginSym = nullptr; 1789 MBBSectionRanges.clear(); 1790 CurExceptionSym = nullptr; 1791 bool NeedsLocalForSize = MAI->needsLocalForSize(); 1792 if (F.hasFnAttribute("patchable-function-entry") || 1793 F.hasFnAttribute("function-instrument") || 1794 F.hasFnAttribute("xray-instruction-threshold") || 1795 needFuncLabelsForEHOrDebugInfo(MF) || NeedsLocalForSize || 1796 MF.getTarget().Options.EmitStackSizeSection) { 1797 CurrentFnBegin = createTempSymbol("func_begin"); 1798 if (NeedsLocalForSize) 1799 CurrentFnSymForSize = CurrentFnBegin; 1800 } 1801 1802 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE(); 1803 } 1804 1805 namespace { 1806 1807 // Keep track the alignment, constpool entries per Section. 1808 struct SectionCPs { 1809 MCSection *S; 1810 Align Alignment; 1811 SmallVector<unsigned, 4> CPEs; 1812 1813 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {} 1814 }; 1815 1816 } // end anonymous namespace 1817 1818 /// EmitConstantPool - Print to the current output stream assembly 1819 /// representations of the constants in the constant pool MCP. This is 1820 /// used to print out constants which have been "spilled to memory" by 1821 /// the code generator. 1822 void AsmPrinter::emitConstantPool() { 1823 const MachineConstantPool *MCP = MF->getConstantPool(); 1824 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 1825 if (CP.empty()) return; 1826 1827 // Calculate sections for constant pool entries. We collect entries to go into 1828 // the same section together to reduce amount of section switch statements. 1829 SmallVector<SectionCPs, 4> CPSections; 1830 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 1831 const MachineConstantPoolEntry &CPE = CP[i]; 1832 Align Alignment = CPE.getAlign(); 1833 1834 SectionKind Kind = CPE.getSectionKind(&getDataLayout()); 1835 1836 const Constant *C = nullptr; 1837 if (!CPE.isMachineConstantPoolEntry()) 1838 C = CPE.Val.ConstVal; 1839 1840 MCSection *S = getObjFileLowering().getSectionForConstant( 1841 getDataLayout(), Kind, C, Alignment); 1842 1843 // The number of sections are small, just do a linear search from the 1844 // last section to the first. 1845 bool Found = false; 1846 unsigned SecIdx = CPSections.size(); 1847 while (SecIdx != 0) { 1848 if (CPSections[--SecIdx].S == S) { 1849 Found = true; 1850 break; 1851 } 1852 } 1853 if (!Found) { 1854 SecIdx = CPSections.size(); 1855 CPSections.push_back(SectionCPs(S, Alignment)); 1856 } 1857 1858 if (Alignment > CPSections[SecIdx].Alignment) 1859 CPSections[SecIdx].Alignment = Alignment; 1860 CPSections[SecIdx].CPEs.push_back(i); 1861 } 1862 1863 // Now print stuff into the calculated sections. 1864 const MCSection *CurSection = nullptr; 1865 unsigned Offset = 0; 1866 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 1867 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 1868 unsigned CPI = CPSections[i].CPEs[j]; 1869 MCSymbol *Sym = GetCPISymbol(CPI); 1870 if (!Sym->isUndefined()) 1871 continue; 1872 1873 if (CurSection != CPSections[i].S) { 1874 OutStreamer->SwitchSection(CPSections[i].S); 1875 emitAlignment(Align(CPSections[i].Alignment)); 1876 CurSection = CPSections[i].S; 1877 Offset = 0; 1878 } 1879 1880 MachineConstantPoolEntry CPE = CP[CPI]; 1881 1882 // Emit inter-object padding for alignment. 1883 unsigned NewOffset = alignTo(Offset, CPE.getAlign()); 1884 OutStreamer->emitZeros(NewOffset - Offset); 1885 1886 Type *Ty = CPE.getType(); 1887 Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty); 1888 1889 OutStreamer->emitLabel(Sym); 1890 if (CPE.isMachineConstantPoolEntry()) 1891 emitMachineConstantPoolValue(CPE.Val.MachineCPVal); 1892 else 1893 emitGlobalConstant(getDataLayout(), CPE.Val.ConstVal); 1894 } 1895 } 1896 } 1897 1898 // Print assembly representations of the jump tables used by the current 1899 // function. 1900 void AsmPrinter::emitJumpTableInfo() { 1901 const DataLayout &DL = MF->getDataLayout(); 1902 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 1903 if (!MJTI) return; 1904 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 1905 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 1906 if (JT.empty()) return; 1907 1908 // Pick the directive to use to print the jump table entries, and switch to 1909 // the appropriate section. 1910 const Function &F = MF->getFunction(); 1911 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1912 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection( 1913 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32, 1914 F); 1915 if (JTInDiffSection) { 1916 // Drop it in the readonly section. 1917 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM); 1918 OutStreamer->SwitchSection(ReadOnlySection); 1919 } 1920 1921 emitAlignment(Align(MJTI->getEntryAlignment(DL))); 1922 1923 // Jump tables in code sections are marked with a data_region directive 1924 // where that's supported. 1925 if (!JTInDiffSection) 1926 OutStreamer->emitDataRegion(MCDR_DataRegionJT32); 1927 1928 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 1929 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 1930 1931 // If this jump table was deleted, ignore it. 1932 if (JTBBs.empty()) continue; 1933 1934 // For the EK_LabelDifference32 entry, if using .set avoids a relocation, 1935 /// emit a .set directive for each unique entry. 1936 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 1937 MAI->doesSetDirectiveSuppressReloc()) { 1938 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 1939 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1940 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 1941 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 1942 const MachineBasicBlock *MBB = JTBBs[ii]; 1943 if (!EmittedSets.insert(MBB).second) 1944 continue; 1945 1946 // .set LJTSet, LBB32-base 1947 const MCExpr *LHS = 1948 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1949 OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 1950 MCBinaryExpr::createSub(LHS, Base, 1951 OutContext)); 1952 } 1953 } 1954 1955 // On some targets (e.g. Darwin) we want to emit two consecutive labels 1956 // before each jump table. The first label is never referenced, but tells 1957 // the assembler and linker the extents of the jump table object. The 1958 // second label is actually referenced by the code. 1959 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix()) 1960 // FIXME: This doesn't have to have any specific name, just any randomly 1961 // named and numbered local label started with 'l' would work. Simplify 1962 // GetJTISymbol. 1963 OutStreamer->emitLabel(GetJTISymbol(JTI, true)); 1964 1965 MCSymbol* JTISymbol = GetJTISymbol(JTI); 1966 OutStreamer->emitLabel(JTISymbol); 1967 1968 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 1969 emitJumpTableEntry(MJTI, JTBBs[ii], JTI); 1970 } 1971 if (!JTInDiffSection) 1972 OutStreamer->emitDataRegion(MCDR_DataRegionEnd); 1973 } 1974 1975 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 1976 /// current stream. 1977 void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI, 1978 const MachineBasicBlock *MBB, 1979 unsigned UID) const { 1980 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block"); 1981 const MCExpr *Value = nullptr; 1982 switch (MJTI->getEntryKind()) { 1983 case MachineJumpTableInfo::EK_Inline: 1984 llvm_unreachable("Cannot emit EK_Inline jump table entry"); 1985 case MachineJumpTableInfo::EK_Custom32: 1986 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry( 1987 MJTI, MBB, UID, OutContext); 1988 break; 1989 case MachineJumpTableInfo::EK_BlockAddress: 1990 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 1991 // .word LBB123 1992 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1993 break; 1994 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 1995 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 1996 // with a relocation as gp-relative, e.g.: 1997 // .gprel32 LBB123 1998 MCSymbol *MBBSym = MBB->getSymbol(); 1999 OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 2000 return; 2001 } 2002 2003 case MachineJumpTableInfo::EK_GPRel64BlockAddress: { 2004 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded 2005 // with a relocation as gp-relative, e.g.: 2006 // .gpdword LBB123 2007 MCSymbol *MBBSym = MBB->getSymbol(); 2008 OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 2009 return; 2010 } 2011 2012 case MachineJumpTableInfo::EK_LabelDifference32: { 2013 // Each entry is the address of the block minus the address of the jump 2014 // table. This is used for PIC jump tables where gprel32 is not supported. 2015 // e.g.: 2016 // .word LBB123 - LJTI1_2 2017 // If the .set directive avoids relocations, this is emitted as: 2018 // .set L4_5_set_123, LBB123 - LJTI1_2 2019 // .word L4_5_set_123 2020 if (MAI->doesSetDirectiveSuppressReloc()) { 2021 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()), 2022 OutContext); 2023 break; 2024 } 2025 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 2026 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 2027 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext); 2028 Value = MCBinaryExpr::createSub(Value, Base, OutContext); 2029 break; 2030 } 2031 } 2032 2033 assert(Value && "Unknown entry kind!"); 2034 2035 unsigned EntrySize = MJTI->getEntrySize(getDataLayout()); 2036 OutStreamer->emitValue(Value, EntrySize); 2037 } 2038 2039 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a 2040 /// special global used by LLVM. If so, emit it and return true, otherwise 2041 /// do nothing and return false. 2042 bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) { 2043 if (GV->getName() == "llvm.used") { 2044 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 2045 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer())); 2046 return true; 2047 } 2048 2049 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 2050 if (GV->getSection() == "llvm.metadata" || 2051 GV->hasAvailableExternallyLinkage()) 2052 return true; 2053 2054 if (!GV->hasAppendingLinkage()) return false; 2055 2056 assert(GV->hasInitializer() && "Not a special LLVM global!"); 2057 2058 if (GV->getName() == "llvm.global_ctors") { 2059 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 2060 /* isCtor */ true); 2061 2062 return true; 2063 } 2064 2065 if (GV->getName() == "llvm.global_dtors") { 2066 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 2067 /* isCtor */ false); 2068 2069 return true; 2070 } 2071 2072 report_fatal_error("unknown special variable"); 2073 } 2074 2075 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 2076 /// global in the specified llvm.used list. 2077 void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) { 2078 // Should be an array of 'i8*'. 2079 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 2080 const GlobalValue *GV = 2081 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 2082 if (GV) 2083 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip); 2084 } 2085 } 2086 2087 namespace { 2088 2089 struct Structor { 2090 int Priority = 0; 2091 Constant *Func = nullptr; 2092 GlobalValue *ComdatKey = nullptr; 2093 2094 Structor() = default; 2095 }; 2096 2097 } // end anonymous namespace 2098 2099 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init 2100 /// priority. 2101 void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List, 2102 bool isCtor) { 2103 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is the 2104 // init priority. 2105 if (!isa<ConstantArray>(List)) return; 2106 2107 // Gather the structors in a form that's convenient for sorting by priority. 2108 SmallVector<Structor, 8> Structors; 2109 for (Value *O : cast<ConstantArray>(List)->operands()) { 2110 auto *CS = cast<ConstantStruct>(O); 2111 if (CS->getOperand(1)->isNullValue()) 2112 break; // Found a null terminator, skip the rest. 2113 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); 2114 if (!Priority) continue; // Malformed. 2115 Structors.push_back(Structor()); 2116 Structor &S = Structors.back(); 2117 S.Priority = Priority->getLimitedValue(65535); 2118 S.Func = CS->getOperand(1); 2119 if (!CS->getOperand(2)->isNullValue()) 2120 S.ComdatKey = 2121 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts()); 2122 } 2123 2124 // Emit the function pointers in the target-specific order 2125 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) { 2126 return L.Priority < R.Priority; 2127 }); 2128 const Align Align = DL.getPointerPrefAlignment(); 2129 for (Structor &S : Structors) { 2130 const TargetLoweringObjectFile &Obj = getObjFileLowering(); 2131 const MCSymbol *KeySym = nullptr; 2132 if (GlobalValue *GV = S.ComdatKey) { 2133 if (GV->isDeclarationForLinker()) 2134 // If the associated variable is not defined in this module 2135 // (it might be available_externally, or have been an 2136 // available_externally definition that was dropped by the 2137 // EliminateAvailableExternally pass), some other TU 2138 // will provide its dynamic initializer. 2139 continue; 2140 2141 KeySym = getSymbol(GV); 2142 } 2143 MCSection *OutputSection = 2144 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym) 2145 : Obj.getStaticDtorSection(S.Priority, KeySym)); 2146 OutStreamer->SwitchSection(OutputSection); 2147 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection()) 2148 emitAlignment(Align); 2149 emitXXStructor(DL, S.Func); 2150 } 2151 } 2152 2153 void AsmPrinter::emitModuleIdents(Module &M) { 2154 if (!MAI->hasIdentDirective()) 2155 return; 2156 2157 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) { 2158 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2159 const MDNode *N = NMD->getOperand(i); 2160 assert(N->getNumOperands() == 1 && 2161 "llvm.ident metadata entry can have only one operand"); 2162 const MDString *S = cast<MDString>(N->getOperand(0)); 2163 OutStreamer->emitIdent(S->getString()); 2164 } 2165 } 2166 } 2167 2168 void AsmPrinter::emitModuleCommandLines(Module &M) { 2169 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines(); 2170 if (!CommandLine) 2171 return; 2172 2173 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline"); 2174 if (!NMD || !NMD->getNumOperands()) 2175 return; 2176 2177 OutStreamer->PushSection(); 2178 OutStreamer->SwitchSection(CommandLine); 2179 OutStreamer->emitZeros(1); 2180 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2181 const MDNode *N = NMD->getOperand(i); 2182 assert(N->getNumOperands() == 1 && 2183 "llvm.commandline metadata entry can have only one operand"); 2184 const MDString *S = cast<MDString>(N->getOperand(0)); 2185 OutStreamer->emitBytes(S->getString()); 2186 OutStreamer->emitZeros(1); 2187 } 2188 OutStreamer->PopSection(); 2189 } 2190 2191 //===--------------------------------------------------------------------===// 2192 // Emission and print routines 2193 // 2194 2195 /// Emit a byte directive and value. 2196 /// 2197 void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); } 2198 2199 /// Emit a short directive and value. 2200 void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); } 2201 2202 /// Emit a long directive and value. 2203 void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); } 2204 2205 /// Emit a long long directive and value. 2206 void AsmPrinter::emitInt64(uint64_t Value) const { 2207 OutStreamer->emitInt64(Value); 2208 } 2209 2210 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive 2211 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses 2212 /// .set if it avoids relocations. 2213 void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 2214 unsigned Size) const { 2215 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size); 2216 } 2217 2218 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset" 2219 /// where the size in bytes of the directive is specified by Size and Label 2220 /// specifies the label. This implicitly uses .set if it is available. 2221 void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 2222 unsigned Size, 2223 bool IsSectionRelative) const { 2224 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) { 2225 OutStreamer->EmitCOFFSecRel32(Label, Offset); 2226 if (Size > 4) 2227 OutStreamer->emitZeros(Size - 4); 2228 return; 2229 } 2230 2231 // Emit Label+Offset (or just Label if Offset is zero) 2232 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext); 2233 if (Offset) 2234 Expr = MCBinaryExpr::createAdd( 2235 Expr, MCConstantExpr::create(Offset, OutContext), OutContext); 2236 2237 OutStreamer->emitValue(Expr, Size); 2238 } 2239 2240 //===----------------------------------------------------------------------===// 2241 2242 // EmitAlignment - Emit an alignment directive to the specified power of 2243 // two boundary. If a global value is specified, and if that global has 2244 // an explicit alignment requested, it will override the alignment request 2245 // if required for correctness. 2246 void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV) const { 2247 if (GV) 2248 Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment); 2249 2250 if (Alignment == Align(1)) 2251 return; // 1-byte aligned: no need to emit alignment. 2252 2253 if (getCurrentSection()->getKind().isText()) 2254 OutStreamer->emitCodeAlignment(Alignment.value()); 2255 else 2256 OutStreamer->emitValueToAlignment(Alignment.value()); 2257 } 2258 2259 //===----------------------------------------------------------------------===// 2260 // Constant emission. 2261 //===----------------------------------------------------------------------===// 2262 2263 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) { 2264 MCContext &Ctx = OutContext; 2265 2266 if (CV->isNullValue() || isa<UndefValue>(CV)) 2267 return MCConstantExpr::create(0, Ctx); 2268 2269 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 2270 return MCConstantExpr::create(CI->getZExtValue(), Ctx); 2271 2272 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 2273 return MCSymbolRefExpr::create(getSymbol(GV), Ctx); 2274 2275 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 2276 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx); 2277 2278 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 2279 if (!CE) { 2280 llvm_unreachable("Unknown constant value to lower!"); 2281 } 2282 2283 switch (CE->getOpcode()) { 2284 default: { 2285 // If the code isn't optimized, there may be outstanding folding 2286 // opportunities. Attempt to fold the expression using DataLayout as a 2287 // last resort before giving up. 2288 Constant *C = ConstantFoldConstant(CE, getDataLayout()); 2289 if (C != CE) 2290 return lowerConstant(C); 2291 2292 // Otherwise report the problem to the user. 2293 std::string S; 2294 raw_string_ostream OS(S); 2295 OS << "Unsupported expression in static initializer: "; 2296 CE->printAsOperand(OS, /*PrintType=*/false, 2297 !MF ? nullptr : MF->getFunction().getParent()); 2298 report_fatal_error(OS.str()); 2299 } 2300 case Instruction::GetElementPtr: { 2301 // Generate a symbolic expression for the byte address 2302 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0); 2303 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI); 2304 2305 const MCExpr *Base = lowerConstant(CE->getOperand(0)); 2306 if (!OffsetAI) 2307 return Base; 2308 2309 int64_t Offset = OffsetAI.getSExtValue(); 2310 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx), 2311 Ctx); 2312 } 2313 2314 case Instruction::Trunc: 2315 // We emit the value and depend on the assembler to truncate the generated 2316 // expression properly. This is important for differences between 2317 // blockaddress labels. Since the two labels are in the same function, it 2318 // is reasonable to treat their delta as a 32-bit value. 2319 LLVM_FALLTHROUGH; 2320 case Instruction::BitCast: 2321 return lowerConstant(CE->getOperand(0)); 2322 2323 case Instruction::IntToPtr: { 2324 const DataLayout &DL = getDataLayout(); 2325 2326 // Handle casts to pointers by changing them into casts to the appropriate 2327 // integer type. This promotes constant folding and simplifies this code. 2328 Constant *Op = CE->getOperand(0); 2329 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()), 2330 false/*ZExt*/); 2331 return lowerConstant(Op); 2332 } 2333 2334 case Instruction::PtrToInt: { 2335 const DataLayout &DL = getDataLayout(); 2336 2337 // Support only foldable casts to/from pointers that can be eliminated by 2338 // changing the pointer to the appropriately sized integer type. 2339 Constant *Op = CE->getOperand(0); 2340 Type *Ty = CE->getType(); 2341 2342 const MCExpr *OpExpr = lowerConstant(Op); 2343 2344 // We can emit the pointer value into this slot if the slot is an 2345 // integer slot equal to the size of the pointer. 2346 // 2347 // If the pointer is larger than the resultant integer, then 2348 // as with Trunc just depend on the assembler to truncate it. 2349 if (DL.getTypeAllocSize(Ty) <= DL.getTypeAllocSize(Op->getType())) 2350 return OpExpr; 2351 2352 // Otherwise the pointer is smaller than the resultant integer, mask off 2353 // the high bits so we are sure to get a proper truncation if the input is 2354 // a constant expr. 2355 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType()); 2356 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx); 2357 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx); 2358 } 2359 2360 case Instruction::Sub: { 2361 GlobalValue *LHSGV; 2362 APInt LHSOffset; 2363 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset, 2364 getDataLayout())) { 2365 GlobalValue *RHSGV; 2366 APInt RHSOffset; 2367 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset, 2368 getDataLayout())) { 2369 const MCExpr *RelocExpr = 2370 getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM); 2371 if (!RelocExpr) 2372 RelocExpr = MCBinaryExpr::createSub( 2373 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx), 2374 MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx); 2375 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue(); 2376 if (Addend != 0) 2377 RelocExpr = MCBinaryExpr::createAdd( 2378 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx); 2379 return RelocExpr; 2380 } 2381 } 2382 } 2383 // else fallthrough 2384 LLVM_FALLTHROUGH; 2385 2386 // The MC library also has a right-shift operator, but it isn't consistently 2387 // signed or unsigned between different targets. 2388 case Instruction::Add: 2389 case Instruction::Mul: 2390 case Instruction::SDiv: 2391 case Instruction::SRem: 2392 case Instruction::Shl: 2393 case Instruction::And: 2394 case Instruction::Or: 2395 case Instruction::Xor: { 2396 const MCExpr *LHS = lowerConstant(CE->getOperand(0)); 2397 const MCExpr *RHS = lowerConstant(CE->getOperand(1)); 2398 switch (CE->getOpcode()) { 2399 default: llvm_unreachable("Unknown binary operator constant cast expr"); 2400 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx); 2401 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx); 2402 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx); 2403 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx); 2404 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx); 2405 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx); 2406 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx); 2407 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx); 2408 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx); 2409 } 2410 } 2411 } 2412 } 2413 2414 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, 2415 AsmPrinter &AP, 2416 const Constant *BaseCV = nullptr, 2417 uint64_t Offset = 0); 2418 2419 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP); 2420 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP); 2421 2422 /// isRepeatedByteSequence - Determine whether the given value is 2423 /// composed of a repeated sequence of identical bytes and return the 2424 /// byte value. If it is not a repeated sequence, return -1. 2425 static int isRepeatedByteSequence(const ConstantDataSequential *V) { 2426 StringRef Data = V->getRawDataValues(); 2427 assert(!Data.empty() && "Empty aggregates should be CAZ node"); 2428 char C = Data[0]; 2429 for (unsigned i = 1, e = Data.size(); i != e; ++i) 2430 if (Data[i] != C) return -1; 2431 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1. 2432 } 2433 2434 /// isRepeatedByteSequence - Determine whether the given value is 2435 /// composed of a repeated sequence of identical bytes and return the 2436 /// byte value. If it is not a repeated sequence, return -1. 2437 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) { 2438 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 2439 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType()); 2440 assert(Size % 8 == 0); 2441 2442 // Extend the element to take zero padding into account. 2443 APInt Value = CI->getValue().zextOrSelf(Size); 2444 if (!Value.isSplat(8)) 2445 return -1; 2446 2447 return Value.zextOrTrunc(8).getZExtValue(); 2448 } 2449 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 2450 // Make sure all array elements are sequences of the same repeated 2451 // byte. 2452 assert(CA->getNumOperands() != 0 && "Should be a CAZ"); 2453 Constant *Op0 = CA->getOperand(0); 2454 int Byte = isRepeatedByteSequence(Op0, DL); 2455 if (Byte == -1) 2456 return -1; 2457 2458 // All array elements must be equal. 2459 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) 2460 if (CA->getOperand(i) != Op0) 2461 return -1; 2462 return Byte; 2463 } 2464 2465 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) 2466 return isRepeatedByteSequence(CDS); 2467 2468 return -1; 2469 } 2470 2471 static void emitGlobalConstantDataSequential(const DataLayout &DL, 2472 const ConstantDataSequential *CDS, 2473 AsmPrinter &AP) { 2474 // See if we can aggregate this into a .fill, if so, emit it as such. 2475 int Value = isRepeatedByteSequence(CDS, DL); 2476 if (Value != -1) { 2477 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType()); 2478 // Don't emit a 1-byte object as a .fill. 2479 if (Bytes > 1) 2480 return AP.OutStreamer->emitFill(Bytes, Value); 2481 } 2482 2483 // If this can be emitted with .ascii/.asciz, emit it as such. 2484 if (CDS->isString()) 2485 return AP.OutStreamer->emitBytes(CDS->getAsString()); 2486 2487 // Otherwise, emit the values in successive locations. 2488 unsigned ElementByteSize = CDS->getElementByteSize(); 2489 if (isa<IntegerType>(CDS->getElementType())) { 2490 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2491 if (AP.isVerbose()) 2492 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2493 CDS->getElementAsInteger(i)); 2494 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(i), 2495 ElementByteSize); 2496 } 2497 } else { 2498 Type *ET = CDS->getElementType(); 2499 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) 2500 emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP); 2501 } 2502 2503 unsigned Size = DL.getTypeAllocSize(CDS->getType()); 2504 unsigned EmittedSize = 2505 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements(); 2506 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!"); 2507 if (unsigned Padding = Size - EmittedSize) 2508 AP.OutStreamer->emitZeros(Padding); 2509 } 2510 2511 static void emitGlobalConstantArray(const DataLayout &DL, 2512 const ConstantArray *CA, AsmPrinter &AP, 2513 const Constant *BaseCV, uint64_t Offset) { 2514 // See if we can aggregate some values. Make sure it can be 2515 // represented as a series of bytes of the constant value. 2516 int Value = isRepeatedByteSequence(CA, DL); 2517 2518 if (Value != -1) { 2519 uint64_t Bytes = DL.getTypeAllocSize(CA->getType()); 2520 AP.OutStreamer->emitFill(Bytes, Value); 2521 } 2522 else { 2523 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) { 2524 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset); 2525 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType()); 2526 } 2527 } 2528 } 2529 2530 static void emitGlobalConstantVector(const DataLayout &DL, 2531 const ConstantVector *CV, AsmPrinter &AP) { 2532 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 2533 emitGlobalConstantImpl(DL, CV->getOperand(i), AP); 2534 2535 unsigned Size = DL.getTypeAllocSize(CV->getType()); 2536 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) * 2537 CV->getType()->getNumElements(); 2538 if (unsigned Padding = Size - EmittedSize) 2539 AP.OutStreamer->emitZeros(Padding); 2540 } 2541 2542 static void emitGlobalConstantStruct(const DataLayout &DL, 2543 const ConstantStruct *CS, AsmPrinter &AP, 2544 const Constant *BaseCV, uint64_t Offset) { 2545 // Print the fields in successive locations. Pad to align if needed! 2546 unsigned Size = DL.getTypeAllocSize(CS->getType()); 2547 const StructLayout *Layout = DL.getStructLayout(CS->getType()); 2548 uint64_t SizeSoFar = 0; 2549 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 2550 const Constant *Field = CS->getOperand(i); 2551 2552 // Print the actual field value. 2553 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar); 2554 2555 // Check if padding is needed and insert one or more 0s. 2556 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType()); 2557 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 2558 - Layout->getElementOffset(i)) - FieldSize; 2559 SizeSoFar += FieldSize + PadSize; 2560 2561 // Insert padding - this may include padding to increase the size of the 2562 // current field up to the ABI size (if the struct is not packed) as well 2563 // as padding to ensure that the next field starts at the right offset. 2564 AP.OutStreamer->emitZeros(PadSize); 2565 } 2566 assert(SizeSoFar == Layout->getSizeInBytes() && 2567 "Layout of constant struct may be incorrect!"); 2568 } 2569 2570 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) { 2571 assert(ET && "Unknown float type"); 2572 APInt API = APF.bitcastToAPInt(); 2573 2574 // First print a comment with what we think the original floating-point value 2575 // should have been. 2576 if (AP.isVerbose()) { 2577 SmallString<8> StrVal; 2578 APF.toString(StrVal); 2579 ET->print(AP.OutStreamer->GetCommentOS()); 2580 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n'; 2581 } 2582 2583 // Now iterate through the APInt chunks, emitting them in endian-correct 2584 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit 2585 // floats). 2586 unsigned NumBytes = API.getBitWidth() / 8; 2587 unsigned TrailingBytes = NumBytes % sizeof(uint64_t); 2588 const uint64_t *p = API.getRawData(); 2589 2590 // PPC's long double has odd notions of endianness compared to how LLVM 2591 // handles it: p[0] goes first for *big* endian on PPC. 2592 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) { 2593 int Chunk = API.getNumWords() - 1; 2594 2595 if (TrailingBytes) 2596 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes); 2597 2598 for (; Chunk >= 0; --Chunk) 2599 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t)); 2600 } else { 2601 unsigned Chunk; 2602 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk) 2603 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t)); 2604 2605 if (TrailingBytes) 2606 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes); 2607 } 2608 2609 // Emit the tail padding for the long double. 2610 const DataLayout &DL = AP.getDataLayout(); 2611 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET)); 2612 } 2613 2614 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) { 2615 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP); 2616 } 2617 2618 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) { 2619 const DataLayout &DL = AP.getDataLayout(); 2620 unsigned BitWidth = CI->getBitWidth(); 2621 2622 // Copy the value as we may massage the layout for constants whose bit width 2623 // is not a multiple of 64-bits. 2624 APInt Realigned(CI->getValue()); 2625 uint64_t ExtraBits = 0; 2626 unsigned ExtraBitsSize = BitWidth & 63; 2627 2628 if (ExtraBitsSize) { 2629 // The bit width of the data is not a multiple of 64-bits. 2630 // The extra bits are expected to be at the end of the chunk of the memory. 2631 // Little endian: 2632 // * Nothing to be done, just record the extra bits to emit. 2633 // Big endian: 2634 // * Record the extra bits to emit. 2635 // * Realign the raw data to emit the chunks of 64-bits. 2636 if (DL.isBigEndian()) { 2637 // Basically the structure of the raw data is a chunk of 64-bits cells: 2638 // 0 1 BitWidth / 64 2639 // [chunk1][chunk2] ... [chunkN]. 2640 // The most significant chunk is chunkN and it should be emitted first. 2641 // However, due to the alignment issue chunkN contains useless bits. 2642 // Realign the chunks so that they contain only useful information: 2643 // ExtraBits 0 1 (BitWidth / 64) - 1 2644 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN] 2645 ExtraBitsSize = alignTo(ExtraBitsSize, 8); 2646 ExtraBits = Realigned.getRawData()[0] & 2647 (((uint64_t)-1) >> (64 - ExtraBitsSize)); 2648 Realigned.lshrInPlace(ExtraBitsSize); 2649 } else 2650 ExtraBits = Realigned.getRawData()[BitWidth / 64]; 2651 } 2652 2653 // We don't expect assemblers to support integer data directives 2654 // for more than 64 bits, so we emit the data in at most 64-bit 2655 // quantities at a time. 2656 const uint64_t *RawData = Realigned.getRawData(); 2657 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 2658 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i]; 2659 AP.OutStreamer->emitIntValue(Val, 8); 2660 } 2661 2662 if (ExtraBitsSize) { 2663 // Emit the extra bits after the 64-bits chunks. 2664 2665 // Emit a directive that fills the expected size. 2666 uint64_t Size = AP.getDataLayout().getTypeStoreSize(CI->getType()); 2667 Size -= (BitWidth / 64) * 8; 2668 assert(Size && Size * 8 >= ExtraBitsSize && 2669 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) 2670 == ExtraBits && "Directive too small for extra bits."); 2671 AP.OutStreamer->emitIntValue(ExtraBits, Size); 2672 } 2673 } 2674 2675 /// Transform a not absolute MCExpr containing a reference to a GOT 2676 /// equivalent global, by a target specific GOT pc relative access to the 2677 /// final symbol. 2678 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, 2679 const Constant *BaseCst, 2680 uint64_t Offset) { 2681 // The global @foo below illustrates a global that uses a got equivalent. 2682 // 2683 // @bar = global i32 42 2684 // @gotequiv = private unnamed_addr constant i32* @bar 2685 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64), 2686 // i64 ptrtoint (i32* @foo to i64)) 2687 // to i32) 2688 // 2689 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually 2690 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the 2691 // form: 2692 // 2693 // foo = cstexpr, where 2694 // cstexpr := <gotequiv> - "." + <cst> 2695 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst> 2696 // 2697 // After canonicalization by evaluateAsRelocatable `ME` turns into: 2698 // 2699 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where 2700 // gotpcrelcst := <offset from @foo base> + <cst> 2701 MCValue MV; 2702 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute()) 2703 return; 2704 const MCSymbolRefExpr *SymA = MV.getSymA(); 2705 if (!SymA) 2706 return; 2707 2708 // Check that GOT equivalent symbol is cached. 2709 const MCSymbol *GOTEquivSym = &SymA->getSymbol(); 2710 if (!AP.GlobalGOTEquivs.count(GOTEquivSym)) 2711 return; 2712 2713 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst); 2714 if (!BaseGV) 2715 return; 2716 2717 // Check for a valid base symbol 2718 const MCSymbol *BaseSym = AP.getSymbol(BaseGV); 2719 const MCSymbolRefExpr *SymB = MV.getSymB(); 2720 2721 if (!SymB || BaseSym != &SymB->getSymbol()) 2722 return; 2723 2724 // Make sure to match: 2725 // 2726 // gotpcrelcst := <offset from @foo base> + <cst> 2727 // 2728 // If gotpcrelcst is positive it means that we can safely fold the pc rel 2729 // displacement into the GOTPCREL. We can also can have an extra offset <cst> 2730 // if the target knows how to encode it. 2731 int64_t GOTPCRelCst = Offset + MV.getConstant(); 2732 if (GOTPCRelCst < 0) 2733 return; 2734 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0) 2735 return; 2736 2737 // Emit the GOT PC relative to replace the got equivalent global, i.e.: 2738 // 2739 // bar: 2740 // .long 42 2741 // gotequiv: 2742 // .quad bar 2743 // foo: 2744 // .long gotequiv - "." + <cst> 2745 // 2746 // is replaced by the target specific equivalent to: 2747 // 2748 // bar: 2749 // .long 42 2750 // foo: 2751 // .long bar@GOTPCREL+<gotpcrelcst> 2752 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym]; 2753 const GlobalVariable *GV = Result.first; 2754 int NumUses = (int)Result.second; 2755 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0)); 2756 const MCSymbol *FinalSym = AP.getSymbol(FinalGV); 2757 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel( 2758 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer); 2759 2760 // Update GOT equivalent usage information 2761 --NumUses; 2762 if (NumUses >= 0) 2763 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses); 2764 } 2765 2766 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV, 2767 AsmPrinter &AP, const Constant *BaseCV, 2768 uint64_t Offset) { 2769 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2770 2771 // Globals with sub-elements such as combinations of arrays and structs 2772 // are handled recursively by emitGlobalConstantImpl. Keep track of the 2773 // constant symbol base and the current position with BaseCV and Offset. 2774 if (!BaseCV && CV->hasOneUse()) 2775 BaseCV = dyn_cast<Constant>(CV->user_back()); 2776 2777 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) 2778 return AP.OutStreamer->emitZeros(Size); 2779 2780 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 2781 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType()); 2782 2783 if (StoreSize < 8) { 2784 if (AP.isVerbose()) 2785 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2786 CI->getZExtValue()); 2787 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize); 2788 } else { 2789 emitGlobalConstantLargeInt(CI, AP); 2790 } 2791 2792 // Emit tail padding if needed 2793 if (Size != StoreSize) 2794 AP.OutStreamer->emitZeros(Size - StoreSize); 2795 2796 return; 2797 } 2798 2799 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 2800 return emitGlobalConstantFP(CFP, AP); 2801 2802 if (isa<ConstantPointerNull>(CV)) { 2803 AP.OutStreamer->emitIntValue(0, Size); 2804 return; 2805 } 2806 2807 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV)) 2808 return emitGlobalConstantDataSequential(DL, CDS, AP); 2809 2810 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 2811 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset); 2812 2813 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 2814 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset); 2815 2816 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 2817 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of 2818 // vectors). 2819 if (CE->getOpcode() == Instruction::BitCast) 2820 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP); 2821 2822 if (Size > 8) { 2823 // If the constant expression's size is greater than 64-bits, then we have 2824 // to emit the value in chunks. Try to constant fold the value and emit it 2825 // that way. 2826 Constant *New = ConstantFoldConstant(CE, DL); 2827 if (New != CE) 2828 return emitGlobalConstantImpl(DL, New, AP); 2829 } 2830 } 2831 2832 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 2833 return emitGlobalConstantVector(DL, V, AP); 2834 2835 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 2836 // thread the streamer with EmitValue. 2837 const MCExpr *ME = AP.lowerConstant(CV); 2838 2839 // Since lowerConstant already folded and got rid of all IR pointer and 2840 // integer casts, detect GOT equivalent accesses by looking into the MCExpr 2841 // directly. 2842 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel()) 2843 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset); 2844 2845 AP.OutStreamer->emitValue(ME, Size); 2846 } 2847 2848 /// EmitGlobalConstant - Print a general LLVM constant to the .s file. 2849 void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV) { 2850 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2851 if (Size) 2852 emitGlobalConstantImpl(DL, CV, *this); 2853 else if (MAI->hasSubsectionsViaSymbols()) { 2854 // If the global has zero size, emit a single byte so that two labels don't 2855 // look like they are at the same location. 2856 OutStreamer->emitIntValue(0, 1); 2857 } 2858 } 2859 2860 void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 2861 // Target doesn't support this yet! 2862 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 2863 } 2864 2865 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 2866 if (Offset > 0) 2867 OS << '+' << Offset; 2868 else if (Offset < 0) 2869 OS << Offset; 2870 } 2871 2872 void AsmPrinter::emitNops(unsigned N) { 2873 MCInst Nop; 2874 MF->getSubtarget().getInstrInfo()->getNoop(Nop); 2875 for (; N; --N) 2876 EmitToStreamer(*OutStreamer, Nop); 2877 } 2878 2879 //===----------------------------------------------------------------------===// 2880 // Symbol Lowering Routines. 2881 //===----------------------------------------------------------------------===// 2882 2883 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const { 2884 return OutContext.createTempSymbol(Name, true); 2885 } 2886 2887 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 2888 return MMI->getAddrLabelSymbol(BA->getBasicBlock()); 2889 } 2890 2891 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 2892 return MMI->getAddrLabelSymbol(BB); 2893 } 2894 2895 /// GetCPISymbol - Return the symbol for the specified constant pool entry. 2896 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 2897 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) { 2898 const MachineConstantPoolEntry &CPE = 2899 MF->getConstantPool()->getConstants()[CPID]; 2900 if (!CPE.isMachineConstantPoolEntry()) { 2901 const DataLayout &DL = MF->getDataLayout(); 2902 SectionKind Kind = CPE.getSectionKind(&DL); 2903 const Constant *C = CPE.Val.ConstVal; 2904 Align Alignment = CPE.Alignment; 2905 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>( 2906 getObjFileLowering().getSectionForConstant(DL, Kind, C, 2907 Alignment))) { 2908 if (MCSymbol *Sym = S->getCOMDATSymbol()) { 2909 if (Sym->isUndefined()) 2910 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global); 2911 return Sym; 2912 } 2913 } 2914 } 2915 } 2916 2917 const DataLayout &DL = getDataLayout(); 2918 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2919 "CPI" + Twine(getFunctionNumber()) + "_" + 2920 Twine(CPID)); 2921 } 2922 2923 /// GetJTISymbol - Return the symbol for the specified jump table entry. 2924 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 2925 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 2926 } 2927 2928 /// GetJTSetSymbol - Return the symbol for the specified jump table .set 2929 /// FIXME: privatize to AsmPrinter. 2930 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 2931 const DataLayout &DL = getDataLayout(); 2932 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2933 Twine(getFunctionNumber()) + "_" + 2934 Twine(UID) + "_set_" + Twine(MBBID)); 2935 } 2936 2937 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV, 2938 StringRef Suffix) const { 2939 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM); 2940 } 2941 2942 /// Return the MCSymbol for the specified ExternalSymbol. 2943 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 2944 SmallString<60> NameStr; 2945 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout()); 2946 return OutContext.getOrCreateSymbol(NameStr); 2947 } 2948 2949 /// PrintParentLoopComment - Print comments about parent loops of this one. 2950 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2951 unsigned FunctionNumber) { 2952 if (!Loop) return; 2953 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 2954 OS.indent(Loop->getLoopDepth()*2) 2955 << "Parent Loop BB" << FunctionNumber << "_" 2956 << Loop->getHeader()->getNumber() 2957 << " Depth=" << Loop->getLoopDepth() << '\n'; 2958 } 2959 2960 /// PrintChildLoopComment - Print comments about child loops within 2961 /// the loop for this basic block, with nesting. 2962 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2963 unsigned FunctionNumber) { 2964 // Add child loop information 2965 for (const MachineLoop *CL : *Loop) { 2966 OS.indent(CL->getLoopDepth()*2) 2967 << "Child Loop BB" << FunctionNumber << "_" 2968 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth() 2969 << '\n'; 2970 PrintChildLoopComment(OS, CL, FunctionNumber); 2971 } 2972 } 2973 2974 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks. 2975 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, 2976 const MachineLoopInfo *LI, 2977 const AsmPrinter &AP) { 2978 // Add loop depth information 2979 const MachineLoop *Loop = LI->getLoopFor(&MBB); 2980 if (!Loop) return; 2981 2982 MachineBasicBlock *Header = Loop->getHeader(); 2983 assert(Header && "No header for loop"); 2984 2985 // If this block is not a loop header, just print out what is the loop header 2986 // and return. 2987 if (Header != &MBB) { 2988 AP.OutStreamer->AddComment(" in Loop: Header=BB" + 2989 Twine(AP.getFunctionNumber())+"_" + 2990 Twine(Loop->getHeader()->getNumber())+ 2991 " Depth="+Twine(Loop->getLoopDepth())); 2992 return; 2993 } 2994 2995 // Otherwise, it is a loop header. Print out information about child and 2996 // parent loops. 2997 raw_ostream &OS = AP.OutStreamer->GetCommentOS(); 2998 2999 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 3000 3001 OS << "=>"; 3002 OS.indent(Loop->getLoopDepth()*2-2); 3003 3004 OS << "This "; 3005 if (Loop->empty()) 3006 OS << "Inner "; 3007 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 3008 3009 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 3010 } 3011 3012 /// emitBasicBlockStart - This method prints the label for the specified 3013 /// MachineBasicBlock, an alignment (if present) and a comment describing 3014 /// it if appropriate. 3015 void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) { 3016 // End the previous funclet and start a new one. 3017 if (MBB.isEHFuncletEntry()) { 3018 for (const HandlerInfo &HI : Handlers) { 3019 HI.Handler->endFunclet(); 3020 HI.Handler->beginFunclet(MBB); 3021 } 3022 } 3023 3024 // Emit an alignment directive for this block, if needed. 3025 const Align Alignment = MBB.getAlignment(); 3026 if (Alignment != Align(1)) 3027 emitAlignment(Alignment); 3028 3029 // If the block has its address taken, emit any labels that were used to 3030 // reference the block. It is possible that there is more than one label 3031 // here, because multiple LLVM BB's may have been RAUW'd to this block after 3032 // the references were generated. 3033 if (MBB.hasAddressTaken()) { 3034 const BasicBlock *BB = MBB.getBasicBlock(); 3035 if (isVerbose()) 3036 OutStreamer->AddComment("Block address taken"); 3037 3038 // MBBs can have their address taken as part of CodeGen without having 3039 // their corresponding BB's address taken in IR 3040 if (BB->hasAddressTaken()) 3041 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB)) 3042 OutStreamer->emitLabel(Sym); 3043 } 3044 3045 // Print some verbose block comments. 3046 if (isVerbose()) { 3047 if (const BasicBlock *BB = MBB.getBasicBlock()) { 3048 if (BB->hasName()) { 3049 BB->printAsOperand(OutStreamer->GetCommentOS(), 3050 /*PrintType=*/false, BB->getModule()); 3051 OutStreamer->GetCommentOS() << '\n'; 3052 } 3053 } 3054 3055 assert(MLI != nullptr && "MachineLoopInfo should has been computed"); 3056 emitBasicBlockLoopComments(MBB, MLI, *this); 3057 } 3058 3059 if (MBB.pred_empty() || 3060 (!MF->hasBBLabels() && isBlockOnlyReachableByFallthrough(&MBB) && 3061 !MBB.isEHFuncletEntry() && !MBB.hasLabelMustBeEmitted())) { 3062 if (isVerbose()) { 3063 // NOTE: Want this comment at start of line, don't emit with AddComment. 3064 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":", 3065 false); 3066 } 3067 } else { 3068 if (isVerbose() && MBB.hasLabelMustBeEmitted()) { 3069 OutStreamer->AddComment("Label of block must be emitted"); 3070 } 3071 // Switch to a new section if this basic block must begin a section. 3072 if (MBB.isBeginSection()) { 3073 OutStreamer->SwitchSection( 3074 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(), 3075 MBB, TM)); 3076 CurrentSectionBeginSym = MBB.getSymbol(); 3077 } 3078 OutStreamer->emitLabel(MBB.getSymbol()); 3079 } 3080 } 3081 3082 void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) {} 3083 3084 void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility, 3085 bool IsDefinition) const { 3086 MCSymbolAttr Attr = MCSA_Invalid; 3087 3088 switch (Visibility) { 3089 default: break; 3090 case GlobalValue::HiddenVisibility: 3091 if (IsDefinition) 3092 Attr = MAI->getHiddenVisibilityAttr(); 3093 else 3094 Attr = MAI->getHiddenDeclarationVisibilityAttr(); 3095 break; 3096 case GlobalValue::ProtectedVisibility: 3097 Attr = MAI->getProtectedVisibilityAttr(); 3098 break; 3099 } 3100 3101 if (Attr != MCSA_Invalid) 3102 OutStreamer->emitSymbolAttribute(Sym, Attr); 3103 } 3104 3105 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 3106 /// exactly one predecessor and the control transfer mechanism between 3107 /// the predecessor and this block is a fall-through. 3108 bool AsmPrinter:: 3109 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 3110 // With BasicBlock Sections, beginning of the section is not a fallthrough. 3111 if (MBB->isBeginSection()) 3112 return false; 3113 3114 // If this is a landing pad, it isn't a fall through. If it has no preds, 3115 // then nothing falls through to it. 3116 if (MBB->isEHPad() || MBB->pred_empty()) 3117 return false; 3118 3119 // If there isn't exactly one predecessor, it can't be a fall through. 3120 if (MBB->pred_size() > 1) 3121 return false; 3122 3123 // The predecessor has to be immediately before this block. 3124 MachineBasicBlock *Pred = *MBB->pred_begin(); 3125 if (!Pred->isLayoutSuccessor(MBB)) 3126 return false; 3127 3128 // If the block is completely empty, then it definitely does fall through. 3129 if (Pred->empty()) 3130 return true; 3131 3132 // Check the terminators in the previous blocks 3133 for (const auto &MI : Pred->terminators()) { 3134 // If it is not a simple branch, we are in a table somewhere. 3135 if (!MI.isBranch() || MI.isIndirectBranch()) 3136 return false; 3137 3138 // If we are the operands of one of the branches, this is not a fall 3139 // through. Note that targets with delay slots will usually bundle 3140 // terminators with the delay slot instruction. 3141 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) { 3142 if (OP->isJTI()) 3143 return false; 3144 if (OP->isMBB() && OP->getMBB() == MBB) 3145 return false; 3146 } 3147 } 3148 3149 return true; 3150 } 3151 3152 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) { 3153 if (!S.usesMetadata()) 3154 return nullptr; 3155 3156 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 3157 gcp_map_type::iterator GCPI = GCMap.find(&S); 3158 if (GCPI != GCMap.end()) 3159 return GCPI->second.get(); 3160 3161 auto Name = S.getName(); 3162 3163 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter : 3164 GCMetadataPrinterRegistry::entries()) 3165 if (Name == GCMetaPrinter.getName()) { 3166 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate(); 3167 GMP->S = &S; 3168 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP))); 3169 return IterBool.first->second.get(); 3170 } 3171 3172 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 3173 } 3174 3175 void AsmPrinter::emitStackMaps(StackMaps &SM) { 3176 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 3177 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 3178 bool NeedsDefault = false; 3179 if (MI->begin() == MI->end()) 3180 // No GC strategy, use the default format. 3181 NeedsDefault = true; 3182 else 3183 for (auto &I : *MI) { 3184 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 3185 if (MP->emitStackMaps(SM, *this)) 3186 continue; 3187 // The strategy doesn't have printer or doesn't emit custom stack maps. 3188 // Use the default format. 3189 NeedsDefault = true; 3190 } 3191 3192 if (NeedsDefault) 3193 SM.serializeToStackMapSection(); 3194 } 3195 3196 /// Pin vtable to this file. 3197 AsmPrinterHandler::~AsmPrinterHandler() = default; 3198 3199 void AsmPrinterHandler::markFunctionEnd() {} 3200 3201 // In the binary's "xray_instr_map" section, an array of these function entries 3202 // describes each instrumentation point. When XRay patches your code, the index 3203 // into this table will be given to your handler as a patch point identifier. 3204 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const { 3205 auto Kind8 = static_cast<uint8_t>(Kind); 3206 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1)); 3207 Out->emitBinaryData( 3208 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1)); 3209 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1)); 3210 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3); 3211 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size"); 3212 Out->emitZeros(Padding); 3213 } 3214 3215 void AsmPrinter::emitXRayTable() { 3216 if (Sleds.empty()) 3217 return; 3218 3219 auto PrevSection = OutStreamer->getCurrentSectionOnly(); 3220 const Function &F = MF->getFunction(); 3221 MCSection *InstMap = nullptr; 3222 MCSection *FnSledIndex = nullptr; 3223 const Triple &TT = TM.getTargetTriple(); 3224 // Use PC-relative addresses on all targets except MIPS (MIPS64 cannot use 3225 // PC-relative addresses because R_MIPS_PC64 does not exist). 3226 bool PCRel = !TT.isMIPS(); 3227 if (TT.isOSBinFormatELF()) { 3228 auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym); 3229 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER; 3230 if (!PCRel) 3231 Flags |= ELF::SHF_WRITE; 3232 StringRef GroupName; 3233 if (F.hasComdat()) { 3234 Flags |= ELF::SHF_GROUP; 3235 GroupName = F.getComdat()->getName(); 3236 } 3237 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, 3238 Flags, 0, GroupName, 3239 MCSection::NonUniqueID, LinkedToSym); 3240 3241 if (!TM.Options.XRayOmitFunctionIndex) 3242 FnSledIndex = OutContext.getELFSection( 3243 "xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0, 3244 GroupName, MCSection::NonUniqueID, LinkedToSym); 3245 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) { 3246 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0, 3247 SectionKind::getReadOnlyWithRel()); 3248 if (!TM.Options.XRayOmitFunctionIndex) 3249 FnSledIndex = OutContext.getMachOSection( 3250 "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel()); 3251 } else { 3252 llvm_unreachable("Unsupported target"); 3253 } 3254 3255 auto WordSizeBytes = MAI->getCodePointerSize(); 3256 3257 // Now we switch to the instrumentation map section. Because this is done 3258 // per-function, we are able to create an index entry that will represent the 3259 // range of sleds associated with a function. 3260 auto &Ctx = OutContext; 3261 MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true); 3262 OutStreamer->SwitchSection(InstMap); 3263 OutStreamer->emitLabel(SledsStart); 3264 for (const auto &Sled : Sleds) { 3265 if (PCRel) { 3266 MCSymbol *Dot = Ctx.createTempSymbol(); 3267 OutStreamer->emitLabel(Dot); 3268 OutStreamer->emitValueImpl( 3269 MCBinaryExpr::createSub(MCSymbolRefExpr::create(Sled.Sled, Ctx), 3270 MCSymbolRefExpr::create(Dot, Ctx), Ctx), 3271 WordSizeBytes); 3272 OutStreamer->emitValueImpl( 3273 MCBinaryExpr::createSub( 3274 MCSymbolRefExpr::create(CurrentFnBegin, Ctx), 3275 MCBinaryExpr::createAdd( 3276 MCSymbolRefExpr::create(Dot, Ctx), 3277 MCConstantExpr::create(WordSizeBytes, Ctx), Ctx), 3278 Ctx), 3279 WordSizeBytes); 3280 } else { 3281 OutStreamer->emitSymbolValue(Sled.Sled, WordSizeBytes); 3282 OutStreamer->emitSymbolValue(CurrentFnSym, WordSizeBytes); 3283 } 3284 Sled.emit(WordSizeBytes, OutStreamer.get()); 3285 } 3286 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true); 3287 OutStreamer->emitLabel(SledsEnd); 3288 3289 // We then emit a single entry in the index per function. We use the symbols 3290 // that bound the instrumentation map as the range for a specific function. 3291 // Each entry here will be 2 * word size aligned, as we're writing down two 3292 // pointers. This should work for both 32-bit and 64-bit platforms. 3293 if (FnSledIndex) { 3294 OutStreamer->SwitchSection(FnSledIndex); 3295 OutStreamer->emitCodeAlignment(2 * WordSizeBytes); 3296 OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false); 3297 OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false); 3298 OutStreamer->SwitchSection(PrevSection); 3299 } 3300 Sleds.clear(); 3301 } 3302 3303 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI, 3304 SledKind Kind, uint8_t Version) { 3305 const Function &F = MI.getMF()->getFunction(); 3306 auto Attr = F.getFnAttribute("function-instrument"); 3307 bool LogArgs = F.hasFnAttribute("xray-log-args"); 3308 bool AlwaysInstrument = 3309 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always"; 3310 if (Kind == SledKind::FUNCTION_ENTER && LogArgs) 3311 Kind = SledKind::LOG_ARGS_ENTER; 3312 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind, 3313 AlwaysInstrument, &F, Version}); 3314 } 3315 3316 void AsmPrinter::emitPatchableFunctionEntries() { 3317 const Function &F = MF->getFunction(); 3318 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0; 3319 (void)F.getFnAttribute("patchable-function-prefix") 3320 .getValueAsString() 3321 .getAsInteger(10, PatchableFunctionPrefix); 3322 (void)F.getFnAttribute("patchable-function-entry") 3323 .getValueAsString() 3324 .getAsInteger(10, PatchableFunctionEntry); 3325 if (!PatchableFunctionPrefix && !PatchableFunctionEntry) 3326 return; 3327 const unsigned PointerSize = getPointerSize(); 3328 if (TM.getTargetTriple().isOSBinFormatELF()) { 3329 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC; 3330 const MCSymbolELF *LinkedToSym = nullptr; 3331 StringRef GroupName; 3332 3333 // GNU as < 2.35 did not support section flag 'o'. Use SHF_LINK_ORDER only 3334 // if we are using the integrated assembler. 3335 if (MAI->useIntegratedAssembler()) { 3336 Flags |= ELF::SHF_LINK_ORDER; 3337 if (F.hasComdat()) { 3338 Flags |= ELF::SHF_GROUP; 3339 GroupName = F.getComdat()->getName(); 3340 } 3341 LinkedToSym = cast<MCSymbolELF>(CurrentFnSym); 3342 } 3343 OutStreamer->SwitchSection(OutContext.getELFSection( 3344 "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName, 3345 MCSection::NonUniqueID, LinkedToSym)); 3346 emitAlignment(Align(PointerSize)); 3347 OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize); 3348 } 3349 } 3350 3351 uint16_t AsmPrinter::getDwarfVersion() const { 3352 return OutStreamer->getContext().getDwarfVersion(); 3353 } 3354 3355 void AsmPrinter::setDwarfVersion(uint16_t Version) { 3356 OutStreamer->getContext().setDwarfVersion(Version); 3357 } 3358