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