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