Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 1 | //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===// |
| 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 Thin Link Time Optimization library. This library is |
| 11 | // intended to be used by linker to optimize code at link time. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
Peter Collingbourne | 5c73220 | 2016-07-14 21:21:16 +0000 | [diff] [blame] | 15 | #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 16 | |
Teresa Johnson | cec0cae | 2016-03-14 21:18:10 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/Statistic.h" |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/StringExtras.h" |
Teresa Johnson | 2d5487c | 2016-04-11 13:58:45 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/ModuleSummaryAnalysis.h" |
Piotr Padlewski | d9830eb | 2016-09-26 20:37:32 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/ProfileSummaryInfo.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/TargetLibraryInfo.h" |
| 22 | #include "llvm/Analysis/TargetTransformInfo.h" |
Teresa Johnson | ad17679 | 2016-11-11 05:34:58 +0000 | [diff] [blame] | 23 | #include "llvm/Bitcode/BitcodeReader.h" |
| 24 | #include "llvm/Bitcode/BitcodeWriter.h" |
Teresa Johnson | cec0cae | 2016-03-14 21:18:10 +0000 | [diff] [blame] | 25 | #include "llvm/Bitcode/BitcodeWriterPass.h" |
Nico Weber | 432a388 | 2018-04-30 14:59:11 +0000 | [diff] [blame] | 26 | #include "llvm/Config/llvm-config.h" |
Adrian Prantl | 981a799 | 2017-05-20 00:00:08 +0000 | [diff] [blame] | 27 | #include "llvm/IR/DebugInfo.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 28 | #include "llvm/IR/DiagnosticPrinter.h" |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 29 | #include "llvm/IR/LLVMContext.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 30 | #include "llvm/IR/LegacyPassManager.h" |
| 31 | #include "llvm/IR/Mangler.h" |
Adrian Prantl | 981a799 | 2017-05-20 00:00:08 +0000 | [diff] [blame] | 32 | #include "llvm/IR/Verifier.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 33 | #include "llvm/IRReader/IRReader.h" |
Teresa Johnson | df6edc5 | 2016-05-23 22:54:06 +0000 | [diff] [blame] | 34 | #include "llvm/LTO/LTO.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 35 | #include "llvm/MC/SubtargetFeature.h" |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 36 | #include "llvm/Object/IRObjectFile.h" |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 37 | #include "llvm/Support/CachePruning.h" |
| 38 | #include "llvm/Support/Debug.h" |
Mehdi Amini | 19f176b | 2016-11-19 18:20:05 +0000 | [diff] [blame] | 39 | #include "llvm/Support/Error.h" |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 40 | #include "llvm/Support/Path.h" |
| 41 | #include "llvm/Support/SHA1.h" |
Weiming Zhao | 79f2d09 | 2018-04-16 03:44:03 +0000 | [diff] [blame] | 42 | #include "llvm/Support/SmallVectorMemoryBuffer.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 43 | #include "llvm/Support/TargetRegistry.h" |
| 44 | #include "llvm/Support/ThreadPool.h" |
Teresa Johnson | ec544c5 | 2016-10-19 17:35:01 +0000 | [diff] [blame] | 45 | #include "llvm/Support/Threading.h" |
Mehdi Amini | 19f176b | 2016-11-19 18:20:05 +0000 | [diff] [blame] | 46 | #include "llvm/Support/ToolOutputFile.h" |
Peter Collingbourne | 942fa56 | 2017-04-13 01:26:12 +0000 | [diff] [blame] | 47 | #include "llvm/Support/VCSRevision.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 48 | #include "llvm/Target/TargetMachine.h" |
| 49 | #include "llvm/Transforms/IPO.h" |
| 50 | #include "llvm/Transforms/IPO/FunctionImport.h" |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 51 | #include "llvm/Transforms/IPO/Internalize.h" |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 52 | #include "llvm/Transforms/IPO/PassManagerBuilder.h" |
| 53 | #include "llvm/Transforms/ObjCARC.h" |
| 54 | #include "llvm/Transforms/Utils/FunctionImportUtils.h" |
| 55 | |
Mehdi Amini | 819e9cd | 2016-05-16 19:33:07 +0000 | [diff] [blame] | 56 | #include <numeric> |
| 57 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 58 | using namespace llvm; |
| 59 | |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 60 | #define DEBUG_TYPE "thinlto" |
| 61 | |
Mehdi Amini | 09b4a8d | 2016-03-10 01:28:54 +0000 | [diff] [blame] | 62 | namespace llvm { |
| 63 | // Flags -discard-value-names, defined in LTOCodeGenerator.cpp |
| 64 | extern cl::opt<bool> LTODiscardValueNames; |
Mehdi Amini | 19f176b | 2016-11-19 18:20:05 +0000 | [diff] [blame] | 65 | extern cl::opt<std::string> LTORemarksFilename; |
Adam Nemet | 4c207a6 | 2016-12-02 17:53:56 +0000 | [diff] [blame] | 66 | extern cl::opt<bool> LTOPassRemarksWithHotness; |
Mehdi Amini | 09b4a8d | 2016-03-10 01:28:54 +0000 | [diff] [blame] | 67 | } |
| 68 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 69 | namespace { |
| 70 | |
Teresa Johnson | ec544c5 | 2016-10-19 17:35:01 +0000 | [diff] [blame] | 71 | static cl::opt<int> |
| 72 | ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency())); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 73 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 74 | // Simple helper to save temporary files for debug. |
| 75 | static void saveTempBitcode(const Module &TheModule, StringRef TempDir, |
| 76 | unsigned count, StringRef Suffix) { |
| 77 | if (TempDir.empty()) |
| 78 | return; |
| 79 | // User asked to save temps, let dump the bitcode file after import. |
Benjamin Kramer | 3a13ed6 | 2017-12-28 16:58:54 +0000 | [diff] [blame] | 80 | std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str(); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 81 | std::error_code EC; |
Teresa Johnson | c44a122 | 2016-08-15 23:24:57 +0000 | [diff] [blame] | 82 | raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 83 | if (EC) |
| 84 | report_fatal_error(Twine("Failed to open ") + SaveTempPath + |
| 85 | " to save optimized bitcode\n"); |
Rafael Espindola | 6a86e25 | 2018-02-14 19:11:32 +0000 | [diff] [blame] | 86 | WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 87 | } |
| 88 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 89 | static const GlobalValueSummary * |
| 90 | getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) { |
| 91 | // If there is any strong definition anywhere, get it. |
| 92 | auto StrongDefForLinker = llvm::find_if( |
| 93 | GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) { |
| 94 | auto Linkage = Summary->linkage(); |
| 95 | return !GlobalValue::isAvailableExternallyLinkage(Linkage) && |
| 96 | !GlobalValue::isWeakForLinker(Linkage); |
| 97 | }); |
| 98 | if (StrongDefForLinker != GVSummaryList.end()) |
| 99 | return StrongDefForLinker->get(); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 100 | // Get the first *linker visible* definition for this global in the summary |
| 101 | // list. |
| 102 | auto FirstDefForLinker = llvm::find_if( |
Teresa Johnson | 28e457b | 2016-04-24 14:57:11 +0000 | [diff] [blame] | 103 | GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) { |
| 104 | auto Linkage = Summary->linkage(); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 105 | return !GlobalValue::isAvailableExternallyLinkage(Linkage); |
| 106 | }); |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 107 | // Extern templates can be emitted as available_externally. |
| 108 | if (FirstDefForLinker == GVSummaryList.end()) |
| 109 | return nullptr; |
| 110 | return FirstDefForLinker->get(); |
Hans Wennborg | fa6e414 | 2016-04-02 01:03:41 +0000 | [diff] [blame] | 111 | } |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 112 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 113 | // Populate map of GUID to the prevailing copy for any multiply defined |
| 114 | // symbols. Currently assume first copy is prevailing, or any strong |
| 115 | // definition. Can be refined with Linker information in the future. |
| 116 | static void computePrevailingCopies( |
| 117 | const ModuleSummaryIndex &Index, |
| 118 | DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) { |
Teresa Johnson | 28e457b | 2016-04-24 14:57:11 +0000 | [diff] [blame] | 119 | auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) { |
| 120 | return GVSummaryList.size() > 1; |
| 121 | }; |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 122 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 123 | for (auto &I : Index) { |
Peter Collingbourne | 9667b91 | 2017-05-04 18:03:25 +0000 | [diff] [blame] | 124 | if (HasMultipleCopies(I.second.SummaryList)) |
| 125 | PrevailingCopy[I.first] = |
| 126 | getFirstDefinitionForLinker(I.second.SummaryList); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 127 | } |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 128 | } |
| 129 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 130 | static StringMap<MemoryBufferRef> |
Mehdi Amini | a0ddb1e | 2017-02-14 02:20:51 +0000 | [diff] [blame] | 131 | generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) { |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 132 | StringMap<MemoryBufferRef> ModuleMap; |
| 133 | for (auto &ModuleBuffer : Modules) { |
| 134 | assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) == |
| 135 | ModuleMap.end() && |
| 136 | "Expect unique Buffer Identifier"); |
Mehdi Amini | a0ddb1e | 2017-02-14 02:20:51 +0000 | [diff] [blame] | 137 | ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer(); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 138 | } |
| 139 | return ModuleMap; |
| 140 | } |
| 141 | |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 142 | static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) { |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 143 | if (renameModuleForThinLTO(TheModule, Index)) |
| 144 | report_fatal_error("renameModuleForThinLTO failed"); |
| 145 | } |
| 146 | |
Adrian Prantl | 981a799 | 2017-05-20 00:00:08 +0000 | [diff] [blame] | 147 | namespace { |
| 148 | class ThinLTODiagnosticInfo : public DiagnosticInfo { |
| 149 | const Twine &Msg; |
| 150 | public: |
| 151 | ThinLTODiagnosticInfo(const Twine &DiagMsg, |
| 152 | DiagnosticSeverity Severity = DS_Error) |
| 153 | : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {} |
| 154 | void print(DiagnosticPrinter &DP) const override { DP << Msg; } |
| 155 | }; |
| 156 | } |
| 157 | |
| 158 | /// Verify the module and strip broken debug info. |
| 159 | static void verifyLoadedModule(Module &TheModule) { |
| 160 | bool BrokenDebugInfo = false; |
Adrian Prantl | a8b2ddb | 2017-10-02 18:31:29 +0000 | [diff] [blame] | 161 | if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo)) |
Adrian Prantl | 981a799 | 2017-05-20 00:00:08 +0000 | [diff] [blame] | 162 | report_fatal_error("Broken module found, compilation aborted!"); |
| 163 | if (BrokenDebugInfo) { |
| 164 | TheModule.getContext().diagnose(ThinLTODiagnosticInfo( |
| 165 | "Invalid debug info found, debug info will be stripped", DS_Warning)); |
| 166 | StripDebugInfo(TheModule); |
| 167 | } |
| 168 | } |
| 169 | |
Peter Collingbourne | dac43b4 | 2016-12-01 05:52:32 +0000 | [diff] [blame] | 170 | static std::unique_ptr<Module> |
| 171 | loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context, |
Teresa Johnson | a61f5e3 | 2016-12-16 21:25:01 +0000 | [diff] [blame] | 172 | bool Lazy, bool IsImporting) { |
Peter Collingbourne | dac43b4 | 2016-12-01 05:52:32 +0000 | [diff] [blame] | 173 | SMDiagnostic Err; |
| 174 | Expected<std::unique_ptr<Module>> ModuleOrErr = |
Teresa Johnson | a61f5e3 | 2016-12-16 21:25:01 +0000 | [diff] [blame] | 175 | Lazy |
| 176 | ? getLazyBitcodeModule(Buffer, Context, |
| 177 | /* ShouldLazyLoadMetadata */ true, IsImporting) |
| 178 | : parseBitcodeFile(Buffer, Context); |
Peter Collingbourne | dac43b4 | 2016-12-01 05:52:32 +0000 | [diff] [blame] | 179 | if (!ModuleOrErr) { |
| 180 | handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) { |
| 181 | SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(), |
| 182 | SourceMgr::DK_Error, EIB.message()); |
| 183 | Err.print("ThinLTO", errs()); |
| 184 | }); |
| 185 | report_fatal_error("Can't load module, abort."); |
| 186 | } |
Adrian Prantl | 981a799 | 2017-05-20 00:00:08 +0000 | [diff] [blame] | 187 | if (!Lazy) |
| 188 | verifyLoadedModule(*ModuleOrErr.get()); |
Peter Collingbourne | dac43b4 | 2016-12-01 05:52:32 +0000 | [diff] [blame] | 189 | return std::move(ModuleOrErr.get()); |
| 190 | } |
| 191 | |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 192 | static void |
| 193 | crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index, |
| 194 | StringMap<MemoryBufferRef> &ModuleMap, |
| 195 | const FunctionImporter::ImportMapTy &ImportList) { |
Peter Collingbourne | dac43b4 | 2016-12-01 05:52:32 +0000 | [diff] [blame] | 196 | auto Loader = [&](StringRef Identifier) { |
| 197 | return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(), |
Teresa Johnson | a61f5e3 | 2016-12-16 21:25:01 +0000 | [diff] [blame] | 198 | /*Lazy=*/true, /*IsImporting*/ true); |
Peter Collingbourne | dac43b4 | 2016-12-01 05:52:32 +0000 | [diff] [blame] | 199 | }; |
| 200 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 201 | FunctionImporter Importer(Index, Loader); |
Adrian Prantl | 6604379 | 2017-05-19 23:32:21 +0000 | [diff] [blame] | 202 | Expected<bool> Result = Importer.importFunctions(TheModule, ImportList); |
Mehdi Amini | 83a807e | 2017-01-08 00:30:27 +0000 | [diff] [blame] | 203 | if (!Result) { |
| 204 | handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) { |
| 205 | SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(), |
| 206 | SourceMgr::DK_Error, EIB.message()); |
| 207 | Err.print("ThinLTO", errs()); |
| 208 | }); |
Peter Collingbourne | 7f00d0a | 2016-11-09 17:49:19 +0000 | [diff] [blame] | 209 | report_fatal_error("importFunctions failed"); |
Mehdi Amini | 83a807e | 2017-01-08 00:30:27 +0000 | [diff] [blame] | 210 | } |
Adrian Prantl | 981a799 | 2017-05-20 00:00:08 +0000 | [diff] [blame] | 211 | // Verify again after cross-importing. |
| 212 | verifyLoadedModule(TheModule); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 213 | } |
| 214 | |
Mehdi Amini | cc7fbf7 | 2016-12-28 19:37:16 +0000 | [diff] [blame] | 215 | static void optimizeModule(Module &TheModule, TargetMachine &TM, |
Mehdi Amini | b5a46c1 | 2017-03-28 18:55:44 +0000 | [diff] [blame] | 216 | unsigned OptLevel, bool Freestanding) { |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 217 | // Populate the PassManager |
| 218 | PassManagerBuilder PMB; |
| 219 | PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple()); |
Mehdi Amini | b5a46c1 | 2017-03-28 18:55:44 +0000 | [diff] [blame] | 220 | if (Freestanding) |
| 221 | PMB.LibraryInfo->disableAllFunctions(); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 222 | PMB.Inliner = createFunctionInliningPass(); |
| 223 | // FIXME: should get it from the bitcode? |
Mehdi Amini | cc7fbf7 | 2016-12-28 19:37:16 +0000 | [diff] [blame] | 224 | PMB.OptLevel = OptLevel; |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 225 | PMB.LoopVectorize = true; |
| 226 | PMB.SLPVectorize = true; |
Adrian Prantl | 981a799 | 2017-05-20 00:00:08 +0000 | [diff] [blame] | 227 | // Already did this in verifyLoadedModule(). |
| 228 | PMB.VerifyInput = false; |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 229 | PMB.VerifyOutput = false; |
| 230 | |
| 231 | legacy::PassManager PM; |
| 232 | |
| 233 | // Add the TTI (required to inform the vectorizer about register size for |
| 234 | // instance) |
| 235 | PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis())); |
| 236 | |
| 237 | // Add optimizations |
| 238 | PMB.populateThinLTOPassManager(PM); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 239 | |
| 240 | PM.run(TheModule); |
| 241 | } |
| 242 | |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 243 | // Convert the PreservedSymbols map from "Name" based to "GUID" based. |
| 244 | static DenseSet<GlobalValue::GUID> |
Mehdi Amini | 1380edf | 2017-02-03 07:41:43 +0000 | [diff] [blame] | 245 | computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols, |
| 246 | const Triple &TheTriple) { |
| 247 | DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size()); |
| 248 | for (auto &Entry : PreservedSymbols) { |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 249 | StringRef Name = Entry.first(); |
| 250 | if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_') |
| 251 | Name = Name.drop_front(); |
Mehdi Amini | 1380edf | 2017-02-03 07:41:43 +0000 | [diff] [blame] | 252 | GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name)); |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 253 | } |
Mehdi Amini | 1380edf | 2017-02-03 07:41:43 +0000 | [diff] [blame] | 254 | return GUIDPreservedSymbols; |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 255 | } |
| 256 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 257 | std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule, |
| 258 | TargetMachine &TM) { |
| 259 | SmallVector<char, 128> OutputBuffer; |
| 260 | |
| 261 | // CodeGen |
| 262 | { |
| 263 | raw_svector_ostream OS(OutputBuffer); |
| 264 | legacy::PassManager PM; |
Mehdi Amini | 215d59e | 2016-04-01 08:22:59 +0000 | [diff] [blame] | 265 | |
| 266 | // If the bitcode files contain ARC code and were compiled with optimization, |
| 267 | // the ObjCARCContractPass must be run, so do it unconditionally here. |
| 268 | PM.add(createObjCARCContractPass()); |
| 269 | |
| 270 | // Setup the codegen now. |
Peter Collingbourne | 9a45114 | 2018-05-21 20:16:41 +0000 | [diff] [blame] | 271 | if (TM.addPassesToEmitFile(PM, OS, nullptr, TargetMachine::CGFT_ObjectFile, |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 272 | /* DisableVerify */ true)) |
| 273 | report_fatal_error("Failed to setup codegen"); |
| 274 | |
| 275 | // Run codegen now. resulting binary is in OutputBuffer. |
| 276 | PM.run(TheModule); |
| 277 | } |
Weiming Zhao | 79f2d09 | 2018-04-16 03:44:03 +0000 | [diff] [blame] | 278 | return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer)); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 279 | } |
| 280 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 281 | /// Manage caching for a single Module. |
| 282 | class ModuleCacheEntry { |
| 283 | SmallString<128> EntryPath; |
| 284 | |
| 285 | public: |
| 286 | // Create a cache entry. This compute a unique hash for the Module considering |
| 287 | // the current list of export/import, and offer an interface to query to |
| 288 | // access the content in the cache. |
| 289 | ModuleCacheEntry( |
| 290 | StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID, |
| 291 | const FunctionImporter::ImportMapTy &ImportList, |
| 292 | const FunctionImporter::ExportSetTy &ExportList, |
| 293 | const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, |
Teresa Johnson | c851d21 | 2016-04-25 21:09:51 +0000 | [diff] [blame] | 294 | const GVSummaryMapTy &DefinedFunctions, |
Mehdi Amini | c92b612 | 2017-01-10 00:55:47 +0000 | [diff] [blame] | 295 | const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel, |
Mehdi Amini | b5a46c1 | 2017-03-28 18:55:44 +0000 | [diff] [blame] | 296 | bool Freestanding, const TargetMachineBuilder &TMBuilder) { |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 297 | if (CachePath.empty()) |
| 298 | return; |
| 299 | |
Mehdi Amini | 00fa140 | 2016-10-08 04:44:18 +0000 | [diff] [blame] | 300 | if (!Index.modulePaths().count(ModuleID)) |
| 301 | // The module does not have an entry, it can't have a hash at all |
| 302 | return; |
| 303 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 304 | // Compute the unique hash for this entry |
| 305 | // This is based on the current compiler version, the module itself, the |
| 306 | // export list, the hash for every single module in the import list, the |
| 307 | // list of ResolvedODR for the module, and the list of preserved symbols. |
| 308 | |
Mehdi Amini | f82bda0 | 2016-10-08 04:44:23 +0000 | [diff] [blame] | 309 | // Include the hash for the current module |
| 310 | auto ModHash = Index.getModuleHash(ModuleID); |
| 311 | |
| 312 | if (all_of(ModHash, [](uint32_t V) { return V == 0; })) |
| 313 | // No hash entry, no caching! |
| 314 | return; |
| 315 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 316 | SHA1 Hasher; |
| 317 | |
Mehdi Amini | c92b612 | 2017-01-10 00:55:47 +0000 | [diff] [blame] | 318 | // Include the parts of the LTO configuration that affect code generation. |
| 319 | auto AddString = [&](StringRef Str) { |
| 320 | Hasher.update(Str); |
| 321 | Hasher.update(ArrayRef<uint8_t>{0}); |
| 322 | }; |
| 323 | auto AddUnsigned = [&](unsigned I) { |
| 324 | uint8_t Data[4]; |
| 325 | Data[0] = I; |
| 326 | Data[1] = I >> 8; |
| 327 | Data[2] = I >> 16; |
| 328 | Data[3] = I >> 24; |
| 329 | Hasher.update(ArrayRef<uint8_t>{Data, 4}); |
| 330 | }; |
| 331 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 332 | // Start with the compiler revision |
| 333 | Hasher.update(LLVM_VERSION_STRING); |
Peter Collingbourne | 942fa56 | 2017-04-13 01:26:12 +0000 | [diff] [blame] | 334 | #ifdef LLVM_REVISION |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 335 | Hasher.update(LLVM_REVISION); |
| 336 | #endif |
| 337 | |
Mehdi Amini | c92b612 | 2017-01-10 00:55:47 +0000 | [diff] [blame] | 338 | // Hash the optimization level and the target machine settings. |
| 339 | AddString(TMBuilder.MCpu); |
| 340 | // FIXME: Hash more of Options. For now all clients initialize Options from |
| 341 | // command-line flags (which is unsupported in production), but may set |
| 342 | // RelaxELFRelocations. The clang driver can also pass FunctionSections, |
| 343 | // DataSections and DebuggerTuning via command line flags. |
| 344 | AddUnsigned(TMBuilder.Options.RelaxELFRelocations); |
| 345 | AddUnsigned(TMBuilder.Options.FunctionSections); |
| 346 | AddUnsigned(TMBuilder.Options.DataSections); |
| 347 | AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning); |
| 348 | AddString(TMBuilder.MAttr); |
| 349 | if (TMBuilder.RelocModel) |
| 350 | AddUnsigned(*TMBuilder.RelocModel); |
| 351 | AddUnsigned(TMBuilder.CGOptLevel); |
| 352 | AddUnsigned(OptLevel); |
Mehdi Amini | b5a46c1 | 2017-03-28 18:55:44 +0000 | [diff] [blame] | 353 | AddUnsigned(Freestanding); |
Mehdi Amini | c92b612 | 2017-01-10 00:55:47 +0000 | [diff] [blame] | 354 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 355 | Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash))); |
| 356 | for (auto F : ExportList) |
| 357 | // The export list can impact the internalization, be conservative here |
| 358 | Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F))); |
| 359 | |
| 360 | // Include the hash for every module we import functions from |
| 361 | for (auto &Entry : ImportList) { |
| 362 | auto ModHash = Index.getModuleHash(Entry.first()); |
| 363 | Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash))); |
| 364 | } |
| 365 | |
| 366 | // Include the hash for the resolved ODR. |
| 367 | for (auto &Entry : ResolvedODR) { |
Sjoerd Meijer | 41beee6 | 2016-04-27 18:35:02 +0000 | [diff] [blame] | 368 | Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first, |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 369 | sizeof(GlobalValue::GUID))); |
Sjoerd Meijer | 41beee6 | 2016-04-27 18:35:02 +0000 | [diff] [blame] | 370 | Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second, |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 371 | sizeof(GlobalValue::LinkageTypes))); |
| 372 | } |
| 373 | |
| 374 | // Include the hash for the preserved symbols. |
| 375 | for (auto &Entry : PreservedSymbols) { |
| 376 | if (DefinedFunctions.count(Entry)) |
| 377 | Hasher.update( |
Sjoerd Meijer | 41beee6 | 2016-04-27 18:35:02 +0000 | [diff] [blame] | 378 | ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID))); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 379 | } |
| 380 | |
Peter Collingbourne | 25a17ba | 2017-03-20 16:41:57 +0000 | [diff] [blame] | 381 | // This choice of file name allows the cache to be pruned (see pruneCache() |
| 382 | // in include/llvm/Support/CachePruning.h). |
| 383 | sys::path::append(EntryPath, CachePath, |
| 384 | "llvmcache-" + toHex(Hasher.result())); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 385 | } |
| 386 | |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 387 | // Access the path to this entry in the cache. |
| 388 | StringRef getEntryPath() { return EntryPath; } |
| 389 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 390 | // Try loading the buffer for this cache entry. |
| 391 | ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() { |
| 392 | if (EntryPath.empty()) |
| 393 | return std::error_code(); |
| 394 | return MemoryBuffer::getFile(EntryPath); |
| 395 | } |
| 396 | |
| 397 | // Cache the Produced object file |
Mehdi Amini | 8e13bc4 | 2016-12-14 04:56:42 +0000 | [diff] [blame] | 398 | void write(const MemoryBuffer &OutputBuffer) { |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 399 | if (EntryPath.empty()) |
Mehdi Amini | 8e13bc4 | 2016-12-14 04:56:42 +0000 | [diff] [blame] | 400 | return; |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 401 | |
| 402 | // Write to a temporary to avoid race condition |
| 403 | SmallString<128> TempFilename; |
Ekaterina Romanova | 0b01dfb | 2018-03-30 21:35:42 +0000 | [diff] [blame] | 404 | SmallString<128> CachePath(EntryPath); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 405 | int TempFD; |
Ekaterina Romanova | 0b01dfb | 2018-03-30 21:35:42 +0000 | [diff] [blame] | 406 | llvm::sys::path::remove_filename(CachePath); |
| 407 | sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o"); |
| 408 | std::error_code EC = |
| 409 | sys::fs::createUniqueFile(TempFilename, TempFD, TempFilename); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 410 | if (EC) { |
| 411 | errs() << "Error: " << EC.message() << "\n"; |
| 412 | report_fatal_error("ThinLTO: Can't get a temporary file"); |
| 413 | } |
| 414 | { |
| 415 | raw_fd_ostream OS(TempFD, /* ShouldClose */ true); |
Mehdi Amini | 8e13bc4 | 2016-12-14 04:56:42 +0000 | [diff] [blame] | 416 | OS << OutputBuffer.getBuffer(); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 417 | } |
Ekaterina Romanova | 0b01dfb | 2018-03-30 21:35:42 +0000 | [diff] [blame] | 418 | // Rename temp file to final destination; rename is atomic |
Mehdi Amini | 2a16a5f | 2016-05-14 04:58:38 +0000 | [diff] [blame] | 419 | EC = sys::fs::rename(TempFilename, EntryPath); |
Ekaterina Romanova | 0b01dfb | 2018-03-30 21:35:42 +0000 | [diff] [blame] | 420 | if (EC) |
Mehdi Amini | b02139d | 2016-05-14 05:16:35 +0000 | [diff] [blame] | 421 | sys::fs::remove(TempFilename); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 422 | } |
| 423 | }; |
| 424 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 425 | static std::unique_ptr<MemoryBuffer> |
| 426 | ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index, |
| 427 | StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM, |
| 428 | const FunctionImporter::ImportMapTy &ImportList, |
| 429 | const FunctionImporter::ExportSetTy &ExportList, |
| 430 | const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, |
| 431 | const GVSummaryMapTy &DefinedGlobals, |
Benjamin Kramer | c321e53 | 2016-06-08 19:09:22 +0000 | [diff] [blame] | 432 | const ThinLTOCodeGenerator::CachingOptions &CacheOptions, |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 433 | bool DisableCodeGen, StringRef SaveTempsDir, |
Mehdi Amini | b5a46c1 | 2017-03-28 18:55:44 +0000 | [diff] [blame] | 434 | bool Freestanding, unsigned OptLevel, unsigned count) { |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 435 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 436 | // "Benchmark"-like optimization: single-source case |
| 437 | bool SingleModule = (ModuleMap.size() == 1); |
| 438 | |
| 439 | if (!SingleModule) { |
| 440 | promoteModule(TheModule, Index); |
| 441 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 442 | // Apply summary-based LinkOnce/Weak resolution decisions. |
| 443 | thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 444 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 445 | // Save temps: after promotion. |
Mehdi Amini | 4b300e0a | 2016-05-05 05:14:16 +0000 | [diff] [blame] | 446 | saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc"); |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 447 | } |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 448 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 449 | // Be friendly and don't nuke totally the module when the client didn't |
| 450 | // supply anything to preserve. |
| 451 | if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) { |
| 452 | // Apply summary-based internalization decisions. |
| 453 | thinLTOInternalizeModule(TheModule, DefinedGlobals); |
| 454 | } |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 455 | |
| 456 | // Save internalized bitcode |
Mehdi Amini | 4b300e0a | 2016-05-05 05:14:16 +0000 | [diff] [blame] | 457 | saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc"); |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 458 | |
| 459 | if (!SingleModule) { |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 460 | crossImportIntoModule(TheModule, Index, ModuleMap, ImportList); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 461 | |
| 462 | // Save temps: after cross-module import. |
Mehdi Amini | 4b300e0a | 2016-05-05 05:14:16 +0000 | [diff] [blame] | 463 | saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc"); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 464 | } |
| 465 | |
Mehdi Amini | b5a46c1 | 2017-03-28 18:55:44 +0000 | [diff] [blame] | 466 | optimizeModule(TheModule, TM, OptLevel, Freestanding); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 467 | |
Mehdi Amini | 4b300e0a | 2016-05-05 05:14:16 +0000 | [diff] [blame] | 468 | saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc"); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 469 | |
Mehdi Amini | 43b657b | 2016-04-01 06:47:02 +0000 | [diff] [blame] | 470 | if (DisableCodeGen) { |
| 471 | // Configured to stop before CodeGen, serialize the bitcode and return. |
| 472 | SmallVector<char, 128> OutputBuffer; |
| 473 | { |
| 474 | raw_svector_ostream OS(OutputBuffer); |
Dehao Chen | 5461d8b | 2016-09-28 21:00:58 +0000 | [diff] [blame] | 475 | ProfileSummaryInfo PSI(TheModule); |
Teresa Johnson | 94624ac | 2017-05-10 18:52:16 +0000 | [diff] [blame] | 476 | auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI); |
Rafael Espindola | 6a86e25 | 2018-02-14 19:11:32 +0000 | [diff] [blame] | 477 | WriteBitcodeToFile(TheModule, OS, true, &Index); |
Mehdi Amini | 43b657b | 2016-04-01 06:47:02 +0000 | [diff] [blame] | 478 | } |
Weiming Zhao | 79f2d09 | 2018-04-16 03:44:03 +0000 | [diff] [blame] | 479 | return make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer)); |
Mehdi Amini | 43b657b | 2016-04-01 06:47:02 +0000 | [diff] [blame] | 480 | } |
| 481 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 482 | return codegenModule(TheModule, TM); |
| 483 | } |
| 484 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 485 | /// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map |
| 486 | /// for caching, and in the \p Index for application during the ThinLTO |
| 487 | /// backends. This is needed for correctness for exported symbols (ensure |
| 488 | /// at least one copy kept) and a compile-time optimization (to drop duplicate |
| 489 | /// copies when possible). |
| 490 | static void resolveWeakForLinkerInIndex( |
| 491 | ModuleSummaryIndex &Index, |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 492 | StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> |
| 493 | &ResolvedODR) { |
| 494 | |
| 495 | DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy; |
| 496 | computePrevailingCopies(Index, PrevailingCopy); |
| 497 | |
| 498 | auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) { |
| 499 | const auto &Prevailing = PrevailingCopy.find(GUID); |
| 500 | // Not in map means that there was only one copy, which must be prevailing. |
| 501 | if (Prevailing == PrevailingCopy.end()) |
| 502 | return true; |
| 503 | return Prevailing->second == S; |
| 504 | }; |
| 505 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 506 | auto recordNewLinkage = [&](StringRef ModuleIdentifier, |
| 507 | GlobalValue::GUID GUID, |
| 508 | GlobalValue::LinkageTypes NewLinkage) { |
| 509 | ResolvedODR[ModuleIdentifier][GUID] = NewLinkage; |
| 510 | }; |
| 511 | |
Peter Collingbourne | 73589f3 | 2016-07-07 18:31:51 +0000 | [diff] [blame] | 512 | thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage); |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 513 | } |
| 514 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 515 | // Initialize the TargetMachine builder for a given Triple |
| 516 | static void initTMBuilder(TargetMachineBuilder &TMBuilder, |
| 517 | const Triple &TheTriple) { |
| 518 | // Set a default CPU for Darwin triples (copied from LTOCodeGenerator). |
| 519 | // FIXME this looks pretty terrible... |
| 520 | if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) { |
| 521 | if (TheTriple.getArch() == llvm::Triple::x86_64) |
| 522 | TMBuilder.MCpu = "core2"; |
| 523 | else if (TheTriple.getArch() == llvm::Triple::x86) |
| 524 | TMBuilder.MCpu = "yonah"; |
| 525 | else if (TheTriple.getArch() == llvm::Triple::aarch64) |
| 526 | TMBuilder.MCpu = "cyclone"; |
| 527 | } |
| 528 | TMBuilder.TheTriple = std::move(TheTriple); |
| 529 | } |
| 530 | |
| 531 | } // end anonymous namespace |
| 532 | |
| 533 | void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) { |
Johan Engelen | dcebe4f | 2017-09-17 18:11:26 +0000 | [diff] [blame] | 534 | ThinLTOBuffer Buffer(Data, Identifier); |
Akira Hatanaka | b10bff1 | 2017-05-18 03:52:29 +0000 | [diff] [blame] | 535 | LLVMContext Context; |
| 536 | StringRef TripleStr; |
| 537 | ErrorOr<std::string> TripleOrErr = expectedToErrorOrAndEmitErrors( |
| 538 | Context, getBitcodeTargetTriple(Buffer.getMemBuffer())); |
| 539 | |
| 540 | if (TripleOrErr) |
| 541 | TripleStr = *TripleOrErr; |
| 542 | |
| 543 | Triple TheTriple(TripleStr); |
| 544 | |
| 545 | if (Modules.empty()) |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 546 | initTMBuilder(TMBuilder, Triple(TheTriple)); |
Akira Hatanaka | b10bff1 | 2017-05-18 03:52:29 +0000 | [diff] [blame] | 547 | else if (TMBuilder.TheTriple != TheTriple) { |
| 548 | if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple)) |
| 549 | report_fatal_error("ThinLTO modules with incompatible triples not " |
| 550 | "supported"); |
| 551 | initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple))); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 552 | } |
Akira Hatanaka | b10bff1 | 2017-05-18 03:52:29 +0000 | [diff] [blame] | 553 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 554 | Modules.push_back(Buffer); |
| 555 | } |
| 556 | |
| 557 | void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) { |
| 558 | PreservedSymbols.insert(Name); |
| 559 | } |
| 560 | |
| 561 | void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) { |
Mehdi Amini | 1380edf | 2017-02-03 07:41:43 +0000 | [diff] [blame] | 562 | // FIXME: At the moment, we don't take advantage of this extra information, |
| 563 | // we're conservatively considering cross-references as preserved. |
| 564 | // CrossReferencedSymbols.insert(Name); |
| 565 | PreservedSymbols.insert(Name); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 566 | } |
| 567 | |
| 568 | // TargetMachine factory |
| 569 | std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const { |
| 570 | std::string ErrMsg; |
| 571 | const Target *TheTarget = |
| 572 | TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg); |
| 573 | if (!TheTarget) { |
| 574 | report_fatal_error("Can't load target for this Triple: " + ErrMsg); |
| 575 | } |
| 576 | |
| 577 | // Use MAttr as the default set of features. |
| 578 | SubtargetFeatures Features(MAttr); |
| 579 | Features.getDefaultSubtargetFeatures(TheTriple); |
| 580 | std::string FeatureStr = Features.getString(); |
Mehdi Amini | cc7fbf7 | 2016-12-28 19:37:16 +0000 | [diff] [blame] | 581 | |
Rafael Espindola | 79e238a | 2017-08-03 02:16:21 +0000 | [diff] [blame] | 582 | return std::unique_ptr<TargetMachine>( |
| 583 | TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options, |
| 584 | RelocModel, None, CGOptLevel)); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 585 | } |
| 586 | |
| 587 | /** |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 588 | * Produce the combined summary index from all the bitcode files: |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 589 | * "thin-link". |
| 590 | */ |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 591 | std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() { |
Peter Collingbourne | 74d22dd | 2017-05-01 22:04:36 +0000 | [diff] [blame] | 592 | std::unique_ptr<ModuleSummaryIndex> CombinedIndex = |
Teresa Johnson | 4ffc3e7 | 2018-06-06 22:22:01 +0000 | [diff] [blame^] | 593 | llvm::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 594 | uint64_t NextModuleId = 0; |
| 595 | for (auto &ModuleBuffer : Modules) { |
Peter Collingbourne | 74d22dd | 2017-05-01 22:04:36 +0000 | [diff] [blame] | 596 | if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(), |
| 597 | *CombinedIndex, NextModuleId++)) { |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 598 | // FIXME diagnose |
Peter Collingbourne | 6de481a | 2016-11-11 19:50:39 +0000 | [diff] [blame] | 599 | logAllUnhandledErrors( |
Peter Collingbourne | 74d22dd | 2017-05-01 22:04:36 +0000 | [diff] [blame] | 600 | std::move(Err), errs(), |
Peter Collingbourne | c15d60b | 2017-05-01 20:42:32 +0000 | [diff] [blame] | 601 | "error: can't create module summary index for buffer: "); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 602 | return nullptr; |
| 603 | } |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 604 | } |
| 605 | return CombinedIndex; |
| 606 | } |
| 607 | |
George Rimar | 2421b6f | 2018-01-17 10:33:05 +0000 | [diff] [blame] | 608 | static void internalizeAndPromoteInIndex( |
| 609 | const StringMap<FunctionImporter::ExportSetTy> &ExportLists, |
| 610 | const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, |
| 611 | ModuleSummaryIndex &Index) { |
| 612 | auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) { |
| 613 | const auto &ExportList = ExportLists.find(ModuleIdentifier); |
| 614 | return (ExportList != ExportLists.end() && |
| 615 | ExportList->second.count(GUID)) || |
| 616 | GUIDPreservedSymbols.count(GUID); |
| 617 | }; |
| 618 | |
| 619 | thinLTOInternalizeAndPromoteInIndex(Index, isExported); |
| 620 | } |
| 621 | |
George Rimar | eaf5172 | 2018-01-29 08:03:30 +0000 | [diff] [blame] | 622 | static void computeDeadSymbolsInIndex( |
| 623 | ModuleSummaryIndex &Index, |
| 624 | const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) { |
| 625 | // We have no symbols resolution available. And can't do any better now in the |
| 626 | // case where the prevailing symbol is in a native object. It can be refined |
| 627 | // with linker information in the future. |
| 628 | auto isPrevailing = [&](GlobalValue::GUID G) { |
| 629 | return PrevailingType::Unknown; |
| 630 | }; |
| 631 | computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing); |
| 632 | } |
| 633 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 634 | /** |
| 635 | * Perform promotion and renaming of exported internal functions. |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 636 | * Index is updated to reflect linkage changes from weak resolution. |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 637 | */ |
| 638 | void ThinLTOCodeGenerator::promote(Module &TheModule, |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 639 | ModuleSummaryIndex &Index) { |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 640 | auto ModuleCount = Index.modulePaths().size(); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 641 | auto ModuleIdentifier = TheModule.getModuleIdentifier(); |
Teresa Johnson | 4fef68c | 2016-11-14 19:21:41 +0000 | [diff] [blame] | 642 | |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 643 | // Collect for each module the list of function it defines (GUID -> Summary). |
Teresa Johnson | c851d21 | 2016-04-25 21:09:51 +0000 | [diff] [blame] | 644 | StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries; |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 645 | Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 646 | |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 647 | // Convert the preserved symbols set from string to GUID |
Mehdi Amini | 1380edf | 2017-02-03 07:41:43 +0000 | [diff] [blame] | 648 | auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 649 | PreservedSymbols, Triple(TheModule.getTargetTriple())); |
| 650 | |
| 651 | // Compute "dead" symbols, we don't want to import/export these! |
George Rimar | eaf5172 | 2018-01-29 08:03:30 +0000 | [diff] [blame] | 652 | computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 653 | |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 654 | // Generate import/export list |
| 655 | StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); |
| 656 | StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); |
| 657 | ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, |
Evgeniy Stepanov | 56584bb | 2017-06-01 20:30:06 +0000 | [diff] [blame] | 658 | ExportLists); |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 659 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 660 | // Resolve LinkOnce/Weak symbols. |
| 661 | StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; |
Peter Collingbourne | 73589f3 | 2016-07-07 18:31:51 +0000 | [diff] [blame] | 662 | resolveWeakForLinkerInIndex(Index, ResolvedODR); |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 663 | |
| 664 | thinLTOResolveWeakForLinkerModule( |
| 665 | TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]); |
Mehdi Amini | 5a2e5d3 | 2016-04-01 21:53:50 +0000 | [diff] [blame] | 666 | |
Teresa Johnson | 4fef68c | 2016-11-14 19:21:41 +0000 | [diff] [blame] | 667 | // Promote the exported values in the index, so that they are promoted |
| 668 | // in the module. |
George Rimar | 2421b6f | 2018-01-17 10:33:05 +0000 | [diff] [blame] | 669 | internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index); |
Teresa Johnson | 4fef68c | 2016-11-14 19:21:41 +0000 | [diff] [blame] | 670 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 671 | promoteModule(TheModule, Index); |
| 672 | } |
| 673 | |
| 674 | /** |
| 675 | * Perform cross-module importing for the module identified by ModuleIdentifier. |
| 676 | */ |
| 677 | void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule, |
Teresa Johnson | 26ab577 | 2016-03-15 00:04:37 +0000 | [diff] [blame] | 678 | ModuleSummaryIndex &Index) { |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 679 | auto ModuleMap = generateModuleMap(Modules); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 680 | auto ModuleCount = Index.modulePaths().size(); |
| 681 | |
| 682 | // Collect for each module the list of function it defines (GUID -> Summary). |
Teresa Johnson | c851d21 | 2016-04-25 21:09:51 +0000 | [diff] [blame] | 683 | StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 684 | Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 685 | |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 686 | // Convert the preserved symbols set from string to GUID |
Mehdi Amini | 1380edf | 2017-02-03 07:41:43 +0000 | [diff] [blame] | 687 | auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 688 | PreservedSymbols, Triple(TheModule.getTargetTriple())); |
| 689 | |
| 690 | // Compute "dead" symbols, we don't want to import/export these! |
George Rimar | eaf5172 | 2018-01-29 08:03:30 +0000 | [diff] [blame] | 691 | computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 692 | |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 693 | // Generate import/export list |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 694 | StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); |
| 695 | StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 696 | ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, |
Evgeniy Stepanov | 56584bb | 2017-06-01 20:30:06 +0000 | [diff] [blame] | 697 | ExportLists); |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 698 | auto &ImportList = ImportLists[TheModule.getModuleIdentifier()]; |
| 699 | |
| 700 | crossImportIntoModule(TheModule, Index, ModuleMap, ImportList); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 701 | } |
| 702 | |
| 703 | /** |
Teresa Johnson | 84174c3 | 2016-05-10 13:48:23 +0000 | [diff] [blame] | 704 | * Compute the list of summaries needed for importing into module. |
| 705 | */ |
| 706 | void ThinLTOCodeGenerator::gatherImportedSummariesForModule( |
| 707 | StringRef ModulePath, ModuleSummaryIndex &Index, |
| 708 | std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { |
| 709 | auto ModuleCount = Index.modulePaths().size(); |
| 710 | |
| 711 | // Collect for each module the list of function it defines (GUID -> Summary). |
| 712 | StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); |
| 713 | Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); |
| 714 | |
| 715 | // Generate import/export list |
| 716 | StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); |
| 717 | StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); |
| 718 | ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, |
| 719 | ExportLists); |
| 720 | |
| 721 | llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries, |
Mehdi Amini | cdbcbf7 | 2016-08-16 05:46:05 +0000 | [diff] [blame] | 722 | ImportLists[ModulePath], |
Teresa Johnson | 84174c3 | 2016-05-10 13:48:23 +0000 | [diff] [blame] | 723 | ModuleToSummariesForIndex); |
| 724 | } |
| 725 | |
| 726 | /** |
Teresa Johnson | 8570fe4 | 2016-05-10 15:54:09 +0000 | [diff] [blame] | 727 | * Emit the list of files needed for importing into module. |
| 728 | */ |
| 729 | void ThinLTOCodeGenerator::emitImports(StringRef ModulePath, |
| 730 | StringRef OutputName, |
| 731 | ModuleSummaryIndex &Index) { |
| 732 | auto ModuleCount = Index.modulePaths().size(); |
| 733 | |
| 734 | // Collect for each module the list of function it defines (GUID -> Summary). |
| 735 | StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); |
| 736 | Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); |
| 737 | |
| 738 | // Generate import/export list |
| 739 | StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); |
| 740 | StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); |
| 741 | ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, |
| 742 | ExportLists); |
| 743 | |
| 744 | std::error_code EC; |
Mehdi Amini | cdbcbf7 | 2016-08-16 05:46:05 +0000 | [diff] [blame] | 745 | if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath]))) |
Teresa Johnson | 8570fe4 | 2016-05-10 15:54:09 +0000 | [diff] [blame] | 746 | report_fatal_error(Twine("Failed to open ") + OutputName + |
| 747 | " to save imports lists\n"); |
| 748 | } |
| 749 | |
| 750 | /** |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 751 | * Perform internalization. Index is updated to reflect linkage changes. |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 752 | */ |
| 753 | void ThinLTOCodeGenerator::internalize(Module &TheModule, |
| 754 | ModuleSummaryIndex &Index) { |
| 755 | initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); |
| 756 | auto ModuleCount = Index.modulePaths().size(); |
| 757 | auto ModuleIdentifier = TheModule.getModuleIdentifier(); |
| 758 | |
| 759 | // Convert the preserved symbols set from string to GUID |
| 760 | auto GUIDPreservedSymbols = |
Mehdi Amini | 1380edf | 2017-02-03 07:41:43 +0000 | [diff] [blame] | 761 | computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple); |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 762 | |
| 763 | // Collect for each module the list of function it defines (GUID -> Summary). |
Teresa Johnson | c851d21 | 2016-04-25 21:09:51 +0000 | [diff] [blame] | 764 | StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 765 | Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); |
| 766 | |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 767 | // Compute "dead" symbols, we don't want to import/export these! |
George Rimar | eaf5172 | 2018-01-29 08:03:30 +0000 | [diff] [blame] | 768 | computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 769 | |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 770 | // Generate import/export list |
| 771 | StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); |
| 772 | StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); |
| 773 | ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, |
Evgeniy Stepanov | 56584bb | 2017-06-01 20:30:06 +0000 | [diff] [blame] | 774 | ExportLists); |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 775 | auto &ExportList = ExportLists[ModuleIdentifier]; |
| 776 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 777 | // Be friendly and don't nuke totally the module when the client didn't |
| 778 | // supply anything to preserve. |
| 779 | if (ExportList.empty() && GUIDPreservedSymbols.empty()) |
| 780 | return; |
| 781 | |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 782 | // Internalization |
George Rimar | 2421b6f | 2018-01-17 10:33:05 +0000 | [diff] [blame] | 783 | internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, Index); |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 784 | thinLTOInternalizeModule(TheModule, |
| 785 | ModuleToDefinedGVSummaries[ModuleIdentifier]); |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 786 | } |
| 787 | |
| 788 | /** |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 789 | * Perform post-importing ThinLTO optimizations. |
| 790 | */ |
| 791 | void ThinLTOCodeGenerator::optimize(Module &TheModule) { |
| 792 | initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 793 | |
| 794 | // Optimize now |
Mehdi Amini | b5a46c1 | 2017-03-28 18:55:44 +0000 | [diff] [blame] | 795 | optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 796 | } |
| 797 | |
| 798 | /** |
| 799 | * Perform ThinLTO CodeGen. |
| 800 | */ |
| 801 | std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) { |
| 802 | initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); |
| 803 | return codegenModule(TheModule, *TMBuilder.create()); |
| 804 | } |
| 805 | |
Mehdi Amini | 8e13bc4 | 2016-12-14 04:56:42 +0000 | [diff] [blame] | 806 | /// Write out the generated object file, either from CacheEntryPath or from |
| 807 | /// OutputBuffer, preferring hard-link when possible. |
| 808 | /// Returns the path to the generated file in SavedObjectsDirectoryPath. |
| 809 | static std::string writeGeneratedObject(int count, StringRef CacheEntryPath, |
| 810 | StringRef SavedObjectsDirectoryPath, |
| 811 | const MemoryBuffer &OutputBuffer) { |
| 812 | SmallString<128> OutputPath(SavedObjectsDirectoryPath); |
| 813 | llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o"); |
| 814 | OutputPath.c_str(); // Ensure the string is null terminated. |
| 815 | if (sys::fs::exists(OutputPath)) |
| 816 | sys::fs::remove(OutputPath); |
| 817 | |
| 818 | // We don't return a memory buffer to the linker, just a list of files. |
| 819 | if (!CacheEntryPath.empty()) { |
| 820 | // Cache is enabled, hard-link the entry (or copy if hard-link fails). |
| 821 | auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath); |
| 822 | if (!Err) |
| 823 | return OutputPath.str(); |
| 824 | // Hard linking failed, try to copy. |
| 825 | Err = sys::fs::copy_file(CacheEntryPath, OutputPath); |
| 826 | if (!Err) |
| 827 | return OutputPath.str(); |
| 828 | // Copy failed (could be because the CacheEntry was removed from the cache |
| 829 | // in the meantime by another process), fall back and try to write down the |
| 830 | // buffer to the output. |
| 831 | errs() << "error: can't link or copy from cached entry '" << CacheEntryPath |
| 832 | << "' to '" << OutputPath << "'\n"; |
| 833 | } |
| 834 | // No cache entry, just write out the buffer. |
| 835 | std::error_code Err; |
| 836 | raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None); |
| 837 | if (Err) |
| 838 | report_fatal_error("Can't open output '" + OutputPath + "'\n"); |
| 839 | OS << OutputBuffer.getBuffer(); |
| 840 | return OutputPath.str(); |
| 841 | } |
| 842 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 843 | // Main entry point for the ThinLTO processing |
| 844 | void ThinLTOCodeGenerator::run() { |
Mehdi Amini | b299046 | 2017-01-20 22:45:34 +0000 | [diff] [blame] | 845 | // Prepare the resulting object vector |
| 846 | assert(ProducedBinaries.empty() && "The generator should not be reused"); |
| 847 | if (SavedObjectsDirectoryPath.empty()) |
| 848 | ProducedBinaries.resize(Modules.size()); |
| 849 | else { |
| 850 | sys::fs::create_directories(SavedObjectsDirectoryPath); |
| 851 | bool IsDir; |
| 852 | sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir); |
| 853 | if (!IsDir) |
| 854 | report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'"); |
| 855 | ProducedBinaryFiles.resize(Modules.size()); |
| 856 | } |
| 857 | |
Mehdi Amini | 43b657b | 2016-04-01 06:47:02 +0000 | [diff] [blame] | 858 | if (CodeGenOnly) { |
| 859 | // Perform only parallel codegen and return. |
| 860 | ThreadPool Pool; |
Mehdi Amini | 43b657b | 2016-04-01 06:47:02 +0000 | [diff] [blame] | 861 | int count = 0; |
| 862 | for (auto &ModuleBuffer : Modules) { |
| 863 | Pool.async([&](int count) { |
| 864 | LLVMContext Context; |
| 865 | Context.setDiscardValueNames(LTODiscardValueNames); |
| 866 | |
| 867 | // Parse module now |
Mehdi Amini | a0ddb1e | 2017-02-14 02:20:51 +0000 | [diff] [blame] | 868 | auto TheModule = |
| 869 | loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false, |
| 870 | /*IsImporting*/ false); |
Mehdi Amini | 43b657b | 2016-04-01 06:47:02 +0000 | [diff] [blame] | 871 | |
| 872 | // CodeGen |
Mehdi Amini | b299046 | 2017-01-20 22:45:34 +0000 | [diff] [blame] | 873 | auto OutputBuffer = codegen(*TheModule); |
| 874 | if (SavedObjectsDirectoryPath.empty()) |
| 875 | ProducedBinaries[count] = std::move(OutputBuffer); |
| 876 | else |
| 877 | ProducedBinaryFiles[count] = writeGeneratedObject( |
| 878 | count, "", SavedObjectsDirectoryPath, *OutputBuffer); |
Mehdi Amini | 43b657b | 2016-04-01 06:47:02 +0000 | [diff] [blame] | 879 | }, count++); |
| 880 | } |
| 881 | |
| 882 | return; |
| 883 | } |
| 884 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 885 | // Sequential linking phase |
| 886 | auto Index = linkCombinedIndex(); |
| 887 | |
| 888 | // Save temps: index. |
| 889 | if (!SaveTempsDir.empty()) { |
| 890 | auto SaveTempPath = SaveTempsDir + "index.bc"; |
| 891 | std::error_code EC; |
| 892 | raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None); |
| 893 | if (EC) |
| 894 | report_fatal_error(Twine("Failed to open ") + SaveTempPath + |
| 895 | " to save optimized bitcode\n"); |
Teresa Johnson | 76a1c1d | 2016-03-11 18:52:24 +0000 | [diff] [blame] | 896 | WriteIndexToFile(*Index, OS); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 897 | } |
| 898 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 899 | |
| 900 | // Prepare the module map. |
| 901 | auto ModuleMap = generateModuleMap(Modules); |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 902 | auto ModuleCount = Modules.size(); |
| 903 | |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 904 | // Collect for each module the list of function it defines (GUID -> Summary). |
Teresa Johnson | c851d21 | 2016-04-25 21:09:51 +0000 | [diff] [blame] | 905 | StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 906 | Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); |
| 907 | |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 908 | // Convert the preserved symbols set from string to GUID, this is needed for |
| 909 | // computing the caching hash and the internalization. |
| 910 | auto GUIDPreservedSymbols = |
Mehdi Amini | 1380edf | 2017-02-03 07:41:43 +0000 | [diff] [blame] | 911 | computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple); |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 912 | |
| 913 | // Compute "dead" symbols, we don't want to import/export these! |
George Rimar | eaf5172 | 2018-01-29 08:03:30 +0000 | [diff] [blame] | 914 | computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols); |
Teresa Johnson | 6c475a7 | 2017-01-05 21:34:18 +0000 | [diff] [blame] | 915 | |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 916 | // Collect the import/export lists for all modules from the call-graph in the |
| 917 | // combined index. |
| 918 | StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); |
| 919 | StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 920 | ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists, |
Evgeniy Stepanov | 56584bb | 2017-06-01 20:30:06 +0000 | [diff] [blame] | 921 | ExportLists); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 922 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 923 | // We use a std::map here to be able to have a defined ordering when |
| 924 | // producing a hash for the cache entry. |
| 925 | // FIXME: we should be able to compute the caching hash for the entry based |
| 926 | // on the index, and nuke this map. |
| 927 | StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; |
| 928 | |
| 929 | // Resolve LinkOnce/Weak symbols, this has to be computed early because it |
| 930 | // impacts the caching. |
Peter Collingbourne | 73589f3 | 2016-07-07 18:31:51 +0000 | [diff] [blame] | 931 | resolveWeakForLinkerInIndex(*Index, ResolvedODR); |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 932 | |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 933 | // Use global summary-based analysis to identify symbols that can be |
| 934 | // internalized (because they aren't exported or preserved as per callback). |
| 935 | // Changes are made in the index, consumed in the ThinLTO backends. |
George Rimar | 2421b6f | 2018-01-17 10:33:05 +0000 | [diff] [blame] | 936 | internalizeAndPromoteInIndex(ExportLists, GUIDPreservedSymbols, *Index); |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 937 | |
Teresa Johnson | 141149f | 2016-05-24 18:44:01 +0000 | [diff] [blame] | 938 | // Make sure that every module has an entry in the ExportLists and |
| 939 | // ResolvedODR maps to enable threaded access to these maps below. |
| 940 | for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { |
Mehdi Amini | af52f28 | 2016-05-15 05:49:47 +0000 | [diff] [blame] | 941 | ExportLists[DefinedGVSummaries.first()]; |
Teresa Johnson | 141149f | 2016-05-24 18:44:01 +0000 | [diff] [blame] | 942 | ResolvedODR[DefinedGVSummaries.first()]; |
| 943 | } |
Mehdi Amini | af52f28 | 2016-05-15 05:49:47 +0000 | [diff] [blame] | 944 | |
Mehdi Amini | 819e9cd | 2016-05-16 19:33:07 +0000 | [diff] [blame] | 945 | // Compute the ordering we will process the inputs: the rough heuristic here |
| 946 | // is to sort them per size so that the largest module get schedule as soon as |
| 947 | // possible. This is purely a compile-time optimization. |
| 948 | std::vector<int> ModulesOrdering; |
| 949 | ModulesOrdering.resize(Modules.size()); |
| 950 | std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0); |
Mandeep Singh Grang | 5416af7 | 2018-04-13 19:12:20 +0000 | [diff] [blame] | 951 | llvm::sort(ModulesOrdering.begin(), ModulesOrdering.end(), |
| 952 | [&](int LeftIndex, int RightIndex) { |
| 953 | auto LSize = Modules[LeftIndex].getBuffer().size(); |
| 954 | auto RSize = Modules[RightIndex].getBuffer().size(); |
| 955 | return LSize > RSize; |
| 956 | }); |
Mehdi Amini | 819e9cd | 2016-05-16 19:33:07 +0000 | [diff] [blame] | 957 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 958 | // Parallel optimizer + codegen |
| 959 | { |
| 960 | ThreadPool Pool(ThreadCount); |
Mehdi Amini | 819e9cd | 2016-05-16 19:33:07 +0000 | [diff] [blame] | 961 | for (auto IndexCount : ModulesOrdering) { |
| 962 | auto &ModuleBuffer = Modules[IndexCount]; |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 963 | Pool.async([&](int count) { |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 964 | auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier(); |
Mehdi Amini | a71a5a6 | 2016-04-21 05:47:17 +0000 | [diff] [blame] | 965 | auto &ExportList = ExportLists[ModuleIdentifier]; |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 966 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 967 | auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier]; |
| 968 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 969 | // The module may be cached, this helps handling it. |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 970 | ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier, |
| 971 | ImportLists[ModuleIdentifier], ExportList, |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 972 | ResolvedODR[ModuleIdentifier], |
Mehdi Amini | c92b612 | 2017-01-10 00:55:47 +0000 | [diff] [blame] | 973 | DefinedFunctions, GUIDPreservedSymbols, |
Mehdi Amini | b5a46c1 | 2017-03-28 18:55:44 +0000 | [diff] [blame] | 974 | OptLevel, Freestanding, TMBuilder); |
Mehdi Amini | 8e13bc4 | 2016-12-14 04:56:42 +0000 | [diff] [blame] | 975 | auto CacheEntryPath = CacheEntry.getEntryPath(); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 976 | |
| 977 | { |
| 978 | auto ErrOrBuffer = CacheEntry.tryLoadingBuffer(); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 979 | LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") |
| 980 | << " '" << CacheEntryPath << "' for buffer " |
| 981 | << count << " " << ModuleIdentifier << "\n"); |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 982 | |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 983 | if (ErrOrBuffer) { |
| 984 | // Cache Hit! |
Mehdi Amini | 8e13bc4 | 2016-12-14 04:56:42 +0000 | [diff] [blame] | 985 | if (SavedObjectsDirectoryPath.empty()) |
| 986 | ProducedBinaries[count] = std::move(ErrOrBuffer.get()); |
| 987 | else |
| 988 | ProducedBinaryFiles[count] = writeGeneratedObject( |
| 989 | count, CacheEntryPath, SavedObjectsDirectoryPath, |
| 990 | *ErrOrBuffer.get()); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 991 | return; |
| 992 | } |
| 993 | } |
| 994 | |
| 995 | LLVMContext Context; |
| 996 | Context.setDiscardValueNames(LTODiscardValueNames); |
| 997 | Context.enableDebugTypeODRUniquing(); |
Davide Italiano | 690ed9d | 2017-02-10 23:49:38 +0000 | [diff] [blame] | 998 | auto DiagFileOrErr = lto::setupOptimizationRemarks( |
Bob Haarman | fb2d342 | 2018-03-08 01:13:10 +0000 | [diff] [blame] | 999 | Context, LTORemarksFilename, LTOPassRemarksWithHotness, count); |
Mehdi Amini | 19f176b | 2016-11-19 18:20:05 +0000 | [diff] [blame] | 1000 | if (!DiagFileOrErr) { |
| 1001 | errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n"; |
| 1002 | report_fatal_error("ThinLTO: Can't get an output file for the " |
| 1003 | "remarks"); |
| 1004 | } |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 1005 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 1006 | // Parse module now |
Mehdi Amini | a0ddb1e | 2017-02-14 02:20:51 +0000 | [diff] [blame] | 1007 | auto TheModule = |
| 1008 | loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false, |
| 1009 | /*IsImporting*/ false); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 1010 | |
| 1011 | // Save temps: original file. |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 1012 | saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc"); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 1013 | |
Mehdi Amini | 1aafabf | 2016-04-16 07:02:16 +0000 | [diff] [blame] | 1014 | auto &ImportList = ImportLists[ModuleIdentifier]; |
Mehdi Amini | 059464f | 2016-04-24 03:18:01 +0000 | [diff] [blame] | 1015 | // Run the main process now, and generates a binary |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 1016 | auto OutputBuffer = ProcessThinLTOModule( |
Mehdi Amini | 01e3213 | 2016-03-26 05:40:34 +0000 | [diff] [blame] | 1017 | *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList, |
Teresa Johnson | 4d2613f | 2016-05-24 17:24:25 +0000 | [diff] [blame] | 1018 | ExportList, GUIDPreservedSymbols, |
| 1019 | ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions, |
Mehdi Amini | b5a46c1 | 2017-03-28 18:55:44 +0000 | [diff] [blame] | 1020 | DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 1021 | |
Mehdi Amini | 8e13bc4 | 2016-12-14 04:56:42 +0000 | [diff] [blame] | 1022 | // Commit to the cache (if enabled) |
| 1023 | CacheEntry.write(*OutputBuffer); |
| 1024 | |
| 1025 | if (SavedObjectsDirectoryPath.empty()) { |
| 1026 | // We need to generated a memory buffer for the linker. |
| 1027 | if (!CacheEntryPath.empty()) { |
Ekaterina Romanova | 0b01dfb | 2018-03-30 21:35:42 +0000 | [diff] [blame] | 1028 | // When cache is enabled, reload from the cache if possible. |
| 1029 | // Releasing the buffer from the heap and reloading it from the |
| 1030 | // cache file with mmap helps us to lower memory pressure. |
| 1031 | // The freed memory can be used for the next input file. |
| 1032 | // The final binary link will read from the VFS cache (hopefully!) |
| 1033 | // or from disk (if the memory pressure was too high). |
Mehdi Amini | 8e13bc4 | 2016-12-14 04:56:42 +0000 | [diff] [blame] | 1034 | auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer(); |
| 1035 | if (auto EC = ReloadedBufferOrErr.getError()) { |
Ekaterina Romanova | 0b01dfb | 2018-03-30 21:35:42 +0000 | [diff] [blame] | 1036 | // On error, keep the preexisting buffer and print a diagnostic. |
Mehdi Amini | 8e13bc4 | 2016-12-14 04:56:42 +0000 | [diff] [blame] | 1037 | errs() << "error: can't reload cached file '" << CacheEntryPath |
| 1038 | << "': " << EC.message() << "\n"; |
| 1039 | } else { |
| 1040 | OutputBuffer = std::move(*ReloadedBufferOrErr); |
| 1041 | } |
| 1042 | } |
| 1043 | ProducedBinaries[count] = std::move(OutputBuffer); |
| 1044 | return; |
| 1045 | } |
| 1046 | ProducedBinaryFiles[count] = writeGeneratedObject( |
| 1047 | count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer); |
Mehdi Amini | 819e9cd | 2016-05-16 19:33:07 +0000 | [diff] [blame] | 1048 | }, IndexCount); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 1049 | } |
| 1050 | } |
| 1051 | |
Peter Collingbourne | cead56f | 2017-03-15 22:54:18 +0000 | [diff] [blame] | 1052 | pruneCache(CacheOptions.Path, CacheOptions.Policy); |
Mehdi Amini | f95f77a | 2016-04-21 05:54:23 +0000 | [diff] [blame] | 1053 | |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 1054 | // If statistics were requested, print them out now. |
| 1055 | if (llvm::AreStatisticsEnabled()) |
| 1056 | llvm::PrintStatistics(); |
James Henderson | 852f6fd | 2017-05-16 09:43:21 +0000 | [diff] [blame] | 1057 | reportAndResetTimings(); |
Mehdi Amini | 7c4a1a8 | 2016-03-09 01:37:22 +0000 | [diff] [blame] | 1058 | } |