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 using namespace lld; 45 using namespace lld::elf; 46 47 // Creates an empty file to store a list of object files for final 48 // linking of distributed ThinLTO. 49 static std::unique_ptr<raw_fd_ostream> openFile(StringRef file) { 50 std::error_code ec; 51 auto ret = 52 std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None); 53 if (ec) { 54 error("cannot open " + file + ": " + ec.message()); 55 return nullptr; 56 } 57 return ret; 58 } 59 60 static std::string getThinLTOOutputFile(StringRef modulePath) { 61 return lto::getThinLTOOutputFile( 62 std::string(modulePath), std::string(config->thinLTOPrefixReplace.first), 63 std::string(config->thinLTOPrefixReplace.second)); 64 } 65 66 static lto::Config createConfig() { 67 lto::Config c; 68 69 // LLD supports the new relocations and address-significance tables. 70 c.Options = initTargetOptionsFromCodeGenFlags(); 71 c.Options.RelaxELFRelocations = true; 72 c.Options.EmitAddrsig = true; 73 74 // Always emit a section per function/datum with LTO. 75 c.Options.FunctionSections = true; 76 c.Options.DataSections = true; 77 78 // Check if basic block sections must be used. 79 // Allowed values for --lto-basicblock-sections are "all", "labels", 80 // "<file name specifying basic block ids>", or none. This is the equivalent 81 // of -fbasicblock-sections= flag in clang. 82 if (!config->ltoBasicBlockSections.empty()) { 83 if (config->ltoBasicBlockSections == "all") { 84 c.Options.BBSections = BasicBlockSection::All; 85 } else if (config->ltoBasicBlockSections == "labels") { 86 c.Options.BBSections = BasicBlockSection::Labels; 87 } else if (config->ltoBasicBlockSections == "none") { 88 c.Options.BBSections = BasicBlockSection::None; 89 } else { 90 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = 91 MemoryBuffer::getFile(config->ltoBasicBlockSections.str()); 92 if (!MBOrErr) { 93 error("cannot open " + config->ltoBasicBlockSections + ":" + 94 MBOrErr.getError().message()); 95 } else { 96 c.Options.BBSectionsFuncListBuf = std::move(*MBOrErr); 97 } 98 c.Options.BBSections = BasicBlockSection::List; 99 } 100 } 101 102 c.Options.UniqueBBSectionNames = config->ltoUniqueBBSectionNames; 103 104 if (auto relocModel = getRelocModelFromCMModel()) 105 c.RelocModel = *relocModel; 106 else if (config->relocatable) 107 c.RelocModel = None; 108 else if (config->isPic) 109 c.RelocModel = Reloc::PIC_; 110 else 111 c.RelocModel = Reloc::Static; 112 113 c.CodeModel = getCodeModelFromCMModel(); 114 c.DisableVerify = config->disableVerify; 115 c.DiagHandler = diagnosticHandler; 116 c.OptLevel = config->ltoo; 117 c.CPU = getCPUStr(); 118 c.MAttrs = getMAttrs(); 119 c.CGOptLevel = args::getCGOptLevel(config->ltoo); 120 121 c.PTO.LoopVectorization = c.OptLevel > 1; 122 c.PTO.SLPVectorization = c.OptLevel > 1; 123 124 // Set up a custom pipeline if we've been asked to. 125 c.OptPipeline = std::string(config->ltoNewPmPasses); 126 c.AAPipeline = std::string(config->ltoAAPipeline); 127 128 // Set up optimization remarks if we've been asked to. 129 c.RemarksFilename = std::string(config->optRemarksFilename); 130 c.RemarksPasses = std::string(config->optRemarksPasses); 131 c.RemarksWithHotness = config->optRemarksWithHotness; 132 c.RemarksFormat = std::string(config->optRemarksFormat); 133 134 c.SampleProfile = std::string(config->ltoSampleProfile); 135 c.UseNewPM = config->ltoNewPassManager; 136 c.DebugPassManager = config->ltoDebugPassManager; 137 c.DwoDir = std::string(config->dwoDir); 138 139 c.HasWholeProgramVisibility = config->ltoWholeProgramVisibility; 140 c.AlwaysEmitRegularLTOObj = !config->ltoObjPath.empty(); 141 142 c.TimeTraceEnabled = config->timeTraceEnabled; 143 c.TimeTraceGranularity = config->timeTraceGranularity; 144 145 c.CSIRProfile = std::string(config->ltoCSProfileFile); 146 c.RunCSIRInstr = config->ltoCSProfileGenerate; 147 148 if (config->emitLLVM) { 149 c.PostInternalizeModuleHook = [](size_t task, const Module &m) { 150 if (std::unique_ptr<raw_fd_ostream> os = openFile(config->outputFile)) 151 WriteBitcodeToFile(m, *os, false); 152 return false; 153 }; 154 } 155 156 if (config->ltoEmitAsm) 157 c.CGFileType = CGFT_AssemblyFile; 158 159 if (config->saveTemps) 160 checkError(c.addSaveTemps(config->outputFile.str() + ".", 161 /*UseInputModulePath*/ true)); 162 return c; 163 } 164 165 BitcodeCompiler::BitcodeCompiler() { 166 // Initialize indexFile. 167 if (!config->thinLTOIndexOnlyArg.empty()) 168 indexFile = openFile(config->thinLTOIndexOnlyArg); 169 170 // Initialize ltoObj. 171 lto::ThinBackend backend; 172 if (config->thinLTOIndexOnly) { 173 auto onIndexWrite = [&](StringRef s) { thinIndices.erase(s); }; 174 backend = lto::createWriteIndexesThinBackend( 175 std::string(config->thinLTOPrefixReplace.first), 176 std::string(config->thinLTOPrefixReplace.second), 177 config->thinLTOEmitImportsFiles, indexFile.get(), onIndexWrite); 178 } else { 179 backend = lto::createInProcessThinBackend( 180 llvm::heavyweight_hardware_concurrency(config->thinLTOJobs)); 181 } 182 183 ltoObj = std::make_unique<lto::LTO>(createConfig(), backend, 184 config->ltoPartitions); 185 186 // Initialize usedStartStop. 187 for (Symbol *sym : symtab->symbols()) { 188 StringRef s = sym->getName(); 189 for (StringRef prefix : {"__start_", "__stop_"}) 190 if (s.startswith(prefix)) 191 usedStartStop.insert(s.substr(prefix.size())); 192 } 193 } 194 195 BitcodeCompiler::~BitcodeCompiler() = default; 196 197 void BitcodeCompiler::add(BitcodeFile &f) { 198 lto::InputFile &obj = *f.obj; 199 bool isExec = !config->shared && !config->relocatable; 200 201 if (config->thinLTOIndexOnly) 202 thinIndices.insert(obj.getName()); 203 204 ArrayRef<Symbol *> syms = f.getSymbols(); 205 ArrayRef<lto::InputFile::Symbol> objSyms = obj.symbols(); 206 std::vector<lto::SymbolResolution> resols(syms.size()); 207 208 // Provide a resolution to the LTO API for each symbol. 209 for (size_t i = 0, e = syms.size(); i != e; ++i) { 210 Symbol *sym = syms[i]; 211 const lto::InputFile::Symbol &objSym = objSyms[i]; 212 lto::SymbolResolution &r = resols[i]; 213 214 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile 215 // reports two symbols for module ASM defined. Without this check, lld 216 // flags an undefined in IR with a definition in ASM as prevailing. 217 // Once IRObjectFile is fixed to report only one symbol this hack can 218 // be removed. 219 r.Prevailing = !objSym.isUndefined() && sym->file == &f; 220 221 // We ask LTO to preserve following global symbols: 222 // 1) All symbols when doing relocatable link, so that them can be used 223 // for doing final link. 224 // 2) Symbols that are used in regular objects. 225 // 3) C named sections if we have corresponding __start_/__stop_ symbol. 226 // 4) Symbols that are defined in bitcode files and used for dynamic linking. 227 r.VisibleToRegularObj = config->relocatable || sym->isUsedInRegularObj || 228 (r.Prevailing && sym->includeInDynsym()) || 229 usedStartStop.count(objSym.getSectionName()); 230 const auto *dr = dyn_cast<Defined>(sym); 231 r.FinalDefinitionInLinkageUnit = 232 (isExec || sym->visibility != STV_DEFAULT) && dr && 233 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations 234 // will be generated by for them, triggering linker errors. 235 // Symbol section is always null for bitcode symbols, hence the check 236 // for isElf(). Skip linker script defined symbols as well: they have 237 // no File defined. 238 !(dr->section == nullptr && (!sym->file || sym->file->isElf())); 239 240 if (r.Prevailing) 241 sym->replace(Undefined{nullptr, sym->getName(), STB_GLOBAL, STV_DEFAULT, 242 sym->type}); 243 244 // We tell LTO to not apply interprocedural optimization for wrapped 245 // (with --wrap) symbols because otherwise LTO would inline them while 246 // their values are still not final. 247 r.LinkerRedefined = !sym->canInline; 248 } 249 checkError(ltoObj->add(std::move(f.obj), resols)); 250 } 251 252 // If LazyObjFile has not been added to link, emit empty index files. 253 // This is needed because this is what GNU gold plugin does and we have a 254 // distributed build system that depends on that behavior. 255 static void thinLTOCreateEmptyIndexFiles() { 256 for (LazyObjFile *f : lazyObjFiles) { 257 if (!isBitcode(f->mb)) 258 continue; 259 std::string path = replaceThinLTOSuffix(getThinLTOOutputFile(f->getName())); 260 std::unique_ptr<raw_fd_ostream> os = openFile(path + ".thinlto.bc"); 261 if (!os) 262 continue; 263 264 ModuleSummaryIndex m(/*HaveGVs*/ false); 265 m.setSkipModuleByDistributedBackend(); 266 WriteIndexToFile(m, *os); 267 if (config->thinLTOEmitImportsFiles) 268 openFile(path + ".imports"); 269 } 270 } 271 272 // Merge all the bitcode files we have seen, codegen the result 273 // and return the resulting ObjectFile(s). 274 std::vector<InputFile *> BitcodeCompiler::compile() { 275 unsigned maxTasks = ltoObj->getMaxTasks(); 276 buf.resize(maxTasks); 277 files.resize(maxTasks); 278 279 // The --thinlto-cache-dir option specifies the path to a directory in which 280 // to cache native object files for ThinLTO incremental builds. If a path was 281 // specified, configure LTO to use it as the cache directory. 282 lto::NativeObjectCache cache; 283 if (!config->thinLTOCacheDir.empty()) 284 cache = check( 285 lto::localCache(config->thinLTOCacheDir, 286 [&](size_t task, std::unique_ptr<MemoryBuffer> mb) { 287 files[task] = std::move(mb); 288 })); 289 290 if (!bitcodeFiles.empty()) 291 checkError(ltoObj->run( 292 [&](size_t task) { 293 return std::make_unique<lto::NativeObjectStream>( 294 std::make_unique<raw_svector_ostream>(buf[task])); 295 }, 296 cache)); 297 298 // Emit empty index files for non-indexed files 299 for (StringRef s : thinIndices) { 300 std::string path = getThinLTOOutputFile(s); 301 openFile(path + ".thinlto.bc"); 302 if (config->thinLTOEmitImportsFiles) 303 openFile(path + ".imports"); 304 } 305 306 if (config->thinLTOIndexOnly) { 307 thinLTOCreateEmptyIndexFiles(); 308 309 if (!config->ltoObjPath.empty()) 310 saveBuffer(buf[0], config->ltoObjPath); 311 312 // ThinLTO with index only option is required to generate only the index 313 // files. After that, we exit from linker and ThinLTO backend runs in a 314 // distributed environment. 315 if (indexFile) 316 indexFile->close(); 317 return {}; 318 } 319 320 if (!config->thinLTOCacheDir.empty()) 321 pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy); 322 323 if (!config->ltoObjPath.empty()) { 324 saveBuffer(buf[0], config->ltoObjPath); 325 for (unsigned i = 1; i != maxTasks; ++i) 326 saveBuffer(buf[i], config->ltoObjPath + Twine(i)); 327 } 328 329 if (config->saveTemps) { 330 if (!buf[0].empty()) 331 saveBuffer(buf[0], config->outputFile + ".lto.o"); 332 for (unsigned i = 1; i != maxTasks; ++i) 333 saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o"); 334 } 335 336 if (config->ltoEmitAsm) { 337 saveBuffer(buf[0], config->outputFile); 338 for (unsigned i = 1; i != maxTasks; ++i) 339 saveBuffer(buf[i], config->outputFile + Twine(i)); 340 return {}; 341 } 342 343 std::vector<InputFile *> ret; 344 for (unsigned i = 0; i != maxTasks; ++i) 345 if (!buf[i].empty()) 346 ret.push_back(createObjectFile(MemoryBufferRef(buf[i], "lto.tmp"))); 347 348 for (std::unique_ptr<MemoryBuffer> &file : files) 349 if (file) 350 ret.push_back(createObjectFile(*file)); 351 return ret; 352 } 353