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