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