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