blob: aa5b5267abd2e03d50f878f09c29b22d8b3fc4bd [file] [log] [blame]
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001//===--- BackendUtil.cpp - LLVM Backend Utilities -------------------------===//
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
Daniel Dunbarc1b17292010-06-15 17:48:49 +000010#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000011#include "clang/Basic/Diagnostic.h"
Dan Gohmanfec0ff82011-07-05 22:02:36 +000012#include "clang/Basic/LangOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/Basic/TargetOptions.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000014#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Kostya Serebryanyce2c7262013-12-27 08:11:08 +000016#include "clang/Frontend/Utils.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000017#include "clang/Lex/HeaderSearchOptions.h"
Hal Finkel1a328f52016-12-15 02:19:17 +000018#include "llvm/ADT/SmallSet.h"
Eric Christopher583a1f72015-09-26 01:25:08 +000019#include "llvm/ADT/StringExtras.h"
Saleem Abdulrasool62849c62014-05-08 02:28:32 +000020#include "llvm/ADT/StringSwitch.h"
Steven Wu27fb5222016-05-11 16:26:03 +000021#include "llvm/ADT/Triple.h"
Chandler Carruth418bd1a2015-01-15 02:16:55 +000022#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthaab5ec02015-01-31 11:18:46 +000023#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonffc4e242016-11-11 05:35:12 +000024#include "llvm/Bitcode/BitcodeReader.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000025#include "llvm/Bitcode/BitcodeWriter.h"
26#include "llvm/Bitcode/BitcodeWriterPass.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000027#include "llvm/CodeGen/RegAllocRegistry.h"
28#include "llvm/CodeGen/SchedulerRegistry.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
Chandler Carruth0a50c492014-01-12 11:11:50 +000030#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth9828e692015-02-13 09:57:03 +000031#include "llvm/IR/LegacyPassManager.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Module.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000033#include "llvm/IR/ModuleSummaryIndex.h"
Chandler Carruthca884742014-01-13 09:26:48 +000034#include "llvm/IR/Verifier.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000035#include "llvm/LTO/LTOBackend.h"
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000036#include "llvm/MC/MCAsmInfo.h"
Evan Chengeeb486d2011-06-29 01:14:32 +000037#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth50f9e892016-12-23 20:44:01 +000038#include "llvm/Passes/PassBuilder.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000039#include "llvm/Support/CommandLine.h"
Teresa Johnson9e3f4742016-08-12 18:12:08 +000040#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000041#include "llvm/Support/PrettyStackTrace.h"
Evan Cheng494eb062011-08-24 18:09:14 +000042#include "llvm/Support/TargetRegistry.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000043#include "llvm/Support/Timer.h"
44#include "llvm/Support/raw_ostream.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000045#include "llvm/Target/TargetMachine.h"
46#include "llvm/Target/TargetOptions.h"
Eric Christopher3de08532014-08-04 21:33:42 +000047#include "llvm/Target/TargetSubtargetInfo.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000048#include "llvm/Transforms/Coroutines.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000049#include "llvm/Transforms/IPO.h"
Chandler Carruthb72c19f2016-08-17 03:09:11 +000050#include "llvm/Transforms/IPO/AlwaysInliner.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000051#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000052#include "llvm/Transforms/Instrumentation.h"
Michael Gottesman90cae772013-01-28 01:36:00 +000053#include "llvm/Transforms/ObjCARC.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000054#include "llvm/Transforms/Scalar.h"
Chandler Carruth4ddaadc2016-03-11 09:02:43 +000055#include "llvm/Transforms/Scalar/GVN.h"
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +000056#include "llvm/Transforms/Utils/SymbolRewriter.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000057#include <memory>
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000058using namespace clang;
59using namespace llvm;
60
61namespace {
62
Davide Italiano945de432017-02-13 16:07:05 +000063// Default filename used for profile generation.
64static constexpr StringLiteral DefaultProfileGenName = "default_%m.profraw";
65
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000066class EmitAssemblyHelper {
David Blaikie9c902b52011-09-25 23:23:43 +000067 DiagnosticsEngine &Diags;
Saleem Abdulrasool888e2892017-01-05 16:02:32 +000068 const HeaderSearchOptions &HSOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000069 const CodeGenOptions &CodeGenOpts;
Nick Lewycky432add52011-12-02 22:17:00 +000070 const clang::TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000071 const LangOptions &LangOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000072 Module *TheModule;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000073
74 Timer CodeGenerationTime;
75
Peter Collingbourne03f89072016-07-15 00:55:40 +000076 std::unique_ptr<raw_pwrite_stream> OS;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000077
Chandler Carruthd294bdb2015-02-01 12:26:23 +000078 TargetIRAnalysis getTargetIRAnalysis() const {
Chandler Carruthaab5ec02015-01-31 11:18:46 +000079 if (TM)
Chandler Carruthd294bdb2015-02-01 12:26:23 +000080 return TM->getTargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +000081
Chandler Carruthd294bdb2015-02-01 12:26:23 +000082 return TargetIRAnalysis();
Chandler Carruthaab5ec02015-01-31 11:18:46 +000083 }
84
Teresa Johnson9e3f4742016-08-12 18:12:08 +000085 void CreatePasses(legacy::PassManager &MPM, legacy::FunctionPassManager &FPM);
Nadav Rotemec57ab32012-10-24 00:53:38 +000086
Rafael Espindola2f16bc12015-04-14 15:15:49 +000087 /// Generates the TargetMachine.
Peter Collingbourne03f89072016-07-15 00:55:40 +000088 /// Leaves TM unchanged if it is unable to create the target machine.
Nadav Rotemdc06b2d2012-10-24 03:52:31 +000089 /// Some of our clang tests specify triples which are not built
90 /// into clang. This is okay because these tests check the generated
91 /// IR, and they require DataLayout which depends on the triple.
92 /// In this case, we allow this method to fail and not report an error.
93 /// When MustCreateTM is used, we print an error if we are unable to load
94 /// the requested target.
Peter Collingbourne03f89072016-07-15 00:55:40 +000095 void CreateTargetMachine(bool MustCreateTM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000096
Rafael Espindola2f16bc12015-04-14 15:15:49 +000097 /// Add passes necessary to emit assembly or LLVM IR.
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000098 ///
99 /// \return True on success.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000100 bool AddEmitPasses(legacy::PassManager &CodeGenPasses, BackendAction Action,
101 raw_pwrite_stream &OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000102
103public:
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000104 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
105 const HeaderSearchOptions &HeaderSearchOpts,
106 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +0000107 const clang::TargetOptions &TOpts,
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000108 const LangOptions &LOpts, Module *M)
Saleem Abdulrasool888e2892017-01-05 16:02:32 +0000109 : Diags(_Diags), HSOpts(HeaderSearchOpts), CodeGenOpts(CGOpts),
110 TargetOpts(TOpts), LangOpts(LOpts), TheModule(M),
111 CodeGenerationTime("codegen", "Code Generation Time") {}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000112
113 ~EmitAssemblyHelper() {
Alp Tokerf4e22382013-12-20 20:26:53 +0000114 if (CodeGenOpts.DisableFree)
David Blaikiea97eaa12014-08-29 16:53:14 +0000115 BuryPointer(std::move(TM));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000116 }
117
Ahmed Charlesb8984322014-03-07 20:03:18 +0000118 std::unique_ptr<TargetMachine> TM;
Alp Tokerf4e22382013-12-20 20:26:53 +0000119
Peter Collingbourne03f89072016-07-15 00:55:40 +0000120 void EmitAssembly(BackendAction Action,
121 std::unique_ptr<raw_pwrite_stream> OS);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000122
123 void EmitAssemblyWithNewPassManager(BackendAction Action,
124 std::unique_ptr<raw_pwrite_stream> OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000125};
126
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000127// We need this wrapper to access LangOpts and CGOpts from extension functions
128// that we add to the PassManagerBuilder.
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000129class PassManagerBuilderWrapper : public PassManagerBuilder {
130public:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000131 PassManagerBuilderWrapper(const Triple &TargetTriple,
132 const CodeGenOptions &CGOpts,
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000133 const LangOptions &LangOpts)
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000134 : PassManagerBuilder(), TargetTriple(TargetTriple), CGOpts(CGOpts),
135 LangOpts(LangOpts) {}
136 const Triple &getTargetTriple() const { return TargetTriple; }
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000137 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000138 const LangOptions &getLangOpts() const { return LangOpts; }
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000139
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000140private:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000141 const Triple &TargetTriple;
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000142 const CodeGenOptions &CGOpts;
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000143 const LangOptions &LangOpts;
144};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000145}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000146
Dan Gohman5932ce22012-01-17 20:54:51 +0000147static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
148 if (Builder.OptLevel > 0)
149 PM.add(createObjCARCAPElimPass());
150}
151
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000152static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
153 if (Builder.OptLevel > 0)
154 PM.add(createObjCARCExpandPass());
155}
156
157static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
158 if (Builder.OptLevel > 0)
159 PM.add(createObjCARCOptPass());
160}
161
Diego Novillob56be642014-03-03 20:06:18 +0000162static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000163 legacy::PassManagerBase &PM) {
Diego Novillob56be642014-03-03 20:06:18 +0000164 PM.add(createAddDiscriminatorsPass());
165}
166
Nuno Lopesa4255892012-05-22 17:19:45 +0000167static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000168 legacy::PassManagerBase &PM) {
Joey Goulyebc59d52012-11-23 10:39:49 +0000169 PM.add(createBoundsCheckingPass());
Nuno Lopesa4255892012-05-22 17:19:45 +0000170}
171
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000172static void addSanitizerCoveragePass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000173 legacy::PassManagerBase &PM) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000174 const PassManagerBuilderWrapper &BuilderWrapper =
175 static_cast<const PassManagerBuilderWrapper&>(Builder);
176 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000177 SanitizerCoverageOptions Opts;
178 Opts.CoverageType =
179 static_cast<SanitizerCoverageOptions::Type>(CGOpts.SanitizeCoverageType);
180 Opts.IndirectCalls = CGOpts.SanitizeCoverageIndirectCalls;
181 Opts.TraceBB = CGOpts.SanitizeCoverageTraceBB;
182 Opts.TraceCmp = CGOpts.SanitizeCoverageTraceCmp;
Kostya Serebryany3b419712016-08-30 01:27:03 +0000183 Opts.TraceDiv = CGOpts.SanitizeCoverageTraceDiv;
184 Opts.TraceGep = CGOpts.SanitizeCoverageTraceGep;
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000185 Opts.Use8bitCounters = CGOpts.SanitizeCoverage8bitCounters;
Kostya Serebryanyd4590c72016-02-17 21:34:43 +0000186 Opts.TracePC = CGOpts.SanitizeCoverageTracePC;
Kostya Serebryany60cdd612016-09-14 01:39:49 +0000187 Opts.TracePCGuard = CGOpts.SanitizeCoverageTracePCGuard;
Alexey Samsonov3f3b3ab2015-05-07 18:31:29 +0000188 PM.add(createSanitizerCoverageModulePass(Opts));
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000189}
190
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000191// Check if ASan should use GC-friendly instrumentation for globals.
192// First of all, there is no point if -fdata-sections is off (expect for MachO,
193// where this is not a factor). Also, on ELF this feature requires an assembler
194// extension that only works with -integrated-as at the moment.
195static bool asanUseGlobalsGC(const Triple &T, const CodeGenOptions &CGOpts) {
196 switch (T.getObjectFormat()) {
197 case Triple::MachO:
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000198 case Triple::COFF:
Evgeniy Stepanovc7b90942017-04-26 00:51:06 +0000199 return true;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000200 case Triple::ELF:
201 return CGOpts.DataSections && !CGOpts.DisableIntegratedAS;
202 default:
203 return false;
204 }
205}
206
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000207static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000208 legacy::PassManagerBase &PM) {
Yury Gribov5bfeca12015-11-11 10:45:48 +0000209 const PassManagerBuilderWrapper &BuilderWrapper =
210 static_cast<const PassManagerBuilderWrapper&>(Builder);
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000211 const Triple &T = BuilderWrapper.getTargetTriple();
Yury Gribov5bfeca12015-11-11 10:45:48 +0000212 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
213 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Address);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000214 bool UseAfterScope = CGOpts.SanitizeAddressUseAfterScope;
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000215 bool UseGlobalsGC = asanUseGlobalsGC(T, CGOpts);
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000216 PM.add(createAddressSanitizerFunctionPass(/*CompileKernel*/ false, Recover,
217 UseAfterScope));
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000218 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/ false, Recover,
219 UseGlobalsGC));
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000220}
221
222static void addKernelAddressSanitizerPasses(const PassManagerBuilder &Builder,
223 legacy::PassManagerBase &PM) {
Vitaly Buka9d4eb6f2016-06-02 00:24:20 +0000224 PM.add(createAddressSanitizerFunctionPass(
225 /*CompileKernel*/ true,
226 /*Recover*/ true, /*UseAfterScope*/ false));
Yury Gribov5bfeca12015-11-11 10:45:48 +0000227 PM.add(createAddressSanitizerModulePass(/*CompileKernel*/true,
228 /*Recover*/true));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000229}
230
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000231static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000232 legacy::PassManagerBase &PM) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000233 const PassManagerBuilderWrapper &BuilderWrapper =
234 static_cast<const PassManagerBuilderWrapper&>(Builder);
235 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Evgeniy Stepanov5b5370a2016-11-07 21:02:11 +0000236 int TrackOrigins = CGOpts.SanitizeMemoryTrackOrigins;
237 bool Recover = CGOpts.SanitizeRecover.has(SanitizerKind::Memory);
238 PM.add(createMemorySanitizerPass(TrackOrigins, Recover));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000239
240 // MemorySanitizer inserts complex instrumentation that mostly follows
241 // the logic of the original code, but operates on "shadow" values.
242 // It can benefit from re-running some general purpose optimization passes.
243 if (Builder.OptLevel > 0) {
244 PM.add(createEarlyCSEPass());
245 PM.add(createReassociatePass());
246 PM.add(createLICMPass());
247 PM.add(createGVNPass());
248 PM.add(createInstructionCombiningPass());
249 PM.add(createDeadStoreEliminationPass());
250 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000251}
252
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000253static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000254 legacy::PassManagerBase &PM) {
Alexey Samsonov1cf07ea2014-06-02 18:08:08 +0000255 PM.add(createThreadSanitizerPass());
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000256}
257
Peter Collingbournec3772752013-08-07 22:47:34 +0000258static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000259 legacy::PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000260 const PassManagerBuilderWrapper &BuilderWrapper =
261 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonovae5804f2014-10-15 20:22:54 +0000262 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonova511cdd2015-02-04 17:40:08 +0000263 PM.add(createDataFlowSanitizerPass(LangOpts.SanitizerBlacklistFiles));
Peter Collingbournec3772752013-08-07 22:47:34 +0000264}
265
Derek Bruening256c2e12016-04-21 21:32:04 +0000266static void addEfficiencySanitizerPass(const PassManagerBuilder &Builder,
267 legacy::PassManagerBase &PM) {
268 const PassManagerBuilderWrapper &BuilderWrapper =
269 static_cast<const PassManagerBuilderWrapper&>(Builder);
270 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
271 EfficiencySanitizerOptions Opts;
272 if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyCacheFrag))
273 Opts.ToolType = EfficiencySanitizerOptions::ESAN_CacheFrag;
Derek Bruening293772e2016-05-25 00:41:24 +0000274 else if (LangOpts.Sanitize.has(SanitizerKind::EfficiencyWorkingSet))
275 Opts.ToolType = EfficiencySanitizerOptions::ESAN_WorkingSet;
Derek Bruening256c2e12016-04-21 21:32:04 +0000276 PM.add(createEfficiencySanitizerPass(Opts));
277}
278
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000279static TargetLibraryInfoImpl *createTLII(llvm::Triple &TargetTriple,
280 const CodeGenOptions &CodeGenOpts) {
281 TargetLibraryInfoImpl *TLII = new TargetLibraryInfoImpl(TargetTriple);
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000282 if (!CodeGenOpts.SimplifyLibCalls)
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000283 TLII->disableAllFunctions();
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000284 else {
285 // Disable individual libc/libm calls in TargetLibraryInfo.
David L. Jones7a7dd032017-01-23 23:16:58 +0000286 LibFunc F;
Chad Rosier7dbc9cf2016-01-06 14:35:46 +0000287 for (auto &FuncName : CodeGenOpts.getNoBuiltinFuncs())
288 if (TLII->getLibFunc(FuncName, F))
289 TLII->setUnavailable(F);
290 }
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000291
292 switch (CodeGenOpts.getVecLib()) {
293 case CodeGenOptions::Accelerate:
294 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::Accelerate);
295 break;
Matt Masten6731dea2016-07-29 16:44:24 +0000296 case CodeGenOptions::SVML:
297 TLII->addVectorizableFunctionsFromVecLib(TargetLibraryInfoImpl::SVML);
298 break;
Michael Zolotukhinc888dd02015-03-17 20:03:11 +0000299 default:
300 break;
301 }
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000302 return TLII;
Rafael Espindolab8a71c52014-08-21 17:58:42 +0000303}
304
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000305static void addSymbolRewriterPass(const CodeGenOptions &Opts,
Chandler Carruth8f4f5092015-02-13 09:47:49 +0000306 legacy::PassManager *MPM) {
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000307 llvm::SymbolRewriter::RewriteDescriptorList DL;
308
309 llvm::SymbolRewriter::RewriteMapParser MapParser;
310 for (const auto &MapFile : Opts.RewriteMapFiles)
311 MapParser.parse(MapFile, &DL);
312
313 MPM->add(createRewriteSymbolsPass(DL));
314}
315
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000316static CodeGenOpt::Level getCGOptLevel(const CodeGenOptions &CodeGenOpts) {
317 switch (CodeGenOpts.OptimizationLevel) {
318 default:
319 llvm_unreachable("Invalid optimization level!");
320 case 0:
321 return CodeGenOpt::None;
322 case 1:
323 return CodeGenOpt::Less;
324 case 2:
325 return CodeGenOpt::Default; // O2/Os/Oz
326 case 3:
327 return CodeGenOpt::Aggressive;
328 }
329}
330
331static llvm::CodeModel::Model getCodeModel(const CodeGenOptions &CodeGenOpts) {
332 unsigned CodeModel =
333 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
334 .Case("small", llvm::CodeModel::Small)
335 .Case("kernel", llvm::CodeModel::Kernel)
336 .Case("medium", llvm::CodeModel::Medium)
337 .Case("large", llvm::CodeModel::Large)
338 .Case("default", llvm::CodeModel::Default)
339 .Default(~0u);
340 assert(CodeModel != ~0u && "invalid code model!");
341 return static_cast<llvm::CodeModel::Model>(CodeModel);
342}
343
344static llvm::Reloc::Model getRelocModel(const CodeGenOptions &CodeGenOpts) {
Davide Italiano1a3665bb2017-04-01 21:07:07 +0000345 // Keep this synced with the equivalent code in
346 // lib/Frontend/CompilerInvocation.cpp
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000347 llvm::Optional<llvm::Reloc::Model> RM;
348 RM = llvm::StringSwitch<llvm::Reloc::Model>(CodeGenOpts.RelocationModel)
349 .Case("static", llvm::Reloc::Static)
350 .Case("pic", llvm::Reloc::PIC_)
351 .Case("ropi", llvm::Reloc::ROPI)
352 .Case("rwpi", llvm::Reloc::RWPI)
353 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
354 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC);
355 assert(RM.hasValue() && "invalid PIC model!");
356 return *RM;
357}
358
359static TargetMachine::CodeGenFileType getCodeGenFileType(BackendAction Action) {
360 if (Action == Backend_EmitObj)
361 return TargetMachine::CGFT_ObjectFile;
362 else if (Action == Backend_EmitMCNull)
363 return TargetMachine::CGFT_Null;
364 else {
365 assert(Action == Backend_EmitAssembly && "Invalid action!");
366 return TargetMachine::CGFT_AssemblyFile;
367 }
368}
369
370static void initTargetOptions(llvm::TargetOptions &Options,
371 const CodeGenOptions &CodeGenOpts,
372 const clang::TargetOptions &TargetOpts,
373 const LangOptions &LangOpts,
374 const HeaderSearchOptions &HSOpts) {
375 Options.ThreadModel =
376 llvm::StringSwitch<llvm::ThreadModel::Model>(CodeGenOpts.ThreadModel)
377 .Case("posix", llvm::ThreadModel::POSIX)
378 .Case("single", llvm::ThreadModel::Single);
379
380 // Set float ABI type.
381 assert((CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp" ||
382 CodeGenOpts.FloatABI == "hard" || CodeGenOpts.FloatABI.empty()) &&
383 "Invalid Floating Point ABI!");
384 Options.FloatABIType =
385 llvm::StringSwitch<llvm::FloatABI::ABIType>(CodeGenOpts.FloatABI)
386 .Case("soft", llvm::FloatABI::Soft)
387 .Case("softfp", llvm::FloatABI::Soft)
388 .Case("hard", llvm::FloatABI::Hard)
389 .Default(llvm::FloatABI::Default);
390
391 // Set FP fusion mode.
392 switch (LangOpts.getDefaultFPContractMode()) {
393 case LangOptions::FPC_Off:
Adam Nemet03af4242017-04-20 17:09:35 +0000394 // Preserve any contraction performed by the front-end. (Strict performs
395 // splitting of the muladd instrinsic in the backend.)
396 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000397 break;
398 case LangOptions::FPC_On:
399 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
400 break;
401 case LangOptions::FPC_Fast:
402 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
403 break;
404 }
405
406 Options.UseInitArray = CodeGenOpts.UseInitArray;
407 Options.DisableIntegratedAS = CodeGenOpts.DisableIntegratedAS;
408 Options.CompressDebugSections = CodeGenOpts.CompressDebugSections;
409 Options.RelaxELFRelocations = CodeGenOpts.RelaxELFRelocations;
410
411 // Set EABI version.
412 Options.EABIVersion = llvm::StringSwitch<llvm::EABI>(TargetOpts.EABIVersion)
413 .Case("4", llvm::EABI::EABI4)
414 .Case("5", llvm::EABI::EABI5)
415 .Case("gnu", llvm::EABI::GNU)
416 .Default(llvm::EABI::Default);
417
418 if (LangOpts.SjLjExceptions)
419 Options.ExceptionModel = llvm::ExceptionHandling::SjLj;
420
421 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
422 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
423 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
424 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
425 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
426 Options.FunctionSections = CodeGenOpts.FunctionSections;
427 Options.DataSections = CodeGenOpts.DataSections;
428 Options.UniqueSectionNames = CodeGenOpts.UniqueSectionNames;
429 Options.EmulatedTLS = CodeGenOpts.EmulatedTLS;
430 Options.DebuggerTuning = CodeGenOpts.getDebuggerTuning();
431
David Blaikie81503552017-04-21 23:35:36 +0000432 if (CodeGenOpts.EnableSplitDwarf)
433 Options.MCOptions.SplitDwarfFile = CodeGenOpts.SplitDwarfFile;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000434 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
435 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
436 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
437 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
438 Options.MCOptions.MCIncrementalLinkerCompatible =
439 CodeGenOpts.IncrementalLinkerCompatible;
440 Options.MCOptions.MCPIECopyRelocations = CodeGenOpts.PIECopyRelocations;
441 Options.MCOptions.MCFatalWarnings = CodeGenOpts.FatalWarnings;
442 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
443 Options.MCOptions.PreserveAsmComments = CodeGenOpts.PreserveAsmComments;
444 Options.MCOptions.ABIName = TargetOpts.ABI;
445 for (const auto &Entry : HSOpts.UserEntries)
446 if (!Entry.IsFramework &&
447 (Entry.Group == frontend::IncludeDirGroup::Quoted ||
448 Entry.Group == frontend::IncludeDirGroup::Angled ||
449 Entry.Group == frontend::IncludeDirGroup::System))
450 Options.MCOptions.IASSearchPaths.push_back(
451 Entry.IgnoreSysRoot ? Entry.Path : HSOpts.Sysroot + Entry.Path);
452}
453
Peter Collingbourne03f89072016-07-15 00:55:40 +0000454void EmitAssemblyHelper::CreatePasses(legacy::PassManager &MPM,
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000455 legacy::FunctionPassManager &FPM) {
Chandler Carruth93786da2016-12-23 00:23:01 +0000456 // Handle disabling of all LLVM passes, where we want to preserve the
457 // internal module before any optimization.
Steven Wu546a1962015-07-17 20:09:56 +0000458 if (CodeGenOpts.DisableLLVMPasses)
459 return;
460
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000461 // Figure out TargetLibraryInfo. This needs to be added to MPM and FPM
462 // manually (and not via PMBuilder), since some passes (eg. InstrProfiling)
463 // are inserted before PMBuilder ones - they'd get the default-constructed
464 // TLI with an unknown target otherwise.
Teresa Johnsonaff22322015-12-07 19:21:34 +0000465 Triple TargetTriple(TheModule->getTargetTriple());
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000466 std::unique_ptr<TargetLibraryInfoImpl> TLII(
467 createTLII(TargetTriple, CodeGenOpts));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000468
Evgeniy Stepanovdf217a22017-04-24 19:34:12 +0000469 PassManagerBuilderWrapper PMBuilder(TargetTriple, CodeGenOpts, LangOpts);
470
Chandler Carruthfcd33142016-12-23 01:24:49 +0000471 // At O0 and O1 we only run the always inliner which is more efficient. At
472 // higher optimization levels we run the normal inliner.
473 if (CodeGenOpts.OptimizationLevel <= 1) {
Mehdi Amini7f873072017-01-06 23:18:09 +0000474 bool InsertLifetimeIntrinsics = (CodeGenOpts.OptimizationLevel != 0 &&
475 !CodeGenOpts.DisableLifetimeMarkers);
Chandler Carruthfcd33142016-12-23 01:24:49 +0000476 PMBuilder.Inliner = createAlwaysInlinerLegacyPass(InsertLifetimeIntrinsics);
477 } else {
Dehao Chence39fdd2017-03-21 19:55:46 +0000478 // We do not want to inline hot callsites for SamplePGO module-summary build
479 // because profile annotation will happen again in ThinLTO backend, and we
480 // want the IR of the hot path to match the profile.
Chandler Carruthfcd33142016-12-23 01:24:49 +0000481 PMBuilder.Inliner = createFunctionInliningPass(
Dehao Chence39fdd2017-03-21 19:55:46 +0000482 CodeGenOpts.OptimizationLevel, CodeGenOpts.OptimizeSize,
483 (!CodeGenOpts.SampleProfileFile.empty() &&
484 CodeGenOpts.EmitSummaryIndex));
Teresa Johnsonaff22322015-12-07 19:21:34 +0000485 }
486
Chandler Carruthfcd33142016-12-23 01:24:49 +0000487 PMBuilder.OptLevel = CodeGenOpts.OptimizationLevel;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000488 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000489 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
490 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
491 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000492
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000493 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Nick Lewyckyf04f2372014-10-24 00:49:29 +0000494 PMBuilder.MergeFunctions = CodeGenOpts.MergeFunctions;
Teresa Johnsona0d29402016-03-15 00:04:44 +0000495 PMBuilder.PrepareForThinLTO = CodeGenOpts.EmitSummaryIndex;
Teresa Johnson8749d8042015-07-06 16:23:00 +0000496 PMBuilder.PrepareForLTO = CodeGenOpts.PrepareForLTO;
Hal Finkelce0697f2013-11-17 16:03:29 +0000497 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000498
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000499 MPM.add(new TargetLibraryInfoWrapperPass(*TLII));
500
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000501 if (TM)
Stanislav Mekhanoshin61da0672017-01-26 16:49:21 +0000502 TM->adjustPassManager(PMBuilder);
Justin Lebar5a7df9c2016-04-27 19:12:56 +0000503
Dehao Chen7810d4f2017-02-21 20:36:21 +0000504 if (CodeGenOpts.DebugInfoForProfiling ||
505 !CodeGenOpts.SampleProfileFile.empty())
506 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
507 addAddDiscriminatorsPass);
Diego Novillob56be642014-03-03 20:06:18 +0000508
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000509 // In ObjC ARC mode, add the main ARC optimization passes.
510 if (LangOpts.ObjCAutoRefCount) {
511 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
512 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000513 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
514 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000515 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
516 addObjCARCOptPass);
517 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000518
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000519 if (LangOpts.Sanitize.has(SanitizerKind::LocalBounds)) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000520 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
521 addBoundsCheckingPass);
522 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
523 addBoundsCheckingPass);
524 }
525
Alexey Samsonovdfa908c2015-05-07 22:34:06 +0000526 if (CodeGenOpts.SanitizeCoverageType ||
527 CodeGenOpts.SanitizeCoverageIndirectCalls ||
528 CodeGenOpts.SanitizeCoverageTraceCmp) {
Kostya Serebryany75b4f9e2014-11-11 22:15:07 +0000529 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
530 addSanitizerCoveragePass);
531 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
532 addSanitizerCoveragePass);
533 }
534
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000535 if (LangOpts.Sanitize.has(SanitizerKind::Address)) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000536 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000537 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000538 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000539 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000540 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000541
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +0000542 if (LangOpts.Sanitize.has(SanitizerKind::KernelAddress)) {
543 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
544 addKernelAddressSanitizerPasses);
545 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
546 addKernelAddressSanitizerPasses);
547 }
548
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000549 if (LangOpts.Sanitize.has(SanitizerKind::Memory)) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000550 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
551 addMemorySanitizerPass);
552 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
553 addMemorySanitizerPass);
554 }
555
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000556 if (LangOpts.Sanitize.has(SanitizerKind::Thread)) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000557 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000558 addThreadSanitizerPass);
559 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
560 addThreadSanitizerPass);
561 }
562
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000563 if (LangOpts.Sanitize.has(SanitizerKind::DataFlow)) {
Peter Collingbournec3772752013-08-07 22:47:34 +0000564 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
565 addDataFlowSanitizerPass);
566 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
567 addDataFlowSanitizerPass);
568 }
569
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000570 if (LangOpts.CoroutinesTS)
571 addCoroutinePassesToExtensionPoints(PMBuilder);
572
Derek Bruening256c2e12016-04-21 21:32:04 +0000573 if (LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency)) {
574 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
575 addEfficiencySanitizerPass);
576 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
577 addEfficiencySanitizerPass);
578 }
579
Chris Lattner5c123672011-05-21 20:40:11 +0000580 // Set up the per-function pass manager.
Marcin Koscielnicki9a063e72016-11-22 20:03:35 +0000581 FPM.add(new TargetLibraryInfoWrapperPass(*TLII));
Chris Lattner5c123672011-05-21 20:40:11 +0000582 if (CodeGenOpts.VerifyModule)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000583 FPM.add(createVerifierPass());
Andrew Trickb2a84722011-04-05 18:49:32 +0000584
Chris Lattner5c123672011-05-21 20:40:11 +0000585 // Set up the per-module pass manager.
Saleem Abdulrasool76a4b952015-01-09 05:10:20 +0000586 if (!CodeGenOpts.RewriteMapFiles.empty())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000587 addSymbolRewriterPass(CodeGenOpts, &MPM);
Chris Lattnerd98cec52011-02-18 22:20:38 +0000588
Nick Lewyckyc02bbb62013-03-20 01:38:16 +0000589 if (!CodeGenOpts.DisableGCov &&
590 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000591 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
592 // LLVM's -default-gcov-version flag is set to something invalid.
593 GCOVOptions Options;
594 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
595 Options.EmitData = CodeGenOpts.EmitGcovArcs;
596 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
597 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
598 Options.NoRedZone = CodeGenOpts.DisableRedZone;
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000599 Options.FunctionNamesInData =
Nick Lewycky6f15b2902013-03-20 02:14:38 +0000600 !CodeGenOpts.CoverageNoFunctionNamesInData;
Justin Bogner4e462372015-03-16 23:52:21 +0000601 Options.ExitBlockBeforeBody = CodeGenOpts.CoverageExitBlockBeforeBody;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000602 MPM.add(createGCOVProfilerPass(Options));
Benjamin Kramer8c305922016-02-02 11:06:51 +0000603 if (CodeGenOpts.getDebugInfo() == codegenoptions::NoDebugInfo)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000604 MPM.add(createStripSymbolsPass(true));
Nick Lewycky207bce32011-04-21 23:44:07 +0000605 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000606
Rong Xu9837ef52016-02-04 18:39:09 +0000607 if (CodeGenOpts.hasProfileClangInstr()) {
Justin Bogner970ac602014-12-08 19:04:51 +0000608 InstrProfOptions Options;
609 Options.NoRedZone = CodeGenOpts.DisableRedZone;
Justin Bognera71e6812015-04-30 23:49:42 +0000610 Options.InstrProfileOutput = CodeGenOpts.InstrProfileOutput;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000611 MPM.add(createInstrProfilingLegacyPass(Options));
Justin Bogner970ac602014-12-08 19:04:51 +0000612 }
Rong Xu522b5cb2016-02-29 18:54:59 +0000613 if (CodeGenOpts.hasProfileIRInstr()) {
Xinliang David Lib65f8ae2016-07-23 04:28:59 +0000614 PMBuilder.EnablePGOInstrGen = true;
Rong Xu522b5cb2016-02-29 18:54:59 +0000615 if (!CodeGenOpts.InstrProfileOutput.empty())
616 PMBuilder.PGOInstrGen = CodeGenOpts.InstrProfileOutput;
617 else
Davide Italiano945de432017-02-13 16:07:05 +0000618 PMBuilder.PGOInstrGen = DefaultProfileGenName;
Rong Xu522b5cb2016-02-29 18:54:59 +0000619 }
Rong Xu9c6f1532016-03-02 20:59:36 +0000620 if (CodeGenOpts.hasProfileIRUse())
621 PMBuilder.PGOInstrUse = CodeGenOpts.ProfileInstrumentUsePath;
Justin Bogner970ac602014-12-08 19:04:51 +0000622
Dehao Chen5717aff2016-12-14 21:41:04 +0000623 if (!CodeGenOpts.SampleProfileFile.empty())
624 PMBuilder.PGOSampleUse = CodeGenOpts.SampleProfileFile;
Diego Novillod3ef1082015-08-25 15:25:13 +0000625
Peter Collingbourne03f89072016-07-15 00:55:40 +0000626 PMBuilder.populateFunctionPassManager(FPM);
627 PMBuilder.populateModulePassManager(MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000628}
629
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000630static void setCommandLineOpts(const CodeGenOptions &CodeGenOpts) {
Yaxun Liub5e80c32016-04-12 20:22:32 +0000631 SmallVector<const char *, 16> BackendArgs;
632 BackendArgs.push_back("clang"); // Fake program name.
633 if (!CodeGenOpts.DebugPass.empty()) {
634 BackendArgs.push_back("-debug-pass");
635 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
636 }
637 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
638 BackendArgs.push_back("-limit-float-precision");
639 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
640 }
641 for (const std::string &BackendOption : CodeGenOpts.BackendOptions)
642 BackendArgs.push_back(BackendOption.c_str());
643 BackendArgs.push_back(nullptr);
644 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
645 BackendArgs.data());
646}
647
Peter Collingbourne03f89072016-07-15 00:55:40 +0000648void EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000649 // Create the TargetMachine for generating code.
650 std::string Error;
651 std::string Triple = TheModule->getTargetTriple();
652 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
653 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000654 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000655 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000656 return;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000657 }
658
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000659 llvm::CodeModel::Model CM = getCodeModel(CodeGenOpts);
Eric Christopher583a1f72015-09-26 01:25:08 +0000660 std::string FeaturesStr =
661 llvm::join(TargetOpts.Features.begin(), TargetOpts.Features.end(), ",");
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000662 llvm::Reloc::Model RM = getRelocModel(CodeGenOpts);
663 CodeGenOpt::Level OptLevel = getCGOptLevel(CodeGenOpts);
Evan Chengdd286bc2011-11-16 08:38:55 +0000664
Nick Lewycky432add52011-12-02 22:17:00 +0000665 llvm::TargetOptions Options;
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000666 initTargetOptions(Options, CodeGenOpts, TargetOpts, LangOpts, HSOpts);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000667 TM.reset(TheTarget->createTargetMachine(Triple, TargetOpts.CPU, FeaturesStr,
668 Options, RM, CM, OptLevel));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000669}
670
Peter Collingbourne03f89072016-07-15 00:55:40 +0000671bool EmitAssemblyHelper::AddEmitPasses(legacy::PassManager &CodeGenPasses,
672 BackendAction Action,
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000673 raw_pwrite_stream &OS) {
Chad Rosierb1cfc682012-02-29 20:14:59 +0000674 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000675 llvm::Triple TargetTriple(TheModule->getTargetTriple());
Chandler Carruth57bb7c72015-01-24 02:25:21 +0000676 std::unique_ptr<TargetLibraryInfoImpl> TLII(
677 createTLII(TargetTriple, CodeGenOpts));
Peter Collingbourne03f89072016-07-15 00:55:40 +0000678 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(*TLII));
Chad Rosierb1cfc682012-02-29 20:14:59 +0000679
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000680 // Normal mode, emit a .s or .o file by running the code generator. Note,
681 // this also adds codegenerator level optimization passes.
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000682 TargetMachine::CodeGenFileType CGFT = getCodeGenFileType(Action);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000683
684 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
685 // "codegen" passes so that it isn't run multiple times when there is
686 // inlining happening.
Steven Wu1d56be82015-05-02 00:56:15 +0000687 if (CodeGenOpts.OptimizationLevel > 0)
Peter Collingbourne03f89072016-07-15 00:55:40 +0000688 CodeGenPasses.add(createObjCARCContractPass());
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000689
Peter Collingbourne03f89072016-07-15 00:55:40 +0000690 if (TM->addPassesToEmitFile(CodeGenPasses, OS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000691 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
692 Diags.Report(diag::err_fe_unable_to_interface_with_target);
693 return false;
694 }
695
696 return true;
697}
698
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000699void EmitAssemblyHelper::EmitAssembly(BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +0000700 std::unique_ptr<raw_pwrite_stream> OS) {
Craig Topper8a13c412014-05-21 05:09:00 +0000701 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000702
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000703 setCommandLineOpts(CodeGenOpts);
Yaxun Liub5e80c32016-04-12 20:22:32 +0000704
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000705 bool UsesCodeGen = (Action != Backend_EmitNothing &&
706 Action != Backend_EmitBC &&
707 Action != Backend_EmitLL);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000708 CreateTargetMachine(UsesCodeGen);
Alp Tokerf4e22382013-12-20 20:26:53 +0000709
Rafael Espindolab633d202015-06-23 13:59:36 +0000710 if (UsesCodeGen && !TM)
711 return;
712 if (TM)
Mehdi Aminica3cf9e2015-07-24 16:04:29 +0000713 TheModule->setDataLayout(TM->createDataLayout());
Teresa Johnson4b4f4b92016-01-08 17:04:29 +0000714
Peter Collingbourne03f89072016-07-15 00:55:40 +0000715 legacy::PassManager PerModulePasses;
716 PerModulePasses.add(
717 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
718
719 legacy::FunctionPassManager PerFunctionPasses(TheModule);
720 PerFunctionPasses.add(
721 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
722
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000723 CreatePasses(PerModulePasses, PerFunctionPasses);
Peter Collingbourne03f89072016-07-15 00:55:40 +0000724
725 legacy::PassManager CodeGenPasses;
726 CodeGenPasses.add(
727 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
Nadav Rotemec57ab32012-10-24 00:53:38 +0000728
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000729 std::unique_ptr<raw_fd_ostream> ThinLinkOS;
730
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000731 switch (Action) {
732 case Backend_EmitNothing:
733 break;
734
735 case Backend_EmitBC:
Teresa Johnson488d1dc2017-03-23 19:47:49 +0000736 if (CodeGenOpts.EmitSummaryIndex) {
737 if (!CodeGenOpts.ThinLinkBitcodeFile.empty()) {
738 std::error_code EC;
739 ThinLinkOS.reset(new llvm::raw_fd_ostream(
740 CodeGenOpts.ThinLinkBitcodeFile, EC,
741 llvm::sys::fs::F_None));
742 if (EC) {
743 Diags.Report(diag::err_fe_unable_to_open_output) << CodeGenOpts.ThinLinkBitcodeFile
744 << EC.message();
745 return;
746 }
747 }
748 PerModulePasses.add(
749 createWriteThinLTOBitcodePass(*OS, ThinLinkOS.get()));
750 }
Peter Collingbourneb8847162017-01-26 23:51:50 +0000751 else
752 PerModulePasses.add(
753 createBitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000754 break;
755
756 case Backend_EmitLL:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000757 PerModulePasses.add(
Duncan P. N. Exon Smithbb9cadf2015-04-15 02:45:28 +0000758 createPrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000759 break;
760
761 default:
Peter Collingbourne03f89072016-07-15 00:55:40 +0000762 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000763 return;
764 }
765
Andrew Trick15e36e82011-04-05 18:56:55 +0000766 // Before executing passes, print the final values of the LLVM options.
767 cl::PrintOptionValues();
768
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000769 // Run passes. For now we do all passes at once, but eventually we
770 // would like to have the option of streaming code generation.
771
Peter Collingbourne03f89072016-07-15 00:55:40 +0000772 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000773 PrettyStackTraceString CrashInfo("Per-function optimization");
774
Peter Collingbourne03f89072016-07-15 00:55:40 +0000775 PerFunctionPasses.doInitialization();
Yaron Keren10d6d162015-06-05 09:40:53 +0000776 for (Function &F : *TheModule)
777 if (!F.isDeclaration())
Peter Collingbourne03f89072016-07-15 00:55:40 +0000778 PerFunctionPasses.run(F);
779 PerFunctionPasses.doFinalization();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000780 }
781
Peter Collingbourne03f89072016-07-15 00:55:40 +0000782 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000783 PrettyStackTraceString CrashInfo("Per-module optimization passes");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000784 PerModulePasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000785 }
786
Peter Collingbourne03f89072016-07-15 00:55:40 +0000787 {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000788 PrettyStackTraceString CrashInfo("Code generation");
Peter Collingbourne03f89072016-07-15 00:55:40 +0000789 CodeGenPasses.run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000790 }
791}
792
Chandler Carruth50f9e892016-12-23 20:44:01 +0000793static PassBuilder::OptimizationLevel mapToLevel(const CodeGenOptions &Opts) {
794 switch (Opts.OptimizationLevel) {
795 default:
796 llvm_unreachable("Invalid optimization level!");
797
798 case 1:
799 return PassBuilder::O1;
800
801 case 2:
802 switch (Opts.OptimizeSize) {
803 default:
804 llvm_unreachable("Invalide optimization level for size!");
805
806 case 0:
807 return PassBuilder::O2;
808
809 case 1:
810 return PassBuilder::Os;
811
812 case 2:
813 return PassBuilder::Oz;
814 }
815
816 case 3:
817 return PassBuilder::O3;
818 }
819}
820
821/// A clean version of `EmitAssembly` that uses the new pass manager.
822///
823/// Not all features are currently supported in this system, but where
824/// necessary it falls back to the legacy pass manager to at least provide
825/// basic functionality.
826///
827/// This API is planned to have its functionality finished and then to replace
828/// `EmitAssembly` at some point in the future when the default switches.
829void EmitAssemblyHelper::EmitAssemblyWithNewPassManager(
830 BackendAction Action, std::unique_ptr<raw_pwrite_stream> OS) {
831 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000832 setCommandLineOpts(CodeGenOpts);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000833
834 // The new pass manager always makes a target machine available to passes
835 // during construction.
836 CreateTargetMachine(/*MustCreateTM*/ true);
837 if (!TM)
838 // This will already be diagnosed, just bail.
839 return;
840 TheModule->setDataLayout(TM->createDataLayout());
841
Davide Italiano945de432017-02-13 16:07:05 +0000842 PGOOptions PGOOpt;
843
844 // -fprofile-generate.
845 PGOOpt.RunProfileGen = CodeGenOpts.hasProfileIRInstr();
846 if (PGOOpt.RunProfileGen)
847 PGOOpt.ProfileGenFile = CodeGenOpts.InstrProfileOutput.empty() ?
848 DefaultProfileGenName : CodeGenOpts.InstrProfileOutput;
849
850 // -fprofile-use.
851 if (CodeGenOpts.hasProfileIRUse())
852 PGOOpt.ProfileUseFile = CodeGenOpts.ProfileInstrumentUsePath;
853
854 // Only pass a PGO options struct if -fprofile-generate or
855 // -fprofile-use were passed on the cmdline.
856 PassBuilder PB(TM.get(),
857 (PGOOpt.RunProfileGen ||
858 !PGOOpt.ProfileUseFile.empty()) ?
859 Optional<PGOOptions>(PGOOpt) : None);
Chandler Carruth50f9e892016-12-23 20:44:01 +0000860
861 LoopAnalysisManager LAM;
862 FunctionAnalysisManager FAM;
863 CGSCCAnalysisManager CGAM;
864 ModuleAnalysisManager MAM;
865
866 // Register the AA manager first so that our version is the one used.
867 FAM.registerPass([&] { return PB.buildDefaultAAPipeline(); });
868
869 // Register all the basic analyses with the managers.
870 PB.registerModuleAnalyses(MAM);
871 PB.registerCGSCCAnalyses(CGAM);
872 PB.registerFunctionAnalyses(FAM);
873 PB.registerLoopAnalyses(LAM);
874 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
875
876 ModulePassManager MPM;
Chandler Carruth50f9e892016-12-23 20:44:01 +0000877
Chandler Carruth6d1b83e2016-12-27 00:13:09 +0000878 if (!CodeGenOpts.DisableLLVMPasses) {
879 if (CodeGenOpts.OptimizationLevel == 0) {
880 // Build a minimal pipeline based on the semantics required by Clang,
881 // which is just that always inlining occurs.
882 MPM.addPass(AlwaysInlinerPass());
883 } else {
884 // Otherwise, use the default pass pipeline. We also have to map our
885 // optimization levels into one of the distinct levels used to configure
886 // the pipeline.
887 PassBuilder::OptimizationLevel Level = mapToLevel(CodeGenOpts);
888
889 MPM = PB.buildPerModuleDefaultPipeline(Level);
890 }
Chandler Carruth50f9e892016-12-23 20:44:01 +0000891 }
892
893 // FIXME: We still use the legacy pass manager to do code generation. We
894 // create that pass manager here and use it as needed below.
895 legacy::PassManager CodeGenPasses;
896 bool NeedCodeGen = false;
897
898 // Append any output we need to the pass manager.
899 switch (Action) {
900 case Backend_EmitNothing:
901 break;
902
903 case Backend_EmitBC:
904 MPM.addPass(BitcodeWriterPass(*OS, CodeGenOpts.EmitLLVMUseLists,
905 CodeGenOpts.EmitSummaryIndex,
906 CodeGenOpts.EmitSummaryIndex));
907 break;
908
909 case Backend_EmitLL:
910 MPM.addPass(PrintModulePass(*OS, "", CodeGenOpts.EmitLLVMUseLists));
911 break;
912
913 case Backend_EmitAssembly:
914 case Backend_EmitMCNull:
915 case Backend_EmitObj:
916 NeedCodeGen = true;
917 CodeGenPasses.add(
918 createTargetTransformInfoWrapperPass(getTargetIRAnalysis()));
919 if (!AddEmitPasses(CodeGenPasses, Action, *OS))
920 // FIXME: Should we handle this error differently?
921 return;
922 break;
923 }
924
925 // Before executing passes, print the final values of the LLVM options.
926 cl::PrintOptionValues();
927
928 // Now that we have all of the passes ready, run them.
929 {
930 PrettyStackTraceString CrashInfo("Optimizer");
931 MPM.run(*TheModule, MAM);
932 }
933
934 // Now if needed, run the legacy PM for codegen.
935 if (NeedCodeGen) {
936 PrettyStackTraceString CrashInfo("Code generation");
937 CodeGenPasses.run(*TheModule);
938 }
939}
940
Peter Collingbourne47d23642017-01-24 19:54:37 +0000941Expected<BitcodeModule> clang::FindThinLTOModule(MemoryBufferRef MBRef) {
942 Expected<std::vector<BitcodeModule>> BMsOrErr = getBitcodeModuleList(MBRef);
943 if (!BMsOrErr)
944 return BMsOrErr.takeError();
945
946 // The bitcode file may contain multiple modules, we want the one with a
947 // summary.
948 for (BitcodeModule &BM : *BMsOrErr) {
949 Expected<bool> HasSummary = BM.hasSummary();
950 if (HasSummary && *HasSummary)
951 return BM;
952 }
953
954 return make_error<StringError>("Could not find module summary",
955 inconvertibleErrorCode());
956}
957
Teresa Johnsoncffeb542017-01-06 23:37:33 +0000958static void runThinLTOBackend(ModuleSummaryIndex *CombinedIndex, Module *M,
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000959 const HeaderSearchOptions &HeaderOpts,
960 const CodeGenOptions &CGOpts,
961 const clang::TargetOptions &TOpts,
962 const LangOptions &LOpts,
Dehao Chena1bd2d62017-01-13 00:51:55 +0000963 std::unique_ptr<raw_pwrite_stream> OS,
Teresa Johnson5ed6c102017-03-31 02:05:15 +0000964 std::string SampleProfile,
965 BackendAction Action) {
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000966 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
967 ModuleToDefinedGVSummaries;
968 CombinedIndex->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
969
David Blaikie6e2ec5f2017-04-19 20:08:21 +0000970 setCommandLineOpts(CGOpts);
971
Teresa Johnsonf9b17d42016-12-28 18:00:08 +0000972 // We can simply import the values mentioned in the combined index, since
973 // we should only invoke this using the individual indexes written out
974 // via a WriteIndexesThinBackend.
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000975 FunctionImporter::ImportMapTy ImportList;
Teresa Johnsonf9b17d42016-12-28 18:00:08 +0000976 for (auto &GlobalList : *CombinedIndex) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000977 // Ignore entries for undefined references.
978 if (GlobalList.second.SummaryList.empty())
979 continue;
980
Teresa Johnsonf9b17d42016-12-28 18:00:08 +0000981 auto GUID = GlobalList.first;
Peter Collingbourne9667b912017-05-04 18:03:25 +0000982 assert(GlobalList.second.SummaryList.size() == 1 &&
Teresa Johnsonf9b17d42016-12-28 18:00:08 +0000983 "Expected individual combined index to have one summary per GUID");
Peter Collingbourne9667b912017-05-04 18:03:25 +0000984 auto &Summary = GlobalList.second.SummaryList[0];
Teresa Johnsonf9b17d42016-12-28 18:00:08 +0000985 // Skip the summaries for the importing module. These are included to
986 // e.g. record required linkage changes.
987 if (Summary->modulePath() == M->getModuleIdentifier())
988 continue;
989 // Doesn't matter what value we plug in to the map, just needs an entry
990 // to provoke importing by thinBackend.
991 ImportList[Summary->modulePath()][GUID] = 1;
992 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000993
994 std::vector<std::unique_ptr<llvm::MemoryBuffer>> OwnedImports;
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000995 MapVector<llvm::StringRef, llvm::BitcodeModule> ModuleMap;
Teresa Johnson9e3f4742016-08-12 18:12:08 +0000996
997 for (auto &I : ImportList) {
998 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MBOrErr =
999 llvm::MemoryBuffer::getFile(I.first());
1000 if (!MBOrErr) {
1001 errs() << "Error loading imported file '" << I.first()
1002 << "': " << MBOrErr.getError().message() << "\n";
1003 return;
1004 }
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001005
Peter Collingbourne47d23642017-01-24 19:54:37 +00001006 Expected<BitcodeModule> BMOrErr = FindThinLTOModule(**MBOrErr);
1007 if (!BMOrErr) {
1008 handleAllErrors(BMOrErr.takeError(), [&](ErrorInfoBase &EIB) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001009 errs() << "Error loading imported file '" << I.first()
1010 << "': " << EIB.message() << '\n';
1011 });
1012 return;
1013 }
Peter Collingbourne47d23642017-01-24 19:54:37 +00001014 ModuleMap.insert({I.first(), *BMOrErr});
Peter Collingbourne1a0720e2016-12-14 01:17:59 +00001015
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001016 OwnedImports.push_back(std::move(*MBOrErr));
1017 }
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001018 auto AddStream = [&](size_t Task) {
1019 return llvm::make_unique<lto::NativeObjectStream>(std::move(OS));
Mehdi Amini406aa222016-08-17 06:23:08 +00001020 };
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001021 lto::Config Conf;
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001022 Conf.CPU = TOpts.CPU;
1023 Conf.CodeModel = getCodeModel(CGOpts);
1024 Conf.MAttrs = TOpts.Features;
1025 Conf.RelocModel = getRelocModel(CGOpts);
1026 Conf.CGOptLevel = getCGOptLevel(CGOpts);
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001027 initTargetOptions(Conf.Options, CGOpts, TOpts, LOpts, HeaderOpts);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001028 Conf.SampleProfile = std::move(SampleProfile);
Teresa Johnsonb637cb02017-03-31 22:35:47 +00001029 switch (Action) {
1030 case Backend_EmitNothing:
1031 Conf.PreCodeGenModuleHook = [](size_t Task, const Module &Mod) {
1032 return false;
1033 };
1034 break;
1035 case Backend_EmitLL:
1036 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1037 M->print(*OS, nullptr, CGOpts.EmitLLVMUseLists);
1038 return false;
1039 };
1040 break;
1041 case Backend_EmitBC:
1042 Conf.PreCodeGenModuleHook = [&](size_t Task, const Module &Mod) {
1043 WriteBitcodeToFile(M, *OS, CGOpts.EmitLLVMUseLists);
1044 return false;
1045 };
1046 break;
1047 default:
1048 Conf.CGFileType = getCodeGenFileType(Action);
1049 break;
1050 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001051 if (Error E = thinBackend(
Peter Collingbourne2d3a26f2016-09-23 21:43:51 +00001052 Conf, 0, AddStream, *M, *CombinedIndex, ImportList,
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001053 ModuleToDefinedGVSummaries[M->getModuleIdentifier()], ModuleMap)) {
1054 handleAllErrors(std::move(E), [&](ErrorInfoBase &EIB) {
1055 errs() << "Error running ThinLTO backend: " << EIB.message() << '\n';
1056 });
1057 }
1058}
1059
David Blaikie9c902b52011-09-25 23:23:43 +00001060void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001061 const HeaderSearchOptions &HeaderOpts,
David Blaikie9c902b52011-09-25 23:23:43 +00001062 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +00001063 const clang::TargetOptions &TOpts,
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001064 const LangOptions &LOpts,
1065 const llvm::DataLayout &TDesc, Module *M,
1066 BackendAction Action,
Peter Collingbourne03f89072016-07-15 00:55:40 +00001067 std::unique_ptr<raw_pwrite_stream> OS) {
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001068 if (!CGOpts.ThinLTOIndexFile.empty()) {
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001069 // If we are performing a ThinLTO importing compile, load the function index
1070 // into memory and pass it into runThinLTOBackend, which will run the
1071 // function importer and invoke LTO passes.
1072 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
1073 llvm::getModuleSummaryIndexForFile(CGOpts.ThinLTOIndexFile);
1074 if (!IndexOrErr) {
1075 logAllUnhandledErrors(IndexOrErr.takeError(), errs(),
1076 "Error loading index file '" +
1077 CGOpts.ThinLTOIndexFile + "': ");
1078 return;
1079 }
1080 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = std::move(*IndexOrErr);
1081 // A null CombinedIndex means we should skip ThinLTO compilation
1082 // (LLVM will optionally ignore empty index files, returning null instead
1083 // of an error).
1084 bool DoThinLTOBackend = CombinedIndex != nullptr;
1085 if (DoThinLTOBackend) {
Teresa Johnson5ed6c102017-03-31 02:05:15 +00001086 runThinLTOBackend(CombinedIndex.get(), M, HeaderOpts, CGOpts, TOpts,
1087 LOpts, std::move(OS), CGOpts.SampleProfileFile, Action);
Teresa Johnsoncffeb542017-01-06 23:37:33 +00001088 return;
1089 }
Teresa Johnson9e3f4742016-08-12 18:12:08 +00001090 }
1091
Saleem Abdulrasool888e2892017-01-05 16:02:32 +00001092 EmitAssemblyHelper AsmHelper(Diags, HeaderOpts, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001093
Chandler Carruth50f9e892016-12-23 20:44:01 +00001094 if (CGOpts.ExperimentalNewPassManager)
1095 AsmHelper.EmitAssemblyWithNewPassManager(Action, std::move(OS));
1096 else
1097 AsmHelper.EmitAssembly(Action, std::move(OS));
Alp Tokere83b9062014-01-02 15:08:04 +00001098
James Y Knightb214cbc2016-03-04 19:00:41 +00001099 // Verify clang's TargetInfo DataLayout against the LLVM TargetMachine's
1100 // DataLayout.
1101 if (AsmHelper.TM) {
Mehdi Aminica3cf9e2015-07-24 16:04:29 +00001102 std::string DLDesc = M->getDataLayout().getStringRepresentation();
James Y Knightb214cbc2016-03-04 19:00:41 +00001103 if (DLDesc != TDesc.getStringRepresentation()) {
Alp Tokere83b9062014-01-02 15:08:04 +00001104 unsigned DiagID = Diags.getCustomDiagID(
1105 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
1106 "expected target description '%1'");
James Y Knightb214cbc2016-03-04 19:00:41 +00001107 Diags.Report(DiagID) << DLDesc << TDesc.getStringRepresentation();
Alp Tokere83b9062014-01-02 15:08:04 +00001108 }
1109 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +00001110}
Steven Wu27fb5222016-05-11 16:26:03 +00001111
1112static const char* getSectionNameForBitcode(const Triple &T) {
1113 switch (T.getObjectFormat()) {
1114 case Triple::MachO:
1115 return "__LLVM,__bitcode";
1116 case Triple::COFF:
1117 case Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00001118 case Triple::Wasm:
Steven Wu27fb5222016-05-11 16:26:03 +00001119 case Triple::UnknownObjectFormat:
1120 return ".llvmbc";
1121 }
Simon Pilgrimbff9dae2016-05-11 21:55:37 +00001122 llvm_unreachable("Unimplemented ObjectFormatType");
Steven Wu27fb5222016-05-11 16:26:03 +00001123}
1124
1125static const char* getSectionNameForCommandline(const Triple &T) {
1126 switch (T.getObjectFormat()) {
1127 case Triple::MachO:
1128 return "__LLVM,__cmdline";
1129 case Triple::COFF:
1130 case Triple::ELF:
Dan Gohman839f2152017-01-17 21:46:38 +00001131 case Triple::Wasm:
Steven Wu27fb5222016-05-11 16:26:03 +00001132 case Triple::UnknownObjectFormat:
1133 return ".llvmcmd";
1134 }
Simon Pilgrimbff9dae2016-05-11 21:55:37 +00001135 llvm_unreachable("Unimplemented ObjectFormatType");
Steven Wu27fb5222016-05-11 16:26:03 +00001136}
1137
1138// With -fembed-bitcode, save a copy of the llvm IR as data in the
1139// __LLVM,__bitcode section.
1140void clang::EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts,
1141 llvm::MemoryBufferRef Buf) {
1142 if (CGOpts.getEmbedBitcode() == CodeGenOptions::Embed_Off)
1143 return;
1144
Steven Wu2c059a52016-05-16 18:54:58 +00001145 // Save llvm.compiler.used and remote it.
1146 SmallVector<Constant*, 2> UsedArray;
1147 SmallSet<GlobalValue*, 4> UsedGlobals;
1148 Type *UsedElementType = Type::getInt8Ty(M->getContext())->getPointerTo(0);
1149 GlobalVariable *Used = collectUsedGlobalVariables(*M, UsedGlobals, true);
1150 for (auto *GV : UsedGlobals) {
1151 if (GV->getName() != "llvm.embedded.module" &&
1152 GV->getName() != "llvm.cmdline")
1153 UsedArray.push_back(
1154 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1155 }
1156 if (Used)
1157 Used->eraseFromParent();
1158
Steven Wu27fb5222016-05-11 16:26:03 +00001159 // Embed the bitcode for the llvm module.
1160 std::string Data;
1161 ArrayRef<uint8_t> ModuleData;
1162 Triple T(M->getTargetTriple());
1163 // Create a constant that contains the bitcode.
1164 // In case of embedding a marker, ignore the input Buf and use the empty
1165 // ArrayRef. It is also legal to create a bitcode marker even Buf is empty.
1166 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Marker) {
1167 if (!isBitcode((const unsigned char *)Buf.getBufferStart(),
1168 (const unsigned char *)Buf.getBufferEnd())) {
1169 // If the input is LLVM Assembly, bitcode is produced by serializing
1170 // the module. Use-lists order need to be perserved in this case.
1171 llvm::raw_string_ostream OS(Data);
1172 llvm::WriteBitcodeToFile(M, OS, /* ShouldPreserveUseListOrder */ true);
1173 ModuleData =
1174 ArrayRef<uint8_t>((const uint8_t *)OS.str().data(), OS.str().size());
1175 } else
1176 // If the input is LLVM bitcode, write the input byte stream directly.
1177 ModuleData = ArrayRef<uint8_t>((const uint8_t *)Buf.getBufferStart(),
1178 Buf.getBufferSize());
1179 }
1180 llvm::Constant *ModuleConstant =
1181 llvm::ConstantDataArray::get(M->getContext(), ModuleData);
Steven Wu27fb5222016-05-11 16:26:03 +00001182 llvm::GlobalVariable *GV = new llvm::GlobalVariable(
Steven Wu2c059a52016-05-16 18:54:58 +00001183 *M, ModuleConstant->getType(), true, llvm::GlobalValue::PrivateLinkage,
Steven Wu27fb5222016-05-11 16:26:03 +00001184 ModuleConstant);
1185 GV->setSection(getSectionNameForBitcode(T));
Steven Wu2c059a52016-05-16 18:54:58 +00001186 UsedArray.push_back(
1187 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
Steven Wu27fb5222016-05-11 16:26:03 +00001188 if (llvm::GlobalVariable *Old =
Steven Wu2c059a52016-05-16 18:54:58 +00001189 M->getGlobalVariable("llvm.embedded.module", true)) {
1190 assert(Old->hasOneUse() &&
1191 "llvm.embedded.module can only be used once in llvm.compiler.used");
Steven Wu27fb5222016-05-11 16:26:03 +00001192 GV->takeName(Old);
1193 Old->eraseFromParent();
1194 } else {
1195 GV->setName("llvm.embedded.module");
1196 }
1197
Steven Wu2c059a52016-05-16 18:54:58 +00001198 // Skip if only bitcode needs to be embedded.
1199 if (CGOpts.getEmbedBitcode() != CodeGenOptions::Embed_Bitcode) {
1200 // Embed command-line options.
Saleem Abdulrasoolb1d50c12016-05-20 03:58:12 +00001201 ArrayRef<uint8_t> CmdData(const_cast<uint8_t *>(CGOpts.CmdArgs.data()),
Steven Wu2c059a52016-05-16 18:54:58 +00001202 CGOpts.CmdArgs.size());
1203 llvm::Constant *CmdConstant =
1204 llvm::ConstantDataArray::get(M->getContext(), CmdData);
1205 GV = new llvm::GlobalVariable(*M, CmdConstant->getType(), true,
1206 llvm::GlobalValue::PrivateLinkage,
1207 CmdConstant);
1208 GV->setSection(getSectionNameForCommandline(T));
1209 UsedArray.push_back(
1210 ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, UsedElementType));
1211 if (llvm::GlobalVariable *Old =
1212 M->getGlobalVariable("llvm.cmdline", true)) {
1213 assert(Old->hasOneUse() &&
1214 "llvm.cmdline can only be used once in llvm.compiler.used");
1215 GV->takeName(Old);
1216 Old->eraseFromParent();
1217 } else {
1218 GV->setName("llvm.cmdline");
1219 }
1220 }
1221
1222 if (UsedArray.empty())
Steven Wu27fb5222016-05-11 16:26:03 +00001223 return;
1224
Steven Wu2c059a52016-05-16 18:54:58 +00001225 // Recreate llvm.compiler.used.
1226 ArrayType *ATy = ArrayType::get(UsedElementType, UsedArray.size());
1227 auto *NewUsed = new GlobalVariable(
1228 *M, ATy, false, llvm::GlobalValue::AppendingLinkage,
1229 llvm::ConstantArray::get(ATy, UsedArray), "llvm.compiler.used");
1230 NewUsed->setSection("llvm.metadata");
Steven Wu27fb5222016-05-11 16:26:03 +00001231}