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 "Driver.h" 12 #include "InputFiles.h" 13 #include "Symbols.h" 14 #include "Target.h" 15 16 #include "lld/Common/Args.h" 17 #include "lld/Common/CommonLinkerContext.h" 18 #include "lld/Common/Strings.h" 19 #include "lld/Common/TargetOptionsCommandFlags.h" 20 #include "llvm/LTO/Config.h" 21 #include "llvm/LTO/LTO.h" 22 #include "llvm/Support/Caching.h" 23 #include "llvm/Support/FileSystem.h" 24 #include "llvm/Support/Path.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Transforms/ObjCARC.h" 27 28 using namespace lld; 29 using namespace lld::macho; 30 using namespace llvm; 31 using namespace llvm::MachO; 32 using namespace llvm::sys; 33 34 static lto::Config createConfig() { 35 lto::Config c; 36 c.Options = initTargetOptionsFromCodeGenFlags(); 37 c.CodeModel = getCodeModelFromCMModel(); 38 c.CPU = getCPUStr(); 39 c.MAttrs = getMAttrs(); 40 c.DiagHandler = diagnosticHandler; 41 c.UseNewPM = config->ltoNewPassManager; 42 c.PreCodeGenPassesHook = [](legacy::PassManager &pm) { 43 pm.add(createObjCARCContractPass()); 44 }; 45 c.TimeTraceEnabled = config->timeTraceEnabled; 46 c.TimeTraceGranularity = config->timeTraceGranularity; 47 c.OptLevel = config->ltoo; 48 c.CGOptLevel = args::getCGOptLevel(config->ltoo); 49 if (config->saveTemps) 50 checkError(c.addSaveTemps(config->outputFile.str() + ".", 51 /*UseInputModulePath=*/true)); 52 return c; 53 } 54 55 BitcodeCompiler::BitcodeCompiler() { 56 lto::ThinBackend backend = lto::createInProcessThinBackend( 57 heavyweight_hardware_concurrency(config->thinLTOJobs)); 58 ltoObj = std::make_unique<lto::LTO>(createConfig(), backend); 59 } 60 61 void BitcodeCompiler::add(BitcodeFile &f) { 62 ArrayRef<lto::InputFile::Symbol> objSyms = f.obj->symbols(); 63 std::vector<lto::SymbolResolution> resols; 64 resols.reserve(objSyms.size()); 65 66 // Provide a resolution to the LTO API for each symbol. 67 auto symIt = f.symbols.begin(); 68 for (const lto::InputFile::Symbol &objSym : objSyms) { 69 resols.emplace_back(); 70 lto::SymbolResolution &r = resols.back(); 71 Symbol *sym = *symIt++; 72 73 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile 74 // reports two symbols for module ASM defined. Without this check, lld 75 // flags an undefined in IR with a definition in ASM as prevailing. 76 // Once IRObjectFile is fixed to report only one symbol this hack can 77 // be removed. 78 r.Prevailing = !objSym.isUndefined() && sym->getFile() == &f; 79 80 // FIXME: What about other output types? And we can probably be less 81 // restrictive with -flat_namespace, but it's an infrequent use case. 82 // FIXME: Honor config->exportDynamic. 83 r.VisibleToRegularObj = config->outputType != MH_EXECUTE || 84 config->namespaceKind == NamespaceKind::flat || 85 sym->isUsedInRegularObj; 86 87 // Un-define the symbol so that we don't get duplicate symbol errors when we 88 // load the ObjFile emitted by LTO compilation. 89 if (r.Prevailing) 90 replaceSymbol<Undefined>(sym, sym->getName(), sym->getFile(), 91 RefState::Strong); 92 93 // TODO: set the other resolution configs properly 94 } 95 checkError(ltoObj->add(std::move(f.obj), resols)); 96 } 97 98 // Merge all the bitcode files we have seen, codegen the result 99 // and return the resulting ObjectFile(s). 100 std::vector<ObjFile *> BitcodeCompiler::compile() { 101 unsigned maxTasks = ltoObj->getMaxTasks(); 102 buf.resize(maxTasks); 103 files.resize(maxTasks); 104 105 // The -cache_path_lto option specifies the path to a directory in which 106 // to cache native object files for ThinLTO incremental builds. If a path was 107 // specified, configure LTO to use it as the cache directory. 108 FileCache cache; 109 if (!config->thinLTOCacheDir.empty()) 110 cache = 111 check(localCache("ThinLTO", "Thin", config->thinLTOCacheDir, 112 [&](size_t task, std::unique_ptr<MemoryBuffer> mb) { 113 files[task] = std::move(mb); 114 })); 115 116 checkError(ltoObj->run( 117 [&](size_t task) { 118 return std::make_unique<CachedFileStream>( 119 std::make_unique<raw_svector_ostream>(buf[task])); 120 }, 121 cache)); 122 123 if (!config->thinLTOCacheDir.empty()) 124 pruneCache(config->thinLTOCacheDir, config->thinLTOCachePolicy); 125 126 if (config->saveTemps) { 127 if (!buf[0].empty()) 128 saveBuffer(buf[0], config->outputFile + ".lto.o"); 129 for (unsigned i = 1; i != maxTasks; ++i) 130 saveBuffer(buf[i], config->outputFile + Twine(i) + ".lto.o"); 131 } 132 133 if (!config->ltoObjPath.empty()) 134 fs::create_directories(config->ltoObjPath); 135 136 std::vector<ObjFile *> ret; 137 for (unsigned i = 0; i != maxTasks; ++i) { 138 if (buf[i].empty()) 139 continue; 140 SmallString<261> filePath("/tmp/lto.tmp"); 141 uint32_t modTime = 0; 142 if (!config->ltoObjPath.empty()) { 143 filePath = config->ltoObjPath; 144 path::append(filePath, Twine(i) + "." + 145 getArchitectureName(config->arch()) + 146 ".lto.o"); 147 saveBuffer(buf[i], filePath); 148 modTime = getModTime(filePath); 149 } 150 ret.push_back(make<ObjFile>( 151 MemoryBufferRef(buf[i], saver().save(filePath.str())), modTime, "")); 152 } 153 for (std::unique_ptr<MemoryBuffer> &file : files) 154 if (file) 155 ret.push_back(make<ObjFile>(*file, 0, "")); 156 return ret; 157 } 158