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