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