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