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