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