blob: a1521dce39fd65bfb114db4d948139bdb19dd281 [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"
Chandler Carruth85098242010-06-15 23:19:56 +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 Abdulrasool62849c62014-05-08 02:28:32 +000017#include "llvm/ADT/StringSwitch.h"
Chandler Carruth1b3304d2014-01-13 07:47:38 +000018#include "llvm/Bitcode/BitcodeWriterPass.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000019#include "llvm/CodeGen/RegAllocRegistry.h"
20#include "llvm/CodeGen/SchedulerRegistry.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000021#include "llvm/IR/DataLayout.h"
Chandler Carruth0a50c492014-01-12 11:11:50 +000022#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000023#include "llvm/IR/Module.h"
Chandler Carruthca884742014-01-13 09:26:48 +000024#include "llvm/IR/Verifier.h"
Evan Chengeeb486d2011-06-29 01:14:32 +000025#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "llvm/PassManager.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FormattedStream.h"
29#include "llvm/Support/PrettyStackTrace.h"
Evan Cheng494eb062011-08-24 18:09:14 +000030#include "llvm/Support/TargetRegistry.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000031#include "llvm/Support/Timer.h"
32#include "llvm/Support/raw_ostream.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000033#include "llvm/Target/TargetLibraryInfo.h"
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000034#include "llvm/Target/TargetMachine.h"
35#include "llvm/Target/TargetOptions.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000036#include "llvm/Transforms/IPO.h"
37#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/Transforms/Instrumentation.h"
Michael Gottesman90cae772013-01-28 01:36:00 +000039#include "llvm/Transforms/ObjCARC.h"
Rafael Espindola56a7dab02011-08-02 21:51:02 +000040#include "llvm/Transforms/Scalar.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000041#include <memory>
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000042using namespace clang;
43using namespace llvm;
44
45namespace {
46
47class EmitAssemblyHelper {
David Blaikie9c902b52011-09-25 23:23:43 +000048 DiagnosticsEngine &Diags;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000049 const CodeGenOptions &CodeGenOpts;
Nick Lewycky432add52011-12-02 22:17:00 +000050 const clang::TargetOptions &TargetOpts;
Dan Gohmanfec0ff82011-07-05 22:02:36 +000051 const LangOptions &LangOpts;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000052 Module *TheModule;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000053
54 Timer CodeGenerationTime;
55
Daniel Dunbar195fa002010-09-17 07:35:16 +000056 mutable PassManager *CodeGenPasses;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000057 mutable PassManager *PerModulePasses;
58 mutable FunctionPassManager *PerFunctionPasses;
59
60private:
Alp Tokerf4e22382013-12-20 20:26:53 +000061 PassManager *getCodeGenPasses() const {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000062 if (!CodeGenPasses) {
Daniel Dunbar195fa002010-09-17 07:35:16 +000063 CodeGenPasses = new PassManager();
Rafael Espindola303f8b02014-02-25 17:30:40 +000064 CodeGenPasses->add(new DataLayoutPass(TheModule));
Chandler Carruthed0f133b2013-01-07 01:38:01 +000065 if (TM)
66 TM->addAnalysisPasses(*CodeGenPasses);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000067 }
68 return CodeGenPasses;
69 }
70
Alp Tokerf4e22382013-12-20 20:26:53 +000071 PassManager *getPerModulePasses() const {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000072 if (!PerModulePasses) {
73 PerModulePasses = new PassManager();
Rafael Espindola303f8b02014-02-25 17:30:40 +000074 PerModulePasses->add(new DataLayoutPass(TheModule));
Chandler Carruthed0f133b2013-01-07 01:38:01 +000075 if (TM)
76 TM->addAnalysisPasses(*PerModulePasses);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000077 }
78 return PerModulePasses;
79 }
80
Alp Tokerf4e22382013-12-20 20:26:53 +000081 FunctionPassManager *getPerFunctionPasses() const {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000082 if (!PerFunctionPasses) {
83 PerFunctionPasses = new FunctionPassManager(TheModule);
Rafael Espindola303f8b02014-02-25 17:30:40 +000084 PerFunctionPasses->add(new DataLayoutPass(TheModule));
Chandler Carruthed0f133b2013-01-07 01:38:01 +000085 if (TM)
86 TM->addAnalysisPasses(*PerFunctionPasses);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +000087 }
88 return PerFunctionPasses;
89 }
90
Alp Tokerf4e22382013-12-20 20:26:53 +000091 void CreatePasses();
Nadav Rotemec57ab32012-10-24 00:53:38 +000092
Nadav Rotemdc06b2d2012-10-24 03:52:31 +000093 /// CreateTargetMachine - Generates the TargetMachine.
94 /// Returns Null if it is unable to create the target machine.
95 /// Some of our clang tests specify triples which are not built
96 /// into clang. This is okay because these tests check the generated
97 /// IR, and they require DataLayout which depends on the triple.
98 /// In this case, we allow this method to fail and not report an error.
99 /// When MustCreateTM is used, we print an error if we are unable to load
100 /// the requested target.
101 TargetMachine *CreateTargetMachine(bool MustCreateTM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000102
103 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
104 ///
105 /// \return True on success.
Alp Tokerf4e22382013-12-20 20:26:53 +0000106 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000107
108public:
David Blaikie9c902b52011-09-25 23:23:43 +0000109 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
Nick Lewycky432add52011-12-02 22:17:00 +0000110 const CodeGenOptions &CGOpts,
111 const clang::TargetOptions &TOpts,
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000112 const LangOptions &LOpts,
Daniel Dunbar3e111522010-06-07 23:21:04 +0000113 Module *M)
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000114 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
Daniel Dunbar3e111522010-06-07 23:21:04 +0000115 TheModule(M), CodeGenerationTime("Code Generation Time"),
Craig Topper8a13c412014-05-21 05:09:00 +0000116 CodeGenPasses(nullptr), PerModulePasses(nullptr),
117 PerFunctionPasses(nullptr) {}
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000118
119 ~EmitAssemblyHelper() {
120 delete CodeGenPasses;
121 delete PerModulePasses;
122 delete PerFunctionPasses;
Alp Tokerf4e22382013-12-20 20:26:53 +0000123 if (CodeGenOpts.DisableFree)
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000124 BuryPointer(TM.release());
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000125 }
126
Ahmed Charlesb8984322014-03-07 20:03:18 +0000127 std::unique_ptr<TargetMachine> TM;
Alp Tokerf4e22382013-12-20 20:26:53 +0000128
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000129 void EmitAssembly(BackendAction Action, raw_ostream *OS);
130};
131
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000132// We need this wrapper to access LangOpts and CGOpts from extension functions
133// that we add to the PassManagerBuilder.
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000134class PassManagerBuilderWrapper : public PassManagerBuilder {
135public:
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000136 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
137 const LangOptions &LangOpts)
138 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
139 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000140 const LangOptions &getLangOpts() const { return LangOpts; }
141private:
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000142 const CodeGenOptions &CGOpts;
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000143 const LangOptions &LangOpts;
144};
145
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000146}
147
Dan Gohman5932ce22012-01-17 20:54:51 +0000148static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
149 if (Builder.OptLevel > 0)
150 PM.add(createObjCARCAPElimPass());
151}
152
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000153static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
154 if (Builder.OptLevel > 0)
155 PM.add(createObjCARCExpandPass());
156}
157
158static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
159 if (Builder.OptLevel > 0)
160 PM.add(createObjCARCOptPass());
161}
162
Diego Novillo5c297052013-11-13 12:22:39 +0000163static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder,
164 PassManagerBase &PM) {
165 const PassManagerBuilderWrapper &BuilderWrapper =
166 static_cast<const PassManagerBuilderWrapper &>(Builder);
167 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
168 PM.add(createSampleProfileLoaderPass(CGOpts.SampleProfileFile));
169}
170
Diego Novillob56be642014-03-03 20:06:18 +0000171static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
172 PassManagerBase &PM) {
173 PM.add(createAddDiscriminatorsPass());
174}
175
Nuno Lopesa4255892012-05-22 17:19:45 +0000176static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
177 PassManagerBase &PM) {
Joey Goulyebc59d52012-11-23 10:39:49 +0000178 PM.add(createBoundsCheckingPass());
Nuno Lopesa4255892012-05-22 17:19:45 +0000179}
180
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000181static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
182 PassManagerBase &PM) {
Alexey Samsonove595e1a2014-06-13 17:53:44 +0000183 PM.add(createAddressSanitizerFunctionPass());
Alexey Samsonovc94285a2014-07-08 00:50:49 +0000184 PM.add(createAddressSanitizerModulePass());
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000185}
186
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000187static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
188 PassManagerBase &PM) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000189 const PassManagerBuilderWrapper &BuilderWrapper =
190 static_cast<const PassManagerBuilderWrapper&>(Builder);
191 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov1cf07ea2014-06-02 18:08:08 +0000192 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000193
194 // MemorySanitizer inserts complex instrumentation that mostly follows
195 // the logic of the original code, but operates on "shadow" values.
196 // It can benefit from re-running some general purpose optimization passes.
197 if (Builder.OptLevel > 0) {
198 PM.add(createEarlyCSEPass());
199 PM.add(createReassociatePass());
200 PM.add(createLICMPass());
201 PM.add(createGVNPass());
202 PM.add(createInstructionCombiningPass());
203 PM.add(createDeadStoreEliminationPass());
204 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000205}
206
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000207static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
208 PassManagerBase &PM) {
Alexey Samsonov1cf07ea2014-06-02 18:08:08 +0000209 PM.add(createThreadSanitizerPass());
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000210}
211
Peter Collingbournec3772752013-08-07 22:47:34 +0000212static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
213 PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000214 const PassManagerBuilderWrapper &BuilderWrapper =
215 static_cast<const PassManagerBuilderWrapper&>(Builder);
216 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
217 PM.add(createDataFlowSanitizerPass(CGOpts.SanitizerBlacklistFile));
Peter Collingbournec3772752013-08-07 22:47:34 +0000218}
219
Alp Tokerf4e22382013-12-20 20:26:53 +0000220void EmitAssemblyHelper::CreatePasses() {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000221 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000222 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000223
224 // Handle disabling of LLVM optimization, where we want to preserve the
225 // internal module before any optimization.
226 if (CodeGenOpts.DisableLLVMOpts) {
227 OptLevel = 0;
228 Inlining = CodeGenOpts.NoInlining;
229 }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000230
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000231 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000232 PMBuilder.OptLevel = OptLevel;
233 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000234 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
235 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
236 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000237
Duncan P. N. Exon Smith85e349f2014-04-18 01:05:25 +0000238 PMBuilder.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000239 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
240 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Hal Finkelce0697f2013-11-17 16:03:29 +0000241 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000242
Diego Novillob56be642014-03-03 20:06:18 +0000243 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
244 addAddDiscriminatorsPass);
245
Diego Novillo5c297052013-11-13 12:22:39 +0000246 if (!CodeGenOpts.SampleProfileFile.empty())
247 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
248 addSampleProfileLoaderPass);
249
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000250 // In ObjC ARC mode, add the main ARC optimization passes.
251 if (LangOpts.ObjCAutoRefCount) {
252 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
253 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000254 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
255 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000256 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
257 addObjCARCOptPass);
258 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000259
Richard Smith6b53e222013-10-22 22:51:04 +0000260 if (LangOpts.Sanitize.LocalBounds) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000261 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
262 addBoundsCheckingPass);
263 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
264 addBoundsCheckingPass);
265 }
266
Will Dietzf54319c2013-01-18 11:30:38 +0000267 if (LangOpts.Sanitize.Address) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000268 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000269 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000270 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000271 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000272 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000273
Will Dietzf54319c2013-01-18 11:30:38 +0000274 if (LangOpts.Sanitize.Memory) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000275 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
276 addMemorySanitizerPass);
277 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
278 addMemorySanitizerPass);
279 }
280
Will Dietzf54319c2013-01-18 11:30:38 +0000281 if (LangOpts.Sanitize.Thread) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000282 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000283 addThreadSanitizerPass);
284 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
285 addThreadSanitizerPass);
286 }
287
Peter Collingbournec3772752013-08-07 22:47:34 +0000288 if (LangOpts.Sanitize.DataFlow) {
289 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
290 addDataFlowSanitizerPass);
291 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
292 addDataFlowSanitizerPass);
293 }
294
Chris Lattner5c123672011-05-21 20:40:11 +0000295 // Figure out TargetLibraryInfo.
Bill Wendling28b9e8b2011-05-17 23:06:23 +0000296 Triple TargetTriple(TheModule->getTargetTriple());
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000297 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
Chris Lattnerfa222df2011-02-18 22:34:47 +0000298 if (!CodeGenOpts.SimplifyLibCalls)
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000299 PMBuilder.LibraryInfo->disableAllFunctions();
Eli Benderskyb5cfa8c2014-03-12 16:30:34 +0000300
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000301 switch (Inlining) {
302 case CodeGenOptions::NoInlining: break;
303 case CodeGenOptions::NormalInlining: {
Eli Benderskyb5cfa8c2014-03-12 16:30:34 +0000304 PMBuilder.Inliner =
305 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000306 break;
307 }
308 case CodeGenOptions::OnlyAlwaysInlining:
Chris Lattner5c123672011-05-21 20:40:11 +0000309 // Respect always_inline.
Chad Rosiere2c45062012-02-25 02:56:13 +0000310 if (OptLevel == 0)
311 // Do not insert lifetime intrinsics at -O0.
312 PMBuilder.Inliner = createAlwaysInlinerPass(false);
313 else
314 PMBuilder.Inliner = createAlwaysInlinerPass();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000315 break;
316 }
317
Chris Lattner5c123672011-05-21 20:40:11 +0000318 // Set up the per-function pass manager.
Alp Tokerf4e22382013-12-20 20:26:53 +0000319 FunctionPassManager *FPM = getPerFunctionPasses();
Chris Lattner5c123672011-05-21 20:40:11 +0000320 if (CodeGenOpts.VerifyModule)
321 FPM->add(createVerifierPass());
322 PMBuilder.populateFunctionPassManager(*FPM);
Andrew Trickb2a84722011-04-05 18:49:32 +0000323
Chris Lattner5c123672011-05-21 20:40:11 +0000324 // Set up the per-module pass manager.
Alp Tokerf4e22382013-12-20 20:26:53 +0000325 PassManager *MPM = getPerModulePasses();
Duncan P. N. Exon Smith52eaffe2014-04-15 16:27:43 +0000326 if (CodeGenOpts.VerifyModule)
327 MPM->add(createDebugInfoVerifierPass());
Chris Lattnerd98cec52011-02-18 22:20:38 +0000328
Nick Lewyckyc02bbb62013-03-20 01:38:16 +0000329 if (!CodeGenOpts.DisableGCov &&
330 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000331 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
332 // LLVM's -default-gcov-version flag is set to something invalid.
333 GCOVOptions Options;
334 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
335 Options.EmitData = CodeGenOpts.EmitGcovArcs;
336 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
337 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
338 Options.NoRedZone = CodeGenOpts.DisableRedZone;
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000339 Options.FunctionNamesInData =
Nick Lewycky6f15b2902013-03-20 02:14:38 +0000340 !CodeGenOpts.CoverageNoFunctionNamesInData;
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000341 MPM->add(createGCOVProfilerPass(Options));
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000342 if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
Nick Lewycky207bce32011-04-21 23:44:07 +0000343 MPM->add(createStripSymbolsPass(true));
344 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000345
Chris Lattner5c123672011-05-21 20:40:11 +0000346 PMBuilder.populateModulePassManager(*MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000347}
348
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000349TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000350 // Create the TargetMachine for generating code.
351 std::string Error;
352 std::string Triple = TheModule->getTargetTriple();
353 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
354 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000355 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000356 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Craig Topper8a13c412014-05-21 05:09:00 +0000357 return nullptr;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000358 }
359
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000360 unsigned CodeModel =
361 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
362 .Case("small", llvm::CodeModel::Small)
363 .Case("kernel", llvm::CodeModel::Kernel)
364 .Case("medium", llvm::CodeModel::Medium)
Saleem Abdulrasool61449c62014-05-08 16:28:48 +0000365 .Case("large", llvm::CodeModel::Large)
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000366 .Case("default", llvm::CodeModel::Default)
367 .Default(~0u);
368 assert(CodeModel != ~0u && "invalid code model!");
369 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000370
David Blaikie09d20ee2012-02-07 19:36:38 +0000371 SmallVector<const char *, 16> BackendArgs;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000372 BackendArgs.push_back("clang"); // Fake program name.
373 if (!CodeGenOpts.DebugPass.empty()) {
374 BackendArgs.push_back("-debug-pass");
375 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
376 }
377 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
378 BackendArgs.push_back("-limit-float-precision");
379 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
380 }
381 if (llvm::TimePassesIsEnabled)
382 BackendArgs.push_back("-time-passes");
Daniel Dunbar12100e22011-03-22 16:48:17 +0000383 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
384 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Chad Rosierba3df1d2011-08-26 00:26:29 +0000385 if (CodeGenOpts.NoGlobalMerge)
386 BackendArgs.push_back("-global-merge=false");
Craig Topper8a13c412014-05-21 05:09:00 +0000387 BackendArgs.push_back(nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000388 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
David Blaikie09d20ee2012-02-07 19:36:38 +0000389 BackendArgs.data());
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000390
391 std::string FeaturesStr;
Evan Chengadc79592011-06-30 02:06:32 +0000392 if (TargetOpts.Features.size()) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000393 SubtargetFeatures Features;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000394 for (std::vector<std::string>::const_iterator
395 it = TargetOpts.Features.begin(),
396 ie = TargetOpts.Features.end(); it != ie; ++it)
397 Features.AddFeature(*it);
398 FeaturesStr = Features.getString();
399 }
Evan Cheng3f37dd02011-07-19 06:37:41 +0000400
401 llvm::Reloc::Model RM = llvm::Reloc::Default;
402 if (CodeGenOpts.RelocationModel == "static") {
403 RM = llvm::Reloc::Static;
404 } else if (CodeGenOpts.RelocationModel == "pic") {
405 RM = llvm::Reloc::PIC_;
406 } else {
407 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
408 "Invalid PIC model!");
409 RM = llvm::Reloc::DynamicNoPIC;
410 }
411
Evan Chengdd286bc2011-11-16 08:38:55 +0000412 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
413 switch (CodeGenOpts.OptimizationLevel) {
414 default: break;
415 case 0: OptLevel = CodeGenOpt::None; break;
416 case 3: OptLevel = CodeGenOpt::Aggressive; break;
417 }
418
Nick Lewycky432add52011-12-02 22:17:00 +0000419 llvm::TargetOptions Options;
420
Rafael Espindola33ebd212014-02-21 03:14:07 +0000421 if (CodeGenOpts.DisableIntegratedAS)
422 Options.DisableIntegratedAS = true;
423
David Blaikie7e2fd942014-03-27 20:47:30 +0000424 if (CodeGenOpts.CompressDebugSections)
425 Options.CompressDebugSections = true;
426
Nick Lewycky432add52011-12-02 22:17:00 +0000427 // Set frame pointer elimination mode.
428 if (!CodeGenOpts.DisableFPElim) {
429 Options.NoFramePointerElim = false;
Nick Lewycky432add52011-12-02 22:17:00 +0000430 } else if (CodeGenOpts.OmitLeafFramePointer) {
431 Options.NoFramePointerElim = false;
Nick Lewycky432add52011-12-02 22:17:00 +0000432 } else {
433 Options.NoFramePointerElim = true;
Nick Lewycky432add52011-12-02 22:17:00 +0000434 }
435
Rafael Espindola66aa0452012-06-19 01:26:10 +0000436 if (CodeGenOpts.UseInitArray)
437 Options.UseInitArray = true;
438
Nick Lewycky432add52011-12-02 22:17:00 +0000439 // Set float ABI type.
440 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
441 Options.FloatABIType = llvm::FloatABI::Soft;
442 else if (CodeGenOpts.FloatABI == "hard")
443 Options.FloatABIType = llvm::FloatABI::Hard;
444 else {
445 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
446 Options.FloatABIType = llvm::FloatABI::Default;
447 }
448
Lang Hamesaa53b932012-07-06 00:59:19 +0000449 // Set FP fusion mode.
Lang Hames65992f42012-11-15 07:51:26 +0000450 switch (CodeGenOpts.getFPContractMode()) {
451 case CodeGenOptions::FPC_Off:
Lang Hamesaa53b932012-07-06 00:59:19 +0000452 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
453 break;
Lang Hames65992f42012-11-15 07:51:26 +0000454 case CodeGenOptions::FPC_On:
Lang Hamesaa53b932012-07-06 00:59:19 +0000455 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
456 break;
Lang Hames65992f42012-11-15 07:51:26 +0000457 case CodeGenOptions::FPC_Fast:
Lang Hamesaa53b932012-07-06 00:59:19 +0000458 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
Nadav Roteme9c233b2012-10-19 04:15:32 +0000459 break;
Lang Hamesaa53b932012-07-06 00:59:19 +0000460 }
461
Nick Lewycky432add52011-12-02 22:17:00 +0000462 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
463 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
464 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
465 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
466 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
467 Options.UseSoftFloat = CodeGenOpts.SoftFloat;
Nick Lewyckyf4d3f7a2011-12-06 03:33:03 +0000468 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
Nick Lewycky1c8c4362012-01-23 08:29:12 +0000469 Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Bob Wilson14adb362012-02-03 06:27:22 +0000470 Options.TrapFuncName = CodeGenOpts.TrapFuncName;
Chandler Carruth097d0192012-04-08 21:09:51 +0000471 Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
Eric Christopheracca0082014-05-20 21:25:41 +0000472 Options.FunctionSections = CodeGenOpts.FunctionSections;
473 Options.DataSections = CodeGenOpts.DataSections;
Nick Lewycky432add52011-12-02 22:17:00 +0000474
Eric Christopher7e72a092014-05-15 01:21:56 +0000475 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
476 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
Eric Christophere76eee42014-05-16 20:46:14 +0000477 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
Eric Christopher7e72a092014-05-15 01:21:56 +0000478 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
Eric Christopher4015e124e2014-05-21 00:00:03 +0000479 Options.MCOptions.AsmVerbose = CodeGenOpts.AsmVerbose;
Eric Christopher7e72a092014-05-15 01:21:56 +0000480
Evan Chengadc79592011-06-30 02:06:32 +0000481 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
Nick Lewycky432add52011-12-02 22:17:00 +0000482 FeaturesStr, Options,
483 RM, CM, OptLevel);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000484
Nadav Rotemec57ab32012-10-24 00:53:38 +0000485 return TM;
486}
487
488bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
Alp Tokerf4e22382013-12-20 20:26:53 +0000489 formatted_raw_ostream &OS) {
Nadav Rotemec57ab32012-10-24 00:53:38 +0000490
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000491 // Create the code generator passes.
Alp Tokerf4e22382013-12-20 20:26:53 +0000492 PassManager *PM = getCodeGenPasses();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000493
Chad Rosierb1cfc682012-02-29 20:14:59 +0000494 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000495 llvm::Triple TargetTriple(TheModule->getTargetTriple());
496 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
Chad Rosierb1cfc682012-02-29 20:14:59 +0000497 if (!CodeGenOpts.SimplifyLibCalls)
498 TLI->disableAllFunctions();
499 PM->add(TLI);
500
Chandler Carruthed0f133b2013-01-07 01:38:01 +0000501 // Add Target specific analysis passes.
502 TM->addAnalysisPasses(*PM);
Nadav Roteme9c233b2012-10-19 04:15:32 +0000503
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000504 // Normal mode, emit a .s or .o file by running the code generator. Note,
505 // this also adds codegenerator level optimization passes.
506 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
507 if (Action == Backend_EmitObj)
508 CGFT = TargetMachine::CGFT_ObjectFile;
509 else if (Action == Backend_EmitMCNull)
510 CGFT = TargetMachine::CGFT_Null;
511 else
512 assert(Action == Backend_EmitAssembly && "Invalid action!");
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000513
514 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
515 // "codegen" passes so that it isn't run multiple times when there is
516 // inlining happening.
Dan Gohman1170b082012-04-04 21:04:56 +0000517 if (LangOpts.ObjCAutoRefCount &&
518 CodeGenOpts.OptimizationLevel > 0)
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000519 PM->add(createObjCARCContractPass());
520
Evan Chengdd286bc2011-11-16 08:38:55 +0000521 if (TM->addPassesToEmitFile(*PM, OS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000522 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
523 Diags.Report(diag::err_fe_unable_to_interface_with_target);
524 return false;
525 }
526
527 return true;
528}
529
530void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
Craig Topper8a13c412014-05-21 05:09:00 +0000531 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : nullptr);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000532 llvm::formatted_raw_ostream FormattedOS;
533
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000534 bool UsesCodeGen = (Action != Backend_EmitNothing &&
535 Action != Backend_EmitBC &&
536 Action != Backend_EmitLL);
Alp Tokerf4e22382013-12-20 20:26:53 +0000537 if (!TM)
538 TM.reset(CreateTargetMachine(UsesCodeGen));
539
Chad Rosierecafbe62013-03-27 00:14:35 +0000540 if (UsesCodeGen && !TM) return;
Alp Tokerf4e22382013-12-20 20:26:53 +0000541 CreatePasses();
Nadav Rotemec57ab32012-10-24 00:53:38 +0000542
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000543 switch (Action) {
544 case Backend_EmitNothing:
545 break;
546
547 case Backend_EmitBC:
Alp Tokerf4e22382013-12-20 20:26:53 +0000548 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000549 break;
550
551 case Backend_EmitLL:
552 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Chandler Carruth809403f2014-01-12 11:31:22 +0000553 getPerModulePasses()->add(createPrintModulePass(FormattedOS));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000554 break;
555
556 default:
557 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Alp Tokerf4e22382013-12-20 20:26:53 +0000558 if (!AddEmitPasses(Action, FormattedOS))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000559 return;
560 }
561
Andrew Trick15e36e82011-04-05 18:56:55 +0000562 // Before executing passes, print the final values of the LLVM options.
563 cl::PrintOptionValues();
564
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000565 // Run passes. For now we do all passes at once, but eventually we
566 // would like to have the option of streaming code generation.
567
568 if (PerFunctionPasses) {
569 PrettyStackTraceString CrashInfo("Per-function optimization");
570
571 PerFunctionPasses->doInitialization();
572 for (Module::iterator I = TheModule->begin(),
573 E = TheModule->end(); I != E; ++I)
574 if (!I->isDeclaration())
575 PerFunctionPasses->run(*I);
576 PerFunctionPasses->doFinalization();
577 }
578
579 if (PerModulePasses) {
580 PrettyStackTraceString CrashInfo("Per-module optimization passes");
581 PerModulePasses->run(*TheModule);
582 }
583
584 if (CodeGenPasses) {
585 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbar195fa002010-09-17 07:35:16 +0000586 CodeGenPasses->run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000587 }
588}
589
David Blaikie9c902b52011-09-25 23:23:43 +0000590void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
591 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +0000592 const clang::TargetOptions &TOpts,
Alp Tokere83b9062014-01-02 15:08:04 +0000593 const LangOptions &LOpts, StringRef TDesc,
594 Module *M, BackendAction Action,
595 raw_ostream *OS) {
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000596 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000597
598 AsmHelper.EmitAssembly(Action, OS);
Alp Tokere83b9062014-01-02 15:08:04 +0000599
600 // If an optional clang TargetInfo description string was passed in, use it to
601 // verify the LLVM TargetMachine's DataLayout.
602 if (AsmHelper.TM && !TDesc.empty()) {
603 std::string DLDesc =
604 AsmHelper.TM->getDataLayout()->getStringRepresentation();
605 if (DLDesc != TDesc) {
606 unsigned DiagID = Diags.getCustomDiagID(
607 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
608 "expected target description '%1'");
609 Diags.Report(DiagID) << DLDesc << TDesc;
610 }
611 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000612}