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