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 is desired and function sections is off, 714 // explicitly request a unique section for this function. 715 if (MF->front().isBeginSection() && !TM.getFunctionSections()) 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.isThreadLocal() && 1852 !GV.hasDLLImportStorageClass() && !GV.getName().startswith("llvm.") && 1853 !GV.hasAtLeastLocalUnnamedAddr()) 1854 OutStreamer->emitAddrsigSym(getSymbol(&GV)); 1855 } 1856 1857 // Emit symbol partition specifications (ELF only). 1858 if (TM.getTargetTriple().isOSBinFormatELF()) { 1859 unsigned UniqueID = 0; 1860 for (const GlobalValue &GV : M.global_values()) { 1861 if (!GV.hasPartition() || GV.isDeclarationForLinker() || 1862 GV.getVisibility() != GlobalValue::DefaultVisibility) 1863 continue; 1864 1865 OutStreamer->SwitchSection( 1866 OutContext.getELFSection(".llvm_sympart", ELF::SHT_LLVM_SYMPART, 0, 0, 1867 "", false, ++UniqueID, nullptr)); 1868 OutStreamer->emitBytes(GV.getPartition()); 1869 OutStreamer->emitZeros(1); 1870 OutStreamer->emitValue( 1871 MCSymbolRefExpr::create(getSymbol(&GV), OutContext), 1872 MAI->getCodePointerSize()); 1873 } 1874 } 1875 1876 // Allow the target to emit any magic that it wants at the end of the file, 1877 // after everything else has gone out. 1878 emitEndOfAsmFile(M); 1879 1880 MMI = nullptr; 1881 1882 OutStreamer->Finish(); 1883 OutStreamer->reset(); 1884 OwnedMLI.reset(); 1885 OwnedMDT.reset(); 1886 1887 return false; 1888 } 1889 1890 MCSymbol *AsmPrinter::getMBBExceptionSym(const MachineBasicBlock &MBB) { 1891 auto Res = MBBSectionExceptionSyms.try_emplace(MBB.getSectionIDNum()); 1892 if (Res.second) 1893 Res.first->second = createTempSymbol("exception"); 1894 return Res.first->second; 1895 } 1896 1897 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1898 this->MF = &MF; 1899 const Function &F = MF.getFunction(); 1900 1901 // Get the function symbol. 1902 if (!MAI->needsFunctionDescriptors()) { 1903 CurrentFnSym = getSymbol(&MF.getFunction()); 1904 } else { 1905 assert(TM.getTargetTriple().isOSAIX() && 1906 "Only AIX uses the function descriptor hooks."); 1907 // AIX is unique here in that the name of the symbol emitted for the 1908 // function body does not have the same name as the source function's 1909 // C-linkage name. 1910 assert(CurrentFnDescSym && "The function descriptor symbol needs to be" 1911 " initalized first."); 1912 1913 // Get the function entry point symbol. 1914 CurrentFnSym = getObjFileLowering().getFunctionEntryPointSymbol(&F, TM); 1915 } 1916 1917 CurrentFnSymForSize = CurrentFnSym; 1918 CurrentFnBegin = nullptr; 1919 CurrentSectionBeginSym = nullptr; 1920 MBBSectionRanges.clear(); 1921 MBBSectionExceptionSyms.clear(); 1922 bool NeedsLocalForSize = MAI->needsLocalForSize(); 1923 if (F.hasFnAttribute("patchable-function-entry") || 1924 F.hasFnAttribute("function-instrument") || 1925 F.hasFnAttribute("xray-instruction-threshold") || 1926 needFuncLabelsForEHOrDebugInfo(MF) || NeedsLocalForSize || 1927 MF.getTarget().Options.EmitStackSizeSection || MF.hasBBLabels()) { 1928 CurrentFnBegin = createTempSymbol("func_begin"); 1929 if (NeedsLocalForSize) 1930 CurrentFnSymForSize = CurrentFnBegin; 1931 } 1932 1933 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE(); 1934 } 1935 1936 namespace { 1937 1938 // Keep track the alignment, constpool entries per Section. 1939 struct SectionCPs { 1940 MCSection *S; 1941 Align Alignment; 1942 SmallVector<unsigned, 4> CPEs; 1943 1944 SectionCPs(MCSection *s, Align a) : S(s), Alignment(a) {} 1945 }; 1946 1947 } // end anonymous namespace 1948 1949 /// EmitConstantPool - Print to the current output stream assembly 1950 /// representations of the constants in the constant pool MCP. This is 1951 /// used to print out constants which have been "spilled to memory" by 1952 /// the code generator. 1953 void AsmPrinter::emitConstantPool() { 1954 const MachineConstantPool *MCP = MF->getConstantPool(); 1955 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 1956 if (CP.empty()) return; 1957 1958 // Calculate sections for constant pool entries. We collect entries to go into 1959 // the same section together to reduce amount of section switch statements. 1960 SmallVector<SectionCPs, 4> CPSections; 1961 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 1962 const MachineConstantPoolEntry &CPE = CP[i]; 1963 Align Alignment = CPE.getAlign(); 1964 1965 SectionKind Kind = CPE.getSectionKind(&getDataLayout()); 1966 1967 const Constant *C = nullptr; 1968 if (!CPE.isMachineConstantPoolEntry()) 1969 C = CPE.Val.ConstVal; 1970 1971 MCSection *S = getObjFileLowering().getSectionForConstant( 1972 getDataLayout(), Kind, C, Alignment); 1973 1974 // The number of sections are small, just do a linear search from the 1975 // last section to the first. 1976 bool Found = false; 1977 unsigned SecIdx = CPSections.size(); 1978 while (SecIdx != 0) { 1979 if (CPSections[--SecIdx].S == S) { 1980 Found = true; 1981 break; 1982 } 1983 } 1984 if (!Found) { 1985 SecIdx = CPSections.size(); 1986 CPSections.push_back(SectionCPs(S, Alignment)); 1987 } 1988 1989 if (Alignment > CPSections[SecIdx].Alignment) 1990 CPSections[SecIdx].Alignment = Alignment; 1991 CPSections[SecIdx].CPEs.push_back(i); 1992 } 1993 1994 // Now print stuff into the calculated sections. 1995 const MCSection *CurSection = nullptr; 1996 unsigned Offset = 0; 1997 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 1998 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 1999 unsigned CPI = CPSections[i].CPEs[j]; 2000 MCSymbol *Sym = GetCPISymbol(CPI); 2001 if (!Sym->isUndefined()) 2002 continue; 2003 2004 if (CurSection != CPSections[i].S) { 2005 OutStreamer->SwitchSection(CPSections[i].S); 2006 emitAlignment(Align(CPSections[i].Alignment)); 2007 CurSection = CPSections[i].S; 2008 Offset = 0; 2009 } 2010 2011 MachineConstantPoolEntry CPE = CP[CPI]; 2012 2013 // Emit inter-object padding for alignment. 2014 unsigned NewOffset = alignTo(Offset, CPE.getAlign()); 2015 OutStreamer->emitZeros(NewOffset - Offset); 2016 2017 Offset = NewOffset + CPE.getSizeInBytes(getDataLayout()); 2018 2019 OutStreamer->emitLabel(Sym); 2020 if (CPE.isMachineConstantPoolEntry()) 2021 emitMachineConstantPoolValue(CPE.Val.MachineCPVal); 2022 else 2023 emitGlobalConstant(getDataLayout(), CPE.Val.ConstVal); 2024 } 2025 } 2026 } 2027 2028 // Print assembly representations of the jump tables used by the current 2029 // function. 2030 void AsmPrinter::emitJumpTableInfo() { 2031 const DataLayout &DL = MF->getDataLayout(); 2032 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 2033 if (!MJTI) return; 2034 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 2035 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 2036 if (JT.empty()) return; 2037 2038 // Pick the directive to use to print the jump table entries, and switch to 2039 // the appropriate section. 2040 const Function &F = MF->getFunction(); 2041 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 2042 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection( 2043 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32, 2044 F); 2045 if (JTInDiffSection) { 2046 // Drop it in the readonly section. 2047 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(F, TM); 2048 OutStreamer->SwitchSection(ReadOnlySection); 2049 } 2050 2051 emitAlignment(Align(MJTI->getEntryAlignment(DL))); 2052 2053 // Jump tables in code sections are marked with a data_region directive 2054 // where that's supported. 2055 if (!JTInDiffSection) 2056 OutStreamer->emitDataRegion(MCDR_DataRegionJT32); 2057 2058 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 2059 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 2060 2061 // If this jump table was deleted, ignore it. 2062 if (JTBBs.empty()) continue; 2063 2064 // For the EK_LabelDifference32 entry, if using .set avoids a relocation, 2065 /// emit a .set directive for each unique entry. 2066 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 2067 MAI->doesSetDirectiveSuppressReloc()) { 2068 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 2069 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 2070 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 2071 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 2072 const MachineBasicBlock *MBB = JTBBs[ii]; 2073 if (!EmittedSets.insert(MBB).second) 2074 continue; 2075 2076 // .set LJTSet, LBB32-base 2077 const MCExpr *LHS = 2078 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 2079 OutStreamer->emitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 2080 MCBinaryExpr::createSub(LHS, Base, 2081 OutContext)); 2082 } 2083 } 2084 2085 // On some targets (e.g. Darwin) we want to emit two consecutive labels 2086 // before each jump table. The first label is never referenced, but tells 2087 // the assembler and linker the extents of the jump table object. The 2088 // second label is actually referenced by the code. 2089 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix()) 2090 // FIXME: This doesn't have to have any specific name, just any randomly 2091 // named and numbered local label started with 'l' would work. Simplify 2092 // GetJTISymbol. 2093 OutStreamer->emitLabel(GetJTISymbol(JTI, true)); 2094 2095 MCSymbol* JTISymbol = GetJTISymbol(JTI); 2096 OutStreamer->emitLabel(JTISymbol); 2097 2098 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 2099 emitJumpTableEntry(MJTI, JTBBs[ii], JTI); 2100 } 2101 if (!JTInDiffSection) 2102 OutStreamer->emitDataRegion(MCDR_DataRegionEnd); 2103 } 2104 2105 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 2106 /// current stream. 2107 void AsmPrinter::emitJumpTableEntry(const MachineJumpTableInfo *MJTI, 2108 const MachineBasicBlock *MBB, 2109 unsigned UID) const { 2110 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block"); 2111 const MCExpr *Value = nullptr; 2112 switch (MJTI->getEntryKind()) { 2113 case MachineJumpTableInfo::EK_Inline: 2114 llvm_unreachable("Cannot emit EK_Inline jump table entry"); 2115 case MachineJumpTableInfo::EK_Custom32: 2116 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry( 2117 MJTI, MBB, UID, OutContext); 2118 break; 2119 case MachineJumpTableInfo::EK_BlockAddress: 2120 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 2121 // .word LBB123 2122 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 2123 break; 2124 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 2125 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 2126 // with a relocation as gp-relative, e.g.: 2127 // .gprel32 LBB123 2128 MCSymbol *MBBSym = MBB->getSymbol(); 2129 OutStreamer->emitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 2130 return; 2131 } 2132 2133 case MachineJumpTableInfo::EK_GPRel64BlockAddress: { 2134 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded 2135 // with a relocation as gp-relative, e.g.: 2136 // .gpdword LBB123 2137 MCSymbol *MBBSym = MBB->getSymbol(); 2138 OutStreamer->emitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 2139 return; 2140 } 2141 2142 case MachineJumpTableInfo::EK_LabelDifference32: { 2143 // Each entry is the address of the block minus the address of the jump 2144 // table. This is used for PIC jump tables where gprel32 is not supported. 2145 // e.g.: 2146 // .word LBB123 - LJTI1_2 2147 // If the .set directive avoids relocations, this is emitted as: 2148 // .set L4_5_set_123, LBB123 - LJTI1_2 2149 // .word L4_5_set_123 2150 if (MAI->doesSetDirectiveSuppressReloc()) { 2151 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()), 2152 OutContext); 2153 break; 2154 } 2155 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 2156 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 2157 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext); 2158 Value = MCBinaryExpr::createSub(Value, Base, OutContext); 2159 break; 2160 } 2161 } 2162 2163 assert(Value && "Unknown entry kind!"); 2164 2165 unsigned EntrySize = MJTI->getEntrySize(getDataLayout()); 2166 OutStreamer->emitValue(Value, EntrySize); 2167 } 2168 2169 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a 2170 /// special global used by LLVM. If so, emit it and return true, otherwise 2171 /// do nothing and return false. 2172 bool AsmPrinter::emitSpecialLLVMGlobal(const GlobalVariable *GV) { 2173 if (GV->getName() == "llvm.used") { 2174 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 2175 emitLLVMUsedList(cast<ConstantArray>(GV->getInitializer())); 2176 return true; 2177 } 2178 2179 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 2180 if (GV->getSection() == "llvm.metadata" || 2181 GV->hasAvailableExternallyLinkage()) 2182 return true; 2183 2184 if (!GV->hasAppendingLinkage()) return false; 2185 2186 assert(GV->hasInitializer() && "Not a special LLVM global!"); 2187 2188 if (GV->getName() == "llvm.global_ctors") { 2189 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 2190 /* isCtor */ true); 2191 2192 return true; 2193 } 2194 2195 if (GV->getName() == "llvm.global_dtors") { 2196 emitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 2197 /* isCtor */ false); 2198 2199 return true; 2200 } 2201 2202 report_fatal_error("unknown special variable"); 2203 } 2204 2205 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 2206 /// global in the specified llvm.used list. 2207 void AsmPrinter::emitLLVMUsedList(const ConstantArray *InitList) { 2208 // Should be an array of 'i8*'. 2209 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 2210 const GlobalValue *GV = 2211 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 2212 if (GV) 2213 OutStreamer->emitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip); 2214 } 2215 } 2216 2217 void AsmPrinter::preprocessXXStructorList(const DataLayout &DL, 2218 const Constant *List, 2219 SmallVector<Structor, 8> &Structors) { 2220 // Should be an array of '{ i32, void ()*, i8* }' structs. The first value is 2221 // the init priority. 2222 if (!isa<ConstantArray>(List)) 2223 return; 2224 2225 // Gather the structors in a form that's convenient for sorting by priority. 2226 for (Value *O : cast<ConstantArray>(List)->operands()) { 2227 auto *CS = cast<ConstantStruct>(O); 2228 if (CS->getOperand(1)->isNullValue()) 2229 break; // Found a null terminator, skip the rest. 2230 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); 2231 if (!Priority) 2232 continue; // Malformed. 2233 Structors.push_back(Structor()); 2234 Structor &S = Structors.back(); 2235 S.Priority = Priority->getLimitedValue(65535); 2236 S.Func = CS->getOperand(1); 2237 if (!CS->getOperand(2)->isNullValue()) { 2238 if (TM.getTargetTriple().isOSAIX()) 2239 llvm::report_fatal_error( 2240 "associated data of XXStructor list is not yet supported on AIX"); 2241 S.ComdatKey = 2242 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts()); 2243 } 2244 } 2245 2246 // Emit the function pointers in the target-specific order 2247 llvm::stable_sort(Structors, [](const Structor &L, const Structor &R) { 2248 return L.Priority < R.Priority; 2249 }); 2250 } 2251 2252 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init 2253 /// priority. 2254 void AsmPrinter::emitXXStructorList(const DataLayout &DL, const Constant *List, 2255 bool IsCtor) { 2256 SmallVector<Structor, 8> Structors; 2257 preprocessXXStructorList(DL, List, Structors); 2258 if (Structors.empty()) 2259 return; 2260 2261 const Align Align = DL.getPointerPrefAlignment(); 2262 for (Structor &S : Structors) { 2263 const TargetLoweringObjectFile &Obj = getObjFileLowering(); 2264 const MCSymbol *KeySym = nullptr; 2265 if (GlobalValue *GV = S.ComdatKey) { 2266 if (GV->isDeclarationForLinker()) 2267 // If the associated variable is not defined in this module 2268 // (it might be available_externally, or have been an 2269 // available_externally definition that was dropped by the 2270 // EliminateAvailableExternally pass), some other TU 2271 // will provide its dynamic initializer. 2272 continue; 2273 2274 KeySym = getSymbol(GV); 2275 } 2276 2277 MCSection *OutputSection = 2278 (IsCtor ? Obj.getStaticCtorSection(S.Priority, KeySym) 2279 : Obj.getStaticDtorSection(S.Priority, KeySym)); 2280 OutStreamer->SwitchSection(OutputSection); 2281 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection()) 2282 emitAlignment(Align); 2283 emitXXStructor(DL, S.Func); 2284 } 2285 } 2286 2287 void AsmPrinter::emitModuleIdents(Module &M) { 2288 if (!MAI->hasIdentDirective()) 2289 return; 2290 2291 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) { 2292 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2293 const MDNode *N = NMD->getOperand(i); 2294 assert(N->getNumOperands() == 1 && 2295 "llvm.ident metadata entry can have only one operand"); 2296 const MDString *S = cast<MDString>(N->getOperand(0)); 2297 OutStreamer->emitIdent(S->getString()); 2298 } 2299 } 2300 } 2301 2302 void AsmPrinter::emitModuleCommandLines(Module &M) { 2303 MCSection *CommandLine = getObjFileLowering().getSectionForCommandLines(); 2304 if (!CommandLine) 2305 return; 2306 2307 const NamedMDNode *NMD = M.getNamedMetadata("llvm.commandline"); 2308 if (!NMD || !NMD->getNumOperands()) 2309 return; 2310 2311 OutStreamer->PushSection(); 2312 OutStreamer->SwitchSection(CommandLine); 2313 OutStreamer->emitZeros(1); 2314 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 2315 const MDNode *N = NMD->getOperand(i); 2316 assert(N->getNumOperands() == 1 && 2317 "llvm.commandline metadata entry can have only one operand"); 2318 const MDString *S = cast<MDString>(N->getOperand(0)); 2319 OutStreamer->emitBytes(S->getString()); 2320 OutStreamer->emitZeros(1); 2321 } 2322 OutStreamer->PopSection(); 2323 } 2324 2325 //===--------------------------------------------------------------------===// 2326 // Emission and print routines 2327 // 2328 2329 /// Emit a byte directive and value. 2330 /// 2331 void AsmPrinter::emitInt8(int Value) const { OutStreamer->emitInt8(Value); } 2332 2333 /// Emit a short directive and value. 2334 void AsmPrinter::emitInt16(int Value) const { OutStreamer->emitInt16(Value); } 2335 2336 /// Emit a long directive and value. 2337 void AsmPrinter::emitInt32(int Value) const { OutStreamer->emitInt32(Value); } 2338 2339 /// Emit a long long directive and value. 2340 void AsmPrinter::emitInt64(uint64_t Value) const { 2341 OutStreamer->emitInt64(Value); 2342 } 2343 2344 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive 2345 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses 2346 /// .set if it avoids relocations. 2347 void AsmPrinter::emitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 2348 unsigned Size) const { 2349 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size); 2350 } 2351 2352 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset" 2353 /// where the size in bytes of the directive is specified by Size and Label 2354 /// specifies the label. This implicitly uses .set if it is available. 2355 void AsmPrinter::emitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 2356 unsigned Size, 2357 bool IsSectionRelative) const { 2358 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) { 2359 OutStreamer->EmitCOFFSecRel32(Label, Offset); 2360 if (Size > 4) 2361 OutStreamer->emitZeros(Size - 4); 2362 return; 2363 } 2364 2365 // Emit Label+Offset (or just Label if Offset is zero) 2366 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext); 2367 if (Offset) 2368 Expr = MCBinaryExpr::createAdd( 2369 Expr, MCConstantExpr::create(Offset, OutContext), OutContext); 2370 2371 OutStreamer->emitValue(Expr, Size); 2372 } 2373 2374 //===----------------------------------------------------------------------===// 2375 2376 // EmitAlignment - Emit an alignment directive to the specified power of 2377 // two boundary. If a global value is specified, and if that global has 2378 // an explicit alignment requested, it will override the alignment request 2379 // if required for correctness. 2380 void AsmPrinter::emitAlignment(Align Alignment, const GlobalObject *GV) const { 2381 if (GV) 2382 Alignment = getGVAlignment(GV, GV->getParent()->getDataLayout(), Alignment); 2383 2384 if (Alignment == Align(1)) 2385 return; // 1-byte aligned: no need to emit alignment. 2386 2387 if (getCurrentSection()->getKind().isText()) 2388 OutStreamer->emitCodeAlignment(Alignment.value()); 2389 else 2390 OutStreamer->emitValueToAlignment(Alignment.value()); 2391 } 2392 2393 //===----------------------------------------------------------------------===// 2394 // Constant emission. 2395 //===----------------------------------------------------------------------===// 2396 2397 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) { 2398 MCContext &Ctx = OutContext; 2399 2400 if (CV->isNullValue() || isa<UndefValue>(CV)) 2401 return MCConstantExpr::create(0, Ctx); 2402 2403 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 2404 return MCConstantExpr::create(CI->getZExtValue(), Ctx); 2405 2406 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 2407 return MCSymbolRefExpr::create(getSymbol(GV), Ctx); 2408 2409 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 2410 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx); 2411 2412 if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(CV)) 2413 return getObjFileLowering().lowerDSOLocalEquivalent(Equiv, TM); 2414 2415 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 2416 if (!CE) { 2417 llvm_unreachable("Unknown constant value to lower!"); 2418 } 2419 2420 switch (CE->getOpcode()) { 2421 case Instruction::AddrSpaceCast: { 2422 const Constant *Op = CE->getOperand(0); 2423 unsigned DstAS = CE->getType()->getPointerAddressSpace(); 2424 unsigned SrcAS = Op->getType()->getPointerAddressSpace(); 2425 if (TM.isNoopAddrSpaceCast(SrcAS, DstAS)) 2426 return lowerConstant(Op); 2427 2428 // Fallthrough to error. 2429 LLVM_FALLTHROUGH; 2430 } 2431 default: { 2432 // If the code isn't optimized, there may be outstanding folding 2433 // opportunities. Attempt to fold the expression using DataLayout as a 2434 // last resort before giving up. 2435 Constant *C = ConstantFoldConstant(CE, getDataLayout()); 2436 if (C != CE) 2437 return lowerConstant(C); 2438 2439 // Otherwise report the problem to the user. 2440 std::string S; 2441 raw_string_ostream OS(S); 2442 OS << "Unsupported expression in static initializer: "; 2443 CE->printAsOperand(OS, /*PrintType=*/false, 2444 !MF ? nullptr : MF->getFunction().getParent()); 2445 report_fatal_error(OS.str()); 2446 } 2447 case Instruction::GetElementPtr: { 2448 // Generate a symbolic expression for the byte address 2449 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0); 2450 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI); 2451 2452 const MCExpr *Base = lowerConstant(CE->getOperand(0)); 2453 if (!OffsetAI) 2454 return Base; 2455 2456 int64_t Offset = OffsetAI.getSExtValue(); 2457 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx), 2458 Ctx); 2459 } 2460 2461 case Instruction::Trunc: 2462 // We emit the value and depend on the assembler to truncate the generated 2463 // expression properly. This is important for differences between 2464 // blockaddress labels. Since the two labels are in the same function, it 2465 // is reasonable to treat their delta as a 32-bit value. 2466 LLVM_FALLTHROUGH; 2467 case Instruction::BitCast: 2468 return lowerConstant(CE->getOperand(0)); 2469 2470 case Instruction::IntToPtr: { 2471 const DataLayout &DL = getDataLayout(); 2472 2473 // Handle casts to pointers by changing them into casts to the appropriate 2474 // integer type. This promotes constant folding and simplifies this code. 2475 Constant *Op = CE->getOperand(0); 2476 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()), 2477 false/*ZExt*/); 2478 return lowerConstant(Op); 2479 } 2480 2481 case Instruction::PtrToInt: { 2482 const DataLayout &DL = getDataLayout(); 2483 2484 // Support only foldable casts to/from pointers that can be eliminated by 2485 // changing the pointer to the appropriately sized integer type. 2486 Constant *Op = CE->getOperand(0); 2487 Type *Ty = CE->getType(); 2488 2489 const MCExpr *OpExpr = lowerConstant(Op); 2490 2491 // We can emit the pointer value into this slot if the slot is an 2492 // integer slot equal to the size of the pointer. 2493 // 2494 // If the pointer is larger than the resultant integer, then 2495 // as with Trunc just depend on the assembler to truncate it. 2496 if (DL.getTypeAllocSize(Ty).getFixedSize() <= 2497 DL.getTypeAllocSize(Op->getType()).getFixedSize()) 2498 return OpExpr; 2499 2500 // Otherwise the pointer is smaller than the resultant integer, mask off 2501 // the high bits so we are sure to get a proper truncation if the input is 2502 // a constant expr. 2503 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType()); 2504 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx); 2505 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx); 2506 } 2507 2508 case Instruction::Sub: { 2509 GlobalValue *LHSGV; 2510 APInt LHSOffset; 2511 DSOLocalEquivalent *DSOEquiv; 2512 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset, 2513 getDataLayout(), &DSOEquiv)) { 2514 GlobalValue *RHSGV; 2515 APInt RHSOffset; 2516 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset, 2517 getDataLayout())) { 2518 const MCExpr *RelocExpr = 2519 getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM); 2520 if (!RelocExpr) { 2521 const MCExpr *LHSExpr = 2522 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx); 2523 if (DSOEquiv && 2524 getObjFileLowering().supportDSOLocalEquivalentLowering()) 2525 LHSExpr = 2526 getObjFileLowering().lowerDSOLocalEquivalent(DSOEquiv, TM); 2527 RelocExpr = MCBinaryExpr::createSub( 2528 LHSExpr, MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx); 2529 } 2530 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue(); 2531 if (Addend != 0) 2532 RelocExpr = MCBinaryExpr::createAdd( 2533 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx); 2534 return RelocExpr; 2535 } 2536 } 2537 } 2538 // else fallthrough 2539 LLVM_FALLTHROUGH; 2540 2541 // The MC library also has a right-shift operator, but it isn't consistently 2542 // signed or unsigned between different targets. 2543 case Instruction::Add: 2544 case Instruction::Mul: 2545 case Instruction::SDiv: 2546 case Instruction::SRem: 2547 case Instruction::Shl: 2548 case Instruction::And: 2549 case Instruction::Or: 2550 case Instruction::Xor: { 2551 const MCExpr *LHS = lowerConstant(CE->getOperand(0)); 2552 const MCExpr *RHS = lowerConstant(CE->getOperand(1)); 2553 switch (CE->getOpcode()) { 2554 default: llvm_unreachable("Unknown binary operator constant cast expr"); 2555 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx); 2556 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx); 2557 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx); 2558 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx); 2559 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx); 2560 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx); 2561 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx); 2562 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx); 2563 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx); 2564 } 2565 } 2566 } 2567 } 2568 2569 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, 2570 AsmPrinter &AP, 2571 const Constant *BaseCV = nullptr, 2572 uint64_t Offset = 0); 2573 2574 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP); 2575 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP); 2576 2577 /// isRepeatedByteSequence - Determine whether the given value is 2578 /// composed of a repeated sequence of identical bytes and return the 2579 /// byte value. If it is not a repeated sequence, return -1. 2580 static int isRepeatedByteSequence(const ConstantDataSequential *V) { 2581 StringRef Data = V->getRawDataValues(); 2582 assert(!Data.empty() && "Empty aggregates should be CAZ node"); 2583 char C = Data[0]; 2584 for (unsigned i = 1, e = Data.size(); i != e; ++i) 2585 if (Data[i] != C) return -1; 2586 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1. 2587 } 2588 2589 /// isRepeatedByteSequence - Determine whether the given value is 2590 /// composed of a repeated sequence of identical bytes and return the 2591 /// byte value. If it is not a repeated sequence, return -1. 2592 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) { 2593 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 2594 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType()); 2595 assert(Size % 8 == 0); 2596 2597 // Extend the element to take zero padding into account. 2598 APInt Value = CI->getValue().zextOrSelf(Size); 2599 if (!Value.isSplat(8)) 2600 return -1; 2601 2602 return Value.zextOrTrunc(8).getZExtValue(); 2603 } 2604 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 2605 // Make sure all array elements are sequences of the same repeated 2606 // byte. 2607 assert(CA->getNumOperands() != 0 && "Should be a CAZ"); 2608 Constant *Op0 = CA->getOperand(0); 2609 int Byte = isRepeatedByteSequence(Op0, DL); 2610 if (Byte == -1) 2611 return -1; 2612 2613 // All array elements must be equal. 2614 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) 2615 if (CA->getOperand(i) != Op0) 2616 return -1; 2617 return Byte; 2618 } 2619 2620 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) 2621 return isRepeatedByteSequence(CDS); 2622 2623 return -1; 2624 } 2625 2626 static void emitGlobalConstantDataSequential(const DataLayout &DL, 2627 const ConstantDataSequential *CDS, 2628 AsmPrinter &AP) { 2629 // See if we can aggregate this into a .fill, if so, emit it as such. 2630 int Value = isRepeatedByteSequence(CDS, DL); 2631 if (Value != -1) { 2632 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType()); 2633 // Don't emit a 1-byte object as a .fill. 2634 if (Bytes > 1) 2635 return AP.OutStreamer->emitFill(Bytes, Value); 2636 } 2637 2638 // If this can be emitted with .ascii/.asciz, emit it as such. 2639 if (CDS->isString()) 2640 return AP.OutStreamer->emitBytes(CDS->getAsString()); 2641 2642 // Otherwise, emit the values in successive locations. 2643 unsigned ElementByteSize = CDS->getElementByteSize(); 2644 if (isa<IntegerType>(CDS->getElementType())) { 2645 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2646 if (AP.isVerbose()) 2647 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2648 CDS->getElementAsInteger(i)); 2649 AP.OutStreamer->emitIntValue(CDS->getElementAsInteger(i), 2650 ElementByteSize); 2651 } 2652 } else { 2653 Type *ET = CDS->getElementType(); 2654 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) 2655 emitGlobalConstantFP(CDS->getElementAsAPFloat(I), ET, AP); 2656 } 2657 2658 unsigned Size = DL.getTypeAllocSize(CDS->getType()); 2659 unsigned EmittedSize = 2660 DL.getTypeAllocSize(CDS->getElementType()) * CDS->getNumElements(); 2661 assert(EmittedSize <= Size && "Size cannot be less than EmittedSize!"); 2662 if (unsigned Padding = Size - EmittedSize) 2663 AP.OutStreamer->emitZeros(Padding); 2664 } 2665 2666 static void emitGlobalConstantArray(const DataLayout &DL, 2667 const ConstantArray *CA, AsmPrinter &AP, 2668 const Constant *BaseCV, uint64_t Offset) { 2669 // See if we can aggregate some values. Make sure it can be 2670 // represented as a series of bytes of the constant value. 2671 int Value = isRepeatedByteSequence(CA, DL); 2672 2673 if (Value != -1) { 2674 uint64_t Bytes = DL.getTypeAllocSize(CA->getType()); 2675 AP.OutStreamer->emitFill(Bytes, Value); 2676 } 2677 else { 2678 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) { 2679 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset); 2680 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType()); 2681 } 2682 } 2683 } 2684 2685 static void emitGlobalConstantVector(const DataLayout &DL, 2686 const ConstantVector *CV, AsmPrinter &AP) { 2687 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 2688 emitGlobalConstantImpl(DL, CV->getOperand(i), AP); 2689 2690 unsigned Size = DL.getTypeAllocSize(CV->getType()); 2691 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) * 2692 CV->getType()->getNumElements(); 2693 if (unsigned Padding = Size - EmittedSize) 2694 AP.OutStreamer->emitZeros(Padding); 2695 } 2696 2697 static void emitGlobalConstantStruct(const DataLayout &DL, 2698 const ConstantStruct *CS, AsmPrinter &AP, 2699 const Constant *BaseCV, uint64_t Offset) { 2700 // Print the fields in successive locations. Pad to align if needed! 2701 unsigned Size = DL.getTypeAllocSize(CS->getType()); 2702 const StructLayout *Layout = DL.getStructLayout(CS->getType()); 2703 uint64_t SizeSoFar = 0; 2704 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 2705 const Constant *Field = CS->getOperand(i); 2706 2707 // Print the actual field value. 2708 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar); 2709 2710 // Check if padding is needed and insert one or more 0s. 2711 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType()); 2712 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 2713 - Layout->getElementOffset(i)) - FieldSize; 2714 SizeSoFar += FieldSize + PadSize; 2715 2716 // Insert padding - this may include padding to increase the size of the 2717 // current field up to the ABI size (if the struct is not packed) as well 2718 // as padding to ensure that the next field starts at the right offset. 2719 AP.OutStreamer->emitZeros(PadSize); 2720 } 2721 assert(SizeSoFar == Layout->getSizeInBytes() && 2722 "Layout of constant struct may be incorrect!"); 2723 } 2724 2725 static void emitGlobalConstantFP(APFloat APF, Type *ET, AsmPrinter &AP) { 2726 assert(ET && "Unknown float type"); 2727 APInt API = APF.bitcastToAPInt(); 2728 2729 // First print a comment with what we think the original floating-point value 2730 // should have been. 2731 if (AP.isVerbose()) { 2732 SmallString<8> StrVal; 2733 APF.toString(StrVal); 2734 ET->print(AP.OutStreamer->GetCommentOS()); 2735 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n'; 2736 } 2737 2738 // Now iterate through the APInt chunks, emitting them in endian-correct 2739 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit 2740 // floats). 2741 unsigned NumBytes = API.getBitWidth() / 8; 2742 unsigned TrailingBytes = NumBytes % sizeof(uint64_t); 2743 const uint64_t *p = API.getRawData(); 2744 2745 // PPC's long double has odd notions of endianness compared to how LLVM 2746 // handles it: p[0] goes first for *big* endian on PPC. 2747 if (AP.getDataLayout().isBigEndian() && !ET->isPPC_FP128Ty()) { 2748 int Chunk = API.getNumWords() - 1; 2749 2750 if (TrailingBytes) 2751 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk--], TrailingBytes); 2752 2753 for (; Chunk >= 0; --Chunk) 2754 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t)); 2755 } else { 2756 unsigned Chunk; 2757 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk) 2758 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], sizeof(uint64_t)); 2759 2760 if (TrailingBytes) 2761 AP.OutStreamer->emitIntValueInHexWithPadding(p[Chunk], TrailingBytes); 2762 } 2763 2764 // Emit the tail padding for the long double. 2765 const DataLayout &DL = AP.getDataLayout(); 2766 AP.OutStreamer->emitZeros(DL.getTypeAllocSize(ET) - DL.getTypeStoreSize(ET)); 2767 } 2768 2769 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) { 2770 emitGlobalConstantFP(CFP->getValueAPF(), CFP->getType(), AP); 2771 } 2772 2773 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) { 2774 const DataLayout &DL = AP.getDataLayout(); 2775 unsigned BitWidth = CI->getBitWidth(); 2776 2777 // Copy the value as we may massage the layout for constants whose bit width 2778 // is not a multiple of 64-bits. 2779 APInt Realigned(CI->getValue()); 2780 uint64_t ExtraBits = 0; 2781 unsigned ExtraBitsSize = BitWidth & 63; 2782 2783 if (ExtraBitsSize) { 2784 // The bit width of the data is not a multiple of 64-bits. 2785 // The extra bits are expected to be at the end of the chunk of the memory. 2786 // Little endian: 2787 // * Nothing to be done, just record the extra bits to emit. 2788 // Big endian: 2789 // * Record the extra bits to emit. 2790 // * Realign the raw data to emit the chunks of 64-bits. 2791 if (DL.isBigEndian()) { 2792 // Basically the structure of the raw data is a chunk of 64-bits cells: 2793 // 0 1 BitWidth / 64 2794 // [chunk1][chunk2] ... [chunkN]. 2795 // The most significant chunk is chunkN and it should be emitted first. 2796 // However, due to the alignment issue chunkN contains useless bits. 2797 // Realign the chunks so that they contain only useful information: 2798 // ExtraBits 0 1 (BitWidth / 64) - 1 2799 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN] 2800 ExtraBitsSize = alignTo(ExtraBitsSize, 8); 2801 ExtraBits = Realigned.getRawData()[0] & 2802 (((uint64_t)-1) >> (64 - ExtraBitsSize)); 2803 Realigned.lshrInPlace(ExtraBitsSize); 2804 } else 2805 ExtraBits = Realigned.getRawData()[BitWidth / 64]; 2806 } 2807 2808 // We don't expect assemblers to support integer data directives 2809 // for more than 64 bits, so we emit the data in at most 64-bit 2810 // quantities at a time. 2811 const uint64_t *RawData = Realigned.getRawData(); 2812 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 2813 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i]; 2814 AP.OutStreamer->emitIntValue(Val, 8); 2815 } 2816 2817 if (ExtraBitsSize) { 2818 // Emit the extra bits after the 64-bits chunks. 2819 2820 // Emit a directive that fills the expected size. 2821 uint64_t Size = AP.getDataLayout().getTypeStoreSize(CI->getType()); 2822 Size -= (BitWidth / 64) * 8; 2823 assert(Size && Size * 8 >= ExtraBitsSize && 2824 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) 2825 == ExtraBits && "Directive too small for extra bits."); 2826 AP.OutStreamer->emitIntValue(ExtraBits, Size); 2827 } 2828 } 2829 2830 /// Transform a not absolute MCExpr containing a reference to a GOT 2831 /// equivalent global, by a target specific GOT pc relative access to the 2832 /// final symbol. 2833 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, 2834 const Constant *BaseCst, 2835 uint64_t Offset) { 2836 // The global @foo below illustrates a global that uses a got equivalent. 2837 // 2838 // @bar = global i32 42 2839 // @gotequiv = private unnamed_addr constant i32* @bar 2840 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64), 2841 // i64 ptrtoint (i32* @foo to i64)) 2842 // to i32) 2843 // 2844 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually 2845 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the 2846 // form: 2847 // 2848 // foo = cstexpr, where 2849 // cstexpr := <gotequiv> - "." + <cst> 2850 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst> 2851 // 2852 // After canonicalization by evaluateAsRelocatable `ME` turns into: 2853 // 2854 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where 2855 // gotpcrelcst := <offset from @foo base> + <cst> 2856 MCValue MV; 2857 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute()) 2858 return; 2859 const MCSymbolRefExpr *SymA = MV.getSymA(); 2860 if (!SymA) 2861 return; 2862 2863 // Check that GOT equivalent symbol is cached. 2864 const MCSymbol *GOTEquivSym = &SymA->getSymbol(); 2865 if (!AP.GlobalGOTEquivs.count(GOTEquivSym)) 2866 return; 2867 2868 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst); 2869 if (!BaseGV) 2870 return; 2871 2872 // Check for a valid base symbol 2873 const MCSymbol *BaseSym = AP.getSymbol(BaseGV); 2874 const MCSymbolRefExpr *SymB = MV.getSymB(); 2875 2876 if (!SymB || BaseSym != &SymB->getSymbol()) 2877 return; 2878 2879 // Make sure to match: 2880 // 2881 // gotpcrelcst := <offset from @foo base> + <cst> 2882 // 2883 // If gotpcrelcst is positive it means that we can safely fold the pc rel 2884 // displacement into the GOTPCREL. We can also can have an extra offset <cst> 2885 // if the target knows how to encode it. 2886 int64_t GOTPCRelCst = Offset + MV.getConstant(); 2887 if (GOTPCRelCst < 0) 2888 return; 2889 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0) 2890 return; 2891 2892 // Emit the GOT PC relative to replace the got equivalent global, i.e.: 2893 // 2894 // bar: 2895 // .long 42 2896 // gotequiv: 2897 // .quad bar 2898 // foo: 2899 // .long gotequiv - "." + <cst> 2900 // 2901 // is replaced by the target specific equivalent to: 2902 // 2903 // bar: 2904 // .long 42 2905 // foo: 2906 // .long bar@GOTPCREL+<gotpcrelcst> 2907 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym]; 2908 const GlobalVariable *GV = Result.first; 2909 int NumUses = (int)Result.second; 2910 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0)); 2911 const MCSymbol *FinalSym = AP.getSymbol(FinalGV); 2912 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel( 2913 FinalGV, FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer); 2914 2915 // Update GOT equivalent usage information 2916 --NumUses; 2917 if (NumUses >= 0) 2918 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses); 2919 } 2920 2921 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV, 2922 AsmPrinter &AP, const Constant *BaseCV, 2923 uint64_t Offset) { 2924 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2925 2926 // Globals with sub-elements such as combinations of arrays and structs 2927 // are handled recursively by emitGlobalConstantImpl. Keep track of the 2928 // constant symbol base and the current position with BaseCV and Offset. 2929 if (!BaseCV && CV->hasOneUse()) 2930 BaseCV = dyn_cast<Constant>(CV->user_back()); 2931 2932 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) 2933 return AP.OutStreamer->emitZeros(Size); 2934 2935 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 2936 const uint64_t StoreSize = DL.getTypeStoreSize(CV->getType()); 2937 2938 if (StoreSize <= 8) { 2939 if (AP.isVerbose()) 2940 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2941 CI->getZExtValue()); 2942 AP.OutStreamer->emitIntValue(CI->getZExtValue(), StoreSize); 2943 } else { 2944 emitGlobalConstantLargeInt(CI, AP); 2945 } 2946 2947 // Emit tail padding if needed 2948 if (Size != StoreSize) 2949 AP.OutStreamer->emitZeros(Size - StoreSize); 2950 2951 return; 2952 } 2953 2954 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 2955 return emitGlobalConstantFP(CFP, AP); 2956 2957 if (isa<ConstantPointerNull>(CV)) { 2958 AP.OutStreamer->emitIntValue(0, Size); 2959 return; 2960 } 2961 2962 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV)) 2963 return emitGlobalConstantDataSequential(DL, CDS, AP); 2964 2965 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 2966 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset); 2967 2968 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 2969 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset); 2970 2971 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 2972 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of 2973 // vectors). 2974 if (CE->getOpcode() == Instruction::BitCast) 2975 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP); 2976 2977 if (Size > 8) { 2978 // If the constant expression's size is greater than 64-bits, then we have 2979 // to emit the value in chunks. Try to constant fold the value and emit it 2980 // that way. 2981 Constant *New = ConstantFoldConstant(CE, DL); 2982 if (New != CE) 2983 return emitGlobalConstantImpl(DL, New, AP); 2984 } 2985 } 2986 2987 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 2988 return emitGlobalConstantVector(DL, V, AP); 2989 2990 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 2991 // thread the streamer with EmitValue. 2992 const MCExpr *ME = AP.lowerConstant(CV); 2993 2994 // Since lowerConstant already folded and got rid of all IR pointer and 2995 // integer casts, detect GOT equivalent accesses by looking into the MCExpr 2996 // directly. 2997 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel()) 2998 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset); 2999 3000 AP.OutStreamer->emitValue(ME, Size); 3001 } 3002 3003 /// EmitGlobalConstant - Print a general LLVM constant to the .s file. 3004 void AsmPrinter::emitGlobalConstant(const DataLayout &DL, const Constant *CV) { 3005 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 3006 if (Size) 3007 emitGlobalConstantImpl(DL, CV, *this); 3008 else if (MAI->hasSubsectionsViaSymbols()) { 3009 // If the global has zero size, emit a single byte so that two labels don't 3010 // look like they are at the same location. 3011 OutStreamer->emitIntValue(0, 1); 3012 } 3013 } 3014 3015 void AsmPrinter::emitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 3016 // Target doesn't support this yet! 3017 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 3018 } 3019 3020 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 3021 if (Offset > 0) 3022 OS << '+' << Offset; 3023 else if (Offset < 0) 3024 OS << Offset; 3025 } 3026 3027 void AsmPrinter::emitNops(unsigned N) { 3028 MCInst Nop = MF->getSubtarget().getInstrInfo()->getNop(); 3029 for (; N; --N) 3030 EmitToStreamer(*OutStreamer, Nop); 3031 } 3032 3033 //===----------------------------------------------------------------------===// 3034 // Symbol Lowering Routines. 3035 //===----------------------------------------------------------------------===// 3036 3037 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const { 3038 return OutContext.createTempSymbol(Name, true); 3039 } 3040 3041 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 3042 return MMI->getAddrLabelSymbol(BA->getBasicBlock()); 3043 } 3044 3045 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 3046 return MMI->getAddrLabelSymbol(BB); 3047 } 3048 3049 /// GetCPISymbol - Return the symbol for the specified constant pool entry. 3050 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 3051 if (getSubtargetInfo().getTargetTriple().isWindowsMSVCEnvironment()) { 3052 const MachineConstantPoolEntry &CPE = 3053 MF->getConstantPool()->getConstants()[CPID]; 3054 if (!CPE.isMachineConstantPoolEntry()) { 3055 const DataLayout &DL = MF->getDataLayout(); 3056 SectionKind Kind = CPE.getSectionKind(&DL); 3057 const Constant *C = CPE.Val.ConstVal; 3058 Align Alignment = CPE.Alignment; 3059 if (const MCSectionCOFF *S = dyn_cast<MCSectionCOFF>( 3060 getObjFileLowering().getSectionForConstant(DL, Kind, C, 3061 Alignment))) { 3062 if (MCSymbol *Sym = S->getCOMDATSymbol()) { 3063 if (Sym->isUndefined()) 3064 OutStreamer->emitSymbolAttribute(Sym, MCSA_Global); 3065 return Sym; 3066 } 3067 } 3068 } 3069 } 3070 3071 const DataLayout &DL = getDataLayout(); 3072 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 3073 "CPI" + Twine(getFunctionNumber()) + "_" + 3074 Twine(CPID)); 3075 } 3076 3077 /// GetJTISymbol - Return the symbol for the specified jump table entry. 3078 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 3079 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 3080 } 3081 3082 /// GetJTSetSymbol - Return the symbol for the specified jump table .set 3083 /// FIXME: privatize to AsmPrinter. 3084 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 3085 const DataLayout &DL = getDataLayout(); 3086 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 3087 Twine(getFunctionNumber()) + "_" + 3088 Twine(UID) + "_set_" + Twine(MBBID)); 3089 } 3090 3091 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV, 3092 StringRef Suffix) const { 3093 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM); 3094 } 3095 3096 /// Return the MCSymbol for the specified ExternalSymbol. 3097 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 3098 SmallString<60> NameStr; 3099 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout()); 3100 return OutContext.getOrCreateSymbol(NameStr); 3101 } 3102 3103 /// PrintParentLoopComment - Print comments about parent loops of this one. 3104 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 3105 unsigned FunctionNumber) { 3106 if (!Loop) return; 3107 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 3108 OS.indent(Loop->getLoopDepth()*2) 3109 << "Parent Loop BB" << FunctionNumber << "_" 3110 << Loop->getHeader()->getNumber() 3111 << " Depth=" << Loop->getLoopDepth() << '\n'; 3112 } 3113 3114 /// PrintChildLoopComment - Print comments about child loops within 3115 /// the loop for this basic block, with nesting. 3116 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 3117 unsigned FunctionNumber) { 3118 // Add child loop information 3119 for (const MachineLoop *CL : *Loop) { 3120 OS.indent(CL->getLoopDepth()*2) 3121 << "Child Loop BB" << FunctionNumber << "_" 3122 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth() 3123 << '\n'; 3124 PrintChildLoopComment(OS, CL, FunctionNumber); 3125 } 3126 } 3127 3128 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks. 3129 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, 3130 const MachineLoopInfo *LI, 3131 const AsmPrinter &AP) { 3132 // Add loop depth information 3133 const MachineLoop *Loop = LI->getLoopFor(&MBB); 3134 if (!Loop) return; 3135 3136 MachineBasicBlock *Header = Loop->getHeader(); 3137 assert(Header && "No header for loop"); 3138 3139 // If this block is not a loop header, just print out what is the loop header 3140 // and return. 3141 if (Header != &MBB) { 3142 AP.OutStreamer->AddComment(" in Loop: Header=BB" + 3143 Twine(AP.getFunctionNumber())+"_" + 3144 Twine(Loop->getHeader()->getNumber())+ 3145 " Depth="+Twine(Loop->getLoopDepth())); 3146 return; 3147 } 3148 3149 // Otherwise, it is a loop header. Print out information about child and 3150 // parent loops. 3151 raw_ostream &OS = AP.OutStreamer->GetCommentOS(); 3152 3153 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 3154 3155 OS << "=>"; 3156 OS.indent(Loop->getLoopDepth()*2-2); 3157 3158 OS << "This "; 3159 if (Loop->isInnermost()) 3160 OS << "Inner "; 3161 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 3162 3163 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 3164 } 3165 3166 /// emitBasicBlockStart - This method prints the label for the specified 3167 /// MachineBasicBlock, an alignment (if present) and a comment describing 3168 /// it if appropriate. 3169 void AsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) { 3170 // End the previous funclet and start a new one. 3171 if (MBB.isEHFuncletEntry()) { 3172 for (const HandlerInfo &HI : Handlers) { 3173 HI.Handler->endFunclet(); 3174 HI.Handler->beginFunclet(MBB); 3175 } 3176 } 3177 3178 // Emit an alignment directive for this block, if needed. 3179 const Align Alignment = MBB.getAlignment(); 3180 if (Alignment != Align(1)) 3181 emitAlignment(Alignment); 3182 3183 // Switch to a new section if this basic block must begin a section. The 3184 // entry block is always placed in the function section and is handled 3185 // separately. 3186 if (MBB.isBeginSection() && !MBB.isEntryBlock()) { 3187 OutStreamer->SwitchSection( 3188 getObjFileLowering().getSectionForMachineBasicBlock(MF->getFunction(), 3189 MBB, TM)); 3190 CurrentSectionBeginSym = MBB.getSymbol(); 3191 } 3192 3193 // If the block has its address taken, emit any labels that were used to 3194 // reference the block. It is possible that there is more than one label 3195 // here, because multiple LLVM BB's may have been RAUW'd to this block after 3196 // the references were generated. 3197 if (MBB.hasAddressTaken()) { 3198 const BasicBlock *BB = MBB.getBasicBlock(); 3199 if (isVerbose()) 3200 OutStreamer->AddComment("Block address taken"); 3201 3202 // MBBs can have their address taken as part of CodeGen without having 3203 // their corresponding BB's address taken in IR 3204 if (BB->hasAddressTaken()) 3205 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB)) 3206 OutStreamer->emitLabel(Sym); 3207 } 3208 3209 // Print some verbose block comments. 3210 if (isVerbose()) { 3211 if (const BasicBlock *BB = MBB.getBasicBlock()) { 3212 if (BB->hasName()) { 3213 BB->printAsOperand(OutStreamer->GetCommentOS(), 3214 /*PrintType=*/false, BB->getModule()); 3215 OutStreamer->GetCommentOS() << '\n'; 3216 } 3217 } 3218 3219 assert(MLI != nullptr && "MachineLoopInfo should has been computed"); 3220 emitBasicBlockLoopComments(MBB, MLI, *this); 3221 } 3222 3223 // Print the main label for the block. 3224 if (shouldEmitLabelForBasicBlock(MBB)) { 3225 if (isVerbose() && MBB.hasLabelMustBeEmitted()) 3226 OutStreamer->AddComment("Label of block must be emitted"); 3227 OutStreamer->emitLabel(MBB.getSymbol()); 3228 } else { 3229 if (isVerbose()) { 3230 // NOTE: Want this comment at start of line, don't emit with AddComment. 3231 OutStreamer->emitRawComment(" %bb." + Twine(MBB.getNumber()) + ":", 3232 false); 3233 } 3234 } 3235 3236 if (MBB.isEHCatchretTarget() && 3237 MAI->getExceptionHandlingType() == ExceptionHandling::WinEH) { 3238 OutStreamer->emitLabel(MBB.getEHCatchretSymbol()); 3239 } 3240 3241 // With BB sections, each basic block must handle CFI information on its own 3242 // if it begins a section (Entry block is handled separately by 3243 // AsmPrinterHandler::beginFunction). 3244 if (MBB.isBeginSection() && !MBB.isEntryBlock()) 3245 for (const HandlerInfo &HI : Handlers) 3246 HI.Handler->beginBasicBlock(MBB); 3247 } 3248 3249 void AsmPrinter::emitBasicBlockEnd(const MachineBasicBlock &MBB) { 3250 // Check if CFI information needs to be updated for this MBB with basic block 3251 // sections. 3252 if (MBB.isEndSection()) 3253 for (const HandlerInfo &HI : Handlers) 3254 HI.Handler->endBasicBlock(MBB); 3255 } 3256 3257 void AsmPrinter::emitVisibility(MCSymbol *Sym, unsigned Visibility, 3258 bool IsDefinition) const { 3259 MCSymbolAttr Attr = MCSA_Invalid; 3260 3261 switch (Visibility) { 3262 default: break; 3263 case GlobalValue::HiddenVisibility: 3264 if (IsDefinition) 3265 Attr = MAI->getHiddenVisibilityAttr(); 3266 else 3267 Attr = MAI->getHiddenDeclarationVisibilityAttr(); 3268 break; 3269 case GlobalValue::ProtectedVisibility: 3270 Attr = MAI->getProtectedVisibilityAttr(); 3271 break; 3272 } 3273 3274 if (Attr != MCSA_Invalid) 3275 OutStreamer->emitSymbolAttribute(Sym, Attr); 3276 } 3277 3278 bool AsmPrinter::shouldEmitLabelForBasicBlock( 3279 const MachineBasicBlock &MBB) const { 3280 // With `-fbasic-block-sections=`, a label is needed for every non-entry block 3281 // in the labels mode (option `=labels`) and every section beginning in the 3282 // sections mode (`=all` and `=list=`). 3283 if ((MF->hasBBLabels() || MBB.isBeginSection()) && !MBB.isEntryBlock()) 3284 return true; 3285 // A label is needed for any block with at least one predecessor (when that 3286 // predecessor is not the fallthrough predecessor, or if it is an EH funclet 3287 // entry, or if a label is forced). 3288 return !MBB.pred_empty() && 3289 (!isBlockOnlyReachableByFallthrough(&MBB) || MBB.isEHFuncletEntry() || 3290 MBB.hasLabelMustBeEmitted()); 3291 } 3292 3293 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 3294 /// exactly one predecessor and the control transfer mechanism between 3295 /// the predecessor and this block is a fall-through. 3296 bool AsmPrinter:: 3297 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 3298 // If this is a landing pad, it isn't a fall through. If it has no preds, 3299 // then nothing falls through to it. 3300 if (MBB->isEHPad() || MBB->pred_empty()) 3301 return false; 3302 3303 // If there isn't exactly one predecessor, it can't be a fall through. 3304 if (MBB->pred_size() > 1) 3305 return false; 3306 3307 // The predecessor has to be immediately before this block. 3308 MachineBasicBlock *Pred = *MBB->pred_begin(); 3309 if (!Pred->isLayoutSuccessor(MBB)) 3310 return false; 3311 3312 // If the block is completely empty, then it definitely does fall through. 3313 if (Pred->empty()) 3314 return true; 3315 3316 // Check the terminators in the previous blocks 3317 for (const auto &MI : Pred->terminators()) { 3318 // If it is not a simple branch, we are in a table somewhere. 3319 if (!MI.isBranch() || MI.isIndirectBranch()) 3320 return false; 3321 3322 // If we are the operands of one of the branches, this is not a fall 3323 // through. Note that targets with delay slots will usually bundle 3324 // terminators with the delay slot instruction. 3325 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) { 3326 if (OP->isJTI()) 3327 return false; 3328 if (OP->isMBB() && OP->getMBB() == MBB) 3329 return false; 3330 } 3331 } 3332 3333 return true; 3334 } 3335 3336 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) { 3337 if (!S.usesMetadata()) 3338 return nullptr; 3339 3340 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 3341 gcp_map_type::iterator GCPI = GCMap.find(&S); 3342 if (GCPI != GCMap.end()) 3343 return GCPI->second.get(); 3344 3345 auto Name = S.getName(); 3346 3347 for (const GCMetadataPrinterRegistry::entry &GCMetaPrinter : 3348 GCMetadataPrinterRegistry::entries()) 3349 if (Name == GCMetaPrinter.getName()) { 3350 std::unique_ptr<GCMetadataPrinter> GMP = GCMetaPrinter.instantiate(); 3351 GMP->S = &S; 3352 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP))); 3353 return IterBool.first->second.get(); 3354 } 3355 3356 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 3357 } 3358 3359 void AsmPrinter::emitStackMaps(StackMaps &SM) { 3360 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 3361 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 3362 bool NeedsDefault = false; 3363 if (MI->begin() == MI->end()) 3364 // No GC strategy, use the default format. 3365 NeedsDefault = true; 3366 else 3367 for (auto &I : *MI) { 3368 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 3369 if (MP->emitStackMaps(SM, *this)) 3370 continue; 3371 // The strategy doesn't have printer or doesn't emit custom stack maps. 3372 // Use the default format. 3373 NeedsDefault = true; 3374 } 3375 3376 if (NeedsDefault) 3377 SM.serializeToStackMapSection(); 3378 } 3379 3380 /// Pin vtable to this file. 3381 AsmPrinterHandler::~AsmPrinterHandler() = default; 3382 3383 void AsmPrinterHandler::markFunctionEnd() {} 3384 3385 // In the binary's "xray_instr_map" section, an array of these function entries 3386 // describes each instrumentation point. When XRay patches your code, the index 3387 // into this table will be given to your handler as a patch point identifier. 3388 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out) const { 3389 auto Kind8 = static_cast<uint8_t>(Kind); 3390 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Kind8), 1)); 3391 Out->emitBinaryData( 3392 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1)); 3393 Out->emitBinaryData(StringRef(reinterpret_cast<const char *>(&Version), 1)); 3394 auto Padding = (4 * Bytes) - ((2 * Bytes) + 3); 3395 assert(Padding >= 0 && "Instrumentation map entry > 4 * Word Size"); 3396 Out->emitZeros(Padding); 3397 } 3398 3399 void AsmPrinter::emitXRayTable() { 3400 if (Sleds.empty()) 3401 return; 3402 3403 auto PrevSection = OutStreamer->getCurrentSectionOnly(); 3404 const Function &F = MF->getFunction(); 3405 MCSection *InstMap = nullptr; 3406 MCSection *FnSledIndex = nullptr; 3407 const Triple &TT = TM.getTargetTriple(); 3408 // Use PC-relative addresses on all targets. 3409 if (TT.isOSBinFormatELF()) { 3410 auto LinkedToSym = cast<MCSymbolELF>(CurrentFnSym); 3411 auto Flags = ELF::SHF_ALLOC | ELF::SHF_LINK_ORDER; 3412 StringRef GroupName; 3413 if (F.hasComdat()) { 3414 Flags |= ELF::SHF_GROUP; 3415 GroupName = F.getComdat()->getName(); 3416 } 3417 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, 3418 Flags, 0, GroupName, F.hasComdat(), 3419 MCSection::NonUniqueID, LinkedToSym); 3420 3421 if (!TM.Options.XRayOmitFunctionIndex) 3422 FnSledIndex = OutContext.getELFSection( 3423 "xray_fn_idx", ELF::SHT_PROGBITS, Flags | ELF::SHF_WRITE, 0, 3424 GroupName, F.hasComdat(), MCSection::NonUniqueID, LinkedToSym); 3425 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) { 3426 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0, 3427 SectionKind::getReadOnlyWithRel()); 3428 if (!TM.Options.XRayOmitFunctionIndex) 3429 FnSledIndex = OutContext.getMachOSection( 3430 "__DATA", "xray_fn_idx", 0, SectionKind::getReadOnlyWithRel()); 3431 } else { 3432 llvm_unreachable("Unsupported target"); 3433 } 3434 3435 auto WordSizeBytes = MAI->getCodePointerSize(); 3436 3437 // Now we switch to the instrumentation map section. Because this is done 3438 // per-function, we are able to create an index entry that will represent the 3439 // range of sleds associated with a function. 3440 auto &Ctx = OutContext; 3441 MCSymbol *SledsStart = OutContext.createTempSymbol("xray_sleds_start", true); 3442 OutStreamer->SwitchSection(InstMap); 3443 OutStreamer->emitLabel(SledsStart); 3444 for (const auto &Sled : Sleds) { 3445 MCSymbol *Dot = Ctx.createTempSymbol(); 3446 OutStreamer->emitLabel(Dot); 3447 OutStreamer->emitValueImpl( 3448 MCBinaryExpr::createSub(MCSymbolRefExpr::create(Sled.Sled, Ctx), 3449 MCSymbolRefExpr::create(Dot, Ctx), Ctx), 3450 WordSizeBytes); 3451 OutStreamer->emitValueImpl( 3452 MCBinaryExpr::createSub( 3453 MCSymbolRefExpr::create(CurrentFnBegin, Ctx), 3454 MCBinaryExpr::createAdd(MCSymbolRefExpr::create(Dot, Ctx), 3455 MCConstantExpr::create(WordSizeBytes, Ctx), 3456 Ctx), 3457 Ctx), 3458 WordSizeBytes); 3459 Sled.emit(WordSizeBytes, OutStreamer.get()); 3460 } 3461 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_sleds_end", true); 3462 OutStreamer->emitLabel(SledsEnd); 3463 3464 // We then emit a single entry in the index per function. We use the symbols 3465 // that bound the instrumentation map as the range for a specific function. 3466 // Each entry here will be 2 * word size aligned, as we're writing down two 3467 // pointers. This should work for both 32-bit and 64-bit platforms. 3468 if (FnSledIndex) { 3469 OutStreamer->SwitchSection(FnSledIndex); 3470 OutStreamer->emitCodeAlignment(2 * WordSizeBytes); 3471 OutStreamer->emitSymbolValue(SledsStart, WordSizeBytes, false); 3472 OutStreamer->emitSymbolValue(SledsEnd, WordSizeBytes, false); 3473 OutStreamer->SwitchSection(PrevSection); 3474 } 3475 Sleds.clear(); 3476 } 3477 3478 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI, 3479 SledKind Kind, uint8_t Version) { 3480 const Function &F = MI.getMF()->getFunction(); 3481 auto Attr = F.getFnAttribute("function-instrument"); 3482 bool LogArgs = F.hasFnAttribute("xray-log-args"); 3483 bool AlwaysInstrument = 3484 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always"; 3485 if (Kind == SledKind::FUNCTION_ENTER && LogArgs) 3486 Kind = SledKind::LOG_ARGS_ENTER; 3487 Sleds.emplace_back(XRayFunctionEntry{Sled, CurrentFnSym, Kind, 3488 AlwaysInstrument, &F, Version}); 3489 } 3490 3491 void AsmPrinter::emitPatchableFunctionEntries() { 3492 const Function &F = MF->getFunction(); 3493 unsigned PatchableFunctionPrefix = 0, PatchableFunctionEntry = 0; 3494 (void)F.getFnAttribute("patchable-function-prefix") 3495 .getValueAsString() 3496 .getAsInteger(10, PatchableFunctionPrefix); 3497 (void)F.getFnAttribute("patchable-function-entry") 3498 .getValueAsString() 3499 .getAsInteger(10, PatchableFunctionEntry); 3500 if (!PatchableFunctionPrefix && !PatchableFunctionEntry) 3501 return; 3502 const unsigned PointerSize = getPointerSize(); 3503 if (TM.getTargetTriple().isOSBinFormatELF()) { 3504 auto Flags = ELF::SHF_WRITE | ELF::SHF_ALLOC; 3505 const MCSymbolELF *LinkedToSym = nullptr; 3506 StringRef GroupName; 3507 3508 // GNU as < 2.35 did not support section flag 'o'. GNU ld < 2.36 did not 3509 // support mixed SHF_LINK_ORDER and non-SHF_LINK_ORDER sections. 3510 if (MAI->useIntegratedAssembler() || MAI->binutilsIsAtLeast(2, 36)) { 3511 Flags |= ELF::SHF_LINK_ORDER; 3512 if (F.hasComdat()) { 3513 Flags |= ELF::SHF_GROUP; 3514 GroupName = F.getComdat()->getName(); 3515 } 3516 LinkedToSym = cast<MCSymbolELF>(CurrentFnSym); 3517 } 3518 OutStreamer->SwitchSection(OutContext.getELFSection( 3519 "__patchable_function_entries", ELF::SHT_PROGBITS, Flags, 0, GroupName, 3520 F.hasComdat(), MCSection::NonUniqueID, LinkedToSym)); 3521 emitAlignment(Align(PointerSize)); 3522 OutStreamer->emitSymbolValue(CurrentPatchableFunctionEntrySym, PointerSize); 3523 } 3524 } 3525 3526 uint16_t AsmPrinter::getDwarfVersion() const { 3527 return OutStreamer->getContext().getDwarfVersion(); 3528 } 3529 3530 void AsmPrinter::setDwarfVersion(uint16_t Version) { 3531 OutStreamer->getContext().setDwarfVersion(Version); 3532 } 3533 3534 bool AsmPrinter::isDwarf64() const { 3535 return OutStreamer->getContext().getDwarfFormat() == dwarf::DWARF64; 3536 } 3537 3538 unsigned int AsmPrinter::getDwarfOffsetByteSize() const { 3539 return dwarf::getDwarfOffsetByteSize( 3540 OutStreamer->getContext().getDwarfFormat()); 3541 } 3542 3543 unsigned int AsmPrinter::getUnitLengthFieldByteSize() const { 3544 return dwarf::getUnitLengthFieldByteSize( 3545 OutStreamer->getContext().getDwarfFormat()); 3546 } 3547