LLVMBuild: Introduce a common section which currently has a list of the
[oota-llvm.git] / lib / Target / PTX / PTXTargetMachine.cpp
1 //===-- PTXTargetMachine.cpp - Define TargetMachine for PTX ---------------===//
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 // Top-level implementation for the PTX target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PTX.h"
15 #include "PTXTargetMachine.h"
16 #include "llvm/PassManager.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/Analysis/Verifier.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Support/TargetRegistry.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetLoweringObjectFile.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include "llvm/Transforms/Scalar.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/TargetRegistry.h"
42
43
44 using namespace llvm;
45
46 namespace llvm {
47   MCStreamer *createPTXAsmStreamer(MCContext &Ctx, formatted_raw_ostream &OS,
48                                    bool isVerboseAsm, bool useLoc,
49                                    bool useCFI, bool useDwarfDirectory,
50                                    MCInstPrinter *InstPrint,
51                                    MCCodeEmitter *CE,
52                                    MCAsmBackend *MAB,
53                                    bool ShowInst);
54 }
55
56 extern "C" void LLVMInitializePTXTarget() {
57
58   RegisterTargetMachine<PTX32TargetMachine> X(ThePTX32Target);
59   RegisterTargetMachine<PTX64TargetMachine> Y(ThePTX64Target);
60
61   TargetRegistry::RegisterAsmStreamer(ThePTX32Target, createPTXAsmStreamer);
62   TargetRegistry::RegisterAsmStreamer(ThePTX64Target, createPTXAsmStreamer);
63 }
64
65 namespace {
66   const char* DataLayout32 =
67     "e-p:32:32-i64:32:32-f64:32:32-v128:32:128-v64:32:64-n32:64";
68   const char* DataLayout64 =
69     "e-p:64:64-i64:32:32-f64:32:32-v128:32:128-v64:32:64-n32:64";
70 }
71
72 // DataLayout and FrameLowering are filled with dummy data
73 PTXTargetMachine::PTXTargetMachine(const Target &T,
74                                    StringRef TT, StringRef CPU, StringRef FS,
75                                    const TargetOptions &Options,
76                                    Reloc::Model RM, CodeModel::Model CM,
77                                    CodeGenOpt::Level OL,
78                                    bool is64Bit)
79   : LLVMTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL),
80     DataLayout(is64Bit ? DataLayout64 : DataLayout32),
81     Subtarget(TT, CPU, FS, is64Bit),
82     FrameLowering(Subtarget),
83     InstrInfo(*this),
84     TSInfo(*this),
85     TLInfo(*this) {
86 }
87
88 PTX32TargetMachine::PTX32TargetMachine(const Target &T, StringRef TT,
89                                        StringRef CPU, StringRef FS,
90                                        const TargetOptions &Options,
91                                        Reloc::Model RM, CodeModel::Model CM,
92                                        CodeGenOpt::Level OL)
93   : PTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {
94 }
95
96 PTX64TargetMachine::PTX64TargetMachine(const Target &T, StringRef TT,
97                                        StringRef CPU, StringRef FS,
98                                        const TargetOptions &Options,
99                                        Reloc::Model RM, CodeModel::Model CM,
100                                        CodeGenOpt::Level OL)
101   : PTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {
102 }
103
104 bool PTXTargetMachine::addInstSelector(PassManagerBase &PM) {
105   PM.add(createPTXISelDag(*this, getOptLevel()));
106   return false;
107 }
108
109 bool PTXTargetMachine::addPostRegAlloc(PassManagerBase &PM) {
110   // PTXMFInfoExtract must after register allocation!
111   //PM.add(createPTXMFInfoExtract(*this));
112   return false;
113 }
114
115 bool PTXTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
116                                            formatted_raw_ostream &Out,
117                                            CodeGenFileType FileType,
118                                            bool DisableVerify) {
119   // This is mostly based on LLVMTargetMachine::addPassesToEmitFile
120
121   // Add common CodeGen passes.
122   MCContext *Context = 0;
123   if (addCommonCodeGenPasses(PM, DisableVerify, Context))
124     return true;
125   assert(Context != 0 && "Failed to get MCContext");
126
127   if (hasMCSaveTempLabels())
128     Context->setAllowTemporaryLabels(false);
129
130   const MCAsmInfo &MAI = *getMCAsmInfo();
131   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
132   OwningPtr<MCStreamer> AsmStreamer;
133
134   switch (FileType) {
135   default: return true;
136   case CGFT_AssemblyFile: {
137     MCInstPrinter *InstPrinter =
138       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
139
140     // Create a code emitter if asked to show the encoding.
141     MCCodeEmitter *MCE = 0;
142     MCAsmBackend *MAB = 0;
143
144     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
145                                                   true, /* verbose asm */
146                                                   hasMCUseLoc(),
147                                                   hasMCUseCFI(),
148                                                   hasMCUseDwarfDirectory(),
149                                                   InstPrinter,
150                                                   MCE, MAB,
151                                                   false /* show MC encoding */);
152     AsmStreamer.reset(S);
153     break;
154   }
155   case CGFT_ObjectFile: {
156     llvm_unreachable("Object file emission is not supported with PTX");
157   }
158   case CGFT_Null:
159     // The Null output is intended for use for performance analysis and testing,
160     // not real users.
161     AsmStreamer.reset(createNullStreamer(*Context));
162     break;
163   }
164
165   // MC Logging
166   //AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
167
168   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
169   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
170   if (Printer == 0)
171     return true;
172
173   // If successful, createAsmPrinter took ownership of AsmStreamer.
174   AsmStreamer.take();
175
176   PM.add(Printer);
177
178   PM.add(createGCInfoDeleter());
179   return false;
180 }
181
182 bool PTXTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
183                                               bool DisableVerify,
184                                               MCContext *&OutContext) {
185   // Add standard LLVM codegen passes.
186   // This is derived from LLVMTargetMachine::addCommonCodeGenPasses, with some
187   // modifications for the PTX target.
188
189   // Standard LLVM-Level Passes.
190
191   // Basic AliasAnalysis support.
192   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
193   // BasicAliasAnalysis wins if they disagree. This is intended to help
194   // support "obvious" type-punning idioms.
195   PM.add(createTypeBasedAliasAnalysisPass());
196   PM.add(createBasicAliasAnalysisPass());
197
198   // Before running any passes, run the verifier to determine if the input
199   // coming from the front-end and/or optimizer is valid.
200   if (!DisableVerify)
201     PM.add(createVerifierPass());
202
203   // Run loop strength reduction before anything else.
204   if (getOptLevel() != CodeGenOpt::None) {
205     PM.add(createLoopStrengthReducePass(getTargetLowering()));
206     //PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
207   }
208
209   PM.add(createGCLoweringPass());
210
211   // Make sure that no unreachable blocks are instruction selected.
212   PM.add(createUnreachableBlockEliminationPass());
213
214   PM.add(createLowerInvokePass(getTargetLowering()));
215   // The lower invoke pass may create unreachable code. Remove it.
216   PM.add(createUnreachableBlockEliminationPass());
217
218   if (getOptLevel() != CodeGenOpt::None)
219     PM.add(createCodeGenPreparePass(getTargetLowering()));
220
221   PM.add(createStackProtectorPass(getTargetLowering()));
222
223   addPreISel(PM);
224
225   //PM.add(createPrintFunctionPass("\n\n"
226   //                               "*** Final LLVM Code input to ISel ***\n",
227   //                               &dbgs()));
228
229   // All passes which modify the LLVM IR are now complete; run the verifier
230   // to ensure that the IR is valid.
231   if (!DisableVerify)
232     PM.add(createVerifierPass());
233
234   // Standard Lower-Level Passes.
235
236   // Install a MachineModuleInfo class, which is an immutable pass that holds
237   // all the per-module stuff we're generating, including MCContext.
238   MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
239                                                  *getRegisterInfo(),
240                                     &getTargetLowering()->getObjFileLowering());
241   PM.add(MMI);
242   OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
243
244   // Set up a MachineFunction for the rest of CodeGen to work on.
245   PM.add(new MachineFunctionAnalysis(*this));
246
247   // Ask the target for an isel.
248   if (addInstSelector(PM))
249     return true;
250
251   // Print the instruction selected machine code...
252   printAndVerify(PM, "After Instruction Selection");
253
254   // Expand pseudo-instructions emitted by ISel.
255   PM.add(createExpandISelPseudosPass());
256
257   // Pre-ra tail duplication.
258   if (getOptLevel() != CodeGenOpt::None) {
259     PM.add(createTailDuplicatePass(true));
260     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
261   }
262
263   // Optimize PHIs before DCE: removing dead PHI cycles may make more
264   // instructions dead.
265   if (getOptLevel() != CodeGenOpt::None)
266     PM.add(createOptimizePHIsPass());
267
268   // If the target requests it, assign local variables to stack slots relative
269   // to one another and simplify frame index references where possible.
270   PM.add(createLocalStackSlotAllocationPass());
271
272   if (getOptLevel() != CodeGenOpt::None) {
273     // With optimization, dead code should already be eliminated. However
274     // there is one known exception: lowered code for arguments that are only
275     // used by tail calls, where the tail calls reuse the incoming stack
276     // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
277     PM.add(createDeadMachineInstructionElimPass());
278     printAndVerify(PM, "After codegen DCE pass");
279
280     PM.add(createMachineLICMPass());
281     PM.add(createMachineCSEPass());
282     PM.add(createMachineSinkingPass());
283     printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
284
285     PM.add(createPeepholeOptimizerPass());
286     printAndVerify(PM, "After codegen peephole optimization pass");
287   }
288
289   // Run pre-ra passes.
290   if (addPreRegAlloc(PM))
291     printAndVerify(PM, "After PreRegAlloc passes");
292
293   // Perform register allocation.
294   PM.add(createPTXRegisterAllocator());
295   printAndVerify(PM, "After Register Allocation");
296
297   // Perform stack slot coloring and post-ra machine LICM.
298   if (getOptLevel() != CodeGenOpt::None) {
299     // FIXME: Re-enable coloring with register when it's capable of adding
300     // kill markers.
301     PM.add(createStackSlotColoringPass(false));
302
303     // FIXME: Post-RA LICM has asserts that fire on virtual registers.
304     // Run post-ra machine LICM to hoist reloads / remats.
305     //if (!DisablePostRAMachineLICM)
306     //  PM.add(createMachineLICMPass(false));
307
308     printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
309   }
310
311   // Run post-ra passes.
312   if (addPostRegAlloc(PM))
313     printAndVerify(PM, "After PostRegAlloc passes");
314
315   PM.add(createExpandPostRAPseudosPass());
316   printAndVerify(PM, "After ExpandPostRAPseudos");
317
318   // Insert prolog/epilog code.  Eliminate abstract frame index references...
319   PM.add(createPrologEpilogCodeInserter());
320   printAndVerify(PM, "After PrologEpilogCodeInserter");
321
322   // Run pre-sched2 passes.
323   if (addPreSched2(PM))
324     printAndVerify(PM, "After PreSched2 passes");
325
326   // Second pass scheduler.
327   if (getOptLevel() != CodeGenOpt::None) {
328     PM.add(createPostRAScheduler(getOptLevel()));
329     printAndVerify(PM, "After PostRAScheduler");
330   }
331
332   // Branch folding must be run after regalloc and prolog/epilog insertion.
333   if (getOptLevel() != CodeGenOpt::None) {
334     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
335     printNoVerify(PM, "After BranchFolding");
336   }
337
338   // Tail duplication.
339   if (getOptLevel() != CodeGenOpt::None) {
340     PM.add(createTailDuplicatePass(false));
341     printNoVerify(PM, "After TailDuplicate");
342   }
343
344   PM.add(createGCMachineCodeAnalysisPass());
345
346   //if (PrintGCInfo)
347   //  PM.add(createGCInfoPrinter(dbgs()));
348
349   if (getOptLevel() != CodeGenOpt::None) {
350     PM.add(createCodePlacementOptPass());
351     printNoVerify(PM, "After CodePlacementOpt");
352   }
353
354   if (addPreEmitPass(PM))
355     printNoVerify(PM, "After PreEmit passes");
356
357   PM.add(createPTXMFInfoExtract(*this, getOptLevel()));
358   PM.add(createPTXFPRoundingModePass(*this, getOptLevel()));
359
360   return false;
361 }