blob: 1a5213ee8f57340b9d41b54c152d271b029698e2 [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"),
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000116 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
117
118 ~EmitAssemblyHelper() {
119 delete CodeGenPasses;
120 delete PerModulePasses;
121 delete PerFunctionPasses;
Alp Tokerf4e22382013-12-20 20:26:53 +0000122 if (CodeGenOpts.DisableFree)
Ahmed Charles9a16beb2014-03-07 19:33:25 +0000123 BuryPointer(TM.release());
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000124 }
125
Ahmed Charlesb8984322014-03-07 20:03:18 +0000126 std::unique_ptr<TargetMachine> TM;
Alp Tokerf4e22382013-12-20 20:26:53 +0000127
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000128 void EmitAssembly(BackendAction Action, raw_ostream *OS);
129};
130
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000131// We need this wrapper to access LangOpts and CGOpts from extension functions
132// that we add to the PassManagerBuilder.
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000133class PassManagerBuilderWrapper : public PassManagerBuilder {
134public:
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000135 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
136 const LangOptions &LangOpts)
137 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
138 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000139 const LangOptions &getLangOpts() const { return LangOpts; }
140private:
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000141 const CodeGenOptions &CGOpts;
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000142 const LangOptions &LangOpts;
143};
144
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000145}
146
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 Novillo5c297052013-11-13 12:22:39 +0000162static void addSampleProfileLoaderPass(const PassManagerBuilder &Builder,
163 PassManagerBase &PM) {
164 const PassManagerBuilderWrapper &BuilderWrapper =
165 static_cast<const PassManagerBuilderWrapper &>(Builder);
166 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
167 PM.add(createSampleProfileLoaderPass(CGOpts.SampleProfileFile));
168}
169
Diego Novillob56be642014-03-03 20:06:18 +0000170static void addAddDiscriminatorsPass(const PassManagerBuilder &Builder,
171 PassManagerBase &PM) {
172 PM.add(createAddDiscriminatorsPass());
173}
174
Nuno Lopesa4255892012-05-22 17:19:45 +0000175static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
176 PassManagerBase &PM) {
Joey Goulyebc59d52012-11-23 10:39:49 +0000177 PM.add(createBoundsCheckingPass());
Nuno Lopesa4255892012-05-22 17:19:45 +0000178}
179
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000180static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
181 PassManagerBase &PM) {
182 const PassManagerBuilderWrapper &BuilderWrapper =
183 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000184 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000185 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonov29524a92013-01-20 13:12:12 +0000186 PM.add(createAddressSanitizerFunctionPass(
187 LangOpts.Sanitize.InitOrder,
188 LangOpts.Sanitize.UseAfterReturn,
189 LangOpts.Sanitize.UseAfterScope,
Evgeniy Stepanovd04b8612014-01-16 10:19:31 +0000190 CGOpts.SanitizerBlacklistFile));
Alexey Samsonov29524a92013-01-20 13:12:12 +0000191 PM.add(createAddressSanitizerModulePass(
192 LangOpts.Sanitize.InitOrder,
Evgeniy Stepanovd04b8612014-01-16 10:19:31 +0000193 CGOpts.SanitizerBlacklistFile));
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000194}
195
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000196static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
197 PassManagerBase &PM) {
Evgeniy Stepanovad8ab3d2012-12-24 08:42:34 +0000198 const PassManagerBuilderWrapper &BuilderWrapper =
199 static_cast<const PassManagerBuilderWrapper&>(Builder);
200 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov29524a92013-01-20 13:12:12 +0000201 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins,
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000202 CGOpts.SanitizerBlacklistFile));
Evgeniy Stepanov10284672013-01-31 09:53:29 +0000203
204 // MemorySanitizer inserts complex instrumentation that mostly follows
205 // the logic of the original code, but operates on "shadow" values.
206 // It can benefit from re-running some general purpose optimization passes.
207 if (Builder.OptLevel > 0) {
208 PM.add(createEarlyCSEPass());
209 PM.add(createReassociatePass());
210 PM.add(createLICMPass());
211 PM.add(createGVNPass());
212 PM.add(createInstructionCombiningPass());
213 PM.add(createDeadStoreEliminationPass());
214 }
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000215}
216
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000217static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
218 PassManagerBase &PM) {
Alexey Samsonovc6515b62012-12-28 09:31:34 +0000219 const PassManagerBuilderWrapper &BuilderWrapper =
220 static_cast<const PassManagerBuilderWrapper&>(Builder);
221 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
222 PM.add(createThreadSanitizerPass(CGOpts.SanitizerBlacklistFile));
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000223}
224
Peter Collingbournec3772752013-08-07 22:47:34 +0000225static void addDataFlowSanitizerPass(const PassManagerBuilder &Builder,
226 PassManagerBase &PM) {
Peter Collingbourne276be3c2013-08-14 18:54:18 +0000227 const PassManagerBuilderWrapper &BuilderWrapper =
228 static_cast<const PassManagerBuilderWrapper&>(Builder);
229 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
230 PM.add(createDataFlowSanitizerPass(CGOpts.SanitizerBlacklistFile));
Peter Collingbournec3772752013-08-07 22:47:34 +0000231}
232
Alp Tokerf4e22382013-12-20 20:26:53 +0000233void EmitAssemblyHelper::CreatePasses() {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000234 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000235 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000236
237 // Handle disabling of LLVM optimization, where we want to preserve the
238 // internal module before any optimization.
239 if (CodeGenOpts.DisableLLVMOpts) {
240 OptLevel = 0;
241 Inlining = CodeGenOpts.NoInlining;
242 }
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000243
Alexey Samsonov9ab73622012-12-03 19:12:58 +0000244 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000245 PMBuilder.OptLevel = OptLevel;
246 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Nick Lewyckyd3f3e4f2013-06-25 01:49:44 +0000247 PMBuilder.BBVectorize = CodeGenOpts.VectorizeBB;
248 PMBuilder.SLPVectorize = CodeGenOpts.VectorizeSLP;
249 PMBuilder.LoopVectorize = CodeGenOpts.VectorizeLoop;
Andrew Trickb2a84722011-04-05 18:49:32 +0000250
Duncan P. N. Exon Smith85e349f2014-04-18 01:05:25 +0000251 PMBuilder.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000252 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
253 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Hal Finkelce0697f2013-11-17 16:03:29 +0000254 PMBuilder.RerollLoops = CodeGenOpts.RerollLoops;
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000255
Diego Novillob56be642014-03-03 20:06:18 +0000256 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
257 addAddDiscriminatorsPass);
258
Diego Novillo5c297052013-11-13 12:22:39 +0000259 if (!CodeGenOpts.SampleProfileFile.empty())
260 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
261 addSampleProfileLoaderPass);
262
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000263 // In ObjC ARC mode, add the main ARC optimization passes.
264 if (LangOpts.ObjCAutoRefCount) {
265 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
266 addObjCARCExpandPass);
Dan Gohman5932ce22012-01-17 20:54:51 +0000267 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
268 addObjCARCAPElimPass);
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000269 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
270 addObjCARCOptPass);
271 }
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000272
Richard Smith6b53e222013-10-22 22:51:04 +0000273 if (LangOpts.Sanitize.LocalBounds) {
Nuno Lopesa4255892012-05-22 17:19:45 +0000274 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
275 addBoundsCheckingPass);
276 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
277 addBoundsCheckingPass);
278 }
279
Will Dietzf54319c2013-01-18 11:30:38 +0000280 if (LangOpts.Sanitize.Address) {
Kostya Serebryany7e247f22012-10-15 14:22:56 +0000281 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000282 addAddressSanitizerPasses);
Kostya Serebryanyd4768572011-11-30 22:20:21 +0000283 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov0e96bec2012-11-29 22:36:21 +0000284 addAddressSanitizerPasses);
Kostya Serebryany8855ff62011-11-16 17:34:26 +0000285 }
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000286
Will Dietzf54319c2013-01-18 11:30:38 +0000287 if (LangOpts.Sanitize.Memory) {
Evgeniy Stepanovaea92e52012-12-03 13:20:43 +0000288 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
289 addMemorySanitizerPass);
290 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
291 addMemorySanitizerPass);
292 }
293
Will Dietzf54319c2013-01-18 11:30:38 +0000294 if (LangOpts.Sanitize.Thread) {
Kostya Serebryanyd18cb502012-03-23 23:25:23 +0000295 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany28a7a112012-03-01 22:27:08 +0000296 addThreadSanitizerPass);
297 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
298 addThreadSanitizerPass);
299 }
300
Peter Collingbournec3772752013-08-07 22:47:34 +0000301 if (LangOpts.Sanitize.DataFlow) {
302 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
303 addDataFlowSanitizerPass);
304 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
305 addDataFlowSanitizerPass);
306 }
307
Chris Lattner5c123672011-05-21 20:40:11 +0000308 // Figure out TargetLibraryInfo.
Bill Wendling28b9e8b2011-05-17 23:06:23 +0000309 Triple TargetTriple(TheModule->getTargetTriple());
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000310 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
Chris Lattnerfa222df2011-02-18 22:34:47 +0000311 if (!CodeGenOpts.SimplifyLibCalls)
Chris Lattnerecf0ba52011-05-21 23:50:44 +0000312 PMBuilder.LibraryInfo->disableAllFunctions();
Eli Benderskyb5cfa8c2014-03-12 16:30:34 +0000313
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000314 switch (Inlining) {
315 case CodeGenOptions::NoInlining: break;
316 case CodeGenOptions::NormalInlining: {
Eli Benderskyb5cfa8c2014-03-12 16:30:34 +0000317 PMBuilder.Inliner =
318 createFunctionInliningPass(OptLevel, CodeGenOpts.OptimizeSize);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000319 break;
320 }
321 case CodeGenOptions::OnlyAlwaysInlining:
Chris Lattner5c123672011-05-21 20:40:11 +0000322 // Respect always_inline.
Chad Rosiere2c45062012-02-25 02:56:13 +0000323 if (OptLevel == 0)
324 // Do not insert lifetime intrinsics at -O0.
325 PMBuilder.Inliner = createAlwaysInlinerPass(false);
326 else
327 PMBuilder.Inliner = createAlwaysInlinerPass();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000328 break;
329 }
330
Chris Lattner5c123672011-05-21 20:40:11 +0000331 // Set up the per-function pass manager.
Alp Tokerf4e22382013-12-20 20:26:53 +0000332 FunctionPassManager *FPM = getPerFunctionPasses();
Chris Lattner5c123672011-05-21 20:40:11 +0000333 if (CodeGenOpts.VerifyModule)
334 FPM->add(createVerifierPass());
335 PMBuilder.populateFunctionPassManager(*FPM);
Andrew Trickb2a84722011-04-05 18:49:32 +0000336
Chris Lattner5c123672011-05-21 20:40:11 +0000337 // Set up the per-module pass manager.
Alp Tokerf4e22382013-12-20 20:26:53 +0000338 PassManager *MPM = getPerModulePasses();
Duncan P. N. Exon Smith52eaffe2014-04-15 16:27:43 +0000339 if (CodeGenOpts.VerifyModule)
340 MPM->add(createDebugInfoVerifierPass());
Chris Lattnerd98cec52011-02-18 22:20:38 +0000341
Nick Lewyckyc02bbb62013-03-20 01:38:16 +0000342 if (!CodeGenOpts.DisableGCov &&
343 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000344 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
345 // LLVM's -default-gcov-version flag is set to something invalid.
346 GCOVOptions Options;
347 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
348 Options.EmitData = CodeGenOpts.EmitGcovArcs;
349 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
350 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
351 Options.NoRedZone = CodeGenOpts.DisableRedZone;
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000352 Options.FunctionNamesInData =
Nick Lewycky6f15b2902013-03-20 02:14:38 +0000353 !CodeGenOpts.CoverageNoFunctionNamesInData;
Nick Lewyckyc8bf8242013-03-14 05:14:01 +0000354 MPM->add(createGCOVProfilerPass(Options));
Douglas Gregorb0eea8b2012-10-23 20:05:01 +0000355 if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
Nick Lewycky207bce32011-04-21 23:44:07 +0000356 MPM->add(createStripSymbolsPass(true));
357 }
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000358
Chris Lattner5c123672011-05-21 20:40:11 +0000359 PMBuilder.populateModulePassManager(*MPM);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000360}
361
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000362TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000363 // Create the TargetMachine for generating code.
364 std::string Error;
365 std::string Triple = TheModule->getTargetTriple();
366 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
367 if (!TheTarget) {
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000368 if (MustCreateTM)
Chad Rosierecafbe62013-03-27 00:14:35 +0000369 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Nadav Rotemec57ab32012-10-24 00:53:38 +0000370 return 0;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000371 }
372
373 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
374 // being gross, this is also totally broken if we ever care about
375 // concurrency.
Daniel Dunbarbb7ac522010-07-01 01:31:45 +0000376
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000377 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
378
379 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
380 TargetMachine::setDataSections (CodeGenOpts.DataSections);
381
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000382 unsigned CodeModel =
383 llvm::StringSwitch<unsigned>(CodeGenOpts.CodeModel)
384 .Case("small", llvm::CodeModel::Small)
385 .Case("kernel", llvm::CodeModel::Kernel)
386 .Case("medium", llvm::CodeModel::Medium)
Saleem Abdulrasool61449c62014-05-08 16:28:48 +0000387 .Case("large", llvm::CodeModel::Large)
Saleem Abdulrasool62849c62014-05-08 02:28:32 +0000388 .Case("default", llvm::CodeModel::Default)
389 .Default(~0u);
390 assert(CodeModel != ~0u && "invalid code model!");
391 llvm::CodeModel::Model CM = static_cast<llvm::CodeModel::Model>(CodeModel);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000392
David Blaikie09d20ee2012-02-07 19:36:38 +0000393 SmallVector<const char *, 16> BackendArgs;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000394 BackendArgs.push_back("clang"); // Fake program name.
395 if (!CodeGenOpts.DebugPass.empty()) {
396 BackendArgs.push_back("-debug-pass");
397 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
398 }
399 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
400 BackendArgs.push_back("-limit-float-precision");
401 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
402 }
403 if (llvm::TimePassesIsEnabled)
404 BackendArgs.push_back("-time-passes");
Daniel Dunbar12100e22011-03-22 16:48:17 +0000405 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
406 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Chad Rosierba3df1d2011-08-26 00:26:29 +0000407 if (CodeGenOpts.NoGlobalMerge)
408 BackendArgs.push_back("-global-merge=false");
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000409 BackendArgs.push_back(0);
410 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
David Blaikie09d20ee2012-02-07 19:36:38 +0000411 BackendArgs.data());
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000412
413 std::string FeaturesStr;
Evan Chengadc79592011-06-30 02:06:32 +0000414 if (TargetOpts.Features.size()) {
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000415 SubtargetFeatures Features;
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000416 for (std::vector<std::string>::const_iterator
417 it = TargetOpts.Features.begin(),
418 ie = TargetOpts.Features.end(); it != ie; ++it)
419 Features.AddFeature(*it);
420 FeaturesStr = Features.getString();
421 }
Evan Cheng3f37dd02011-07-19 06:37:41 +0000422
423 llvm::Reloc::Model RM = llvm::Reloc::Default;
424 if (CodeGenOpts.RelocationModel == "static") {
425 RM = llvm::Reloc::Static;
426 } else if (CodeGenOpts.RelocationModel == "pic") {
427 RM = llvm::Reloc::PIC_;
428 } else {
429 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
430 "Invalid PIC model!");
431 RM = llvm::Reloc::DynamicNoPIC;
432 }
433
Evan Chengdd286bc2011-11-16 08:38:55 +0000434 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
435 switch (CodeGenOpts.OptimizationLevel) {
436 default: break;
437 case 0: OptLevel = CodeGenOpt::None; break;
438 case 3: OptLevel = CodeGenOpt::Aggressive; break;
439 }
440
Nick Lewycky432add52011-12-02 22:17:00 +0000441 llvm::TargetOptions Options;
442
Rafael Espindola33ebd212014-02-21 03:14:07 +0000443 if (CodeGenOpts.DisableIntegratedAS)
444 Options.DisableIntegratedAS = true;
445
David Blaikie7e2fd942014-03-27 20:47:30 +0000446 if (CodeGenOpts.CompressDebugSections)
447 Options.CompressDebugSections = true;
448
Nick Lewycky432add52011-12-02 22:17:00 +0000449 // Set frame pointer elimination mode.
450 if (!CodeGenOpts.DisableFPElim) {
451 Options.NoFramePointerElim = false;
Nick Lewycky432add52011-12-02 22:17:00 +0000452 } else if (CodeGenOpts.OmitLeafFramePointer) {
453 Options.NoFramePointerElim = false;
Nick Lewycky432add52011-12-02 22:17:00 +0000454 } else {
455 Options.NoFramePointerElim = true;
Nick Lewycky432add52011-12-02 22:17:00 +0000456 }
457
Rafael Espindola66aa0452012-06-19 01:26:10 +0000458 if (CodeGenOpts.UseInitArray)
459 Options.UseInitArray = true;
460
Nick Lewycky432add52011-12-02 22:17:00 +0000461 // Set float ABI type.
462 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
463 Options.FloatABIType = llvm::FloatABI::Soft;
464 else if (CodeGenOpts.FloatABI == "hard")
465 Options.FloatABIType = llvm::FloatABI::Hard;
466 else {
467 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
468 Options.FloatABIType = llvm::FloatABI::Default;
469 }
470
Lang Hamesaa53b932012-07-06 00:59:19 +0000471 // Set FP fusion mode.
Lang Hames65992f42012-11-15 07:51:26 +0000472 switch (CodeGenOpts.getFPContractMode()) {
473 case CodeGenOptions::FPC_Off:
Lang Hamesaa53b932012-07-06 00:59:19 +0000474 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
475 break;
Lang Hames65992f42012-11-15 07:51:26 +0000476 case CodeGenOptions::FPC_On:
Lang Hamesaa53b932012-07-06 00:59:19 +0000477 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
478 break;
Lang Hames65992f42012-11-15 07:51:26 +0000479 case CodeGenOptions::FPC_Fast:
Lang Hamesaa53b932012-07-06 00:59:19 +0000480 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
Nadav Roteme9c233b2012-10-19 04:15:32 +0000481 break;
Lang Hamesaa53b932012-07-06 00:59:19 +0000482 }
483
Nick Lewycky432add52011-12-02 22:17:00 +0000484 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
485 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
486 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
487 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
488 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
489 Options.UseSoftFloat = CodeGenOpts.SoftFloat;
Nick Lewyckyf4d3f7a2011-12-06 03:33:03 +0000490 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
Nick Lewycky1c8c4362012-01-23 08:29:12 +0000491 Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Bob Wilson14adb362012-02-03 06:27:22 +0000492 Options.TrapFuncName = CodeGenOpts.TrapFuncName;
Chandler Carruth097d0192012-04-08 21:09:51 +0000493 Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
Nick Lewycky432add52011-12-02 22:17:00 +0000494
Eric Christopher7e72a092014-05-15 01:21:56 +0000495 Options.MCOptions.MCRelaxAll = CodeGenOpts.RelaxAll;
496 Options.MCOptions.MCSaveTempLabels = CodeGenOpts.SaveTempLabels;
Eric Christophere76eee42014-05-16 20:46:14 +0000497 Options.MCOptions.MCUseDwarfDirectory = !CodeGenOpts.NoDwarfDirectoryAsm;
Eric Christopher7e72a092014-05-15 01:21:56 +0000498 Options.MCOptions.MCNoExecStack = CodeGenOpts.NoExecStack;
499
Evan Chengadc79592011-06-30 02:06:32 +0000500 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
Nick Lewycky432add52011-12-02 22:17:00 +0000501 FeaturesStr, Options,
502 RM, CM, OptLevel);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000503
Nadav Rotemec57ab32012-10-24 00:53:38 +0000504 return TM;
505}
506
507bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
Alp Tokerf4e22382013-12-20 20:26:53 +0000508 formatted_raw_ostream &OS) {
Nadav Rotemec57ab32012-10-24 00:53:38 +0000509
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000510 // Create the code generator passes.
Alp Tokerf4e22382013-12-20 20:26:53 +0000511 PassManager *PM = getCodeGenPasses();
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000512
Chad Rosierb1cfc682012-02-29 20:14:59 +0000513 // Add LibraryInfo.
Daniel Dunbaraa437df2012-10-19 20:10:10 +0000514 llvm::Triple TargetTriple(TheModule->getTargetTriple());
515 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
Chad Rosierb1cfc682012-02-29 20:14:59 +0000516 if (!CodeGenOpts.SimplifyLibCalls)
517 TLI->disableAllFunctions();
518 PM->add(TLI);
519
Chandler Carruthed0f133b2013-01-07 01:38:01 +0000520 // Add Target specific analysis passes.
521 TM->addAnalysisPasses(*PM);
Nadav Roteme9c233b2012-10-19 04:15:32 +0000522
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000523 // Normal mode, emit a .s or .o file by running the code generator. Note,
524 // this also adds codegenerator level optimization passes.
525 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
526 if (Action == Backend_EmitObj)
527 CGFT = TargetMachine::CGFT_ObjectFile;
528 else if (Action == Backend_EmitMCNull)
529 CGFT = TargetMachine::CGFT_Null;
530 else
531 assert(Action == Backend_EmitAssembly && "Invalid action!");
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000532
533 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
534 // "codegen" passes so that it isn't run multiple times when there is
535 // inlining happening.
Dan Gohman1170b082012-04-04 21:04:56 +0000536 if (LangOpts.ObjCAutoRefCount &&
537 CodeGenOpts.OptimizationLevel > 0)
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000538 PM->add(createObjCARCContractPass());
539
Evan Chengdd286bc2011-11-16 08:38:55 +0000540 if (TM->addPassesToEmitFile(*PM, OS, CGFT,
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000541 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
542 Diags.Report(diag::err_fe_unable_to_interface_with_target);
543 return false;
544 }
545
546 return true;
547}
548
549void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
550 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
551 llvm::formatted_raw_ostream FormattedOS;
552
Nadav Rotemdc06b2d2012-10-24 03:52:31 +0000553 bool UsesCodeGen = (Action != Backend_EmitNothing &&
554 Action != Backend_EmitBC &&
555 Action != Backend_EmitLL);
Alp Tokerf4e22382013-12-20 20:26:53 +0000556 if (!TM)
557 TM.reset(CreateTargetMachine(UsesCodeGen));
558
Chad Rosierecafbe62013-03-27 00:14:35 +0000559 if (UsesCodeGen && !TM) return;
Alp Tokerf4e22382013-12-20 20:26:53 +0000560 CreatePasses();
Nadav Rotemec57ab32012-10-24 00:53:38 +0000561
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000562 switch (Action) {
563 case Backend_EmitNothing:
564 break;
565
566 case Backend_EmitBC:
Alp Tokerf4e22382013-12-20 20:26:53 +0000567 getPerModulePasses()->add(createBitcodeWriterPass(*OS));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000568 break;
569
570 case Backend_EmitLL:
571 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Chandler Carruth809403f2014-01-12 11:31:22 +0000572 getPerModulePasses()->add(createPrintModulePass(FormattedOS));
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000573 break;
574
575 default:
576 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Alp Tokerf4e22382013-12-20 20:26:53 +0000577 if (!AddEmitPasses(Action, FormattedOS))
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000578 return;
579 }
580
Andrew Trick15e36e82011-04-05 18:56:55 +0000581 // Before executing passes, print the final values of the LLVM options.
582 cl::PrintOptionValues();
583
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000584 // Run passes. For now we do all passes at once, but eventually we
585 // would like to have the option of streaming code generation.
586
587 if (PerFunctionPasses) {
588 PrettyStackTraceString CrashInfo("Per-function optimization");
589
590 PerFunctionPasses->doInitialization();
591 for (Module::iterator I = TheModule->begin(),
592 E = TheModule->end(); I != E; ++I)
593 if (!I->isDeclaration())
594 PerFunctionPasses->run(*I);
595 PerFunctionPasses->doFinalization();
596 }
597
598 if (PerModulePasses) {
599 PrettyStackTraceString CrashInfo("Per-module optimization passes");
600 PerModulePasses->run(*TheModule);
601 }
602
603 if (CodeGenPasses) {
604 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbar195fa002010-09-17 07:35:16 +0000605 CodeGenPasses->run(*TheModule);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000606 }
607}
608
David Blaikie9c902b52011-09-25 23:23:43 +0000609void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
610 const CodeGenOptions &CGOpts,
Nick Lewycky432add52011-12-02 22:17:00 +0000611 const clang::TargetOptions &TOpts,
Alp Tokere83b9062014-01-02 15:08:04 +0000612 const LangOptions &LOpts, StringRef TDesc,
613 Module *M, BackendAction Action,
614 raw_ostream *OS) {
Dan Gohmanfec0ff82011-07-05 22:02:36 +0000615 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000616
617 AsmHelper.EmitAssembly(Action, OS);
Alp Tokere83b9062014-01-02 15:08:04 +0000618
619 // If an optional clang TargetInfo description string was passed in, use it to
620 // verify the LLVM TargetMachine's DataLayout.
621 if (AsmHelper.TM && !TDesc.empty()) {
622 std::string DLDesc =
623 AsmHelper.TM->getDataLayout()->getStringRepresentation();
624 if (DLDesc != TDesc) {
625 unsigned DiagID = Diags.getCustomDiagID(
626 DiagnosticsEngine::Error, "backend data layout '%0' does not match "
627 "expected target description '%1'");
628 Diags.Report(DiagID) << DLDesc << TDesc;
629 }
630 }
Daniel Dunbarf976d1b2010-06-07 23:20:08 +0000631}