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