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