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