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