1 //===- LTO.cpp ------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "LTO.h" 10 #include "Config.h" 11 #include "InputFiles.h" 12 #include "LinkerScript.h" 13 #include "SymbolTable.h" 14 #include "Symbols.h" 15 #include "lld/Common/Args.h" 16 #include "lld/Common/ErrorHandler.h" 17 #include "lld/Common/TargetOptionsCommandFlags.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallString.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/ADT/Twine.h" 22 #include "llvm/BinaryFormat/ELF.h" 23 #include "llvm/Bitcode/BitcodeReader.h" 24 #include "llvm/Bitcode/BitcodeWriter.h" 25 #include "llvm/IR/DiagnosticPrinter.h" 26 #include "llvm/LTO/Caching.h" 27 #include "llvm/LTO/Config.h" 28 #include "llvm/LTO/LTO.h" 29 #include "llvm/Object/SymbolicFile.h" 30 #include "llvm/Support/CodeGen.h" 31 #include "llvm/Support/Error.h" 32 #include "llvm/Support/FileSystem.h" 33 #include "llvm/Support/MemoryBuffer.h" 34 #include <algorithm> 35 #include <cstddef> 36 #include <memory> 37 #include <string> 38 #include <system_error> 39 #include <vector> 40 41 using namespace llvm; 42 using namespace llvm::object; 43 using namespace llvm::ELF; 44 45 using namespace lld; 46 using namespace lld::elf; 47 48 // Creates an empty file to store a list of object files for final 49 // linking of distributed ThinLTO. 50 static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) { 51 std::error_code ec; 52 auto ret = 53 std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None); 54 if (ec) { 55 error("cannot open " + file + ": " + ec.message()); 56 return nullptr; 57 } 58 return ret; 59 } 60 61 static std::string getThinLTOOutputFile(StringRef modulePath) { 62 return lto::getThinLTOOutputFile(modulePath, 63 config->thinLTOPrefixReplace.first, 64 config->thinLTOPrefixReplace.second); 65 } 66 67 static lto::Config createConfig() { 68 lto::Config c; 69 70 // LLD supports the new relocations and address-significance tables. 71 c.Options = initTargetOptionsFromCodeGenFlags(); 72 c.Options.RelaxELFRelocations = true; 73 c.Options.EmitAddrsig = true; 74 75 // Always emit a section per function/datum with LTO. 76 c.Options.FunctionSections = true; 77 c.Options.DataSections = true; 78 79 if (auto relocModel = getRelocModelFromCMModel()) 80 c.RelocModel = *relocModel; 81 else if (config->relocatable) 82 c.RelocModel = None; 83 else if (config->isPic) 84 c.RelocModel = Reloc::PIC_; 85 else 86 c.RelocModel = Reloc::Static; 87 88 c.CodeModel = getCodeModelFromCMModel(); 89 c.DisableVerify = config->disableVerify; 90 c.DiagHandler = diagnosticHandler; 91 c.OptLevel = config->ltoo; 92 c.CPU = getCPUStr(); 93 c.MAttrs = getMAttrs(); 94 c.CGOptLevel = args::getCGOptLevel(config->ltoo); 95 96 // Set up a custom pipeline if we've been asked to. 97 c.OptPipeline = config->ltoNewPmPasses; 98 c.AAPipeline = config->ltoAAPipeline; 99 100 // Set up optimization remarks if we've been asked to. 101 c.RemarksFilename = config->optRemarksFilename; 102 c.RemarksPasses = config->optRemarksPasses; 103 c.RemarksWithHotness = config->optRemarksWithHotness; 104 c.RemarksFormat = config->optRemarksFormat; 105 106 c.SampleProfile = config->ltoSampleProfile; 107 c.UseNewPM = config->ltoNewPassManager; 108 c.DebugPassManager = config->ltoDebugPassManager; 109 c.DwoDir = config->dwoDir; 110 111 c.CSIRProfile = config->ltoCSProfileFile; 112 c.RunCSIRInstr = config->ltoCSProfileGenerate; 113 114 if (config->emitLLVM) { 115 c.PostInternalizeModuleHook = [](size_t task, const Module &m) { 116 if (std::unique_ptr<raw_fd_ostream> os = openFile(config->outputFile)) 117 WriteBitcodeToFile(m, *os, false); 118 return false; 119 }; 120 } 121 122 if (config->saveTemps) 123 checkError(c.addSaveTemps(config->outputFile.str() + ".", 124 /*UseInputModulePath*/ true)); 125 return c; 126 } 127 128 BitcodeCompiler::BitcodeCompiler() { 129 // Initialize indexFile. 130 if (!config->thinLTOIndexOnlyArg.empty()) 131 indexFile = openFile(config->thinLTOIndexOnlyArg); 132 133 // Initialize ltoObj. 134 lto::ThinBackend backend; 135 if (config->thinLTOIndexOnly) { 136 auto onIndexWrite = [&](StringRef s) { thinIndices.erase(s); }; 137 backend = lto::createWriteIndexesThinBackend( 138 config->thinLTOPrefixReplace.first, config->thinLTOPrefixReplace.second, 139 config->thinLTOEmitImportsFiles, indexFile.get(), onIndexWrite); 140 } else if (config->thinLTOJobs != -1U) { 141 backend = lto::createInProcessThinBackend(config->thinLTOJobs); 142 } 143 144 ltoObj = std::make_unique<lto::LTO>(createConfig(), backend, 145 config->ltoPartitions); 146 147 // Initialize usedStartStop. 148 symtab->forEachSymbol([&](Symbol *sym) { 149 StringRef s = sym->getName(); 150 for (StringRef prefix : {"__start_", "__stop_"}) 151 if (s.startswith(prefix)) 152 usedStartStop.insert(s.substr(prefix.size())); 153 }); 154 } 155 156 BitcodeCompiler::~BitcodeCompiler() = default; 157 158 void BitcodeCompiler::add(BitcodeFile &f) { 159 lto::InputFile &obj = *f.obj; 160 bool isExec = !config->shared && !config->relocatable; 161 162 if (config->thinLTOIndexOnly) 163 thinIndices.insert(obj.getName()); 164 165 ArrayRef<Symbol *> syms = f.getSymbols(); 166 ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols(); 167 std::vector<lto::SymbolResolution> resols(syms.size()); 168 169 // Provide a resolution to the LTO API for each symbol. 170 for (size_t i = 0, e = syms.size(); i != e; ++i) { 171 Symbol *sym = syms[i]; 172 const lto::InputFile::Symbol &objSym = objSyms[i]; 173 lto::SymbolResolution &r = resols[i]; 174 175 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile 176 // reports two symbols for module ASM defined. Without this check, lld 177 // flags an undefined in IR with a definition in ASM as prevailing. 178 // Once IRObjectFile is fixed to report only one symbol this hack can 179 // be removed. 180 r.Prevailing = !objSym.isUndefined() && sym->file == &f; 181 182 // We ask LTO to preserve following global symbols: 183 // 1) All symbols when doing relocatable link, so that them can be used 184 // for doing final link. 185 // 2) Symbols that are used in regular objects. 186 // 3) C named sections if we have corresponding __start_/__stop_ symbol. 187 // 4) Symbols that are defined in bitcode files and used for dynamic linking. 188 r.VisibleToRegularObj = config->relocatable || sym->isUsedInRegularObj || 189 (r.Prevailing && sym->includeInDynsym()) || 190 usedStartStop.count(objSym.getSectionName()); 191 const auto *dr = dyn_cast<Defined>(sym); 192 r.FinalDefinitionInLinkageUnit = 193 (isExec || sym->visibility != STV_DEFAULT) && dr && 194 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations 195 // will be generated by for them, triggering linker errors. 196 // Symbol section is always null for bitcode symbols, hence the check 197 // for isElf(). Skip linker script defined symbols as well: they have 198 // no File defined. 199 !(dr->section == nullptr && (!sym->file || sym->file->isElf())); 200 201 if (r.Prevailing) 202 sym->replace(Undefined{nullptr, sym->getName(), STB_GLOBAL, STV_DEFAULT, 203 sym->type}); 204 205 // We tell LTO to not apply interprocedural optimization for wrapped 206 // (with --wrap) symbols because otherwise LTO would inline them while 207 // their values are still not final. 208 r.LinkerRedefined = !sym->canInline; 209 } 210 checkError(ltoObj->add(std::move(f.obj), resols)); 211 } 212 213 // If LazyObjFile has not been added to link, emit empty index files. 214 // This is needed because this is what GNU gold plugin does and we have a 215 // distributed build system that depends on that behavior. 216 static void thinLTOCreateEmptyIndexFiles() { 217 for (LazyObjFile *f : lazyObjFiles) { 218 if (!isBitcode(f->mb)) 219 continue; 220 std::string path = replaceThinLTOSuffix(getThinLTOOutputFile(f->getName())); 221 std::unique_ptr<raw_fd_ostream> os = openFile(path + ".thinlto.bc"); 222 if (!os) 223 continue; 224 225 ModuleSummaryIndex m(/*HaveGVs*/ false); 226 m.setSkipModuleByDistributedBackend(); 227 WriteIndexToFile(m, *os); 228 if (config->thinLTOEmitImportsFiles) 229 openFile(path + ".imports"); 230 } 231 } 232 233 // Merge all the bitcode files we have seen, codegen the result 234 // and return the resulting ObjectFile(s). 235 std::vector<InputFile *> BitcodeCompiler::compile() { 236 unsigned maxTasks = ltoObj->getMaxTasks(); 237 buf.resize(maxTasks); 238 files.resize(maxTasks); 239 240 // The --thinlto-cache-dir option specifies the path to a directory in which 241 // to cache native object files for ThinLTO incremental builds. If a path was 242 // specified, configure LTO to use it as the cache directory. 243 lto::NativeObjectCache cache; 244 if (!config->thinLTOCacheDir.empty()) 245 cache = check( 246 lto::localCache(config->thinLTOCacheDir, 247 [&](size_t task, std::unique_ptr<MemoryBuffer> mb) { 248 files[task] = std::move(mb); 249 })); 250 251 if (!bitcodeFiles.empty()) 252 checkError(ltoObj->run( 253 [&](size_t task) { 254 return std::make_unique<lto::NativeObjectStream>( 255 std::make_unique<raw_svector_ostream>(buf[task])); 256 }, 257 cache)); 258 259 // Emit empty index files for non-indexed files 260 for (StringRef s : thinIndices) { 261 std::string path = getThinLTOOutputFile(s); 262 openFile(path + ".thinlto.bc"); 263 if (config->thinLTOEmitImportsFiles) 264 openFile(path + ".imports"); 265 } 266 267 if (config->thinLTOIndexOnly) { 268 thinLTOCreateEmptyIndexFiles(); 269 270 if (!config->ltoObjPath.empty()) 271 saveBuffer(buf[0], config->ltoObjPath); 272 273 // ThinLTO with index only option is required to generate only the index 274 // files. After that, we exit from linker and ThinLTO backend runs in a 275 // distributed environment. 276 if (indexFile) 277 indexFile->close(); 278 return {}; 279 } 280 281 if (!config->thinLTOCacheDir.empty()) 282 pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy); 283 284 if (!config->ltoObjPath.empty()) { 285 saveBuffer(buf[0], config->ltoObjPath); 286 for (unsigned i = 1; i != maxTasks; ++i) 287 saveBuffer(buf[i], config->ltoObjPath + Twine(i)); 288 } 289 290 if (config->saveTemps) { 291 saveBuffer(buf[0], config->outputFile + ".lto.o"); 292 for (unsigned i = 1; i != maxTasks; ++i) 293 saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o"); 294 } 295 296 std::vector<InputFile *> ret; 297 for (unsigned i = 0; i != maxTasks; ++i) 298 if (!buf[i].empty()) 299 ret.push_back(createObjectFile(MemoryBufferRef(buf[i], "lto.tmp"))); 300 301 for (std::unique_ptr<MemoryBuffer> &file : files) 302 if (file) 303 ret.push_back(createObjectFile(*file)); 304 return ret; 305 } 306