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