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