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