1 //===-- AsmPrinter.cpp - Common AsmPrinter code ---------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the AsmPrinter class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "AsmPrinterHandler.h" 15 #include "CodeViewDebug.h" 16 #include "DwarfDebug.h" 17 #include "DwarfException.h" 18 #include "WinException.h" 19 #include "llvm/ADT/APFloat.h" 20 #include "llvm/ADT/APInt.h" 21 #include "llvm/ADT/DenseMap.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallString.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/StringRef.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/ADT/Twine.h" 30 #include "llvm/Analysis/ConstantFolding.h" 31 #include "llvm/Analysis/ObjectUtils.h" 32 #include "llvm/CodeGen/Analysis.h" 33 #include "llvm/CodeGen/AsmPrinter.h" 34 #include "llvm/CodeGen/GCMetadata.h" 35 #include "llvm/CodeGen/GCMetadataPrinter.h" 36 #include "llvm/CodeGen/GCStrategy.h" 37 #include "llvm/CodeGen/MachineBasicBlock.h" 38 #include "llvm/CodeGen/MachineConstantPool.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineFunctionPass.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBundle.h" 44 #include "llvm/CodeGen/MachineJumpTableInfo.h" 45 #include "llvm/CodeGen/MachineLoopInfo.h" 46 #include "llvm/CodeGen/MachineMemOperand.h" 47 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 48 #include "llvm/CodeGen/MachineOperand.h" 49 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 50 #include "llvm/IR/BasicBlock.h" 51 #include "llvm/IR/Constant.h" 52 #include "llvm/IR/Constants.h" 53 #include "llvm/IR/DataLayout.h" 54 #include "llvm/IR/DebugInfoMetadata.h" 55 #include "llvm/IR/DerivedTypes.h" 56 #include "llvm/IR/Function.h" 57 #include "llvm/IR/GlobalAlias.h" 58 #include "llvm/IR/GlobalIFunc.h" 59 #include "llvm/IR/GlobalIndirectSymbol.h" 60 #include "llvm/IR/GlobalObject.h" 61 #include "llvm/IR/GlobalValue.h" 62 #include "llvm/IR/GlobalVariable.h" 63 #include "llvm/IR/Mangler.h" 64 #include "llvm/IR/Metadata.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/Operator.h" 67 #include "llvm/IR/Value.h" 68 #include "llvm/MC/MCAsmInfo.h" 69 #include "llvm/MC/MCContext.h" 70 #include "llvm/MC/MCDirectives.h" 71 #include "llvm/MC/MCExpr.h" 72 #include "llvm/MC/MCInst.h" 73 #include "llvm/MC/MCSection.h" 74 #include "llvm/MC/MCSectionELF.h" 75 #include "llvm/MC/MCSectionMachO.h" 76 #include "llvm/MC/MCStreamer.h" 77 #include "llvm/MC/MCSubtargetInfo.h" 78 #include "llvm/MC/MCSymbol.h" 79 #include "llvm/MC/MCTargetOptions.h" 80 #include "llvm/MC/MCValue.h" 81 #include "llvm/MC/SectionKind.h" 82 #include "llvm/Pass.h" 83 #include "llvm/Support/Casting.h" 84 #include "llvm/Support/Compiler.h" 85 #include "llvm/Support/Dwarf.h" 86 #include "llvm/Support/ELF.h" 87 #include "llvm/Support/ErrorHandling.h" 88 #include "llvm/Support/Format.h" 89 #include "llvm/Support/MathExtras.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include "llvm/Support/TargetRegistry.h" 92 #include "llvm/Support/Timer.h" 93 #include "llvm/Target/TargetFrameLowering.h" 94 #include "llvm/Target/TargetInstrInfo.h" 95 #include "llvm/Target/TargetLowering.h" 96 #include "llvm/Target/TargetLoweringObjectFile.h" 97 #include "llvm/Target/TargetMachine.h" 98 #include "llvm/Target/TargetRegisterInfo.h" 99 #include "llvm/Target/TargetSubtargetInfo.h" 100 #include <algorithm> 101 #include <cassert> 102 #include <cinttypes> 103 #include <cstdint> 104 #include <limits> 105 #include <memory> 106 #include <string> 107 #include <utility> 108 #include <vector> 109 110 using namespace llvm; 111 112 #define DEBUG_TYPE "asm-printer" 113 114 static const char *const DWARFGroupName = "dwarf"; 115 static const char *const DWARFGroupDescription = "DWARF Emission"; 116 static const char *const DbgTimerName = "emit"; 117 static const char *const DbgTimerDescription = "Debug Info Emission"; 118 static const char *const EHTimerName = "write_exception"; 119 static const char *const EHTimerDescription = "DWARF Exception Writer"; 120 static const char *const CodeViewLineTablesGroupName = "linetables"; 121 static const char *const CodeViewLineTablesGroupDescription = 122 "CodeView Line Tables"; 123 124 STATISTIC(EmittedInsts, "Number of machine instrs printed"); 125 126 static cl::opt<bool> 127 PrintSchedule("print-schedule", cl::Hidden, cl::init(false), 128 cl::desc("Print 'sched: [latency:throughput]' in .s output")); 129 130 char AsmPrinter::ID = 0; 131 132 typedef DenseMap<GCStrategy*, std::unique_ptr<GCMetadataPrinter>> gcp_map_type; 133 static gcp_map_type &getGCMap(void *&P) { 134 if (!P) 135 P = new gcp_map_type(); 136 return *(gcp_map_type*)P; 137 } 138 139 /// getGVAlignmentLog2 - Return the alignment to use for the specified global 140 /// value in log2 form. This rounds up to the preferred alignment if possible 141 /// and legal. 142 static unsigned getGVAlignmentLog2(const GlobalValue *GV, const DataLayout &DL, 143 unsigned InBits = 0) { 144 unsigned NumBits = 0; 145 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) 146 NumBits = DL.getPreferredAlignmentLog(GVar); 147 148 // If InBits is specified, round it to it. 149 if (InBits > NumBits) 150 NumBits = InBits; 151 152 // If the GV has a specified alignment, take it into account. 153 if (GV->getAlignment() == 0) 154 return NumBits; 155 156 unsigned GVAlign = Log2_32(GV->getAlignment()); 157 158 // If the GVAlign is larger than NumBits, or if we are required to obey 159 // NumBits because the GV has an assigned section, obey it. 160 if (GVAlign > NumBits || GV->hasSection()) 161 NumBits = GVAlign; 162 return NumBits; 163 } 164 165 AsmPrinter::AsmPrinter(TargetMachine &tm, std::unique_ptr<MCStreamer> Streamer) 166 : MachineFunctionPass(ID), TM(tm), MAI(tm.getMCAsmInfo()), 167 OutContext(Streamer->getContext()), OutStreamer(std::move(Streamer)) { 168 VerboseAsm = OutStreamer->isVerboseAsm(); 169 } 170 171 AsmPrinter::~AsmPrinter() { 172 assert(!DD && Handlers.empty() && "Debug/EH info didn't get finalized"); 173 174 if (GCMetadataPrinters) { 175 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 176 177 delete &GCMap; 178 GCMetadataPrinters = nullptr; 179 } 180 } 181 182 bool AsmPrinter::isPositionIndependent() const { 183 return TM.isPositionIndependent(); 184 } 185 186 /// getFunctionNumber - Return a unique ID for the current function. 187 /// 188 unsigned AsmPrinter::getFunctionNumber() const { 189 return MF->getFunctionNumber(); 190 } 191 192 const TargetLoweringObjectFile &AsmPrinter::getObjFileLowering() const { 193 return *TM.getObjFileLowering(); 194 } 195 196 const DataLayout &AsmPrinter::getDataLayout() const { 197 return MMI->getModule()->getDataLayout(); 198 } 199 200 // Do not use the cached DataLayout because some client use it without a Module 201 // (llvm-dsymutil, llvm-dwarfdump). 202 unsigned AsmPrinter::getPointerSize() const { return TM.getPointerSize(); } 203 204 const MCSubtargetInfo &AsmPrinter::getSubtargetInfo() const { 205 assert(MF && "getSubtargetInfo requires a valid MachineFunction!"); 206 return MF->getSubtarget<MCSubtargetInfo>(); 207 } 208 209 void AsmPrinter::EmitToStreamer(MCStreamer &S, const MCInst &Inst) { 210 S.EmitInstruction(Inst, getSubtargetInfo()); 211 } 212 213 /// getCurrentSection() - Return the current section we are emitting to. 214 const MCSection *AsmPrinter::getCurrentSection() const { 215 return OutStreamer->getCurrentSectionOnly(); 216 } 217 218 void AsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const { 219 AU.setPreservesAll(); 220 MachineFunctionPass::getAnalysisUsage(AU); 221 AU.addRequired<MachineModuleInfo>(); 222 AU.addRequired<MachineOptimizationRemarkEmitterPass>(); 223 AU.addRequired<GCModuleInfo>(); 224 if (isVerbose()) 225 AU.addRequired<MachineLoopInfo>(); 226 } 227 228 bool AsmPrinter::doInitialization(Module &M) { 229 MMI = getAnalysisIfAvailable<MachineModuleInfo>(); 230 231 // Initialize TargetLoweringObjectFile. 232 const_cast<TargetLoweringObjectFile&>(getObjFileLowering()) 233 .Initialize(OutContext, TM); 234 235 OutStreamer->InitSections(false); 236 237 // Emit the version-min deplyment target directive if needed. 238 // 239 // FIXME: If we end up with a collection of these sorts of Darwin-specific 240 // or ELF-specific things, it may make sense to have a platform helper class 241 // that will work with the target helper class. For now keep it here, as the 242 // alternative is duplicated code in each of the target asm printers that 243 // use the directive, where it would need the same conditionalization 244 // anyway. 245 const Triple &TT = TM.getTargetTriple(); 246 // If there is a version specified, Major will be non-zero. 247 if (TT.isOSDarwin() && TT.getOSMajorVersion() != 0) { 248 unsigned Major, Minor, Update; 249 MCVersionMinType VersionType; 250 if (TT.isWatchOS()) { 251 VersionType = MCVM_WatchOSVersionMin; 252 TT.getWatchOSVersion(Major, Minor, Update); 253 } else if (TT.isTvOS()) { 254 VersionType = MCVM_TvOSVersionMin; 255 TT.getiOSVersion(Major, Minor, Update); 256 } else if (TT.isMacOSX()) { 257 VersionType = MCVM_OSXVersionMin; 258 if (!TT.getMacOSXVersion(Major, Minor, Update)) 259 Major = 0; 260 } else { 261 VersionType = MCVM_IOSVersionMin; 262 TT.getiOSVersion(Major, Minor, Update); 263 } 264 if (Major != 0) 265 OutStreamer->EmitVersionMin(VersionType, Major, Minor, Update); 266 } 267 268 // Allow the target to emit any magic that it wants at the start of the file. 269 EmitStartOfAsmFile(M); 270 271 // Very minimal debug info. It is ignored if we emit actual debug info. If we 272 // don't, this at least helps the user find where a global came from. 273 if (MAI->hasSingleParameterDotFile()) { 274 // .file "foo.c" 275 OutStreamer->EmitFileDirective(M.getSourceFileName()); 276 } 277 278 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 279 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 280 for (auto &I : *MI) 281 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(*I)) 282 MP->beginAssembly(M, *MI, *this); 283 284 // Emit module-level inline asm if it exists. 285 if (!M.getModuleInlineAsm().empty()) { 286 // We're at the module level. Construct MCSubtarget from the default CPU 287 // and target triple. 288 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo( 289 TM.getTargetTriple().str(), TM.getTargetCPU(), 290 TM.getTargetFeatureString())); 291 OutStreamer->AddComment("Start of file scope inline assembly"); 292 OutStreamer->AddBlankLine(); 293 EmitInlineAsm(M.getModuleInlineAsm()+"\n", 294 OutContext.getSubtargetCopy(*STI), TM.Options.MCOptions); 295 OutStreamer->AddComment("End of file scope inline assembly"); 296 OutStreamer->AddBlankLine(); 297 } 298 299 if (MAI->doesSupportDebugInformation()) { 300 bool EmitCodeView = MMI->getModule()->getCodeViewFlag(); 301 if (EmitCodeView && (TM.getTargetTriple().isKnownWindowsMSVCEnvironment() || 302 TM.getTargetTriple().isWindowsItaniumEnvironment())) { 303 Handlers.push_back(HandlerInfo(new CodeViewDebug(this), 304 DbgTimerName, DbgTimerDescription, 305 CodeViewLineTablesGroupName, 306 CodeViewLineTablesGroupDescription)); 307 } 308 if (!EmitCodeView || MMI->getModule()->getDwarfVersion()) { 309 DD = new DwarfDebug(this, &M); 310 DD->beginModule(); 311 Handlers.push_back(HandlerInfo(DD, DbgTimerName, DbgTimerDescription, 312 DWARFGroupName, DWARFGroupDescription)); 313 } 314 } 315 316 switch (MAI->getExceptionHandlingType()) { 317 case ExceptionHandling::SjLj: 318 case ExceptionHandling::DwarfCFI: 319 case ExceptionHandling::ARM: 320 isCFIMoveForDebugging = true; 321 if (MAI->getExceptionHandlingType() != ExceptionHandling::DwarfCFI) 322 break; 323 for (auto &F: M.getFunctionList()) { 324 // If the module contains any function with unwind data, 325 // .eh_frame has to be emitted. 326 // Ignore functions that won't get emitted. 327 if (!F.isDeclarationForLinker() && F.needsUnwindTableEntry()) { 328 isCFIMoveForDebugging = false; 329 break; 330 } 331 } 332 break; 333 default: 334 isCFIMoveForDebugging = false; 335 break; 336 } 337 338 EHStreamer *ES = nullptr; 339 switch (MAI->getExceptionHandlingType()) { 340 case ExceptionHandling::None: 341 break; 342 case ExceptionHandling::SjLj: 343 case ExceptionHandling::DwarfCFI: 344 ES = new DwarfCFIException(this); 345 break; 346 case ExceptionHandling::ARM: 347 ES = new ARMException(this); 348 break; 349 case ExceptionHandling::WinEH: 350 switch (MAI->getWinEHEncodingType()) { 351 default: llvm_unreachable("unsupported unwinding information encoding"); 352 case WinEH::EncodingType::Invalid: 353 break; 354 case WinEH::EncodingType::X86: 355 case WinEH::EncodingType::Itanium: 356 ES = new WinException(this); 357 break; 358 } 359 break; 360 } 361 if (ES) 362 Handlers.push_back(HandlerInfo(ES, EHTimerName, EHTimerDescription, 363 DWARFGroupName, DWARFGroupDescription)); 364 return false; 365 } 366 367 static bool canBeHidden(const GlobalValue *GV, const MCAsmInfo &MAI) { 368 if (!MAI.hasWeakDefCanBeHiddenDirective()) 369 return false; 370 371 return canBeOmittedFromSymbolTable(GV); 372 } 373 374 void AsmPrinter::EmitLinkage(const GlobalValue *GV, MCSymbol *GVSym) const { 375 GlobalValue::LinkageTypes Linkage = GV->getLinkage(); 376 switch (Linkage) { 377 case GlobalValue::CommonLinkage: 378 case GlobalValue::LinkOnceAnyLinkage: 379 case GlobalValue::LinkOnceODRLinkage: 380 case GlobalValue::WeakAnyLinkage: 381 case GlobalValue::WeakODRLinkage: 382 if (MAI->hasWeakDefDirective()) { 383 // .globl _foo 384 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 385 386 if (!canBeHidden(GV, *MAI)) 387 // .weak_definition _foo 388 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefinition); 389 else 390 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_WeakDefAutoPrivate); 391 } else if (MAI->hasLinkOnceDirective()) { 392 // .globl _foo 393 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 394 //NOTE: linkonce is handled by the section the symbol was assigned to. 395 } else { 396 // .weak _foo 397 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Weak); 398 } 399 return; 400 case GlobalValue::ExternalLinkage: 401 // If external, declare as a global symbol: .globl _foo 402 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Global); 403 return; 404 case GlobalValue::PrivateLinkage: 405 case GlobalValue::InternalLinkage: 406 return; 407 case GlobalValue::AppendingLinkage: 408 case GlobalValue::AvailableExternallyLinkage: 409 case GlobalValue::ExternalWeakLinkage: 410 llvm_unreachable("Should never emit this"); 411 } 412 llvm_unreachable("Unknown linkage type!"); 413 } 414 415 void AsmPrinter::getNameWithPrefix(SmallVectorImpl<char> &Name, 416 const GlobalValue *GV) const { 417 TM.getNameWithPrefix(Name, GV, getObjFileLowering().getMangler()); 418 } 419 420 MCSymbol *AsmPrinter::getSymbol(const GlobalValue *GV) const { 421 return TM.getSymbol(GV); 422 } 423 424 /// EmitGlobalVariable - Emit the specified global variable to the .s file. 425 void AsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) { 426 bool IsEmuTLSVar = TM.Options.EmulatedTLS && GV->isThreadLocal(); 427 assert(!(IsEmuTLSVar && GV->hasCommonLinkage()) && 428 "No emulated TLS variables in the common section"); 429 430 // Never emit TLS variable xyz in emulated TLS model. 431 // The initialization value is in __emutls_t.xyz instead of xyz. 432 if (IsEmuTLSVar) 433 return; 434 435 if (GV->hasInitializer()) { 436 // Check to see if this is a special global used by LLVM, if so, emit it. 437 if (EmitSpecialLLVMGlobal(GV)) 438 return; 439 440 // Skip the emission of global equivalents. The symbol can be emitted later 441 // on by emitGlobalGOTEquivs in case it turns out to be needed. 442 if (GlobalGOTEquivs.count(getSymbol(GV))) 443 return; 444 445 if (isVerbose()) { 446 // When printing the control variable __emutls_v.*, 447 // we don't need to print the original TLS variable name. 448 GV->printAsOperand(OutStreamer->GetCommentOS(), 449 /*PrintType=*/false, GV->getParent()); 450 OutStreamer->GetCommentOS() << '\n'; 451 } 452 } 453 454 MCSymbol *GVSym = getSymbol(GV); 455 MCSymbol *EmittedSym = GVSym; 456 457 // getOrCreateEmuTLSControlSym only creates the symbol with name and default 458 // attributes. 459 // GV's or GVSym's attributes will be used for the EmittedSym. 460 EmitVisibility(EmittedSym, GV->getVisibility(), !GV->isDeclaration()); 461 462 if (!GV->hasInitializer()) // External globals require no extra code. 463 return; 464 465 GVSym->redefineIfPossible(); 466 if (GVSym->isDefined() || GVSym->isVariable()) 467 report_fatal_error("symbol '" + Twine(GVSym->getName()) + 468 "' is already defined"); 469 470 if (MAI->hasDotTypeDotSizeDirective()) 471 OutStreamer->EmitSymbolAttribute(EmittedSym, MCSA_ELF_TypeObject); 472 473 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM); 474 475 const DataLayout &DL = GV->getParent()->getDataLayout(); 476 uint64_t Size = DL.getTypeAllocSize(GV->getType()->getElementType()); 477 478 // If the alignment is specified, we *must* obey it. Overaligning a global 479 // with a specified alignment is a prompt way to break globals emitted to 480 // sections and expected to be contiguous (e.g. ObjC metadata). 481 unsigned AlignLog = getGVAlignmentLog2(GV, DL); 482 483 for (const HandlerInfo &HI : Handlers) { 484 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 485 HI.TimerGroupName, HI.TimerGroupDescription, 486 TimePassesIsEnabled); 487 HI.Handler->setSymbolSize(GVSym, Size); 488 } 489 490 // Handle common symbols 491 if (GVKind.isCommon()) { 492 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it. 493 unsigned Align = 1 << AlignLog; 494 if (!getObjFileLowering().getCommDirectiveSupportsAlignment()) 495 Align = 0; 496 497 // .comm _foo, 42, 4 498 OutStreamer->EmitCommonSymbol(GVSym, Size, Align); 499 return; 500 } 501 502 // Determine to which section this global should be emitted. 503 MCSection *TheSection = getObjFileLowering().SectionForGlobal(GV, GVKind, TM); 504 505 // If we have a bss global going to a section that supports the 506 // zerofill directive, do so here. 507 if (GVKind.isBSS() && MAI->hasMachoZeroFillDirective() && 508 TheSection->isVirtualSection()) { 509 if (Size == 0) 510 Size = 1; // zerofill of 0 bytes is undefined. 511 unsigned Align = 1 << AlignLog; 512 EmitLinkage(GV, GVSym); 513 // .zerofill __DATA, __bss, _foo, 400, 5 514 OutStreamer->EmitZerofill(TheSection, GVSym, Size, Align); 515 return; 516 } 517 518 // If this is a BSS local symbol and we are emitting in the BSS 519 // section use .lcomm/.comm directive. 520 if (GVKind.isBSSLocal() && 521 getObjFileLowering().getBSSSection() == TheSection) { 522 if (Size == 0) 523 Size = 1; // .comm Foo, 0 is undefined, avoid it. 524 unsigned Align = 1 << AlignLog; 525 526 // Use .lcomm only if it supports user-specified alignment. 527 // Otherwise, while it would still be correct to use .lcomm in some 528 // cases (e.g. when Align == 1), the external assembler might enfore 529 // some -unknown- default alignment behavior, which could cause 530 // spurious differences between external and integrated assembler. 531 // Prefer to simply fall back to .local / .comm in this case. 532 if (MAI->getLCOMMDirectiveAlignmentType() != LCOMM::NoAlignment) { 533 // .lcomm _foo, 42 534 OutStreamer->EmitLocalCommonSymbol(GVSym, Size, Align); 535 return; 536 } 537 538 if (!getObjFileLowering().getCommDirectiveSupportsAlignment()) 539 Align = 0; 540 541 // .local _foo 542 OutStreamer->EmitSymbolAttribute(GVSym, MCSA_Local); 543 // .comm _foo, 42, 4 544 OutStreamer->EmitCommonSymbol(GVSym, Size, Align); 545 return; 546 } 547 548 // Handle thread local data for mach-o which requires us to output an 549 // additional structure of data and mangle the original symbol so that we 550 // can reference it later. 551 // 552 // TODO: This should become an "emit thread local global" method on TLOF. 553 // All of this macho specific stuff should be sunk down into TLOFMachO and 554 // stuff like "TLSExtraDataSection" should no longer be part of the parent 555 // TLOF class. This will also make it more obvious that stuff like 556 // MCStreamer::EmitTBSSSymbol is macho specific and only called from macho 557 // specific code. 558 if (GVKind.isThreadLocal() && MAI->hasMachoTBSSDirective()) { 559 // Emit the .tbss symbol 560 MCSymbol *MangSym = 561 OutContext.getOrCreateSymbol(GVSym->getName() + Twine("$tlv$init")); 562 563 if (GVKind.isThreadBSS()) { 564 TheSection = getObjFileLowering().getTLSBSSSection(); 565 OutStreamer->EmitTBSSSymbol(TheSection, MangSym, Size, 1 << AlignLog); 566 } else if (GVKind.isThreadData()) { 567 OutStreamer->SwitchSection(TheSection); 568 569 EmitAlignment(AlignLog, GV); 570 OutStreamer->EmitLabel(MangSym); 571 572 EmitGlobalConstant(GV->getParent()->getDataLayout(), 573 GV->getInitializer()); 574 } 575 576 OutStreamer->AddBlankLine(); 577 578 // Emit the variable struct for the runtime. 579 MCSection *TLVSect = getObjFileLowering().getTLSExtraDataSection(); 580 581 OutStreamer->SwitchSection(TLVSect); 582 // Emit the linkage here. 583 EmitLinkage(GV, GVSym); 584 OutStreamer->EmitLabel(GVSym); 585 586 // Three pointers in size: 587 // - __tlv_bootstrap - used to make sure support exists 588 // - spare pointer, used when mapped by the runtime 589 // - pointer to mangled symbol above with initializer 590 unsigned PtrSize = DL.getPointerTypeSize(GV->getType()); 591 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("_tlv_bootstrap"), 592 PtrSize); 593 OutStreamer->EmitIntValue(0, PtrSize); 594 OutStreamer->EmitSymbolValue(MangSym, PtrSize); 595 596 OutStreamer->AddBlankLine(); 597 return; 598 } 599 600 MCSymbol *EmittedInitSym = GVSym; 601 602 OutStreamer->SwitchSection(TheSection); 603 604 EmitLinkage(GV, EmittedInitSym); 605 EmitAlignment(AlignLog, GV); 606 607 OutStreamer->EmitLabel(EmittedInitSym); 608 609 EmitGlobalConstant(GV->getParent()->getDataLayout(), GV->getInitializer()); 610 611 if (MAI->hasDotTypeDotSizeDirective()) 612 // .size foo, 42 613 OutStreamer->emitELFSize(EmittedInitSym, 614 MCConstantExpr::create(Size, OutContext)); 615 616 OutStreamer->AddBlankLine(); 617 } 618 619 /// Emit the directive and value for debug thread local expression 620 /// 621 /// \p Value - The value to emit. 622 /// \p Size - The size of the integer (in bytes) to emit. 623 void AsmPrinter::EmitDebugThreadLocal(const MCExpr *Value, 624 unsigned Size) const { 625 OutStreamer->EmitValue(Value, Size); 626 } 627 628 /// EmitFunctionHeader - This method emits the header for the current 629 /// function. 630 void AsmPrinter::EmitFunctionHeader() { 631 const Function *F = MF->getFunction(); 632 633 if (isVerbose()) 634 OutStreamer->GetCommentOS() << "-- Begin function " << F->getName() << '\n'; 635 636 // Print out constants referenced by the function 637 EmitConstantPool(); 638 639 // Print the 'header' of function. 640 OutStreamer->SwitchSection(getObjFileLowering().SectionForGlobal(F, TM)); 641 EmitVisibility(CurrentFnSym, F->getVisibility()); 642 643 EmitLinkage(F, CurrentFnSym); 644 if (MAI->hasFunctionAlignment()) 645 EmitAlignment(MF->getAlignment(), F); 646 647 if (MAI->hasDotTypeDotSizeDirective()) 648 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_ELF_TypeFunction); 649 650 if (isVerbose()) { 651 F->printAsOperand(OutStreamer->GetCommentOS(), 652 /*PrintType=*/false, F->getParent()); 653 OutStreamer->GetCommentOS() << '\n'; 654 } 655 656 // Emit the prefix data. 657 if (F->hasPrefixData()) { 658 if (MAI->hasSubsectionsViaSymbols()) { 659 // Preserving prefix data on platforms which use subsections-via-symbols 660 // is a bit tricky. Here we introduce a symbol for the prefix data 661 // and use the .alt_entry attribute to mark the function's real entry point 662 // as an alternative entry point to the prefix-data symbol. 663 MCSymbol *PrefixSym = OutContext.createLinkerPrivateTempSymbol(); 664 OutStreamer->EmitLabel(PrefixSym); 665 666 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrefixData()); 667 668 // Emit an .alt_entry directive for the actual function symbol. 669 OutStreamer->EmitSymbolAttribute(CurrentFnSym, MCSA_AltEntry); 670 } else { 671 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrefixData()); 672 } 673 } 674 675 // Emit the CurrentFnSym. This is a virtual function to allow targets to 676 // do their wild and crazy things as required. 677 EmitFunctionEntryLabel(); 678 679 // If the function had address-taken blocks that got deleted, then we have 680 // references to the dangling symbols. Emit them at the start of the function 681 // so that we don't get references to undefined symbols. 682 std::vector<MCSymbol*> DeadBlockSyms; 683 MMI->takeDeletedSymbolsForFunction(F, DeadBlockSyms); 684 for (unsigned i = 0, e = DeadBlockSyms.size(); i != e; ++i) { 685 OutStreamer->AddComment("Address taken block that was later removed"); 686 OutStreamer->EmitLabel(DeadBlockSyms[i]); 687 } 688 689 if (CurrentFnBegin) { 690 if (MAI->useAssignmentForEHBegin()) { 691 MCSymbol *CurPos = OutContext.createTempSymbol(); 692 OutStreamer->EmitLabel(CurPos); 693 OutStreamer->EmitAssignment(CurrentFnBegin, 694 MCSymbolRefExpr::create(CurPos, OutContext)); 695 } else { 696 OutStreamer->EmitLabel(CurrentFnBegin); 697 } 698 } 699 700 // Emit pre-function debug and/or EH information. 701 for (const HandlerInfo &HI : Handlers) { 702 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 703 HI.TimerGroupDescription, TimePassesIsEnabled); 704 HI.Handler->beginFunction(MF); 705 } 706 707 // Emit the prologue data. 708 if (F->hasPrologueData()) 709 EmitGlobalConstant(F->getParent()->getDataLayout(), F->getPrologueData()); 710 } 711 712 /// EmitFunctionEntryLabel - Emit the label that is the entrypoint for the 713 /// function. This can be overridden by targets as required to do custom stuff. 714 void AsmPrinter::EmitFunctionEntryLabel() { 715 CurrentFnSym->redefineIfPossible(); 716 717 // The function label could have already been emitted if two symbols end up 718 // conflicting due to asm renaming. Detect this and emit an error. 719 if (CurrentFnSym->isVariable()) 720 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 721 "' is a protected alias"); 722 if (CurrentFnSym->isDefined()) 723 report_fatal_error("'" + Twine(CurrentFnSym->getName()) + 724 "' label emitted multiple times to assembly file"); 725 726 return OutStreamer->EmitLabel(CurrentFnSym); 727 } 728 729 /// emitComments - Pretty-print comments for instructions. 730 static void emitComments(const MachineInstr &MI, raw_ostream &CommentOS, 731 AsmPrinter *AP) { 732 const MachineFunction *MF = MI.getParent()->getParent(); 733 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 734 735 // Check for spills and reloads 736 int FI; 737 738 const MachineFrameInfo &MFI = MF->getFrameInfo(); 739 bool Commented = false; 740 741 // We assume a single instruction only has a spill or reload, not 742 // both. 743 const MachineMemOperand *MMO; 744 if (TII->isLoadFromStackSlotPostFE(MI, FI)) { 745 if (MFI.isSpillSlotObjectIndex(FI)) { 746 MMO = *MI.memoperands_begin(); 747 CommentOS << MMO->getSize() << "-byte Reload"; 748 Commented = true; 749 } 750 } else if (TII->hasLoadFromStackSlot(MI, MMO, FI)) { 751 if (MFI.isSpillSlotObjectIndex(FI)) { 752 CommentOS << MMO->getSize() << "-byte Folded Reload"; 753 Commented = true; 754 } 755 } else if (TII->isStoreToStackSlotPostFE(MI, FI)) { 756 if (MFI.isSpillSlotObjectIndex(FI)) { 757 MMO = *MI.memoperands_begin(); 758 CommentOS << MMO->getSize() << "-byte Spill"; 759 Commented = true; 760 } 761 } else if (TII->hasStoreToStackSlot(MI, MMO, FI)) { 762 if (MFI.isSpillSlotObjectIndex(FI)) { 763 CommentOS << MMO->getSize() << "-byte Folded Spill"; 764 Commented = true; 765 } 766 } 767 768 // Check for spill-induced copies 769 if (MI.getAsmPrinterFlag(MachineInstr::ReloadReuse)) { 770 Commented = true; 771 CommentOS << " Reload Reuse"; 772 } 773 774 if (Commented && AP->EnablePrintSchedInfo) 775 // If any comment was added above and we need sched info comment then 776 // add this new comment just after the above comment w/o "\n" between them. 777 CommentOS << " " << MF->getSubtarget().getSchedInfoStr(MI) << "\n"; 778 else if (Commented) 779 CommentOS << "\n"; 780 } 781 782 /// emitImplicitDef - This method emits the specified machine instruction 783 /// that is an implicit def. 784 void AsmPrinter::emitImplicitDef(const MachineInstr *MI) const { 785 unsigned RegNo = MI->getOperand(0).getReg(); 786 787 SmallString<128> Str; 788 raw_svector_ostream OS(Str); 789 OS << "implicit-def: " 790 << PrintReg(RegNo, MF->getSubtarget().getRegisterInfo()); 791 792 OutStreamer->AddComment(OS.str()); 793 OutStreamer->AddBlankLine(); 794 } 795 796 static void emitKill(const MachineInstr *MI, AsmPrinter &AP) { 797 std::string Str; 798 raw_string_ostream OS(Str); 799 OS << "kill:"; 800 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 801 const MachineOperand &Op = MI->getOperand(i); 802 assert(Op.isReg() && "KILL instruction must have only register operands"); 803 OS << ' ' 804 << PrintReg(Op.getReg(), 805 AP.MF->getSubtarget().getRegisterInfo()) 806 << (Op.isDef() ? "<def>" : "<kill>"); 807 } 808 AP.OutStreamer->AddComment(OS.str()); 809 AP.OutStreamer->AddBlankLine(); 810 } 811 812 /// emitDebugValueComment - This method handles the target-independent form 813 /// of DBG_VALUE, returning true if it was able to do so. A false return 814 /// means the target will need to handle MI in EmitInstruction. 815 static bool emitDebugValueComment(const MachineInstr *MI, AsmPrinter &AP) { 816 // This code handles only the 4-operand target-independent form. 817 if (MI->getNumOperands() != 4) 818 return false; 819 820 SmallString<128> Str; 821 raw_svector_ostream OS(Str); 822 OS << "DEBUG_VALUE: "; 823 824 const DILocalVariable *V = MI->getDebugVariable(); 825 if (auto *SP = dyn_cast<DISubprogram>(V->getScope())) { 826 StringRef Name = SP->getName(); 827 if (!Name.empty()) 828 OS << Name << ":"; 829 } 830 OS << V->getName(); 831 OS << " <- "; 832 833 // The second operand is only an offset if it's an immediate. 834 bool MemLoc = MI->getOperand(0).isReg() && MI->getOperand(1).isImm(); 835 int64_t Offset = MemLoc ? MI->getOperand(1).getImm() : 0; 836 const DIExpression *Expr = MI->getDebugExpression(); 837 if (Expr->getNumElements()) { 838 OS << '['; 839 bool NeedSep = false; 840 for (auto Op : Expr->expr_ops()) { 841 if (NeedSep) 842 OS << ", "; 843 else 844 NeedSep = true; 845 OS << dwarf::OperationEncodingString(Op.getOp()); 846 for (unsigned I = 0; I < Op.getNumArgs(); ++I) 847 OS << ' ' << Op.getArg(I); 848 } 849 OS << "] "; 850 } 851 852 // Register or immediate value. Register 0 means undef. 853 if (MI->getOperand(0).isFPImm()) { 854 APFloat APF = APFloat(MI->getOperand(0).getFPImm()->getValueAPF()); 855 if (MI->getOperand(0).getFPImm()->getType()->isFloatTy()) { 856 OS << (double)APF.convertToFloat(); 857 } else if (MI->getOperand(0).getFPImm()->getType()->isDoubleTy()) { 858 OS << APF.convertToDouble(); 859 } else { 860 // There is no good way to print long double. Convert a copy to 861 // double. Ah well, it's only a comment. 862 bool ignored; 863 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, 864 &ignored); 865 OS << "(long double) " << APF.convertToDouble(); 866 } 867 } else if (MI->getOperand(0).isImm()) { 868 OS << MI->getOperand(0).getImm(); 869 } else if (MI->getOperand(0).isCImm()) { 870 MI->getOperand(0).getCImm()->getValue().print(OS, false /*isSigned*/); 871 } else { 872 unsigned Reg; 873 if (MI->getOperand(0).isReg()) { 874 Reg = MI->getOperand(0).getReg(); 875 } else { 876 assert(MI->getOperand(0).isFI() && "Unknown operand type"); 877 const TargetFrameLowering *TFI = AP.MF->getSubtarget().getFrameLowering(); 878 Offset += TFI->getFrameIndexReference(*AP.MF, 879 MI->getOperand(0).getIndex(), Reg); 880 MemLoc = true; 881 } 882 if (Reg == 0) { 883 // Suppress offset, it is not meaningful here. 884 OS << "undef"; 885 // NOTE: Want this comment at start of line, don't emit with AddComment. 886 AP.OutStreamer->emitRawComment(OS.str()); 887 return true; 888 } 889 if (MemLoc) 890 OS << '['; 891 OS << PrintReg(Reg, AP.MF->getSubtarget().getRegisterInfo()); 892 } 893 894 if (MemLoc) 895 OS << '+' << Offset << ']'; 896 897 // NOTE: Want this comment at start of line, don't emit with AddComment. 898 AP.OutStreamer->emitRawComment(OS.str()); 899 return true; 900 } 901 902 AsmPrinter::CFIMoveType AsmPrinter::needsCFIMoves() { 903 if (MAI->getExceptionHandlingType() == ExceptionHandling::DwarfCFI && 904 MF->getFunction()->needsUnwindTableEntry()) 905 return CFI_M_EH; 906 907 if (MMI->hasDebugInfo()) 908 return CFI_M_Debug; 909 910 return CFI_M_None; 911 } 912 913 bool AsmPrinter::needsSEHMoves() { 914 return MAI->usesWindowsCFI() && MF->getFunction()->needsUnwindTableEntry(); 915 } 916 917 void AsmPrinter::emitCFIInstruction(const MachineInstr &MI) { 918 ExceptionHandling ExceptionHandlingType = MAI->getExceptionHandlingType(); 919 if (ExceptionHandlingType != ExceptionHandling::DwarfCFI && 920 ExceptionHandlingType != ExceptionHandling::ARM) 921 return; 922 923 if (needsCFIMoves() == CFI_M_None) 924 return; 925 926 // If there is no "real" instruction following this CFI instruction, skip 927 // emitting it; it would be beyond the end of the function's FDE range. 928 auto *MBB = MI.getParent(); 929 auto I = std::next(MI.getIterator()); 930 while (I != MBB->end() && I->isTransient()) 931 ++I; 932 if (I == MBB->instr_end() && 933 MBB->getReverseIterator() == MBB->getParent()->rbegin()) 934 return; 935 936 const std::vector<MCCFIInstruction> &Instrs = MF->getFrameInstructions(); 937 unsigned CFIIndex = MI.getOperand(0).getCFIIndex(); 938 const MCCFIInstruction &CFI = Instrs[CFIIndex]; 939 emitCFIInstruction(CFI); 940 } 941 942 void AsmPrinter::emitFrameAlloc(const MachineInstr &MI) { 943 // The operands are the MCSymbol and the frame offset of the allocation. 944 MCSymbol *FrameAllocSym = MI.getOperand(0).getMCSymbol(); 945 int FrameOffset = MI.getOperand(1).getImm(); 946 947 // Emit a symbol assignment. 948 OutStreamer->EmitAssignment(FrameAllocSym, 949 MCConstantExpr::create(FrameOffset, OutContext)); 950 } 951 952 /// EmitFunctionBody - This method emits the body and trailer for a 953 /// function. 954 void AsmPrinter::EmitFunctionBody() { 955 EmitFunctionHeader(); 956 957 // Emit target-specific gunk before the function body. 958 EmitFunctionBodyStart(); 959 960 bool ShouldPrintDebugScopes = MMI->hasDebugInfo(); 961 962 // Print out code for the function. 963 bool HasAnyRealCode = false; 964 int NumInstsInFunction = 0; 965 for (auto &MBB : *MF) { 966 // Print a label for the basic block. 967 EmitBasicBlockStart(MBB); 968 for (auto &MI : MBB) { 969 970 // Print the assembly for the instruction. 971 if (!MI.isPosition() && !MI.isImplicitDef() && !MI.isKill() && 972 !MI.isDebugValue()) { 973 HasAnyRealCode = true; 974 ++NumInstsInFunction; 975 } 976 977 if (ShouldPrintDebugScopes) { 978 for (const HandlerInfo &HI : Handlers) { 979 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 980 HI.TimerGroupName, HI.TimerGroupDescription, 981 TimePassesIsEnabled); 982 HI.Handler->beginInstruction(&MI); 983 } 984 } 985 986 if (isVerbose()) 987 emitComments(MI, OutStreamer->GetCommentOS(), this); 988 989 switch (MI.getOpcode()) { 990 case TargetOpcode::CFI_INSTRUCTION: 991 emitCFIInstruction(MI); 992 break; 993 994 case TargetOpcode::LOCAL_ESCAPE: 995 emitFrameAlloc(MI); 996 break; 997 998 case TargetOpcode::EH_LABEL: 999 case TargetOpcode::GC_LABEL: 1000 OutStreamer->EmitLabel(MI.getOperand(0).getMCSymbol()); 1001 break; 1002 case TargetOpcode::INLINEASM: 1003 EmitInlineAsm(&MI); 1004 break; 1005 case TargetOpcode::DBG_VALUE: 1006 if (isVerbose()) { 1007 if (!emitDebugValueComment(&MI, *this)) 1008 EmitInstruction(&MI); 1009 } 1010 break; 1011 case TargetOpcode::IMPLICIT_DEF: 1012 if (isVerbose()) emitImplicitDef(&MI); 1013 break; 1014 case TargetOpcode::KILL: 1015 if (isVerbose()) emitKill(&MI, *this); 1016 break; 1017 default: 1018 EmitInstruction(&MI); 1019 break; 1020 } 1021 1022 if (ShouldPrintDebugScopes) { 1023 for (const HandlerInfo &HI : Handlers) { 1024 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, 1025 HI.TimerGroupName, HI.TimerGroupDescription, 1026 TimePassesIsEnabled); 1027 HI.Handler->endInstruction(); 1028 } 1029 } 1030 } 1031 1032 EmitBasicBlockEnd(MBB); 1033 } 1034 1035 EmittedInsts += NumInstsInFunction; 1036 MachineOptimizationRemarkAnalysis R(DEBUG_TYPE, "InstructionCount", 1037 MF->getFunction()->getSubprogram(), 1038 &MF->front()); 1039 R << ore::NV("NumInstructions", NumInstsInFunction) 1040 << " instructions in function"; 1041 ORE->emit(R); 1042 1043 // If the function is empty and the object file uses .subsections_via_symbols, 1044 // then we need to emit *something* to the function body to prevent the 1045 // labels from collapsing together. Just emit a noop. 1046 // Similarly, don't emit empty functions on Windows either. It can lead to 1047 // duplicate entries (two functions with the same RVA) in the Guard CF Table 1048 // after linking, causing the kernel not to load the binary: 1049 // https://developercommunity.visualstudio.com/content/problem/45366/vc-linker-creates-invalid-dll-with-clang-cl.html 1050 // FIXME: Hide this behind some API in e.g. MCAsmInfo or MCTargetStreamer. 1051 const Triple &TT = TM.getTargetTriple(); 1052 if (!HasAnyRealCode && (MAI->hasSubsectionsViaSymbols() || 1053 (TT.isOSWindows() && TT.isOSBinFormatCOFF()))) { 1054 MCInst Noop; 1055 MF->getSubtarget().getInstrInfo()->getNoop(Noop); 1056 1057 // Targets can opt-out of emitting the noop here by leaving the opcode 1058 // unspecified. 1059 if (Noop.getOpcode()) { 1060 OutStreamer->AddComment("avoids zero-length function"); 1061 OutStreamer->EmitInstruction(Noop, getSubtargetInfo()); 1062 } 1063 } 1064 1065 const Function *F = MF->getFunction(); 1066 for (const auto &BB : *F) { 1067 if (!BB.hasAddressTaken()) 1068 continue; 1069 MCSymbol *Sym = GetBlockAddressSymbol(&BB); 1070 if (Sym->isDefined()) 1071 continue; 1072 OutStreamer->AddComment("Address of block that was removed by CodeGen"); 1073 OutStreamer->EmitLabel(Sym); 1074 } 1075 1076 // Emit target-specific gunk after the function body. 1077 EmitFunctionBodyEnd(); 1078 1079 if (!MF->getLandingPads().empty() || MMI->hasDebugInfo() || 1080 MF->hasEHFunclets() || MAI->hasDotTypeDotSizeDirective()) { 1081 // Create a symbol for the end of function. 1082 CurrentFnEnd = createTempSymbol("func_end"); 1083 OutStreamer->EmitLabel(CurrentFnEnd); 1084 } 1085 1086 // If the target wants a .size directive for the size of the function, emit 1087 // it. 1088 if (MAI->hasDotTypeDotSizeDirective()) { 1089 // We can get the size as difference between the function label and the 1090 // temp label. 1091 const MCExpr *SizeExp = MCBinaryExpr::createSub( 1092 MCSymbolRefExpr::create(CurrentFnEnd, OutContext), 1093 MCSymbolRefExpr::create(CurrentFnSymForSize, OutContext), OutContext); 1094 OutStreamer->emitELFSize(CurrentFnSym, SizeExp); 1095 } 1096 1097 for (const HandlerInfo &HI : Handlers) { 1098 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1099 HI.TimerGroupDescription, TimePassesIsEnabled); 1100 HI.Handler->markFunctionEnd(); 1101 } 1102 1103 // Print out jump tables referenced by the function. 1104 EmitJumpTableInfo(); 1105 1106 // Emit post-function debug and/or EH information. 1107 for (const HandlerInfo &HI : Handlers) { 1108 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1109 HI.TimerGroupDescription, TimePassesIsEnabled); 1110 HI.Handler->endFunction(MF); 1111 } 1112 1113 if (isVerbose()) 1114 OutStreamer->GetCommentOS() << "-- End function\n"; 1115 1116 OutStreamer->AddBlankLine(); 1117 } 1118 1119 /// \brief Compute the number of Global Variables that uses a Constant. 1120 static unsigned getNumGlobalVariableUses(const Constant *C) { 1121 if (!C) 1122 return 0; 1123 1124 if (isa<GlobalVariable>(C)) 1125 return 1; 1126 1127 unsigned NumUses = 0; 1128 for (auto *CU : C->users()) 1129 NumUses += getNumGlobalVariableUses(dyn_cast<Constant>(CU)); 1130 1131 return NumUses; 1132 } 1133 1134 /// \brief Only consider global GOT equivalents if at least one user is a 1135 /// cstexpr inside an initializer of another global variables. Also, don't 1136 /// handle cstexpr inside instructions. During global variable emission, 1137 /// candidates are skipped and are emitted later in case at least one cstexpr 1138 /// isn't replaced by a PC relative GOT entry access. 1139 static bool isGOTEquivalentCandidate(const GlobalVariable *GV, 1140 unsigned &NumGOTEquivUsers) { 1141 // Global GOT equivalents are unnamed private globals with a constant 1142 // pointer initializer to another global symbol. They must point to a 1143 // GlobalVariable or Function, i.e., as GlobalValue. 1144 if (!GV->hasGlobalUnnamedAddr() || !GV->hasInitializer() || 1145 !GV->isConstant() || !GV->isDiscardableIfUnused() || 1146 !dyn_cast<GlobalValue>(GV->getOperand(0))) 1147 return false; 1148 1149 // To be a got equivalent, at least one of its users need to be a constant 1150 // expression used by another global variable. 1151 for (auto *U : GV->users()) 1152 NumGOTEquivUsers += getNumGlobalVariableUses(dyn_cast<Constant>(U)); 1153 1154 return NumGOTEquivUsers > 0; 1155 } 1156 1157 /// \brief Unnamed constant global variables solely contaning a pointer to 1158 /// another globals variable is equivalent to a GOT table entry; it contains the 1159 /// the address of another symbol. Optimize it and replace accesses to these 1160 /// "GOT equivalents" by using the GOT entry for the final global instead. 1161 /// Compute GOT equivalent candidates among all global variables to avoid 1162 /// emitting them if possible later on, after it use is replaced by a GOT entry 1163 /// access. 1164 void AsmPrinter::computeGlobalGOTEquivs(Module &M) { 1165 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1166 return; 1167 1168 for (const auto &G : M.globals()) { 1169 unsigned NumGOTEquivUsers = 0; 1170 if (!isGOTEquivalentCandidate(&G, NumGOTEquivUsers)) 1171 continue; 1172 1173 const MCSymbol *GOTEquivSym = getSymbol(&G); 1174 GlobalGOTEquivs[GOTEquivSym] = std::make_pair(&G, NumGOTEquivUsers); 1175 } 1176 } 1177 1178 /// \brief Constant expressions using GOT equivalent globals may not be eligible 1179 /// for PC relative GOT entry conversion, in such cases we need to emit such 1180 /// globals we previously omitted in EmitGlobalVariable. 1181 void AsmPrinter::emitGlobalGOTEquivs() { 1182 if (!getObjFileLowering().supportIndirectSymViaGOTPCRel()) 1183 return; 1184 1185 SmallVector<const GlobalVariable *, 8> FailedCandidates; 1186 for (auto &I : GlobalGOTEquivs) { 1187 const GlobalVariable *GV = I.second.first; 1188 unsigned Cnt = I.second.second; 1189 if (Cnt) 1190 FailedCandidates.push_back(GV); 1191 } 1192 GlobalGOTEquivs.clear(); 1193 1194 for (auto *GV : FailedCandidates) 1195 EmitGlobalVariable(GV); 1196 } 1197 1198 void AsmPrinter::emitGlobalIndirectSymbol(Module &M, 1199 const GlobalIndirectSymbol& GIS) { 1200 MCSymbol *Name = getSymbol(&GIS); 1201 1202 if (GIS.hasExternalLinkage() || !MAI->getWeakRefDirective()) 1203 OutStreamer->EmitSymbolAttribute(Name, MCSA_Global); 1204 else if (GIS.hasWeakLinkage() || GIS.hasLinkOnceLinkage()) 1205 OutStreamer->EmitSymbolAttribute(Name, MCSA_WeakReference); 1206 else 1207 assert(GIS.hasLocalLinkage() && "Invalid alias or ifunc linkage"); 1208 1209 // Set the symbol type to function if the alias has a function type. 1210 // This affects codegen when the aliasee is not a function. 1211 if (GIS.getType()->getPointerElementType()->isFunctionTy()) { 1212 OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeFunction); 1213 if (isa<GlobalIFunc>(GIS)) 1214 OutStreamer->EmitSymbolAttribute(Name, MCSA_ELF_TypeIndFunction); 1215 } 1216 1217 EmitVisibility(Name, GIS.getVisibility()); 1218 1219 const MCExpr *Expr = lowerConstant(GIS.getIndirectSymbol()); 1220 1221 if (isa<GlobalAlias>(&GIS) && MAI->hasAltEntry() && isa<MCBinaryExpr>(Expr)) 1222 OutStreamer->EmitSymbolAttribute(Name, MCSA_AltEntry); 1223 1224 // Emit the directives as assignments aka .set: 1225 OutStreamer->EmitAssignment(Name, Expr); 1226 1227 if (auto *GA = dyn_cast<GlobalAlias>(&GIS)) { 1228 // If the aliasee does not correspond to a symbol in the output, i.e. the 1229 // alias is not of an object or the aliased object is private, then set the 1230 // size of the alias symbol from the type of the alias. We don't do this in 1231 // other situations as the alias and aliasee having differing types but same 1232 // size may be intentional. 1233 const GlobalObject *BaseObject = GA->getBaseObject(); 1234 if (MAI->hasDotTypeDotSizeDirective() && GA->getValueType()->isSized() && 1235 (!BaseObject || BaseObject->hasPrivateLinkage())) { 1236 const DataLayout &DL = M.getDataLayout(); 1237 uint64_t Size = DL.getTypeAllocSize(GA->getValueType()); 1238 OutStreamer->emitELFSize(Name, MCConstantExpr::create(Size, OutContext)); 1239 } 1240 } 1241 } 1242 1243 bool AsmPrinter::doFinalization(Module &M) { 1244 // Set the MachineFunction to nullptr so that we can catch attempted 1245 // accesses to MF specific features at the module level and so that 1246 // we can conditionalize accesses based on whether or not it is nullptr. 1247 MF = nullptr; 1248 1249 // Gather all GOT equivalent globals in the module. We really need two 1250 // passes over the globals: one to compute and another to avoid its emission 1251 // in EmitGlobalVariable, otherwise we would not be able to handle cases 1252 // where the got equivalent shows up before its use. 1253 computeGlobalGOTEquivs(M); 1254 1255 // Emit global variables. 1256 for (const auto &G : M.globals()) 1257 EmitGlobalVariable(&G); 1258 1259 // Emit remaining GOT equivalent globals. 1260 emitGlobalGOTEquivs(); 1261 1262 // Emit visibility info for declarations 1263 for (const Function &F : M) { 1264 if (!F.isDeclarationForLinker()) 1265 continue; 1266 GlobalValue::VisibilityTypes V = F.getVisibility(); 1267 if (V == GlobalValue::DefaultVisibility) 1268 continue; 1269 1270 MCSymbol *Name = getSymbol(&F); 1271 EmitVisibility(Name, V, false); 1272 } 1273 1274 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1275 1276 // Emit module flags. 1277 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 1278 M.getModuleFlagsMetadata(ModuleFlags); 1279 if (!ModuleFlags.empty()) 1280 TLOF.emitModuleFlags(*OutStreamer, ModuleFlags, TM); 1281 1282 if (TM.getTargetTriple().isOSBinFormatELF()) { 1283 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>(); 1284 1285 // Output stubs for external and common global variables. 1286 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList(); 1287 if (!Stubs.empty()) { 1288 OutStreamer->SwitchSection(TLOF.getDataSection()); 1289 const DataLayout &DL = M.getDataLayout(); 1290 1291 for (const auto &Stub : Stubs) { 1292 OutStreamer->EmitLabel(Stub.first); 1293 OutStreamer->EmitSymbolValue(Stub.second.getPointer(), 1294 DL.getPointerSize()); 1295 } 1296 } 1297 } 1298 1299 // Finalize debug and EH information. 1300 for (const HandlerInfo &HI : Handlers) { 1301 NamedRegionTimer T(HI.TimerName, HI.TimerDescription, HI.TimerGroupName, 1302 HI.TimerGroupDescription, TimePassesIsEnabled); 1303 HI.Handler->endModule(); 1304 delete HI.Handler; 1305 } 1306 Handlers.clear(); 1307 DD = nullptr; 1308 1309 // If the target wants to know about weak references, print them all. 1310 if (MAI->getWeakRefDirective()) { 1311 // FIXME: This is not lazy, it would be nice to only print weak references 1312 // to stuff that is actually used. Note that doing so would require targets 1313 // to notice uses in operands (due to constant exprs etc). This should 1314 // happen with the MC stuff eventually. 1315 1316 // Print out module-level global objects here. 1317 for (const auto &GO : M.global_objects()) { 1318 if (!GO.hasExternalWeakLinkage()) 1319 continue; 1320 OutStreamer->EmitSymbolAttribute(getSymbol(&GO), MCSA_WeakReference); 1321 } 1322 } 1323 1324 OutStreamer->AddBlankLine(); 1325 1326 // Print aliases in topological order, that is, for each alias a = b, 1327 // b must be printed before a. 1328 // This is because on some targets (e.g. PowerPC) linker expects aliases in 1329 // such an order to generate correct TOC information. 1330 SmallVector<const GlobalAlias *, 16> AliasStack; 1331 SmallPtrSet<const GlobalAlias *, 16> AliasVisited; 1332 for (const auto &Alias : M.aliases()) { 1333 for (const GlobalAlias *Cur = &Alias; Cur; 1334 Cur = dyn_cast<GlobalAlias>(Cur->getAliasee())) { 1335 if (!AliasVisited.insert(Cur).second) 1336 break; 1337 AliasStack.push_back(Cur); 1338 } 1339 for (const GlobalAlias *AncestorAlias : llvm::reverse(AliasStack)) 1340 emitGlobalIndirectSymbol(M, *AncestorAlias); 1341 AliasStack.clear(); 1342 } 1343 for (const auto &IFunc : M.ifuncs()) 1344 emitGlobalIndirectSymbol(M, IFunc); 1345 1346 GCModuleInfo *MI = getAnalysisIfAvailable<GCModuleInfo>(); 1347 assert(MI && "AsmPrinter didn't require GCModuleInfo?"); 1348 for (GCModuleInfo::iterator I = MI->end(), E = MI->begin(); I != E; ) 1349 if (GCMetadataPrinter *MP = GetOrCreateGCPrinter(**--I)) 1350 MP->finishAssembly(M, *MI, *this); 1351 1352 // Emit llvm.ident metadata in an '.ident' directive. 1353 EmitModuleIdents(M); 1354 1355 // Emit __morestack address if needed for indirect calls. 1356 if (MMI->usesMorestackAddr()) { 1357 unsigned Align = 1; 1358 MCSection *ReadOnlySection = getObjFileLowering().getSectionForConstant( 1359 getDataLayout(), SectionKind::getReadOnly(), 1360 /*C=*/nullptr, Align); 1361 OutStreamer->SwitchSection(ReadOnlySection); 1362 1363 MCSymbol *AddrSymbol = 1364 OutContext.getOrCreateSymbol(StringRef("__morestack_addr")); 1365 OutStreamer->EmitLabel(AddrSymbol); 1366 1367 unsigned PtrSize = MAI->getCodePointerSize(); 1368 OutStreamer->EmitSymbolValue(GetExternalSymbolSymbol("__morestack"), 1369 PtrSize); 1370 } 1371 1372 // If we don't have any trampolines, then we don't require stack memory 1373 // to be executable. Some targets have a directive to declare this. 1374 Function *InitTrampolineIntrinsic = M.getFunction("llvm.init.trampoline"); 1375 if (!InitTrampolineIntrinsic || InitTrampolineIntrinsic->use_empty()) 1376 if (MCSection *S = MAI->getNonexecutableStackSection(OutContext)) 1377 OutStreamer->SwitchSection(S); 1378 1379 // Allow the target to emit any magic that it wants at the end of the file, 1380 // after everything else has gone out. 1381 EmitEndOfAsmFile(M); 1382 1383 MMI = nullptr; 1384 1385 OutStreamer->Finish(); 1386 OutStreamer->reset(); 1387 1388 return false; 1389 } 1390 1391 MCSymbol *AsmPrinter::getCurExceptionSym() { 1392 if (!CurExceptionSym) 1393 CurExceptionSym = createTempSymbol("exception"); 1394 return CurExceptionSym; 1395 } 1396 1397 void AsmPrinter::SetupMachineFunction(MachineFunction &MF) { 1398 this->MF = &MF; 1399 // Get the function symbol. 1400 CurrentFnSym = getSymbol(MF.getFunction()); 1401 CurrentFnSymForSize = CurrentFnSym; 1402 CurrentFnBegin = nullptr; 1403 CurExceptionSym = nullptr; 1404 bool NeedsLocalForSize = MAI->needsLocalForSize(); 1405 if (!MF.getLandingPads().empty() || MMI->hasDebugInfo() || 1406 MF.hasEHFunclets() || NeedsLocalForSize) { 1407 CurrentFnBegin = createTempSymbol("func_begin"); 1408 if (NeedsLocalForSize) 1409 CurrentFnSymForSize = CurrentFnBegin; 1410 } 1411 1412 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE(); 1413 if (isVerbose()) 1414 LI = &getAnalysis<MachineLoopInfo>(); 1415 1416 const TargetSubtargetInfo &STI = MF.getSubtarget(); 1417 EnablePrintSchedInfo = PrintSchedule.getNumOccurrences() 1418 ? PrintSchedule 1419 : STI.supportPrintSchedInfo(); 1420 } 1421 1422 namespace { 1423 1424 // Keep track the alignment, constpool entries per Section. 1425 struct SectionCPs { 1426 MCSection *S; 1427 unsigned Alignment; 1428 SmallVector<unsigned, 4> CPEs; 1429 1430 SectionCPs(MCSection *s, unsigned a) : S(s), Alignment(a) {} 1431 }; 1432 1433 } // end anonymous namespace 1434 1435 /// EmitConstantPool - Print to the current output stream assembly 1436 /// representations of the constants in the constant pool MCP. This is 1437 /// used to print out constants which have been "spilled to memory" by 1438 /// the code generator. 1439 /// 1440 void AsmPrinter::EmitConstantPool() { 1441 const MachineConstantPool *MCP = MF->getConstantPool(); 1442 const std::vector<MachineConstantPoolEntry> &CP = MCP->getConstants(); 1443 if (CP.empty()) return; 1444 1445 // Calculate sections for constant pool entries. We collect entries to go into 1446 // the same section together to reduce amount of section switch statements. 1447 SmallVector<SectionCPs, 4> CPSections; 1448 for (unsigned i = 0, e = CP.size(); i != e; ++i) { 1449 const MachineConstantPoolEntry &CPE = CP[i]; 1450 unsigned Align = CPE.getAlignment(); 1451 1452 SectionKind Kind = CPE.getSectionKind(&getDataLayout()); 1453 1454 const Constant *C = nullptr; 1455 if (!CPE.isMachineConstantPoolEntry()) 1456 C = CPE.Val.ConstVal; 1457 1458 MCSection *S = getObjFileLowering().getSectionForConstant(getDataLayout(), 1459 Kind, C, Align); 1460 1461 // The number of sections are small, just do a linear search from the 1462 // last section to the first. 1463 bool Found = false; 1464 unsigned SecIdx = CPSections.size(); 1465 while (SecIdx != 0) { 1466 if (CPSections[--SecIdx].S == S) { 1467 Found = true; 1468 break; 1469 } 1470 } 1471 if (!Found) { 1472 SecIdx = CPSections.size(); 1473 CPSections.push_back(SectionCPs(S, Align)); 1474 } 1475 1476 if (Align > CPSections[SecIdx].Alignment) 1477 CPSections[SecIdx].Alignment = Align; 1478 CPSections[SecIdx].CPEs.push_back(i); 1479 } 1480 1481 // Now print stuff into the calculated sections. 1482 const MCSection *CurSection = nullptr; 1483 unsigned Offset = 0; 1484 for (unsigned i = 0, e = CPSections.size(); i != e; ++i) { 1485 for (unsigned j = 0, ee = CPSections[i].CPEs.size(); j != ee; ++j) { 1486 unsigned CPI = CPSections[i].CPEs[j]; 1487 MCSymbol *Sym = GetCPISymbol(CPI); 1488 if (!Sym->isUndefined()) 1489 continue; 1490 1491 if (CurSection != CPSections[i].S) { 1492 OutStreamer->SwitchSection(CPSections[i].S); 1493 EmitAlignment(Log2_32(CPSections[i].Alignment)); 1494 CurSection = CPSections[i].S; 1495 Offset = 0; 1496 } 1497 1498 MachineConstantPoolEntry CPE = CP[CPI]; 1499 1500 // Emit inter-object padding for alignment. 1501 unsigned AlignMask = CPE.getAlignment() - 1; 1502 unsigned NewOffset = (Offset + AlignMask) & ~AlignMask; 1503 OutStreamer->EmitZeros(NewOffset - Offset); 1504 1505 Type *Ty = CPE.getType(); 1506 Offset = NewOffset + getDataLayout().getTypeAllocSize(Ty); 1507 1508 OutStreamer->EmitLabel(Sym); 1509 if (CPE.isMachineConstantPoolEntry()) 1510 EmitMachineConstantPoolValue(CPE.Val.MachineCPVal); 1511 else 1512 EmitGlobalConstant(getDataLayout(), CPE.Val.ConstVal); 1513 } 1514 } 1515 } 1516 1517 /// EmitJumpTableInfo - Print assembly representations of the jump tables used 1518 /// by the current function to the current output stream. 1519 /// 1520 void AsmPrinter::EmitJumpTableInfo() { 1521 const DataLayout &DL = MF->getDataLayout(); 1522 const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo(); 1523 if (!MJTI) return; 1524 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_Inline) return; 1525 const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables(); 1526 if (JT.empty()) return; 1527 1528 // Pick the directive to use to print the jump table entries, and switch to 1529 // the appropriate section. 1530 const Function *F = MF->getFunction(); 1531 const TargetLoweringObjectFile &TLOF = getObjFileLowering(); 1532 bool JTInDiffSection = !TLOF.shouldPutJumpTableInFunctionSection( 1533 MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32, 1534 *F); 1535 if (JTInDiffSection) { 1536 // Drop it in the readonly section. 1537 MCSection *ReadOnlySection = TLOF.getSectionForJumpTable(*F, TM); 1538 OutStreamer->SwitchSection(ReadOnlySection); 1539 } 1540 1541 EmitAlignment(Log2_32(MJTI->getEntryAlignment(DL))); 1542 1543 // Jump tables in code sections are marked with a data_region directive 1544 // where that's supported. 1545 if (!JTInDiffSection) 1546 OutStreamer->EmitDataRegion(MCDR_DataRegionJT32); 1547 1548 for (unsigned JTI = 0, e = JT.size(); JTI != e; ++JTI) { 1549 const std::vector<MachineBasicBlock*> &JTBBs = JT[JTI].MBBs; 1550 1551 // If this jump table was deleted, ignore it. 1552 if (JTBBs.empty()) continue; 1553 1554 // For the EK_LabelDifference32 entry, if using .set avoids a relocation, 1555 /// emit a .set directive for each unique entry. 1556 if (MJTI->getEntryKind() == MachineJumpTableInfo::EK_LabelDifference32 && 1557 MAI->doesSetDirectiveSuppressReloc()) { 1558 SmallPtrSet<const MachineBasicBlock*, 16> EmittedSets; 1559 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1560 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF,JTI,OutContext); 1561 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) { 1562 const MachineBasicBlock *MBB = JTBBs[ii]; 1563 if (!EmittedSets.insert(MBB).second) 1564 continue; 1565 1566 // .set LJTSet, LBB32-base 1567 const MCExpr *LHS = 1568 MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1569 OutStreamer->EmitAssignment(GetJTSetSymbol(JTI, MBB->getNumber()), 1570 MCBinaryExpr::createSub(LHS, Base, 1571 OutContext)); 1572 } 1573 } 1574 1575 // On some targets (e.g. Darwin) we want to emit two consecutive labels 1576 // before each jump table. The first label is never referenced, but tells 1577 // the assembler and linker the extents of the jump table object. The 1578 // second label is actually referenced by the code. 1579 if (JTInDiffSection && DL.hasLinkerPrivateGlobalPrefix()) 1580 // FIXME: This doesn't have to have any specific name, just any randomly 1581 // named and numbered 'l' label would work. Simplify GetJTISymbol. 1582 OutStreamer->EmitLabel(GetJTISymbol(JTI, true)); 1583 1584 OutStreamer->EmitLabel(GetJTISymbol(JTI)); 1585 1586 for (unsigned ii = 0, ee = JTBBs.size(); ii != ee; ++ii) 1587 EmitJumpTableEntry(MJTI, JTBBs[ii], JTI); 1588 } 1589 if (!JTInDiffSection) 1590 OutStreamer->EmitDataRegion(MCDR_DataRegionEnd); 1591 } 1592 1593 /// EmitJumpTableEntry - Emit a jump table entry for the specified MBB to the 1594 /// current stream. 1595 void AsmPrinter::EmitJumpTableEntry(const MachineJumpTableInfo *MJTI, 1596 const MachineBasicBlock *MBB, 1597 unsigned UID) const { 1598 assert(MBB && MBB->getNumber() >= 0 && "Invalid basic block"); 1599 const MCExpr *Value = nullptr; 1600 switch (MJTI->getEntryKind()) { 1601 case MachineJumpTableInfo::EK_Inline: 1602 llvm_unreachable("Cannot emit EK_Inline jump table entry"); 1603 case MachineJumpTableInfo::EK_Custom32: 1604 Value = MF->getSubtarget().getTargetLowering()->LowerCustomJumpTableEntry( 1605 MJTI, MBB, UID, OutContext); 1606 break; 1607 case MachineJumpTableInfo::EK_BlockAddress: 1608 // EK_BlockAddress - Each entry is a plain address of block, e.g.: 1609 // .word LBB123 1610 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1611 break; 1612 case MachineJumpTableInfo::EK_GPRel32BlockAddress: { 1613 // EK_GPRel32BlockAddress - Each entry is an address of block, encoded 1614 // with a relocation as gp-relative, e.g.: 1615 // .gprel32 LBB123 1616 MCSymbol *MBBSym = MBB->getSymbol(); 1617 OutStreamer->EmitGPRel32Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 1618 return; 1619 } 1620 1621 case MachineJumpTableInfo::EK_GPRel64BlockAddress: { 1622 // EK_GPRel64BlockAddress - Each entry is an address of block, encoded 1623 // with a relocation as gp-relative, e.g.: 1624 // .gpdword LBB123 1625 MCSymbol *MBBSym = MBB->getSymbol(); 1626 OutStreamer->EmitGPRel64Value(MCSymbolRefExpr::create(MBBSym, OutContext)); 1627 return; 1628 } 1629 1630 case MachineJumpTableInfo::EK_LabelDifference32: { 1631 // Each entry is the address of the block minus the address of the jump 1632 // table. This is used for PIC jump tables where gprel32 is not supported. 1633 // e.g.: 1634 // .word LBB123 - LJTI1_2 1635 // If the .set directive avoids relocations, this is emitted as: 1636 // .set L4_5_set_123, LBB123 - LJTI1_2 1637 // .word L4_5_set_123 1638 if (MAI->doesSetDirectiveSuppressReloc()) { 1639 Value = MCSymbolRefExpr::create(GetJTSetSymbol(UID, MBB->getNumber()), 1640 OutContext); 1641 break; 1642 } 1643 Value = MCSymbolRefExpr::create(MBB->getSymbol(), OutContext); 1644 const TargetLowering *TLI = MF->getSubtarget().getTargetLowering(); 1645 const MCExpr *Base = TLI->getPICJumpTableRelocBaseExpr(MF, UID, OutContext); 1646 Value = MCBinaryExpr::createSub(Value, Base, OutContext); 1647 break; 1648 } 1649 } 1650 1651 assert(Value && "Unknown entry kind!"); 1652 1653 unsigned EntrySize = MJTI->getEntrySize(getDataLayout()); 1654 OutStreamer->EmitValue(Value, EntrySize); 1655 } 1656 1657 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a 1658 /// special global used by LLVM. If so, emit it and return true, otherwise 1659 /// do nothing and return false. 1660 bool AsmPrinter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) { 1661 if (GV->getName() == "llvm.used") { 1662 if (MAI->hasNoDeadStrip()) // No need to emit this at all. 1663 EmitLLVMUsedList(cast<ConstantArray>(GV->getInitializer())); 1664 return true; 1665 } 1666 1667 // Ignore debug and non-emitted data. This handles llvm.compiler.used. 1668 if (GV->getSection() == "llvm.metadata" || 1669 GV->hasAvailableExternallyLinkage()) 1670 return true; 1671 1672 if (!GV->hasAppendingLinkage()) return false; 1673 1674 assert(GV->hasInitializer() && "Not a special LLVM global!"); 1675 1676 if (GV->getName() == "llvm.global_ctors") { 1677 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 1678 /* isCtor */ true); 1679 1680 return true; 1681 } 1682 1683 if (GV->getName() == "llvm.global_dtors") { 1684 EmitXXStructorList(GV->getParent()->getDataLayout(), GV->getInitializer(), 1685 /* isCtor */ false); 1686 1687 return true; 1688 } 1689 1690 report_fatal_error("unknown special variable"); 1691 } 1692 1693 /// EmitLLVMUsedList - For targets that define a MAI::UsedDirective, mark each 1694 /// global in the specified llvm.used list for which emitUsedDirectiveFor 1695 /// is true, as being used with this directive. 1696 void AsmPrinter::EmitLLVMUsedList(const ConstantArray *InitList) { 1697 // Should be an array of 'i8*'. 1698 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 1699 const GlobalValue *GV = 1700 dyn_cast<GlobalValue>(InitList->getOperand(i)->stripPointerCasts()); 1701 if (GV) 1702 OutStreamer->EmitSymbolAttribute(getSymbol(GV), MCSA_NoDeadStrip); 1703 } 1704 } 1705 1706 namespace { 1707 1708 struct Structor { 1709 int Priority = 0; 1710 Constant *Func = nullptr; 1711 GlobalValue *ComdatKey = nullptr; 1712 1713 Structor() = default; 1714 }; 1715 1716 } // end anonymous namespace 1717 1718 /// EmitXXStructorList - Emit the ctor or dtor list taking into account the init 1719 /// priority. 1720 void AsmPrinter::EmitXXStructorList(const DataLayout &DL, const Constant *List, 1721 bool isCtor) { 1722 // Should be an array of '{ int, void ()* }' structs. The first value is the 1723 // init priority. 1724 if (!isa<ConstantArray>(List)) return; 1725 1726 // Sanity check the structors list. 1727 const ConstantArray *InitList = dyn_cast<ConstantArray>(List); 1728 if (!InitList) return; // Not an array! 1729 StructType *ETy = dyn_cast<StructType>(InitList->getType()->getElementType()); 1730 // FIXME: Only allow the 3-field form in LLVM 4.0. 1731 if (!ETy || ETy->getNumElements() < 2 || ETy->getNumElements() > 3) 1732 return; // Not an array of two or three elements! 1733 if (!isa<IntegerType>(ETy->getTypeAtIndex(0U)) || 1734 !isa<PointerType>(ETy->getTypeAtIndex(1U))) return; // Not (int, ptr). 1735 if (ETy->getNumElements() == 3 && !isa<PointerType>(ETy->getTypeAtIndex(2U))) 1736 return; // Not (int, ptr, ptr). 1737 1738 // Gather the structors in a form that's convenient for sorting by priority. 1739 SmallVector<Structor, 8> Structors; 1740 for (Value *O : InitList->operands()) { 1741 ConstantStruct *CS = dyn_cast<ConstantStruct>(O); 1742 if (!CS) continue; // Malformed. 1743 if (CS->getOperand(1)->isNullValue()) 1744 break; // Found a null terminator, skip the rest. 1745 ConstantInt *Priority = dyn_cast<ConstantInt>(CS->getOperand(0)); 1746 if (!Priority) continue; // Malformed. 1747 Structors.push_back(Structor()); 1748 Structor &S = Structors.back(); 1749 S.Priority = Priority->getLimitedValue(65535); 1750 S.Func = CS->getOperand(1); 1751 if (ETy->getNumElements() == 3 && !CS->getOperand(2)->isNullValue()) 1752 S.ComdatKey = 1753 dyn_cast<GlobalValue>(CS->getOperand(2)->stripPointerCasts()); 1754 } 1755 1756 // Emit the function pointers in the target-specific order 1757 unsigned Align = Log2_32(DL.getPointerPrefAlignment()); 1758 std::stable_sort(Structors.begin(), Structors.end(), 1759 [](const Structor &L, 1760 const Structor &R) { return L.Priority < R.Priority; }); 1761 for (Structor &S : Structors) { 1762 const TargetLoweringObjectFile &Obj = getObjFileLowering(); 1763 const MCSymbol *KeySym = nullptr; 1764 if (GlobalValue *GV = S.ComdatKey) { 1765 if (GV->isDeclarationForLinker()) 1766 // If the associated variable is not defined in this module 1767 // (it might be available_externally, or have been an 1768 // available_externally definition that was dropped by the 1769 // EliminateAvailableExternally pass), some other TU 1770 // will provide its dynamic initializer. 1771 continue; 1772 1773 KeySym = getSymbol(GV); 1774 } 1775 MCSection *OutputSection = 1776 (isCtor ? Obj.getStaticCtorSection(S.Priority, KeySym) 1777 : Obj.getStaticDtorSection(S.Priority, KeySym)); 1778 OutStreamer->SwitchSection(OutputSection); 1779 if (OutStreamer->getCurrentSection() != OutStreamer->getPreviousSection()) 1780 EmitAlignment(Align); 1781 EmitXXStructor(DL, S.Func); 1782 } 1783 } 1784 1785 void AsmPrinter::EmitModuleIdents(Module &M) { 1786 if (!MAI->hasIdentDirective()) 1787 return; 1788 1789 if (const NamedMDNode *NMD = M.getNamedMetadata("llvm.ident")) { 1790 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) { 1791 const MDNode *N = NMD->getOperand(i); 1792 assert(N->getNumOperands() == 1 && 1793 "llvm.ident metadata entry can have only one operand"); 1794 const MDString *S = cast<MDString>(N->getOperand(0)); 1795 OutStreamer->EmitIdent(S->getString()); 1796 } 1797 } 1798 } 1799 1800 //===--------------------------------------------------------------------===// 1801 // Emission and print routines 1802 // 1803 1804 /// EmitInt8 - Emit a byte directive and value. 1805 /// 1806 void AsmPrinter::EmitInt8(int Value) const { 1807 OutStreamer->EmitIntValue(Value, 1); 1808 } 1809 1810 /// EmitInt16 - Emit a short directive and value. 1811 /// 1812 void AsmPrinter::EmitInt16(int Value) const { 1813 OutStreamer->EmitIntValue(Value, 2); 1814 } 1815 1816 /// EmitInt32 - Emit a long directive and value. 1817 /// 1818 void AsmPrinter::EmitInt32(int Value) const { 1819 OutStreamer->EmitIntValue(Value, 4); 1820 } 1821 1822 /// Emit something like ".long Hi-Lo" where the size in bytes of the directive 1823 /// is specified by Size and Hi/Lo specify the labels. This implicitly uses 1824 /// .set if it avoids relocations. 1825 void AsmPrinter::EmitLabelDifference(const MCSymbol *Hi, const MCSymbol *Lo, 1826 unsigned Size) const { 1827 OutStreamer->emitAbsoluteSymbolDiff(Hi, Lo, Size); 1828 } 1829 1830 /// EmitLabelPlusOffset - Emit something like ".long Label+Offset" 1831 /// where the size in bytes of the directive is specified by Size and Label 1832 /// specifies the label. This implicitly uses .set if it is available. 1833 void AsmPrinter::EmitLabelPlusOffset(const MCSymbol *Label, uint64_t Offset, 1834 unsigned Size, 1835 bool IsSectionRelative) const { 1836 if (MAI->needsDwarfSectionOffsetDirective() && IsSectionRelative) { 1837 OutStreamer->EmitCOFFSecRel32(Label, Offset); 1838 if (Size > 4) 1839 OutStreamer->EmitZeros(Size - 4); 1840 return; 1841 } 1842 1843 // Emit Label+Offset (or just Label if Offset is zero) 1844 const MCExpr *Expr = MCSymbolRefExpr::create(Label, OutContext); 1845 if (Offset) 1846 Expr = MCBinaryExpr::createAdd( 1847 Expr, MCConstantExpr::create(Offset, OutContext), OutContext); 1848 1849 OutStreamer->EmitValue(Expr, Size); 1850 } 1851 1852 //===----------------------------------------------------------------------===// 1853 1854 // EmitAlignment - Emit an alignment directive to the specified power of 1855 // two boundary. For example, if you pass in 3 here, you will get an 8 1856 // byte alignment. If a global value is specified, and if that global has 1857 // an explicit alignment requested, it will override the alignment request 1858 // if required for correctness. 1859 // 1860 void AsmPrinter::EmitAlignment(unsigned NumBits, const GlobalObject *GV) const { 1861 if (GV) 1862 NumBits = getGVAlignmentLog2(GV, GV->getParent()->getDataLayout(), NumBits); 1863 1864 if (NumBits == 0) return; // 1-byte aligned: no need to emit alignment. 1865 1866 assert(NumBits < 1867 static_cast<unsigned>(std::numeric_limits<unsigned>::digits) && 1868 "undefined behavior"); 1869 if (getCurrentSection()->getKind().isText()) 1870 OutStreamer->EmitCodeAlignment(1u << NumBits); 1871 else 1872 OutStreamer->EmitValueToAlignment(1u << NumBits); 1873 } 1874 1875 //===----------------------------------------------------------------------===// 1876 // Constant emission. 1877 //===----------------------------------------------------------------------===// 1878 1879 const MCExpr *AsmPrinter::lowerConstant(const Constant *CV) { 1880 MCContext &Ctx = OutContext; 1881 1882 if (CV->isNullValue() || isa<UndefValue>(CV)) 1883 return MCConstantExpr::create(0, Ctx); 1884 1885 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) 1886 return MCConstantExpr::create(CI->getZExtValue(), Ctx); 1887 1888 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) 1889 return MCSymbolRefExpr::create(getSymbol(GV), Ctx); 1890 1891 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV)) 1892 return MCSymbolRefExpr::create(GetBlockAddressSymbol(BA), Ctx); 1893 1894 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV); 1895 if (!CE) { 1896 llvm_unreachable("Unknown constant value to lower!"); 1897 } 1898 1899 switch (CE->getOpcode()) { 1900 default: 1901 // If the code isn't optimized, there may be outstanding folding 1902 // opportunities. Attempt to fold the expression using DataLayout as a 1903 // last resort before giving up. 1904 if (Constant *C = ConstantFoldConstant(CE, getDataLayout())) 1905 if (C != CE) 1906 return lowerConstant(C); 1907 1908 // Otherwise report the problem to the user. 1909 { 1910 std::string S; 1911 raw_string_ostream OS(S); 1912 OS << "Unsupported expression in static initializer: "; 1913 CE->printAsOperand(OS, /*PrintType=*/false, 1914 !MF ? nullptr : MF->getFunction()->getParent()); 1915 report_fatal_error(OS.str()); 1916 } 1917 case Instruction::GetElementPtr: { 1918 // Generate a symbolic expression for the byte address 1919 APInt OffsetAI(getDataLayout().getPointerTypeSizeInBits(CE->getType()), 0); 1920 cast<GEPOperator>(CE)->accumulateConstantOffset(getDataLayout(), OffsetAI); 1921 1922 const MCExpr *Base = lowerConstant(CE->getOperand(0)); 1923 if (!OffsetAI) 1924 return Base; 1925 1926 int64_t Offset = OffsetAI.getSExtValue(); 1927 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx), 1928 Ctx); 1929 } 1930 1931 case Instruction::Trunc: 1932 // We emit the value and depend on the assembler to truncate the generated 1933 // expression properly. This is important for differences between 1934 // blockaddress labels. Since the two labels are in the same function, it 1935 // is reasonable to treat their delta as a 32-bit value. 1936 LLVM_FALLTHROUGH; 1937 case Instruction::BitCast: 1938 return lowerConstant(CE->getOperand(0)); 1939 1940 case Instruction::IntToPtr: { 1941 const DataLayout &DL = getDataLayout(); 1942 1943 // Handle casts to pointers by changing them into casts to the appropriate 1944 // integer type. This promotes constant folding and simplifies this code. 1945 Constant *Op = CE->getOperand(0); 1946 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()), 1947 false/*ZExt*/); 1948 return lowerConstant(Op); 1949 } 1950 1951 case Instruction::PtrToInt: { 1952 const DataLayout &DL = getDataLayout(); 1953 1954 // Support only foldable casts to/from pointers that can be eliminated by 1955 // changing the pointer to the appropriately sized integer type. 1956 Constant *Op = CE->getOperand(0); 1957 Type *Ty = CE->getType(); 1958 1959 const MCExpr *OpExpr = lowerConstant(Op); 1960 1961 // We can emit the pointer value into this slot if the slot is an 1962 // integer slot equal to the size of the pointer. 1963 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType())) 1964 return OpExpr; 1965 1966 // Otherwise the pointer is smaller than the resultant integer, mask off 1967 // the high bits so we are sure to get a proper truncation if the input is 1968 // a constant expr. 1969 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType()); 1970 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx); 1971 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx); 1972 } 1973 1974 case Instruction::Sub: { 1975 GlobalValue *LHSGV; 1976 APInt LHSOffset; 1977 if (IsConstantOffsetFromGlobal(CE->getOperand(0), LHSGV, LHSOffset, 1978 getDataLayout())) { 1979 GlobalValue *RHSGV; 1980 APInt RHSOffset; 1981 if (IsConstantOffsetFromGlobal(CE->getOperand(1), RHSGV, RHSOffset, 1982 getDataLayout())) { 1983 const MCExpr *RelocExpr = 1984 getObjFileLowering().lowerRelativeReference(LHSGV, RHSGV, TM); 1985 if (!RelocExpr) 1986 RelocExpr = MCBinaryExpr::createSub( 1987 MCSymbolRefExpr::create(getSymbol(LHSGV), Ctx), 1988 MCSymbolRefExpr::create(getSymbol(RHSGV), Ctx), Ctx); 1989 int64_t Addend = (LHSOffset - RHSOffset).getSExtValue(); 1990 if (Addend != 0) 1991 RelocExpr = MCBinaryExpr::createAdd( 1992 RelocExpr, MCConstantExpr::create(Addend, Ctx), Ctx); 1993 return RelocExpr; 1994 } 1995 } 1996 } 1997 // else fallthrough 1998 1999 // The MC library also has a right-shift operator, but it isn't consistently 2000 // signed or unsigned between different targets. 2001 case Instruction::Add: 2002 case Instruction::Mul: 2003 case Instruction::SDiv: 2004 case Instruction::SRem: 2005 case Instruction::Shl: 2006 case Instruction::And: 2007 case Instruction::Or: 2008 case Instruction::Xor: { 2009 const MCExpr *LHS = lowerConstant(CE->getOperand(0)); 2010 const MCExpr *RHS = lowerConstant(CE->getOperand(1)); 2011 switch (CE->getOpcode()) { 2012 default: llvm_unreachable("Unknown binary operator constant cast expr"); 2013 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx); 2014 case Instruction::Sub: return MCBinaryExpr::createSub(LHS, RHS, Ctx); 2015 case Instruction::Mul: return MCBinaryExpr::createMul(LHS, RHS, Ctx); 2016 case Instruction::SDiv: return MCBinaryExpr::createDiv(LHS, RHS, Ctx); 2017 case Instruction::SRem: return MCBinaryExpr::createMod(LHS, RHS, Ctx); 2018 case Instruction::Shl: return MCBinaryExpr::createShl(LHS, RHS, Ctx); 2019 case Instruction::And: return MCBinaryExpr::createAnd(LHS, RHS, Ctx); 2020 case Instruction::Or: return MCBinaryExpr::createOr (LHS, RHS, Ctx); 2021 case Instruction::Xor: return MCBinaryExpr::createXor(LHS, RHS, Ctx); 2022 } 2023 } 2024 } 2025 } 2026 2027 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *C, 2028 AsmPrinter &AP, 2029 const Constant *BaseCV = nullptr, 2030 uint64_t Offset = 0); 2031 2032 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP); 2033 2034 /// isRepeatedByteSequence - Determine whether the given value is 2035 /// composed of a repeated sequence of identical bytes and return the 2036 /// byte value. If it is not a repeated sequence, return -1. 2037 static int isRepeatedByteSequence(const ConstantDataSequential *V) { 2038 StringRef Data = V->getRawDataValues(); 2039 assert(!Data.empty() && "Empty aggregates should be CAZ node"); 2040 char C = Data[0]; 2041 for (unsigned i = 1, e = Data.size(); i != e; ++i) 2042 if (Data[i] != C) return -1; 2043 return static_cast<uint8_t>(C); // Ensure 255 is not returned as -1. 2044 } 2045 2046 /// isRepeatedByteSequence - Determine whether the given value is 2047 /// composed of a repeated sequence of identical bytes and return the 2048 /// byte value. If it is not a repeated sequence, return -1. 2049 static int isRepeatedByteSequence(const Value *V, const DataLayout &DL) { 2050 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) { 2051 uint64_t Size = DL.getTypeAllocSizeInBits(V->getType()); 2052 assert(Size % 8 == 0); 2053 2054 // Extend the element to take zero padding into account. 2055 APInt Value = CI->getValue().zextOrSelf(Size); 2056 if (!Value.isSplat(8)) 2057 return -1; 2058 2059 return Value.zextOrTrunc(8).getZExtValue(); 2060 } 2061 if (const ConstantArray *CA = dyn_cast<ConstantArray>(V)) { 2062 // Make sure all array elements are sequences of the same repeated 2063 // byte. 2064 assert(CA->getNumOperands() != 0 && "Should be a CAZ"); 2065 Constant *Op0 = CA->getOperand(0); 2066 int Byte = isRepeatedByteSequence(Op0, DL); 2067 if (Byte == -1) 2068 return -1; 2069 2070 // All array elements must be equal. 2071 for (unsigned i = 1, e = CA->getNumOperands(); i != e; ++i) 2072 if (CA->getOperand(i) != Op0) 2073 return -1; 2074 return Byte; 2075 } 2076 2077 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(V)) 2078 return isRepeatedByteSequence(CDS); 2079 2080 return -1; 2081 } 2082 2083 static void emitGlobalConstantDataSequential(const DataLayout &DL, 2084 const ConstantDataSequential *CDS, 2085 AsmPrinter &AP) { 2086 // See if we can aggregate this into a .fill, if so, emit it as such. 2087 int Value = isRepeatedByteSequence(CDS, DL); 2088 if (Value != -1) { 2089 uint64_t Bytes = DL.getTypeAllocSize(CDS->getType()); 2090 // Don't emit a 1-byte object as a .fill. 2091 if (Bytes > 1) 2092 return AP.OutStreamer->emitFill(Bytes, Value); 2093 } 2094 2095 // If this can be emitted with .ascii/.asciz, emit it as such. 2096 if (CDS->isString()) 2097 return AP.OutStreamer->EmitBytes(CDS->getAsString()); 2098 2099 // Otherwise, emit the values in successive locations. 2100 unsigned ElementByteSize = CDS->getElementByteSize(); 2101 if (isa<IntegerType>(CDS->getElementType())) { 2102 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 2103 if (AP.isVerbose()) 2104 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2105 CDS->getElementAsInteger(i)); 2106 AP.OutStreamer->EmitIntValue(CDS->getElementAsInteger(i), 2107 ElementByteSize); 2108 } 2109 } else { 2110 for (unsigned I = 0, E = CDS->getNumElements(); I != E; ++I) 2111 emitGlobalConstantFP(cast<ConstantFP>(CDS->getElementAsConstant(I)), AP); 2112 } 2113 2114 unsigned Size = DL.getTypeAllocSize(CDS->getType()); 2115 unsigned EmittedSize = DL.getTypeAllocSize(CDS->getType()->getElementType()) * 2116 CDS->getNumElements(); 2117 if (unsigned Padding = Size - EmittedSize) 2118 AP.OutStreamer->EmitZeros(Padding); 2119 } 2120 2121 static void emitGlobalConstantArray(const DataLayout &DL, 2122 const ConstantArray *CA, AsmPrinter &AP, 2123 const Constant *BaseCV, uint64_t Offset) { 2124 // See if we can aggregate some values. Make sure it can be 2125 // represented as a series of bytes of the constant value. 2126 int Value = isRepeatedByteSequence(CA, DL); 2127 2128 if (Value != -1) { 2129 uint64_t Bytes = DL.getTypeAllocSize(CA->getType()); 2130 AP.OutStreamer->emitFill(Bytes, Value); 2131 } 2132 else { 2133 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) { 2134 emitGlobalConstantImpl(DL, CA->getOperand(i), AP, BaseCV, Offset); 2135 Offset += DL.getTypeAllocSize(CA->getOperand(i)->getType()); 2136 } 2137 } 2138 } 2139 2140 static void emitGlobalConstantVector(const DataLayout &DL, 2141 const ConstantVector *CV, AsmPrinter &AP) { 2142 for (unsigned i = 0, e = CV->getType()->getNumElements(); i != e; ++i) 2143 emitGlobalConstantImpl(DL, CV->getOperand(i), AP); 2144 2145 unsigned Size = DL.getTypeAllocSize(CV->getType()); 2146 unsigned EmittedSize = DL.getTypeAllocSize(CV->getType()->getElementType()) * 2147 CV->getType()->getNumElements(); 2148 if (unsigned Padding = Size - EmittedSize) 2149 AP.OutStreamer->EmitZeros(Padding); 2150 } 2151 2152 static void emitGlobalConstantStruct(const DataLayout &DL, 2153 const ConstantStruct *CS, AsmPrinter &AP, 2154 const Constant *BaseCV, uint64_t Offset) { 2155 // Print the fields in successive locations. Pad to align if needed! 2156 unsigned Size = DL.getTypeAllocSize(CS->getType()); 2157 const StructLayout *Layout = DL.getStructLayout(CS->getType()); 2158 uint64_t SizeSoFar = 0; 2159 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i) { 2160 const Constant *Field = CS->getOperand(i); 2161 2162 // Print the actual field value. 2163 emitGlobalConstantImpl(DL, Field, AP, BaseCV, Offset + SizeSoFar); 2164 2165 // Check if padding is needed and insert one or more 0s. 2166 uint64_t FieldSize = DL.getTypeAllocSize(Field->getType()); 2167 uint64_t PadSize = ((i == e-1 ? Size : Layout->getElementOffset(i+1)) 2168 - Layout->getElementOffset(i)) - FieldSize; 2169 SizeSoFar += FieldSize + PadSize; 2170 2171 // Insert padding - this may include padding to increase the size of the 2172 // current field up to the ABI size (if the struct is not packed) as well 2173 // as padding to ensure that the next field starts at the right offset. 2174 AP.OutStreamer->EmitZeros(PadSize); 2175 } 2176 assert(SizeSoFar == Layout->getSizeInBytes() && 2177 "Layout of constant struct may be incorrect!"); 2178 } 2179 2180 static void emitGlobalConstantFP(const ConstantFP *CFP, AsmPrinter &AP) { 2181 APInt API = CFP->getValueAPF().bitcastToAPInt(); 2182 2183 // First print a comment with what we think the original floating-point value 2184 // should have been. 2185 if (AP.isVerbose()) { 2186 SmallString<8> StrVal; 2187 CFP->getValueAPF().toString(StrVal); 2188 2189 if (CFP->getType()) 2190 CFP->getType()->print(AP.OutStreamer->GetCommentOS()); 2191 else 2192 AP.OutStreamer->GetCommentOS() << "Printing <null> Type"; 2193 AP.OutStreamer->GetCommentOS() << ' ' << StrVal << '\n'; 2194 } 2195 2196 // Now iterate through the APInt chunks, emitting them in endian-correct 2197 // order, possibly with a smaller chunk at beginning/end (e.g. for x87 80-bit 2198 // floats). 2199 unsigned NumBytes = API.getBitWidth() / 8; 2200 unsigned TrailingBytes = NumBytes % sizeof(uint64_t); 2201 const uint64_t *p = API.getRawData(); 2202 2203 // PPC's long double has odd notions of endianness compared to how LLVM 2204 // handles it: p[0] goes first for *big* endian on PPC. 2205 if (AP.getDataLayout().isBigEndian() && !CFP->getType()->isPPC_FP128Ty()) { 2206 int Chunk = API.getNumWords() - 1; 2207 2208 if (TrailingBytes) 2209 AP.OutStreamer->EmitIntValue(p[Chunk--], TrailingBytes); 2210 2211 for (; Chunk >= 0; --Chunk) 2212 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t)); 2213 } else { 2214 unsigned Chunk; 2215 for (Chunk = 0; Chunk < NumBytes / sizeof(uint64_t); ++Chunk) 2216 AP.OutStreamer->EmitIntValue(p[Chunk], sizeof(uint64_t)); 2217 2218 if (TrailingBytes) 2219 AP.OutStreamer->EmitIntValue(p[Chunk], TrailingBytes); 2220 } 2221 2222 // Emit the tail padding for the long double. 2223 const DataLayout &DL = AP.getDataLayout(); 2224 AP.OutStreamer->EmitZeros(DL.getTypeAllocSize(CFP->getType()) - 2225 DL.getTypeStoreSize(CFP->getType())); 2226 } 2227 2228 static void emitGlobalConstantLargeInt(const ConstantInt *CI, AsmPrinter &AP) { 2229 const DataLayout &DL = AP.getDataLayout(); 2230 unsigned BitWidth = CI->getBitWidth(); 2231 2232 // Copy the value as we may massage the layout for constants whose bit width 2233 // is not a multiple of 64-bits. 2234 APInt Realigned(CI->getValue()); 2235 uint64_t ExtraBits = 0; 2236 unsigned ExtraBitsSize = BitWidth & 63; 2237 2238 if (ExtraBitsSize) { 2239 // The bit width of the data is not a multiple of 64-bits. 2240 // The extra bits are expected to be at the end of the chunk of the memory. 2241 // Little endian: 2242 // * Nothing to be done, just record the extra bits to emit. 2243 // Big endian: 2244 // * Record the extra bits to emit. 2245 // * Realign the raw data to emit the chunks of 64-bits. 2246 if (DL.isBigEndian()) { 2247 // Basically the structure of the raw data is a chunk of 64-bits cells: 2248 // 0 1 BitWidth / 64 2249 // [chunk1][chunk2] ... [chunkN]. 2250 // The most significant chunk is chunkN and it should be emitted first. 2251 // However, due to the alignment issue chunkN contains useless bits. 2252 // Realign the chunks so that they contain only useless information: 2253 // ExtraBits 0 1 (BitWidth / 64) - 1 2254 // chu[nk1 chu][nk2 chu] ... [nkN-1 chunkN] 2255 ExtraBits = Realigned.getRawData()[0] & 2256 (((uint64_t)-1) >> (64 - ExtraBitsSize)); 2257 Realigned.lshrInPlace(ExtraBitsSize); 2258 } else 2259 ExtraBits = Realigned.getRawData()[BitWidth / 64]; 2260 } 2261 2262 // We don't expect assemblers to support integer data directives 2263 // for more than 64 bits, so we emit the data in at most 64-bit 2264 // quantities at a time. 2265 const uint64_t *RawData = Realigned.getRawData(); 2266 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) { 2267 uint64_t Val = DL.isBigEndian() ? RawData[e - i - 1] : RawData[i]; 2268 AP.OutStreamer->EmitIntValue(Val, 8); 2269 } 2270 2271 if (ExtraBitsSize) { 2272 // Emit the extra bits after the 64-bits chunks. 2273 2274 // Emit a directive that fills the expected size. 2275 uint64_t Size = AP.getDataLayout().getTypeAllocSize(CI->getType()); 2276 Size -= (BitWidth / 64) * 8; 2277 assert(Size && Size * 8 >= ExtraBitsSize && 2278 (ExtraBits & (((uint64_t)-1) >> (64 - ExtraBitsSize))) 2279 == ExtraBits && "Directive too small for extra bits."); 2280 AP.OutStreamer->EmitIntValue(ExtraBits, Size); 2281 } 2282 } 2283 2284 /// \brief Transform a not absolute MCExpr containing a reference to a GOT 2285 /// equivalent global, by a target specific GOT pc relative access to the 2286 /// final symbol. 2287 static void handleIndirectSymViaGOTPCRel(AsmPrinter &AP, const MCExpr **ME, 2288 const Constant *BaseCst, 2289 uint64_t Offset) { 2290 // The global @foo below illustrates a global that uses a got equivalent. 2291 // 2292 // @bar = global i32 42 2293 // @gotequiv = private unnamed_addr constant i32* @bar 2294 // @foo = i32 trunc (i64 sub (i64 ptrtoint (i32** @gotequiv to i64), 2295 // i64 ptrtoint (i32* @foo to i64)) 2296 // to i32) 2297 // 2298 // The cstexpr in @foo is converted into the MCExpr `ME`, where we actually 2299 // check whether @foo is suitable to use a GOTPCREL. `ME` is usually in the 2300 // form: 2301 // 2302 // foo = cstexpr, where 2303 // cstexpr := <gotequiv> - "." + <cst> 2304 // cstexpr := <gotequiv> - (<foo> - <offset from @foo base>) + <cst> 2305 // 2306 // After canonicalization by evaluateAsRelocatable `ME` turns into: 2307 // 2308 // cstexpr := <gotequiv> - <foo> + gotpcrelcst, where 2309 // gotpcrelcst := <offset from @foo base> + <cst> 2310 // 2311 MCValue MV; 2312 if (!(*ME)->evaluateAsRelocatable(MV, nullptr, nullptr) || MV.isAbsolute()) 2313 return; 2314 const MCSymbolRefExpr *SymA = MV.getSymA(); 2315 if (!SymA) 2316 return; 2317 2318 // Check that GOT equivalent symbol is cached. 2319 const MCSymbol *GOTEquivSym = &SymA->getSymbol(); 2320 if (!AP.GlobalGOTEquivs.count(GOTEquivSym)) 2321 return; 2322 2323 const GlobalValue *BaseGV = dyn_cast_or_null<GlobalValue>(BaseCst); 2324 if (!BaseGV) 2325 return; 2326 2327 // Check for a valid base symbol 2328 const MCSymbol *BaseSym = AP.getSymbol(BaseGV); 2329 const MCSymbolRefExpr *SymB = MV.getSymB(); 2330 2331 if (!SymB || BaseSym != &SymB->getSymbol()) 2332 return; 2333 2334 // Make sure to match: 2335 // 2336 // gotpcrelcst := <offset from @foo base> + <cst> 2337 // 2338 // If gotpcrelcst is positive it means that we can safely fold the pc rel 2339 // displacement into the GOTPCREL. We can also can have an extra offset <cst> 2340 // if the target knows how to encode it. 2341 // 2342 int64_t GOTPCRelCst = Offset + MV.getConstant(); 2343 if (GOTPCRelCst < 0) 2344 return; 2345 if (!AP.getObjFileLowering().supportGOTPCRelWithOffset() && GOTPCRelCst != 0) 2346 return; 2347 2348 // Emit the GOT PC relative to replace the got equivalent global, i.e.: 2349 // 2350 // bar: 2351 // .long 42 2352 // gotequiv: 2353 // .quad bar 2354 // foo: 2355 // .long gotequiv - "." + <cst> 2356 // 2357 // is replaced by the target specific equivalent to: 2358 // 2359 // bar: 2360 // .long 42 2361 // foo: 2362 // .long bar@GOTPCREL+<gotpcrelcst> 2363 // 2364 AsmPrinter::GOTEquivUsePair Result = AP.GlobalGOTEquivs[GOTEquivSym]; 2365 const GlobalVariable *GV = Result.first; 2366 int NumUses = (int)Result.second; 2367 const GlobalValue *FinalGV = dyn_cast<GlobalValue>(GV->getOperand(0)); 2368 const MCSymbol *FinalSym = AP.getSymbol(FinalGV); 2369 *ME = AP.getObjFileLowering().getIndirectSymViaGOTPCRel( 2370 FinalSym, MV, Offset, AP.MMI, *AP.OutStreamer); 2371 2372 // Update GOT equivalent usage information 2373 --NumUses; 2374 if (NumUses >= 0) 2375 AP.GlobalGOTEquivs[GOTEquivSym] = std::make_pair(GV, NumUses); 2376 } 2377 2378 static void emitGlobalConstantImpl(const DataLayout &DL, const Constant *CV, 2379 AsmPrinter &AP, const Constant *BaseCV, 2380 uint64_t Offset) { 2381 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2382 2383 // Globals with sub-elements such as combinations of arrays and structs 2384 // are handled recursively by emitGlobalConstantImpl. Keep track of the 2385 // constant symbol base and the current position with BaseCV and Offset. 2386 if (!BaseCV && CV->hasOneUse()) 2387 BaseCV = dyn_cast<Constant>(CV->user_back()); 2388 2389 if (isa<ConstantAggregateZero>(CV) || isa<UndefValue>(CV)) 2390 return AP.OutStreamer->EmitZeros(Size); 2391 2392 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) { 2393 switch (Size) { 2394 case 1: 2395 case 2: 2396 case 4: 2397 case 8: 2398 if (AP.isVerbose()) 2399 AP.OutStreamer->GetCommentOS() << format("0x%" PRIx64 "\n", 2400 CI->getZExtValue()); 2401 AP.OutStreamer->EmitIntValue(CI->getZExtValue(), Size); 2402 return; 2403 default: 2404 emitGlobalConstantLargeInt(CI, AP); 2405 return; 2406 } 2407 } 2408 2409 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) 2410 return emitGlobalConstantFP(CFP, AP); 2411 2412 if (isa<ConstantPointerNull>(CV)) { 2413 AP.OutStreamer->EmitIntValue(0, Size); 2414 return; 2415 } 2416 2417 if (const ConstantDataSequential *CDS = dyn_cast<ConstantDataSequential>(CV)) 2418 return emitGlobalConstantDataSequential(DL, CDS, AP); 2419 2420 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) 2421 return emitGlobalConstantArray(DL, CVA, AP, BaseCV, Offset); 2422 2423 if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) 2424 return emitGlobalConstantStruct(DL, CVS, AP, BaseCV, Offset); 2425 2426 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) { 2427 // Look through bitcasts, which might not be able to be MCExpr'ized (e.g. of 2428 // vectors). 2429 if (CE->getOpcode() == Instruction::BitCast) 2430 return emitGlobalConstantImpl(DL, CE->getOperand(0), AP); 2431 2432 if (Size > 8) { 2433 // If the constant expression's size is greater than 64-bits, then we have 2434 // to emit the value in chunks. Try to constant fold the value and emit it 2435 // that way. 2436 Constant *New = ConstantFoldConstant(CE, DL); 2437 if (New && New != CE) 2438 return emitGlobalConstantImpl(DL, New, AP); 2439 } 2440 } 2441 2442 if (const ConstantVector *V = dyn_cast<ConstantVector>(CV)) 2443 return emitGlobalConstantVector(DL, V, AP); 2444 2445 // Otherwise, it must be a ConstantExpr. Lower it to an MCExpr, then emit it 2446 // thread the streamer with EmitValue. 2447 const MCExpr *ME = AP.lowerConstant(CV); 2448 2449 // Since lowerConstant already folded and got rid of all IR pointer and 2450 // integer casts, detect GOT equivalent accesses by looking into the MCExpr 2451 // directly. 2452 if (AP.getObjFileLowering().supportIndirectSymViaGOTPCRel()) 2453 handleIndirectSymViaGOTPCRel(AP, &ME, BaseCV, Offset); 2454 2455 AP.OutStreamer->EmitValue(ME, Size); 2456 } 2457 2458 /// EmitGlobalConstant - Print a general LLVM constant to the .s file. 2459 void AsmPrinter::EmitGlobalConstant(const DataLayout &DL, const Constant *CV) { 2460 uint64_t Size = DL.getTypeAllocSize(CV->getType()); 2461 if (Size) 2462 emitGlobalConstantImpl(DL, CV, *this); 2463 else if (MAI->hasSubsectionsViaSymbols()) { 2464 // If the global has zero size, emit a single byte so that two labels don't 2465 // look like they are at the same location. 2466 OutStreamer->EmitIntValue(0, 1); 2467 } 2468 } 2469 2470 void AsmPrinter::EmitMachineConstantPoolValue(MachineConstantPoolValue *MCPV) { 2471 // Target doesn't support this yet! 2472 llvm_unreachable("Target does not support EmitMachineConstantPoolValue"); 2473 } 2474 2475 void AsmPrinter::printOffset(int64_t Offset, raw_ostream &OS) const { 2476 if (Offset > 0) 2477 OS << '+' << Offset; 2478 else if (Offset < 0) 2479 OS << Offset; 2480 } 2481 2482 //===----------------------------------------------------------------------===// 2483 // Symbol Lowering Routines. 2484 //===----------------------------------------------------------------------===// 2485 2486 MCSymbol *AsmPrinter::createTempSymbol(const Twine &Name) const { 2487 return OutContext.createTempSymbol(Name, true); 2488 } 2489 2490 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BlockAddress *BA) const { 2491 return MMI->getAddrLabelSymbol(BA->getBasicBlock()); 2492 } 2493 2494 MCSymbol *AsmPrinter::GetBlockAddressSymbol(const BasicBlock *BB) const { 2495 return MMI->getAddrLabelSymbol(BB); 2496 } 2497 2498 /// GetCPISymbol - Return the symbol for the specified constant pool entry. 2499 MCSymbol *AsmPrinter::GetCPISymbol(unsigned CPID) const { 2500 const DataLayout &DL = getDataLayout(); 2501 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2502 "CPI" + Twine(getFunctionNumber()) + "_" + 2503 Twine(CPID)); 2504 } 2505 2506 /// GetJTISymbol - Return the symbol for the specified jump table entry. 2507 MCSymbol *AsmPrinter::GetJTISymbol(unsigned JTID, bool isLinkerPrivate) const { 2508 return MF->getJTISymbol(JTID, OutContext, isLinkerPrivate); 2509 } 2510 2511 /// GetJTSetSymbol - Return the symbol for the specified jump table .set 2512 /// FIXME: privatize to AsmPrinter. 2513 MCSymbol *AsmPrinter::GetJTSetSymbol(unsigned UID, unsigned MBBID) const { 2514 const DataLayout &DL = getDataLayout(); 2515 return OutContext.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 2516 Twine(getFunctionNumber()) + "_" + 2517 Twine(UID) + "_set_" + Twine(MBBID)); 2518 } 2519 2520 MCSymbol *AsmPrinter::getSymbolWithGlobalValueBase(const GlobalValue *GV, 2521 StringRef Suffix) const { 2522 return getObjFileLowering().getSymbolWithGlobalValueBase(GV, Suffix, TM); 2523 } 2524 2525 /// Return the MCSymbol for the specified ExternalSymbol. 2526 MCSymbol *AsmPrinter::GetExternalSymbolSymbol(StringRef Sym) const { 2527 SmallString<60> NameStr; 2528 Mangler::getNameWithPrefix(NameStr, Sym, getDataLayout()); 2529 return OutContext.getOrCreateSymbol(NameStr); 2530 } 2531 2532 /// PrintParentLoopComment - Print comments about parent loops of this one. 2533 static void PrintParentLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2534 unsigned FunctionNumber) { 2535 if (!Loop) return; 2536 PrintParentLoopComment(OS, Loop->getParentLoop(), FunctionNumber); 2537 OS.indent(Loop->getLoopDepth()*2) 2538 << "Parent Loop BB" << FunctionNumber << "_" 2539 << Loop->getHeader()->getNumber() 2540 << " Depth=" << Loop->getLoopDepth() << '\n'; 2541 } 2542 2543 2544 /// PrintChildLoopComment - Print comments about child loops within 2545 /// the loop for this basic block, with nesting. 2546 static void PrintChildLoopComment(raw_ostream &OS, const MachineLoop *Loop, 2547 unsigned FunctionNumber) { 2548 // Add child loop information 2549 for (const MachineLoop *CL : *Loop) { 2550 OS.indent(CL->getLoopDepth()*2) 2551 << "Child Loop BB" << FunctionNumber << "_" 2552 << CL->getHeader()->getNumber() << " Depth " << CL->getLoopDepth() 2553 << '\n'; 2554 PrintChildLoopComment(OS, CL, FunctionNumber); 2555 } 2556 } 2557 2558 /// emitBasicBlockLoopComments - Pretty-print comments for basic blocks. 2559 static void emitBasicBlockLoopComments(const MachineBasicBlock &MBB, 2560 const MachineLoopInfo *LI, 2561 const AsmPrinter &AP) { 2562 // Add loop depth information 2563 const MachineLoop *Loop = LI->getLoopFor(&MBB); 2564 if (!Loop) return; 2565 2566 MachineBasicBlock *Header = Loop->getHeader(); 2567 assert(Header && "No header for loop"); 2568 2569 // If this block is not a loop header, just print out what is the loop header 2570 // and return. 2571 if (Header != &MBB) { 2572 AP.OutStreamer->AddComment(" in Loop: Header=BB" + 2573 Twine(AP.getFunctionNumber())+"_" + 2574 Twine(Loop->getHeader()->getNumber())+ 2575 " Depth="+Twine(Loop->getLoopDepth())); 2576 return; 2577 } 2578 2579 // Otherwise, it is a loop header. Print out information about child and 2580 // parent loops. 2581 raw_ostream &OS = AP.OutStreamer->GetCommentOS(); 2582 2583 PrintParentLoopComment(OS, Loop->getParentLoop(), AP.getFunctionNumber()); 2584 2585 OS << "=>"; 2586 OS.indent(Loop->getLoopDepth()*2-2); 2587 2588 OS << "This "; 2589 if (Loop->empty()) 2590 OS << "Inner "; 2591 OS << "Loop Header: Depth=" + Twine(Loop->getLoopDepth()) << '\n'; 2592 2593 PrintChildLoopComment(OS, Loop, AP.getFunctionNumber()); 2594 } 2595 2596 /// EmitBasicBlockStart - This method prints the label for the specified 2597 /// MachineBasicBlock, an alignment (if present) and a comment describing 2598 /// it if appropriate. 2599 void AsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const { 2600 // End the previous funclet and start a new one. 2601 if (MBB.isEHFuncletEntry()) { 2602 for (const HandlerInfo &HI : Handlers) { 2603 HI.Handler->endFunclet(); 2604 HI.Handler->beginFunclet(MBB); 2605 } 2606 } 2607 2608 // Emit an alignment directive for this block, if needed. 2609 if (unsigned Align = MBB.getAlignment()) 2610 EmitAlignment(Align); 2611 2612 // If the block has its address taken, emit any labels that were used to 2613 // reference the block. It is possible that there is more than one label 2614 // here, because multiple LLVM BB's may have been RAUW'd to this block after 2615 // the references were generated. 2616 if (MBB.hasAddressTaken()) { 2617 const BasicBlock *BB = MBB.getBasicBlock(); 2618 if (isVerbose()) 2619 OutStreamer->AddComment("Block address taken"); 2620 2621 // MBBs can have their address taken as part of CodeGen without having 2622 // their corresponding BB's address taken in IR 2623 if (BB->hasAddressTaken()) 2624 for (MCSymbol *Sym : MMI->getAddrLabelSymbolToEmit(BB)) 2625 OutStreamer->EmitLabel(Sym); 2626 } 2627 2628 // Print some verbose block comments. 2629 if (isVerbose()) { 2630 if (const BasicBlock *BB = MBB.getBasicBlock()) { 2631 if (BB->hasName()) { 2632 BB->printAsOperand(OutStreamer->GetCommentOS(), 2633 /*PrintType=*/false, BB->getModule()); 2634 OutStreamer->GetCommentOS() << '\n'; 2635 } 2636 } 2637 emitBasicBlockLoopComments(MBB, LI, *this); 2638 } 2639 2640 // Print the main label for the block. 2641 if (MBB.pred_empty() || 2642 (isBlockOnlyReachableByFallthrough(&MBB) && !MBB.isEHFuncletEntry())) { 2643 if (isVerbose()) { 2644 // NOTE: Want this comment at start of line, don't emit with AddComment. 2645 OutStreamer->emitRawComment(" BB#" + Twine(MBB.getNumber()) + ":", false); 2646 } 2647 } else { 2648 OutStreamer->EmitLabel(MBB.getSymbol()); 2649 } 2650 } 2651 2652 void AsmPrinter::EmitVisibility(MCSymbol *Sym, unsigned Visibility, 2653 bool IsDefinition) const { 2654 MCSymbolAttr Attr = MCSA_Invalid; 2655 2656 switch (Visibility) { 2657 default: break; 2658 case GlobalValue::HiddenVisibility: 2659 if (IsDefinition) 2660 Attr = MAI->getHiddenVisibilityAttr(); 2661 else 2662 Attr = MAI->getHiddenDeclarationVisibilityAttr(); 2663 break; 2664 case GlobalValue::ProtectedVisibility: 2665 Attr = MAI->getProtectedVisibilityAttr(); 2666 break; 2667 } 2668 2669 if (Attr != MCSA_Invalid) 2670 OutStreamer->EmitSymbolAttribute(Sym, Attr); 2671 } 2672 2673 /// isBlockOnlyReachableByFallthough - Return true if the basic block has 2674 /// exactly one predecessor and the control transfer mechanism between 2675 /// the predecessor and this block is a fall-through. 2676 bool AsmPrinter:: 2677 isBlockOnlyReachableByFallthrough(const MachineBasicBlock *MBB) const { 2678 // If this is a landing pad, it isn't a fall through. If it has no preds, 2679 // then nothing falls through to it. 2680 if (MBB->isEHPad() || MBB->pred_empty()) 2681 return false; 2682 2683 // If there isn't exactly one predecessor, it can't be a fall through. 2684 if (MBB->pred_size() > 1) 2685 return false; 2686 2687 // The predecessor has to be immediately before this block. 2688 MachineBasicBlock *Pred = *MBB->pred_begin(); 2689 if (!Pred->isLayoutSuccessor(MBB)) 2690 return false; 2691 2692 // If the block is completely empty, then it definitely does fall through. 2693 if (Pred->empty()) 2694 return true; 2695 2696 // Check the terminators in the previous blocks 2697 for (const auto &MI : Pred->terminators()) { 2698 // If it is not a simple branch, we are in a table somewhere. 2699 if (!MI.isBranch() || MI.isIndirectBranch()) 2700 return false; 2701 2702 // If we are the operands of one of the branches, this is not a fall 2703 // through. Note that targets with delay slots will usually bundle 2704 // terminators with the delay slot instruction. 2705 for (ConstMIBundleOperands OP(MI); OP.isValid(); ++OP) { 2706 if (OP->isJTI()) 2707 return false; 2708 if (OP->isMBB() && OP->getMBB() == MBB) 2709 return false; 2710 } 2711 } 2712 2713 return true; 2714 } 2715 2716 GCMetadataPrinter *AsmPrinter::GetOrCreateGCPrinter(GCStrategy &S) { 2717 if (!S.usesMetadata()) 2718 return nullptr; 2719 2720 assert(!S.useStatepoints() && "statepoints do not currently support custom" 2721 " stackmap formats, please see the documentation for a description of" 2722 " the default format. If you really need a custom serialized format," 2723 " please file a bug"); 2724 2725 gcp_map_type &GCMap = getGCMap(GCMetadataPrinters); 2726 gcp_map_type::iterator GCPI = GCMap.find(&S); 2727 if (GCPI != GCMap.end()) 2728 return GCPI->second.get(); 2729 2730 auto Name = S.getName(); 2731 2732 for (GCMetadataPrinterRegistry::iterator 2733 I = GCMetadataPrinterRegistry::begin(), 2734 E = GCMetadataPrinterRegistry::end(); I != E; ++I) 2735 if (Name == I->getName()) { 2736 std::unique_ptr<GCMetadataPrinter> GMP = I->instantiate(); 2737 GMP->S = &S; 2738 auto IterBool = GCMap.insert(std::make_pair(&S, std::move(GMP))); 2739 return IterBool.first->second.get(); 2740 } 2741 2742 report_fatal_error("no GCMetadataPrinter registered for GC: " + Twine(Name)); 2743 } 2744 2745 /// Pin vtable to this file. 2746 AsmPrinterHandler::~AsmPrinterHandler() = default; 2747 2748 void AsmPrinterHandler::markFunctionEnd() {} 2749 2750 // In the binary's "xray_instr_map" section, an array of these function entries 2751 // describes each instrumentation point. When XRay patches your code, the index 2752 // into this table will be given to your handler as a patch point identifier. 2753 void AsmPrinter::XRayFunctionEntry::emit(int Bytes, MCStreamer *Out, 2754 const MCSymbol *CurrentFnSym) const { 2755 Out->EmitSymbolValue(Sled, Bytes); 2756 Out->EmitSymbolValue(CurrentFnSym, Bytes); 2757 auto Kind8 = static_cast<uint8_t>(Kind); 2758 Out->EmitBytes(StringRef(reinterpret_cast<const char *>(&Kind8), 1)); 2759 Out->EmitBytes( 2760 StringRef(reinterpret_cast<const char *>(&AlwaysInstrument), 1)); 2761 Out->EmitZeros(2 * Bytes - 2); // Pad the previous two entries 2762 } 2763 2764 void AsmPrinter::emitXRayTable() { 2765 if (Sleds.empty()) 2766 return; 2767 2768 auto PrevSection = OutStreamer->getCurrentSectionOnly(); 2769 auto Fn = MF->getFunction(); 2770 MCSection *InstMap = nullptr; 2771 MCSection *FnSledIndex = nullptr; 2772 if (MF->getSubtarget().getTargetTriple().isOSBinFormatELF()) { 2773 if (Fn->hasComdat()) { 2774 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, 2775 ELF::SHF_ALLOC | ELF::SHF_GROUP, 0, 2776 Fn->getComdat()->getName()); 2777 FnSledIndex = OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, 2778 ELF::SHF_ALLOC | ELF::SHF_GROUP, 0, 2779 Fn->getComdat()->getName()); 2780 } else { 2781 InstMap = OutContext.getELFSection("xray_instr_map", ELF::SHT_PROGBITS, 2782 ELF::SHF_ALLOC); 2783 FnSledIndex = OutContext.getELFSection("xray_fn_idx", ELF::SHT_PROGBITS, 2784 ELF::SHF_ALLOC); 2785 } 2786 } else if (MF->getSubtarget().getTargetTriple().isOSBinFormatMachO()) { 2787 InstMap = OutContext.getMachOSection("__DATA", "xray_instr_map", 0, 2788 SectionKind::getReadOnlyWithRel()); 2789 FnSledIndex = OutContext.getMachOSection("__DATA", "xray_fn_idx", 0, 2790 SectionKind::getReadOnlyWithRel()); 2791 } else { 2792 llvm_unreachable("Unsupported target"); 2793 } 2794 2795 // Before we switch over, we force a reference to a label inside the 2796 // xray_instr_map and xray_fn_idx sections. Since this function is always 2797 // called just before the function's end, we assume that this is happening 2798 // after the last return instruction. We also use the synthetic label in the 2799 // xray_inster_map as a delimeter for the range of sleds for this function in 2800 // the index. 2801 auto WordSizeBytes = MAI->getCodePointerSize(); 2802 MCSymbol *SledsStart = OutContext.createTempSymbol("xray_synthetic_", true); 2803 MCSymbol *IdxRef = OutContext.createTempSymbol("xray_fn_idx_synth_", true); 2804 OutStreamer->EmitCodeAlignment(16); 2805 OutStreamer->EmitSymbolValue(SledsStart, WordSizeBytes, false); 2806 OutStreamer->EmitSymbolValue(IdxRef, WordSizeBytes, false); 2807 2808 // Now we switch to the instrumentation map section. Because this is done 2809 // per-function, we are able to create an index entry that will represent the 2810 // range of sleds associated with a function. 2811 OutStreamer->SwitchSection(InstMap); 2812 OutStreamer->EmitLabel(SledsStart); 2813 for (const auto &Sled : Sleds) 2814 Sled.emit(WordSizeBytes, OutStreamer.get(), CurrentFnSym); 2815 MCSymbol *SledsEnd = OutContext.createTempSymbol("xray_synthetic_end", true); 2816 OutStreamer->EmitLabel(SledsEnd); 2817 2818 // We then emit a single entry in the index per function. We use the symbols 2819 // that bound the instrumentation map as the range for a specific function. 2820 // Each entry here will be 2 * word size aligned, as we're writing down two 2821 // pointers. This should work for both 32-bit and 64-bit platforms. 2822 OutStreamer->SwitchSection(FnSledIndex); 2823 OutStreamer->EmitCodeAlignment(2 * WordSizeBytes); 2824 OutStreamer->EmitLabel(IdxRef); 2825 OutStreamer->EmitSymbolValue(SledsStart, WordSizeBytes); 2826 OutStreamer->EmitSymbolValue(SledsEnd, WordSizeBytes); 2827 OutStreamer->SwitchSection(PrevSection); 2828 Sleds.clear(); 2829 } 2830 2831 void AsmPrinter::recordSled(MCSymbol *Sled, const MachineInstr &MI, 2832 SledKind Kind) { 2833 auto Fn = MI.getParent()->getParent()->getFunction(); 2834 auto Attr = Fn->getFnAttribute("function-instrument"); 2835 bool LogArgs = Fn->hasFnAttribute("xray-log-args"); 2836 bool AlwaysInstrument = 2837 Attr.isStringAttribute() && Attr.getValueAsString() == "xray-always"; 2838 if (Kind == SledKind::FUNCTION_ENTER && LogArgs) 2839 Kind = SledKind::LOG_ARGS_ENTER; 2840 Sleds.emplace_back( 2841 XRayFunctionEntry{ Sled, CurrentFnSym, Kind, AlwaysInstrument, Fn }); 2842 } 2843 2844 uint16_t AsmPrinter::getDwarfVersion() const { 2845 return OutStreamer->getContext().getDwarfVersion(); 2846 } 2847 2848 void AsmPrinter::setDwarfVersion(uint16_t Version) { 2849 OutStreamer->getContext().setDwarfVersion(Version); 2850 } 2851