1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVMTargetMachine class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/Analysis/Passes.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/BasicTTIImpl.h"
18 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/IR/IRPrintingPasses.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/IR/Verifier.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCContext.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Transforms/Scalar.h"
36 using namespace llvm;
37 
38 // Enable or disable FastISel. Both options are needed, because
39 // FastISel is enabled by default with -fast, and we wish to be
40 // able to enable or disable fast-isel independently from -O0.
41 static cl::opt<cl::boolOrDefault>
42 EnableFastISelOption("fast-isel", cl::Hidden,
43   cl::desc("Enable the \"fast\" instruction selector"));
44 
45 static cl::opt<bool>
46     EnableGlobalISel("global-isel", cl::Hidden, cl::init(false),
47                      cl::desc("Enable the \"global\" instruction selector"));
48 
49 void LLVMTargetMachine::initAsmInfo() {
50   MRI = TheTarget.createMCRegInfo(getTargetTriple().str());
51   MII = TheTarget.createMCInstrInfo();
52   // FIXME: Having an MCSubtargetInfo on the target machine is a hack due
53   // to some backends having subtarget feature dependent module level
54   // code generation. This is similar to the hack in the AsmPrinter for
55   // module level assembly etc.
56   STI = TheTarget.createMCSubtargetInfo(getTargetTriple().str(), getTargetCPU(),
57                                         getTargetFeatureString());
58 
59   MCAsmInfo *TmpAsmInfo =
60       TheTarget.createMCAsmInfo(*MRI, getTargetTriple().str());
61   // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
62   // and if the old one gets included then MCAsmInfo will be NULL and
63   // we'll crash later.
64   // Provide the user with a useful error message about what's wrong.
65   assert(TmpAsmInfo && "MCAsmInfo not initialized. "
66          "Make sure you include the correct TargetSelect.h"
67          "and that InitializeAllTargetMCs() is being invoked!");
68 
69   if (Options.DisableIntegratedAS)
70     TmpAsmInfo->setUseIntegratedAssembler(false);
71 
72   if (Options.CompressDebugSections)
73     TmpAsmInfo->setCompressDebugSections(true);
74 
75   AsmInfo = TmpAsmInfo;
76 }
77 
78 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
79                                      StringRef DataLayoutString,
80                                      const Triple &TT, StringRef CPU,
81                                      StringRef FS, TargetOptions Options,
82                                      Reloc::Model RM, CodeModel::Model CM,
83                                      CodeGenOpt::Level OL)
84     : TargetMachine(T, DataLayoutString, TT, CPU, FS, Options) {
85   CodeGenInfo = T.createMCCodeGenInfo(TT.str(), RM, CM, OL);
86 }
87 
88 TargetIRAnalysis LLVMTargetMachine::getTargetIRAnalysis() {
89   return TargetIRAnalysis([this](const Function &F) {
90     return TargetTransformInfo(BasicTTIImpl(this, F));
91   });
92 }
93 
94 /// addPassesToX helper drives creation and initialization of TargetPassConfig.
95 static MCContext *
96 addPassesToGenerateCode(LLVMTargetMachine *TM, PassManagerBase &PM,
97                         bool DisableVerify, AnalysisID StartBefore,
98                         AnalysisID StartAfter, AnalysisID StopAfter,
99                         MachineFunctionInitializer *MFInitializer = nullptr) {
100 
101   // When in emulated TLS mode, add the LowerEmuTLS pass.
102   if (TM->Options.EmulatedTLS)
103     PM.add(createLowerEmuTLSPass(TM));
104 
105   // Add internal analysis passes from the target machine.
106   PM.add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
107 
108   // Targets may override createPassConfig to provide a target-specific
109   // subclass.
110   TargetPassConfig *PassConfig = TM->createPassConfig(PM);
111   PassConfig->setStartStopPasses(StartBefore, StartAfter, StopAfter);
112 
113   // Set PassConfig options provided by TargetMachine.
114   PassConfig->setDisableVerify(DisableVerify);
115 
116   PM.add(PassConfig);
117 
118   PassConfig->addIRPasses();
119 
120   PassConfig->addCodeGenPrepare();
121 
122   PassConfig->addPassesToHandleExceptions();
123 
124   PassConfig->addISelPrepare();
125 
126   // Install a MachineModuleInfo class, which is an immutable pass that holds
127   // all the per-module stuff we're generating, including MCContext.
128   MachineModuleInfo *MMI = new MachineModuleInfo(
129       *TM->getMCAsmInfo(), *TM->getMCRegisterInfo(), TM->getObjFileLowering());
130   PM.add(MMI);
131 
132   // Set up a MachineFunction for the rest of CodeGen to work on.
133   PM.add(new MachineFunctionAnalysis(*TM, MFInitializer));
134 
135   // Enable FastISel with -fast, but allow that to be overridden.
136   TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
137   if (EnableFastISelOption == cl::BOU_TRUE ||
138       (TM->getOptLevel() == CodeGenOpt::None &&
139        TM->getO0WantsFastISel()))
140     TM->setFastISel(true);
141 
142   // Ask the target for an isel.
143   if (LLVM_UNLIKELY(EnableGlobalISel)) {
144     if (PassConfig->addIRTranslator())
145       return nullptr;
146   } else if (PassConfig->addInstSelector())
147     return nullptr;
148 
149   PassConfig->addMachinePasses();
150 
151   PassConfig->setInitialized();
152 
153   return &MMI->getContext();
154 }
155 
156 bool LLVMTargetMachine::addPassesToEmitFile(
157     PassManagerBase &PM, raw_pwrite_stream &Out, CodeGenFileType FileType,
158     bool DisableVerify, AnalysisID StartBefore, AnalysisID StartAfter,
159     AnalysisID StopAfter, MachineFunctionInitializer *MFInitializer) {
160   // Add common CodeGen passes.
161   MCContext *Context =
162       addPassesToGenerateCode(this, PM, DisableVerify, StartBefore, StartAfter,
163                               StopAfter, MFInitializer);
164   if (!Context)
165     return true;
166 
167   if (StopAfter) {
168     PM.add(createPrintMIRPass(errs()));
169     return false;
170   }
171 
172   if (Options.MCOptions.MCSaveTempLabels)
173     Context->setAllowTemporaryLabels(false);
174 
175   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
176   const MCAsmInfo &MAI = *getMCAsmInfo();
177   const MCRegisterInfo &MRI = *getMCRegisterInfo();
178   const MCInstrInfo &MII = *getMCInstrInfo();
179 
180   std::unique_ptr<MCStreamer> AsmStreamer;
181 
182   switch (FileType) {
183   case CGFT_AssemblyFile: {
184     MCInstPrinter *InstPrinter = getTarget().createMCInstPrinter(
185         getTargetTriple(), MAI.getAssemblerDialect(), MAI, MII, MRI);
186 
187     // Create a code emitter if asked to show the encoding.
188     MCCodeEmitter *MCE = nullptr;
189     if (Options.MCOptions.ShowMCEncoding)
190       MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
191 
192     MCAsmBackend *MAB =
193         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
194     auto FOut = llvm::make_unique<formatted_raw_ostream>(Out);
195     MCStreamer *S = getTarget().createAsmStreamer(
196         *Context, std::move(FOut), Options.MCOptions.AsmVerbose,
197         Options.MCOptions.MCUseDwarfDirectory, InstPrinter, MCE, MAB,
198         Options.MCOptions.ShowMCInst);
199     AsmStreamer.reset(S);
200     break;
201   }
202   case CGFT_ObjectFile: {
203     // Create the code emitter for the target if it exists.  If not, .o file
204     // emission fails.
205     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(MII, MRI, *Context);
206     MCAsmBackend *MAB =
207         getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
208     if (!MCE || !MAB)
209       return true;
210 
211     // Don't waste memory on names of temp labels.
212     Context->setUseNamesOnTempLabels(false);
213 
214     Triple T(getTargetTriple().str());
215     AsmStreamer.reset(getTarget().createMCObjectStreamer(
216         T, *Context, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
217         Options.MCOptions.MCIncrementalLinkerCompatible,
218         /*DWARFMustBeAtTheEnd*/ true));
219     break;
220   }
221   case CGFT_Null:
222     // The Null output is intended for use for performance analysis and testing,
223     // not real users.
224     AsmStreamer.reset(getTarget().createNullStreamer(*Context));
225     break;
226   }
227 
228   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
229   FunctionPass *Printer =
230       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
231   if (!Printer)
232     return true;
233 
234   PM.add(Printer);
235 
236   return false;
237 }
238 
239 /// addPassesToEmitMC - Add passes to the specified pass manager to get
240 /// machine code emitted with the MCJIT. This method returns true if machine
241 /// code is not supported. It fills the MCContext Ctx pointer which can be
242 /// used to build custom MCStreamer.
243 ///
244 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, MCContext *&Ctx,
245                                           raw_pwrite_stream &Out,
246                                           bool DisableVerify) {
247   // Add common CodeGen passes.
248   Ctx = addPassesToGenerateCode(this, PM, DisableVerify, nullptr, nullptr,
249                                 nullptr);
250   if (!Ctx)
251     return true;
252 
253   if (Options.MCOptions.MCSaveTempLabels)
254     Ctx->setAllowTemporaryLabels(false);
255 
256   // Create the code emitter for the target if it exists.  If not, .o file
257   // emission fails.
258   const MCRegisterInfo &MRI = *getMCRegisterInfo();
259   MCCodeEmitter *MCE =
260       getTarget().createMCCodeEmitter(*getMCInstrInfo(), MRI, *Ctx);
261   MCAsmBackend *MAB =
262       getTarget().createMCAsmBackend(MRI, getTargetTriple().str(), TargetCPU);
263   if (!MCE || !MAB)
264     return true;
265 
266   const Triple &T = getTargetTriple();
267   const MCSubtargetInfo &STI = *getMCSubtargetInfo();
268   std::unique_ptr<MCStreamer> AsmStreamer(getTarget().createMCObjectStreamer(
269       T, *Ctx, *MAB, Out, MCE, STI, Options.MCOptions.MCRelaxAll,
270       Options.MCOptions.MCIncrementalLinkerCompatible,
271       /*DWARFMustBeAtTheEnd*/ true));
272 
273   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
274   FunctionPass *Printer =
275       getTarget().createAsmPrinter(*this, std::move(AsmStreamer));
276   if (!Printer)
277     return true;
278 
279   PM.add(Printer);
280 
281   return false; // success!
282 }
283