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