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