blob: 23d8b97ae137a06ca5378846c9e0dd9e736baa41 [file] [log] [blame]
Daniel Dunbar897c6762010-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 Dunbar9b414d32010-06-15 17:48:49 +000010#include "clang/CodeGen/BackendUtil.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000011#include "clang/Basic/Diagnostic.h"
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000012#include "clang/Basic/LangOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000013#include "clang/Basic/TargetOptions.h"
Chandler Carruth06057ce2010-06-15 23:19:56 +000014#include "clang/Frontend/CodeGenOptions.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000016#include "llvm/Analysis/Verifier.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000017#include "llvm/Assembly/PrintModulePass.h"
18#include "llvm/Bitcode/ReaderWriter.h"
19#include "llvm/CodeGen/RegAllocRegistry.h"
20#include "llvm/CodeGen/SchedulerRegistry.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000021#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Module.h"
Evan Cheng693769c2011-06-29 01:14:32 +000023#include "llvm/MC/SubtargetFeature.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "llvm/PassManager.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000025#include "llvm/Support/CommandLine.h"
26#include "llvm/Support/FormattedStream.h"
27#include "llvm/Support/PrettyStackTrace.h"
Evan Chenga6b40452011-08-24 18:09:14 +000028#include "llvm/Support/TargetRegistry.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000029#include "llvm/Support/Timer.h"
30#include "llvm/Support/raw_ostream.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000031#include "llvm/Target/TargetLibraryInfo.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000032#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetOptions.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000034#include "llvm/Transforms/IPO.h"
35#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/Transforms/Instrumentation.h"
Michael Gottesman23d5b092013-01-28 01:36:00 +000037#include "llvm/Transforms/ObjCARC.h"
Rafael Espindolacf565c52011-08-02 21:51:02 +000038#include "llvm/Transforms/Scalar.h"
Daniel Dunbar897c6762010-06-07 23:20:08 +000039using namespace clang;
40using namespace llvm;
41
42namespace {
43
44class EmitAssemblyHelper {
David Blaikied6471f72011-09-25 23:23:43 +000045 DiagnosticsEngine &Diags;
Daniel Dunbar897c6762010-06-07 23:20:08 +000046 const CodeGenOptions &CodeGenOpts;
Nick Lewycky3aaeccc2011-12-02 22:17:00 +000047 const clang::TargetOptions &TargetOpts;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +000048 const LangOptions &LangOpts;
Daniel Dunbar897c6762010-06-07 23:20:08 +000049 Module *TheModule;
Daniel Dunbar897c6762010-06-07 23:20:08 +000050
51 Timer CodeGenerationTime;
52
Daniel Dunbardb2f2372010-09-17 07:35:16 +000053 mutable PassManager *CodeGenPasses;
Daniel Dunbar897c6762010-06-07 23:20:08 +000054 mutable PassManager *PerModulePasses;
55 mutable FunctionPassManager *PerFunctionPasses;
56
57private:
Nadav Rotemfa60be02012-10-24 00:53:38 +000058 PassManager *getCodeGenPasses(TargetMachine *TM) const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000059 if (!CodeGenPasses) {
Daniel Dunbardb2f2372010-09-17 07:35:16 +000060 CodeGenPasses = new PassManager();
Micah Villmow25a6a842012-10-08 16:25:52 +000061 CodeGenPasses->add(new DataLayout(TheModule));
Chandler Carruthd938e872013-01-07 01:38:01 +000062 if (TM)
63 TM->addAnalysisPasses(*CodeGenPasses);
Daniel Dunbar897c6762010-06-07 23:20:08 +000064 }
65 return CodeGenPasses;
66 }
67
Nadav Rotemfa60be02012-10-24 00:53:38 +000068 PassManager *getPerModulePasses(TargetMachine *TM) const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000069 if (!PerModulePasses) {
70 PerModulePasses = new PassManager();
Micah Villmow25a6a842012-10-08 16:25:52 +000071 PerModulePasses->add(new DataLayout(TheModule));
Chandler Carruthd938e872013-01-07 01:38:01 +000072 if (TM)
73 TM->addAnalysisPasses(*PerModulePasses);
Daniel Dunbar897c6762010-06-07 23:20:08 +000074 }
75 return PerModulePasses;
76 }
77
Nadav Rotemfa60be02012-10-24 00:53:38 +000078 FunctionPassManager *getPerFunctionPasses(TargetMachine *TM) const {
Daniel Dunbar897c6762010-06-07 23:20:08 +000079 if (!PerFunctionPasses) {
80 PerFunctionPasses = new FunctionPassManager(TheModule);
Micah Villmow25a6a842012-10-08 16:25:52 +000081 PerFunctionPasses->add(new DataLayout(TheModule));
Chandler Carruthd938e872013-01-07 01:38:01 +000082 if (TM)
83 TM->addAnalysisPasses(*PerFunctionPasses);
Daniel Dunbar897c6762010-06-07 23:20:08 +000084 }
85 return PerFunctionPasses;
86 }
87
Nadav Rotemfa60be02012-10-24 00:53:38 +000088
89 void CreatePasses(TargetMachine *TM);
90
Nadav Rotem129369d2012-10-24 03:52:31 +000091 /// CreateTargetMachine - Generates the TargetMachine.
92 /// Returns Null if it is unable to create the target machine.
93 /// Some of our clang tests specify triples which are not built
94 /// into clang. This is okay because these tests check the generated
95 /// IR, and they require DataLayout which depends on the triple.
96 /// In this case, we allow this method to fail and not report an error.
97 /// When MustCreateTM is used, we print an error if we are unable to load
98 /// the requested target.
99 TargetMachine *CreateTargetMachine(bool MustCreateTM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000100
101 /// AddEmitPasses - Add passes necessary to emit assembly or LLVM IR.
102 ///
103 /// \return True on success.
Nadav Rotemfa60be02012-10-24 00:53:38 +0000104 bool AddEmitPasses(BackendAction Action, formatted_raw_ostream &OS,
105 TargetMachine *TM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000106
107public:
David Blaikied6471f72011-09-25 23:23:43 +0000108 EmitAssemblyHelper(DiagnosticsEngine &_Diags,
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000109 const CodeGenOptions &CGOpts,
110 const clang::TargetOptions &TOpts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000111 const LangOptions &LOpts,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000112 Module *M)
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000113 : Diags(_Diags), CodeGenOpts(CGOpts), TargetOpts(TOpts), LangOpts(LOpts),
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000114 TheModule(M), CodeGenerationTime("Code Generation Time"),
Daniel Dunbar897c6762010-06-07 23:20:08 +0000115 CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
116
117 ~EmitAssemblyHelper() {
118 delete CodeGenPasses;
119 delete PerModulePasses;
120 delete PerFunctionPasses;
121 }
122
123 void EmitAssembly(BackendAction Action, raw_ostream *OS);
124};
125
Alexey Samsonove8c03222012-12-28 09:31:34 +0000126// We need this wrapper to access LangOpts and CGOpts from extension functions
127// that we add to the PassManagerBuilder.
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000128class PassManagerBuilderWrapper : public PassManagerBuilder {
129public:
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000130 PassManagerBuilderWrapper(const CodeGenOptions &CGOpts,
131 const LangOptions &LangOpts)
132 : PassManagerBuilder(), CGOpts(CGOpts), LangOpts(LangOpts) {}
133 const CodeGenOptions &getCGOpts() const { return CGOpts; }
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000134 const LangOptions &getLangOpts() const { return LangOpts; }
135private:
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000136 const CodeGenOptions &CGOpts;
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000137 const LangOptions &LangOpts;
138};
139
Daniel Dunbar897c6762010-06-07 23:20:08 +0000140}
141
Dan Gohmana8398ea2012-01-17 20:54:51 +0000142static void addObjCARCAPElimPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
143 if (Builder.OptLevel > 0)
144 PM.add(createObjCARCAPElimPass());
145}
146
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000147static void addObjCARCExpandPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
148 if (Builder.OptLevel > 0)
149 PM.add(createObjCARCExpandPass());
150}
151
152static void addObjCARCOptPass(const PassManagerBuilder &Builder, PassManagerBase &PM) {
153 if (Builder.OptLevel > 0)
154 PM.add(createObjCARCOptPass());
155}
156
Nuno Lopesdef18492012-05-22 17:19:45 +0000157static void addBoundsCheckingPass(const PassManagerBuilder &Builder,
158 PassManagerBase &PM) {
Joey Gouly85489082012-11-23 10:39:49 +0000159 PM.add(createBoundsCheckingPass());
Nuno Lopesdef18492012-05-22 17:19:45 +0000160}
161
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000162static void addAddressSanitizerPasses(const PassManagerBuilder &Builder,
163 PassManagerBase &PM) {
164 const PassManagerBuilderWrapper &BuilderWrapper =
165 static_cast<const PassManagerBuilderWrapper&>(Builder);
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000166 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000167 const LangOptions &LangOpts = BuilderWrapper.getLangOpts();
Alexey Samsonov4bdc6042013-01-20 13:12:12 +0000168 PM.add(createAddressSanitizerFunctionPass(
169 LangOpts.Sanitize.InitOrder,
170 LangOpts.Sanitize.UseAfterReturn,
171 LangOpts.Sanitize.UseAfterScope,
172 CGOpts.SanitizerBlacklistFile,
173 CGOpts.SanitizeAddressZeroBaseShadow));
174 PM.add(createAddressSanitizerModulePass(
175 LangOpts.Sanitize.InitOrder,
176 CGOpts.SanitizerBlacklistFile,
177 CGOpts.SanitizeAddressZeroBaseShadow));
Kostya Serebryany1b4eca62011-11-16 17:34:26 +0000178}
179
Evgeniy Stepanov09ccf392012-12-03 13:20:43 +0000180static void addMemorySanitizerPass(const PassManagerBuilder &Builder,
181 PassManagerBase &PM) {
Evgeniy Stepanov34ef11b2012-12-24 08:42:34 +0000182 const PassManagerBuilderWrapper &BuilderWrapper =
183 static_cast<const PassManagerBuilderWrapper&>(Builder);
184 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
Alexey Samsonov4bdc6042013-01-20 13:12:12 +0000185 PM.add(createMemorySanitizerPass(CGOpts.SanitizeMemoryTrackOrigins,
Alexey Samsonove8c03222012-12-28 09:31:34 +0000186 CGOpts.SanitizerBlacklistFile));
Evgeniy Stepanova8d39042013-01-31 09:53:29 +0000187
188 // MemorySanitizer inserts complex instrumentation that mostly follows
189 // the logic of the original code, but operates on "shadow" values.
190 // It can benefit from re-running some general purpose optimization passes.
191 if (Builder.OptLevel > 0) {
192 PM.add(createEarlyCSEPass());
193 PM.add(createReassociatePass());
194 PM.add(createLICMPass());
195 PM.add(createGVNPass());
196 PM.add(createInstructionCombiningPass());
197 PM.add(createDeadStoreEliminationPass());
198 }
Evgeniy Stepanov09ccf392012-12-03 13:20:43 +0000199}
200
Kostya Serebryany3c931222012-03-01 22:27:08 +0000201static void addThreadSanitizerPass(const PassManagerBuilder &Builder,
202 PassManagerBase &PM) {
Alexey Samsonove8c03222012-12-28 09:31:34 +0000203 const PassManagerBuilderWrapper &BuilderWrapper =
204 static_cast<const PassManagerBuilderWrapper&>(Builder);
205 const CodeGenOptions &CGOpts = BuilderWrapper.getCGOpts();
206 PM.add(createThreadSanitizerPass(CGOpts.SanitizerBlacklistFile));
Kostya Serebryany3c931222012-03-01 22:27:08 +0000207}
208
Nadav Rotemfa60be02012-10-24 00:53:38 +0000209void EmitAssemblyHelper::CreatePasses(TargetMachine *TM) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000210 unsigned OptLevel = CodeGenOpts.OptimizationLevel;
Douglas Gregor4cdad312012-10-23 20:05:01 +0000211 CodeGenOptions::InliningMethod Inlining = CodeGenOpts.getInlining();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000212
213 // Handle disabling of LLVM optimization, where we want to preserve the
214 // internal module before any optimization.
215 if (CodeGenOpts.DisableLLVMOpts) {
216 OptLevel = 0;
217 Inlining = CodeGenOpts.NoInlining;
218 }
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000219
Alexey Samsonov91ecfa62012-12-03 19:12:58 +0000220 PassManagerBuilderWrapper PMBuilder(CodeGenOpts, LangOpts);
Chris Lattner9ca02e52011-05-21 23:50:44 +0000221 PMBuilder.OptLevel = OptLevel;
222 PMBuilder.SizeLevel = CodeGenOpts.OptimizeSize;
Andrew Trick6445d622011-04-05 18:49:32 +0000223
Chris Lattner9ca02e52011-05-21 23:50:44 +0000224 PMBuilder.DisableSimplifyLibCalls = !CodeGenOpts.SimplifyLibCalls;
225 PMBuilder.DisableUnitAtATime = !CodeGenOpts.UnitAtATime;
226 PMBuilder.DisableUnrollLoops = !CodeGenOpts.UnrollLoops;
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000227
228 // In ObjC ARC mode, add the main ARC optimization passes.
229 if (LangOpts.ObjCAutoRefCount) {
230 PMBuilder.addExtension(PassManagerBuilder::EP_EarlyAsPossible,
231 addObjCARCExpandPass);
Dan Gohmana8398ea2012-01-17 20:54:51 +0000232 PMBuilder.addExtension(PassManagerBuilder::EP_ModuleOptimizerEarly,
233 addObjCARCAPElimPass);
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000234 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
235 addObjCARCOptPass);
236 }
Kostya Serebryany1b4eca62011-11-16 17:34:26 +0000237
Will Dietz4f45bc02013-01-18 11:30:38 +0000238 if (LangOpts.Sanitize.Bounds) {
Nuno Lopesdef18492012-05-22 17:19:45 +0000239 PMBuilder.addExtension(PassManagerBuilder::EP_ScalarOptimizerLate,
240 addBoundsCheckingPass);
241 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
242 addBoundsCheckingPass);
243 }
244
Will Dietz4f45bc02013-01-18 11:30:38 +0000245 if (LangOpts.Sanitize.Address) {
Kostya Serebryanyba1f0402012-10-15 14:22:56 +0000246 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000247 addAddressSanitizerPasses);
Kostya Serebryanye5dd2ea2011-11-30 22:20:21 +0000248 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
Alexey Samsonov4d1a6e42012-11-29 22:36:21 +0000249 addAddressSanitizerPasses);
Kostya Serebryany1b4eca62011-11-16 17:34:26 +0000250 }
Kostya Serebryany3c931222012-03-01 22:27:08 +0000251
Will Dietz4f45bc02013-01-18 11:30:38 +0000252 if (LangOpts.Sanitize.Memory) {
Evgeniy Stepanov09ccf392012-12-03 13:20:43 +0000253 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
254 addMemorySanitizerPass);
255 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
256 addMemorySanitizerPass);
257 }
258
Will Dietz4f45bc02013-01-18 11:30:38 +0000259 if (LangOpts.Sanitize.Thread) {
Kostya Serebryanye78ec3e2012-03-23 23:25:23 +0000260 PMBuilder.addExtension(PassManagerBuilder::EP_OptimizerLast,
Kostya Serebryany3c931222012-03-01 22:27:08 +0000261 addThreadSanitizerPass);
262 PMBuilder.addExtension(PassManagerBuilder::EP_EnabledOnOptLevel0,
263 addThreadSanitizerPass);
264 }
265
Chris Lattner33c09d52011-05-21 20:40:11 +0000266 // Figure out TargetLibraryInfo.
Bill Wendling3621b312011-05-17 23:06:23 +0000267 Triple TargetTriple(TheModule->getTargetTriple());
Chris Lattner9ca02e52011-05-21 23:50:44 +0000268 PMBuilder.LibraryInfo = new TargetLibraryInfo(TargetTriple);
Chris Lattner98ec3f72011-02-18 22:34:47 +0000269 if (!CodeGenOpts.SimplifyLibCalls)
Chris Lattner9ca02e52011-05-21 23:50:44 +0000270 PMBuilder.LibraryInfo->disableAllFunctions();
Chris Lattner33c09d52011-05-21 20:40:11 +0000271
Daniel Dunbar897c6762010-06-07 23:20:08 +0000272 switch (Inlining) {
273 case CodeGenOptions::NoInlining: break;
274 case CodeGenOptions::NormalInlining: {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000275 // FIXME: Derive these constants in a principled fashion.
276 unsigned Threshold = 225;
Chris Lattner33c09d52011-05-21 20:40:11 +0000277 if (CodeGenOpts.OptimizeSize == 1) // -Os
Daniel Dunbar897c6762010-06-07 23:20:08 +0000278 Threshold = 75;
Chris Lattner33c09d52011-05-21 20:40:11 +0000279 else if (CodeGenOpts.OptimizeSize == 2) // -Oz
Bob Wilsona0fa2032011-04-29 22:49:50 +0000280 Threshold = 25;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000281 else if (OptLevel > 2)
282 Threshold = 275;
Chris Lattner9ca02e52011-05-21 23:50:44 +0000283 PMBuilder.Inliner = createFunctionInliningPass(Threshold);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000284 break;
285 }
286 case CodeGenOptions::OnlyAlwaysInlining:
Chris Lattner33c09d52011-05-21 20:40:11 +0000287 // Respect always_inline.
Chad Rosier98759622012-02-25 02:56:13 +0000288 if (OptLevel == 0)
289 // Do not insert lifetime intrinsics at -O0.
290 PMBuilder.Inliner = createAlwaysInlinerPass(false);
291 else
292 PMBuilder.Inliner = createAlwaysInlinerPass();
Daniel Dunbar897c6762010-06-07 23:20:08 +0000293 break;
294 }
295
Chris Lattner33c09d52011-05-21 20:40:11 +0000296 // Set up the per-function pass manager.
Nadav Rotemfa60be02012-10-24 00:53:38 +0000297 FunctionPassManager *FPM = getPerFunctionPasses(TM);
Chris Lattner33c09d52011-05-21 20:40:11 +0000298 if (CodeGenOpts.VerifyModule)
299 FPM->add(createVerifierPass());
300 PMBuilder.populateFunctionPassManager(*FPM);
Andrew Trick6445d622011-04-05 18:49:32 +0000301
Chris Lattner33c09d52011-05-21 20:40:11 +0000302 // Set up the per-module pass manager.
Nadav Rotemfa60be02012-10-24 00:53:38 +0000303 PassManager *MPM = getPerModulePasses(TM);
Chris Lattnerdf619762011-02-18 22:20:38 +0000304
Nick Lewyckyf2b5e072013-03-20 01:38:16 +0000305 if (!CodeGenOpts.DisableGCov &&
306 (CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)) {
Nick Lewyckyc3ae5832013-03-14 05:14:01 +0000307 // Not using 'GCOVOptions::getDefault' allows us to avoid exiting if
308 // LLVM's -default-gcov-version flag is set to something invalid.
309 GCOVOptions Options;
310 Options.EmitNotes = CodeGenOpts.EmitGcovNotes;
311 Options.EmitData = CodeGenOpts.EmitGcovArcs;
312 memcpy(Options.Version, CodeGenOpts.CoverageVersion, 4);
313 Options.UseCfgChecksum = CodeGenOpts.CoverageExtraChecksum;
314 Options.NoRedZone = CodeGenOpts.DisableRedZone;
315 // FIXME: the clang flag name is backwards.
316 Options.FunctionNamesInData =
317 !CodeGenOpts.CoverageFunctionNamesInData;
318 MPM->add(createGCOVProfilerPass(Options));
Douglas Gregor4cdad312012-10-23 20:05:01 +0000319 if (CodeGenOpts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000320 MPM->add(createStripSymbolsPass(true));
321 }
Nadav Rotem129369d2012-10-24 03:52:31 +0000322
Chris Lattner33c09d52011-05-21 20:40:11 +0000323 PMBuilder.populateModulePassManager(*MPM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000324}
325
Nadav Rotem129369d2012-10-24 03:52:31 +0000326TargetMachine *EmitAssemblyHelper::CreateTargetMachine(bool MustCreateTM) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000327 // Create the TargetMachine for generating code.
328 std::string Error;
329 std::string Triple = TheModule->getTargetTriple();
330 const llvm::Target *TheTarget = TargetRegistry::lookupTarget(Triple, Error);
331 if (!TheTarget) {
Nadav Rotem129369d2012-10-24 03:52:31 +0000332 if (MustCreateTM)
333 Diags.Report(diag::err_fe_unable_to_create_target) << Error;
Nadav Rotemfa60be02012-10-24 00:53:38 +0000334 return 0;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000335 }
336
337 // FIXME: Expose these capabilities via actual APIs!!!! Aside from just
338 // being gross, this is also totally broken if we ever care about
339 // concurrency.
Daniel Dunbar1ad66482010-07-01 01:31:45 +0000340
Daniel Dunbar897c6762010-06-07 23:20:08 +0000341 TargetMachine::setAsmVerbosityDefault(CodeGenOpts.AsmVerbose);
342
343 TargetMachine::setFunctionSections(CodeGenOpts.FunctionSections);
344 TargetMachine::setDataSections (CodeGenOpts.DataSections);
345
346 // FIXME: Parse this earlier.
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000347 llvm::CodeModel::Model CM;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000348 if (CodeGenOpts.CodeModel == "small") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000349 CM = llvm::CodeModel::Small;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000350 } else if (CodeGenOpts.CodeModel == "kernel") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000351 CM = llvm::CodeModel::Kernel;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000352 } else if (CodeGenOpts.CodeModel == "medium") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000353 CM = llvm::CodeModel::Medium;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000354 } else if (CodeGenOpts.CodeModel == "large") {
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000355 CM = llvm::CodeModel::Large;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000356 } else {
357 assert(CodeGenOpts.CodeModel.empty() && "Invalid code model!");
Benjamin Kramer77577ce2011-07-20 14:43:06 +0000358 CM = llvm::CodeModel::Default;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000359 }
360
David Blaikie6bd17d22012-02-07 19:36:38 +0000361 SmallVector<const char *, 16> BackendArgs;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000362 BackendArgs.push_back("clang"); // Fake program name.
363 if (!CodeGenOpts.DebugPass.empty()) {
364 BackendArgs.push_back("-debug-pass");
365 BackendArgs.push_back(CodeGenOpts.DebugPass.c_str());
366 }
367 if (!CodeGenOpts.LimitFloatPrecision.empty()) {
368 BackendArgs.push_back("-limit-float-precision");
369 BackendArgs.push_back(CodeGenOpts.LimitFloatPrecision.c_str());
370 }
371 if (llvm::TimePassesIsEnabled)
372 BackendArgs.push_back("-time-passes");
Daniel Dunbar3c66d302011-03-22 16:48:17 +0000373 for (unsigned i = 0, e = CodeGenOpts.BackendOptions.size(); i != e; ++i)
374 BackendArgs.push_back(CodeGenOpts.BackendOptions[i].c_str());
Chad Rosier1b906052011-08-26 00:26:29 +0000375 if (CodeGenOpts.NoGlobalMerge)
376 BackendArgs.push_back("-global-merge=false");
Daniel Dunbar897c6762010-06-07 23:20:08 +0000377 BackendArgs.push_back(0);
378 llvm::cl::ParseCommandLineOptions(BackendArgs.size() - 1,
David Blaikie6bd17d22012-02-07 19:36:38 +0000379 BackendArgs.data());
Daniel Dunbar897c6762010-06-07 23:20:08 +0000380
381 std::string FeaturesStr;
Evan Cheng368691e2011-06-30 02:06:32 +0000382 if (TargetOpts.Features.size()) {
Daniel Dunbar897c6762010-06-07 23:20:08 +0000383 SubtargetFeatures Features;
Daniel Dunbar897c6762010-06-07 23:20:08 +0000384 for (std::vector<std::string>::const_iterator
385 it = TargetOpts.Features.begin(),
386 ie = TargetOpts.Features.end(); it != ie; ++it)
387 Features.AddFeature(*it);
388 FeaturesStr = Features.getString();
389 }
Evan Cheng2860e302011-07-19 06:37:41 +0000390
391 llvm::Reloc::Model RM = llvm::Reloc::Default;
392 if (CodeGenOpts.RelocationModel == "static") {
393 RM = llvm::Reloc::Static;
394 } else if (CodeGenOpts.RelocationModel == "pic") {
395 RM = llvm::Reloc::PIC_;
396 } else {
397 assert(CodeGenOpts.RelocationModel == "dynamic-no-pic" &&
398 "Invalid PIC model!");
399 RM = llvm::Reloc::DynamicNoPIC;
400 }
401
Evan Cheng9254bf72011-11-16 08:38:55 +0000402 CodeGenOpt::Level OptLevel = CodeGenOpt::Default;
403 switch (CodeGenOpts.OptimizationLevel) {
404 default: break;
405 case 0: OptLevel = CodeGenOpt::None; break;
406 case 3: OptLevel = CodeGenOpt::Aggressive; break;
407 }
408
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000409 llvm::TargetOptions Options;
410
411 // Set frame pointer elimination mode.
412 if (!CodeGenOpts.DisableFPElim) {
413 Options.NoFramePointerElim = false;
414 Options.NoFramePointerElimNonLeaf = false;
415 } else if (CodeGenOpts.OmitLeafFramePointer) {
416 Options.NoFramePointerElim = false;
417 Options.NoFramePointerElimNonLeaf = true;
418 } else {
419 Options.NoFramePointerElim = true;
420 Options.NoFramePointerElimNonLeaf = true;
421 }
422
Rafael Espindola8af669f2012-06-19 01:26:10 +0000423 if (CodeGenOpts.UseInitArray)
424 Options.UseInitArray = true;
425
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000426 // Set float ABI type.
427 if (CodeGenOpts.FloatABI == "soft" || CodeGenOpts.FloatABI == "softfp")
428 Options.FloatABIType = llvm::FloatABI::Soft;
429 else if (CodeGenOpts.FloatABI == "hard")
430 Options.FloatABIType = llvm::FloatABI::Hard;
431 else {
432 assert(CodeGenOpts.FloatABI.empty() && "Invalid float abi!");
433 Options.FloatABIType = llvm::FloatABI::Default;
434 }
435
Lang Hamesc9686712012-07-06 00:59:19 +0000436 // Set FP fusion mode.
Lang Hames931c0832012-11-15 07:51:26 +0000437 switch (CodeGenOpts.getFPContractMode()) {
438 case CodeGenOptions::FPC_Off:
Lang Hamesc9686712012-07-06 00:59:19 +0000439 Options.AllowFPOpFusion = llvm::FPOpFusion::Strict;
440 break;
Lang Hames931c0832012-11-15 07:51:26 +0000441 case CodeGenOptions::FPC_On:
Lang Hamesc9686712012-07-06 00:59:19 +0000442 Options.AllowFPOpFusion = llvm::FPOpFusion::Standard;
443 break;
Lang Hames931c0832012-11-15 07:51:26 +0000444 case CodeGenOptions::FPC_Fast:
Lang Hamesc9686712012-07-06 00:59:19 +0000445 Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
Nadav Rotem25030c42012-10-19 04:15:32 +0000446 break;
Lang Hamesc9686712012-07-06 00:59:19 +0000447 }
448
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000449 Options.LessPreciseFPMADOption = CodeGenOpts.LessPreciseFPMAD;
450 Options.NoInfsFPMath = CodeGenOpts.NoInfsFPMath;
451 Options.NoNaNsFPMath = CodeGenOpts.NoNaNsFPMath;
452 Options.NoZerosInBSS = CodeGenOpts.NoZeroInitializedInBSS;
453 Options.UnsafeFPMath = CodeGenOpts.UnsafeFPMath;
454 Options.UseSoftFloat = CodeGenOpts.SoftFloat;
Nick Lewycky4e785c92011-12-06 03:33:03 +0000455 Options.StackAlignmentOverride = CodeGenOpts.StackAlignment;
456 Options.RealignStack = CodeGenOpts.StackRealignment;
Nick Lewycky1db772b2012-01-23 08:29:12 +0000457 Options.DisableTailCalls = CodeGenOpts.DisableTailCalls;
Bob Wilson71fd6cc2012-02-03 06:27:22 +0000458 Options.TrapFuncName = CodeGenOpts.TrapFuncName;
Chandler Carruth5081de52012-04-08 21:09:51 +0000459 Options.PositionIndependentExecutable = LangOpts.PIELevel != 0;
Chad Rosiera7afeb02012-08-21 16:16:06 +0000460 Options.SSPBufferSize = CodeGenOpts.SSPBufferSize;
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000461
Evan Cheng368691e2011-06-30 02:06:32 +0000462 TargetMachine *TM = TheTarget->createTargetMachine(Triple, TargetOpts.CPU,
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000463 FeaturesStr, Options,
464 RM, CM, OptLevel);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000465
466 if (CodeGenOpts.RelaxAll)
467 TM->setMCRelaxAll(true);
Daniel Dunbar96932322011-03-28 22:49:28 +0000468 if (CodeGenOpts.SaveTempLabels)
469 TM->setMCSaveTempLabels(true);
Rafael Espindolaf24a1512011-04-30 18:35:43 +0000470 if (CodeGenOpts.NoDwarf2CFIAsm)
471 TM->setMCUseCFI(false);
Nick Lewyckyaaf2f362011-10-31 01:06:42 +0000472 if (!CodeGenOpts.NoDwarfDirectoryAsm)
473 TM->setMCUseDwarfDirectory(true);
Nick Lewyckyc3b90142011-06-21 00:14:18 +0000474 if (CodeGenOpts.NoExecStack)
475 TM->setMCNoExecStack(true);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000476
Nadav Rotemfa60be02012-10-24 00:53:38 +0000477 return TM;
478}
479
480bool EmitAssemblyHelper::AddEmitPasses(BackendAction Action,
481 formatted_raw_ostream &OS,
482 TargetMachine *TM) {
483
Daniel Dunbar897c6762010-06-07 23:20:08 +0000484 // Create the code generator passes.
Nadav Rotemfa60be02012-10-24 00:53:38 +0000485 PassManager *PM = getCodeGenPasses(TM);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000486
Chad Rosier3f3335d2012-02-29 20:14:59 +0000487 // Add LibraryInfo.
Daniel Dunbarcbbe2c02012-10-19 20:10:10 +0000488 llvm::Triple TargetTriple(TheModule->getTargetTriple());
489 TargetLibraryInfo *TLI = new TargetLibraryInfo(TargetTriple);
Chad Rosier3f3335d2012-02-29 20:14:59 +0000490 if (!CodeGenOpts.SimplifyLibCalls)
491 TLI->disableAllFunctions();
492 PM->add(TLI);
493
Chandler Carruthd938e872013-01-07 01:38:01 +0000494 // Add Target specific analysis passes.
495 TM->addAnalysisPasses(*PM);
Nadav Rotem25030c42012-10-19 04:15:32 +0000496
Daniel Dunbar897c6762010-06-07 23:20:08 +0000497 // Normal mode, emit a .s or .o file by running the code generator. Note,
498 // this also adds codegenerator level optimization passes.
499 TargetMachine::CodeGenFileType CGFT = TargetMachine::CGFT_AssemblyFile;
500 if (Action == Backend_EmitObj)
501 CGFT = TargetMachine::CGFT_ObjectFile;
502 else if (Action == Backend_EmitMCNull)
503 CGFT = TargetMachine::CGFT_Null;
504 else
505 assert(Action == Backend_EmitAssembly && "Invalid action!");
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000506
507 // Add ObjC ARC final-cleanup optimizations. This is done as part of the
508 // "codegen" passes so that it isn't run multiple times when there is
509 // inlining happening.
Dan Gohman465a8992012-04-04 21:04:56 +0000510 if (LangOpts.ObjCAutoRefCount &&
511 CodeGenOpts.OptimizationLevel > 0)
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000512 PM->add(createObjCARCContractPass());
513
Evan Cheng9254bf72011-11-16 08:38:55 +0000514 if (TM->addPassesToEmitFile(*PM, OS, CGFT,
Daniel Dunbar897c6762010-06-07 23:20:08 +0000515 /*DisableVerify=*/!CodeGenOpts.VerifyModule)) {
516 Diags.Report(diag::err_fe_unable_to_interface_with_target);
517 return false;
518 }
519
520 return true;
521}
522
523void EmitAssemblyHelper::EmitAssembly(BackendAction Action, raw_ostream *OS) {
524 TimeRegion Region(llvm::TimePassesIsEnabled ? &CodeGenerationTime : 0);
525 llvm::formatted_raw_ostream FormattedOS;
526
Nadav Rotem129369d2012-10-24 03:52:31 +0000527 bool UsesCodeGen = (Action != Backend_EmitNothing &&
528 Action != Backend_EmitBC &&
529 Action != Backend_EmitLL);
530 TargetMachine *TM = CreateTargetMachine(UsesCodeGen);
Nadav Rotemfa60be02012-10-24 00:53:38 +0000531 CreatePasses(TM);
532
Daniel Dunbar897c6762010-06-07 23:20:08 +0000533 switch (Action) {
534 case Backend_EmitNothing:
535 break;
536
537 case Backend_EmitBC:
Nadav Rotemfa60be02012-10-24 00:53:38 +0000538 getPerModulePasses(TM)->add(createBitcodeWriterPass(*OS));
Daniel Dunbar897c6762010-06-07 23:20:08 +0000539 break;
540
541 case Backend_EmitLL:
542 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Nadav Rotemfa60be02012-10-24 00:53:38 +0000543 getPerModulePasses(TM)->add(createPrintModulePass(&FormattedOS));
Daniel Dunbar897c6762010-06-07 23:20:08 +0000544 break;
545
546 default:
547 FormattedOS.setStream(*OS, formatted_raw_ostream::PRESERVE_STREAM);
Nadav Rotemfa60be02012-10-24 00:53:38 +0000548 if (!AddEmitPasses(Action, FormattedOS, TM))
Daniel Dunbar897c6762010-06-07 23:20:08 +0000549 return;
550 }
551
Andrew Trick92b5d942011-04-05 18:56:55 +0000552 // Before executing passes, print the final values of the LLVM options.
553 cl::PrintOptionValues();
554
Daniel Dunbar897c6762010-06-07 23:20:08 +0000555 // Run passes. For now we do all passes at once, but eventually we
556 // would like to have the option of streaming code generation.
557
558 if (PerFunctionPasses) {
559 PrettyStackTraceString CrashInfo("Per-function optimization");
560
561 PerFunctionPasses->doInitialization();
562 for (Module::iterator I = TheModule->begin(),
563 E = TheModule->end(); I != E; ++I)
564 if (!I->isDeclaration())
565 PerFunctionPasses->run(*I);
566 PerFunctionPasses->doFinalization();
567 }
568
569 if (PerModulePasses) {
570 PrettyStackTraceString CrashInfo("Per-module optimization passes");
571 PerModulePasses->run(*TheModule);
572 }
573
574 if (CodeGenPasses) {
575 PrettyStackTraceString CrashInfo("Code generation");
Daniel Dunbardb2f2372010-09-17 07:35:16 +0000576 CodeGenPasses->run(*TheModule);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000577 }
578}
579
David Blaikied6471f72011-09-25 23:23:43 +0000580void clang::EmitBackendOutput(DiagnosticsEngine &Diags,
581 const CodeGenOptions &CGOpts,
Nick Lewycky3aaeccc2011-12-02 22:17:00 +0000582 const clang::TargetOptions &TOpts,
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000583 const LangOptions &LOpts,
584 Module *M,
Daniel Dunbar05a7f3d2010-06-07 23:21:04 +0000585 BackendAction Action, raw_ostream *OS) {
Dan Gohmanb18b8ad2011-07-05 22:02:36 +0000586 EmitAssemblyHelper AsmHelper(Diags, CGOpts, TOpts, LOpts, M);
Daniel Dunbar897c6762010-06-07 23:20:08 +0000587
588 AsmHelper.EmitAssembly(Action, OS);
589}