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/ADT/OwningPtr.h"
16#include "llvm/Assembly/PrintModulePass.h"
17#include "llvm/CodeGen/AsmPrinter.h"
18#include "llvm/CodeGen/MachineFunctionAnalysis.h"
19#include "llvm/CodeGen/MachineModuleInfo.h"
20#include "llvm/CodeGen/Passes.h"
21#include "llvm/MC/MCAsmInfo.h"
22#include "llvm/MC/MCContext.h"
23#include "llvm/MC/MCInstrInfo.h"
24#include "llvm/MC/MCStreamer.h"
25#include "llvm/MC/MCSubtargetInfo.h"
26#include "llvm/PassManager.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/FormattedStream.h"
30#include "llvm/Support/TargetRegistry.h"
31#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetLowering.h"
33#include "llvm/Target/TargetLoweringObjectFile.h"
34#include "llvm/Target/TargetOptions.h"
35#include "llvm/Target/TargetRegisterInfo.h"
36#include "llvm/Target/TargetSubtargetInfo.h"
37#include "llvm/Transforms/Scalar.h"
38using namespace llvm;
39
40// Enable or disable FastISel. Both options are needed, because
41// FastISel is enabled by default with -fast, and we wish to be
42// able to enable or disable fast-isel independently from -O0.
43static cl::opt<cl::boolOrDefault>
44EnableFastISelOption("fast-isel", cl::Hidden,
45  cl::desc("Enable the \"fast\" instruction selector"));
46
47static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
48    cl::desc("Show encoding in .s output"));
49static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
50    cl::desc("Show instruction structure in .s output"));
51
52static cl::opt<cl::boolOrDefault>
53AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
54           cl::init(cl::BOU_UNSET));
55
56static bool getVerboseAsm() {
57  switch (AsmVerbose) {
58  case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
59  case cl::BOU_TRUE:  return true;
60  case cl::BOU_FALSE: return false;
61  }
62  llvm_unreachable("Invalid verbose asm state");
63}
64
65LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
66                                     StringRef CPU, StringRef FS,
67                                     TargetOptions Options,
68                                     Reloc::Model RM, CodeModel::Model CM,
69                                     CodeGenOpt::Level OL)
70  : TargetMachine(T, Triple, CPU, FS, Options) {
71  CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
72  AsmInfo = T.createMCAsmInfo(Triple);
73  // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
74  // and if the old one gets included then MCAsmInfo will be NULL and
75  // we'll crash later.
76  // Provide the user with a useful error message about what's wrong.
77  assert(AsmInfo && "MCAsmInfo not initialized."
78         "Make sure you include the correct TargetSelect.h"
79         "and that InitializeAllTargetMCs() is being invoked!");
80}
81
82void LLVMTargetMachine::addAnalysisPasses(PassManagerBase &PM) {
83  PM.add(createBasicTargetTransformInfoPass(getTargetLowering()));
84}
85
86/// addPassesToX helper drives creation and initialization of TargetPassConfig.
87static MCContext *addPassesToGenerateCode(LLVMTargetMachine *TM,
88                                          PassManagerBase &PM,
89                                          bool DisableVerify,
90                                          AnalysisID StartAfter,
91                                          AnalysisID StopAfter) {
92  // Targets may override createPassConfig to provide a target-specific sublass.
93  TargetPassConfig *PassConfig = TM->createPassConfig(PM);
94  PassConfig->setStartStopPasses(StartAfter, StopAfter);
95
96  // Set PassConfig options provided by TargetMachine.
97  PassConfig->setDisableVerify(DisableVerify);
98
99  PM.add(PassConfig);
100
101  PassConfig->addIRPasses();
102
103  PassConfig->addCodeGenPrepare();
104
105  PassConfig->addPassesToHandleExceptions();
106
107  PassConfig->addISelPrepare();
108
109  // Install a MachineModuleInfo class, which is an immutable pass that holds
110  // all the per-module stuff we're generating, including MCContext.
111  MachineModuleInfo *MMI =
112    new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
113                          &TM->getTargetLowering()->getObjFileLowering());
114  PM.add(MMI);
115  MCContext *Context = &MMI->getContext(); // Return the MCContext by-ref.
116
117  // Set up a MachineFunction for the rest of CodeGen to work on.
118  PM.add(new MachineFunctionAnalysis(*TM));
119
120  // Enable FastISel with -fast, but allow that to be overridden.
121  if (EnableFastISelOption == cl::BOU_TRUE ||
122      (TM->getOptLevel() == CodeGenOpt::None &&
123       EnableFastISelOption != cl::BOU_FALSE))
124    TM->setFastISel(true);
125
126  // Ask the target for an isel.
127  if (PassConfig->addInstSelector())
128    return NULL;
129
130  PassConfig->addMachinePasses();
131
132  PassConfig->setInitialized();
133
134  return Context;
135}
136
137bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
138                                            formatted_raw_ostream &Out,
139                                            CodeGenFileType FileType,
140                                            bool DisableVerify,
141                                            AnalysisID StartAfter,
142                                            AnalysisID StopAfter) {
143  // Add common CodeGen passes.
144  MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify,
145                                               StartAfter, StopAfter);
146  if (!Context)
147    return true;
148
149  if (StopAfter) {
150    // FIXME: The intent is that this should eventually write out a YAML file,
151    // containing the LLVM IR, the machine-level IR (when stopping after a
152    // machine-level pass), and whatever other information is needed to
153    // deserialize the code and resume compilation.  For now, just write the
154    // LLVM IR.
155    PM.add(createPrintModulePass(&Out));
156    return false;
157  }
158
159  if (hasMCSaveTempLabels())
160    Context->setAllowTemporaryLabels(false);
161
162  const MCAsmInfo &MAI = *getMCAsmInfo();
163  const MCRegisterInfo &MRI = *getRegisterInfo();
164  const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
165  OwningPtr<MCStreamer> AsmStreamer;
166
167  switch (FileType) {
168  case CGFT_AssemblyFile: {
169    MCInstPrinter *InstPrinter =
170      getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI,
171                                      *getInstrInfo(),
172                                      Context->getRegisterInfo(), STI);
173
174    // Create a code emitter if asked to show the encoding.
175    MCCodeEmitter *MCE = 0;
176    MCAsmBackend *MAB = 0;
177    if (ShowMCEncoding) {
178      const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
179      MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI, STI,
180                                            *Context);
181      MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
182    }
183
184    MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
185                                                  getVerboseAsm(),
186                                                  hasMCUseLoc(),
187                                                  hasMCUseCFI(),
188                                                  hasMCUseDwarfDirectory(),
189                                                  InstPrinter,
190                                                  MCE, MAB,
191                                                  ShowMCInst);
192    AsmStreamer.reset(S);
193    break;
194  }
195  case CGFT_ObjectFile: {
196    // Create the code emitter for the target if it exists.  If not, .o file
197    // emission fails.
198    MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
199                                                         STI, *Context);
200    MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(),
201                                                       TargetCPU);
202    if (MCE == 0 || MAB == 0)
203      return true;
204
205    AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
206                                                         *Context, *MAB, Out,
207                                                         MCE, hasMCRelaxAll(),
208                                                         hasMCNoExecStack()));
209    AsmStreamer.get()->setAutoInitSections(true);
210    break;
211  }
212  case CGFT_Null:
213    // The Null output is intended for use for performance analysis and testing,
214    // not real users.
215    AsmStreamer.reset(createNullStreamer(*Context));
216    break;
217  }
218
219  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
220  FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
221  if (Printer == 0)
222    return true;
223
224  // If successful, createAsmPrinter took ownership of AsmStreamer.
225  AsmStreamer.take();
226
227  PM.add(Printer);
228
229  return false;
230}
231
232/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
233/// get machine code emitted.  This uses a JITCodeEmitter object to handle
234/// actually outputting the machine code and resolving things like the address
235/// of functions.  This method should returns true if machine code emission is
236/// not supported.
237///
238bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
239                                                   JITCodeEmitter &JCE,
240                                                   bool DisableVerify) {
241  // Add common CodeGen passes.
242  MCContext *Context = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
243  if (!Context)
244    return true;
245
246  addCodeEmitter(PM, JCE);
247
248  return false; // success!
249}
250
251/// addPassesToEmitMC - Add passes to the specified pass manager to get
252/// machine code emitted with the MCJIT. This method returns true if machine
253/// code is not supported. It fills the MCContext Ctx pointer which can be
254/// used to build custom MCStreamer.
255///
256bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
257                                          MCContext *&Ctx,
258                                          raw_ostream &Out,
259                                          bool DisableVerify) {
260  // Add common CodeGen passes.
261  Ctx = addPassesToGenerateCode(this, PM, DisableVerify, 0, 0);
262  if (!Ctx)
263    return true;
264
265  if (hasMCSaveTempLabels())
266    Ctx->setAllowTemporaryLabels(false);
267
268  // Create the code emitter for the target if it exists.  If not, .o file
269  // emission fails.
270  const MCRegisterInfo &MRI = *getRegisterInfo();
271  const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
272  MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), MRI,
273                                                       STI, *Ctx);
274  MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple(), TargetCPU);
275  if (MCE == 0 || MAB == 0)
276    return true;
277
278  OwningPtr<MCStreamer> AsmStreamer;
279  AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
280                                                       *MAB, Out, MCE,
281                                                       hasMCRelaxAll(),
282                                                       hasMCNoExecStack()));
283  AsmStreamer.get()->InitSections();
284
285  // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
286  FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
287  if (Printer == 0)
288    return true;
289
290  // If successful, createAsmPrinter took ownership of AsmStreamer.
291  AsmStreamer.take();
292
293  PM.add(Printer);
294
295  return false; // success!
296}
297