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