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