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