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