LLVM  8.0.1
NVPTXTargetMachine.cpp
Go to the documentation of this file.
1 //===-- NVPTXTargetMachine.cpp - Define TargetMachine for NVPTX -----------===//
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 NVPTX target.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "NVPTXTargetMachine.h"
15 #include "NVPTX.h"
16 #include "NVPTXAllocaHoisting.h"
17 #include "NVPTXLowerAggrCopies.h"
18 #include "NVPTXTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/Pass.h"
32 #include "llvm/Transforms/Scalar.h"
35 #include <cassert>
36 #include <string>
37 
38 using namespace llvm;
39 
40 // LSV is still relatively new; this switch lets us turn it off in case we
41 // encounter (or suspect) a bug.
42 static cl::opt<bool>
43  DisableLoadStoreVectorizer("disable-nvptx-load-store-vectorizer",
44  cl::desc("Disable load/store vectorizer"),
45  cl::init(false), cl::Hidden);
46 
47 // TODO: Remove this flag when we are confident with no regressions.
49  "disable-nvptx-require-structured-cfg",
50  cl::desc("Transitional flag to turn off NVPTX's requirement on preserving "
51  "structured CFG. The requirement should be disabled only when "
52  "unexpected regressions happen."),
53  cl::init(false), cl::Hidden);
54 
56  "nvptx-short-ptr",
57  cl::desc(
58  "Use 32-bit pointers for accessing const/local/shared address spaces."),
59  cl::init(false), cl::Hidden);
60 
61 namespace llvm {
62 
72 
73 } // end namespace llvm
74 
75 extern "C" void LLVMInitializeNVPTXTarget() {
76  // Register the target.
79 
80  // FIXME: This pass is really intended to be invoked during IR optimization,
81  // but it's very NVPTX-specific.
92 }
93 
94 static std::string computeDataLayout(bool is64Bit, bool UseShortPointers) {
95  std::string Ret = "e";
96 
97  if (!is64Bit)
98  Ret += "-p:32:32";
99  else if (UseShortPointers)
100  Ret += "-p3:32:32-p4:32:32-p5:32:32";
101 
102  Ret += "-i64:64-i128:128-v16:16-v32:32-n16:32:64";
103 
104  return Ret;
105 }
106 
108  StringRef CPU, StringRef FS,
109  const TargetOptions &Options,
112  CodeGenOpt::Level OL, bool is64bit)
113  // The pic relocation model is used regardless of what the client has
114  // specified, as it is the only relocation model currently supported.
116  CPU, FS, Options, Reloc::PIC_,
117  getEffectiveCodeModel(CM, CodeModel::Small), OL),
118  is64bit(is64bit), UseShortPointers(UseShortPointersOpt),
120  Subtarget(TT, CPU, FS, *this) {
121  if (TT.getOS() == Triple::NVCL)
122  drvInterface = NVPTX::NVCL;
123  else
124  drvInterface = NVPTX::CUDA;
127  initAsmInfo();
128 }
129 
131 
132 void NVPTXTargetMachine32::anchor() {}
133 
135  StringRef CPU, StringRef FS,
136  const TargetOptions &Options,
139  CodeGenOpt::Level OL, bool JIT)
140  : NVPTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, false) {}
141 
142 void NVPTXTargetMachine64::anchor() {}
143 
145  StringRef CPU, StringRef FS,
146  const TargetOptions &Options,
149  CodeGenOpt::Level OL, bool JIT)
150  : NVPTXTargetMachine(T, TT, CPU, FS, Options, RM, CM, OL, true) {}
151 
152 namespace {
153 
154 class NVPTXPassConfig : public TargetPassConfig {
155 public:
156  NVPTXPassConfig(NVPTXTargetMachine &TM, PassManagerBase &PM)
157  : TargetPassConfig(TM, PM) {}
158 
159  NVPTXTargetMachine &getNVPTXTargetMachine() const {
160  return getTM<NVPTXTargetMachine>();
161  }
162 
163  void addIRPasses() override;
164  bool addInstSelector() override;
165  void addPreRegAlloc() override;
166  void addPostRegAlloc() override;
167  void addMachineSSAOptimization() override;
168 
169  FunctionPass *createTargetRegisterAllocator(bool) override;
170  void addFastRegAlloc(FunctionPass *RegAllocPass) override;
171  void addOptimizedRegAlloc(FunctionPass *RegAllocPass) override;
172 
173 private:
174  // If the opt level is aggressive, add GVN; otherwise, add EarlyCSE. This
175  // function is only called in opt mode.
176  void addEarlyCSEOrGVNPass();
177 
178  // Add passes that propagate special memory spaces.
179  void addAddressSpaceInferencePasses();
180 
181  // Add passes that perform straight-line scalar optimizations.
182  void addStraightLineScalarOptimizationPasses();
183 };
184 
185 } // end anonymous namespace
186 
188  return new NVPTXPassConfig(*this, PM);
189 }
190 
192  Builder.addExtension(
194  [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
195  PM.add(createNVVMReflectPass(Subtarget.getSmVersion()));
196  PM.add(createNVVMIntrRangePass(Subtarget.getSmVersion()));
197  });
198 }
199 
202  return TargetTransformInfo(NVPTXTTIImpl(this, F));
203 }
204 
205 void NVPTXPassConfig::addEarlyCSEOrGVNPass() {
207  addPass(createGVNPass());
208  else
209  addPass(createEarlyCSEPass());
210 }
211 
212 void NVPTXPassConfig::addAddressSpaceInferencePasses() {
213  // NVPTXLowerArgs emits alloca for byval parameters which can often
214  // be eliminated by SROA.
215  addPass(createSROAPass());
216  addPass(createNVPTXLowerAllocaPass());
217  addPass(createInferAddressSpacesPass());
218 }
219 
220 void NVPTXPassConfig::addStraightLineScalarOptimizationPasses() {
223  // ReassociateGEPs exposes more opportunites for SLSR. See
224  // the example in reassociate-geps-and-slsr.ll.
226  // SeparateConstOffsetFromGEP and SLSR creates common expressions which GVN or
227  // EarlyCSE can reuse. GVN generates significantly better code than EarlyCSE
228  // for some of our benchmarks.
229  addEarlyCSEOrGVNPass();
230  // Run NaryReassociate after EarlyCSE/GVN to be more effective.
231  addPass(createNaryReassociatePass());
232  // NaryReassociate on GEPs creates redundant common expressions, so run
233  // EarlyCSE after it.
234  addPass(createEarlyCSEPass());
235 }
236 
237 void NVPTXPassConfig::addIRPasses() {
238  // The following passes are known to not play well with virtual regs hanging
239  // around after register allocation (which in our case, is *all* registers).
240  // We explicitly disable them here. We do, however, need some functionality
241  // of the PrologEpilogCodeInserter pass, so we emulate that behavior in the
242  // NVPTXPrologEpilog pass (see NVPTXPrologEpilogPass.cpp).
243  disablePass(&PrologEpilogCodeInserterID);
244  disablePass(&MachineCopyPropagationID);
245  disablePass(&TailDuplicateID);
246  disablePass(&StackMapLivenessID);
247  disablePass(&LiveDebugValuesID);
248  disablePass(&PostRAMachineSinkingID);
249  disablePass(&PostRASchedulerID);
250  disablePass(&FuncletLayoutID);
251  disablePass(&PatchableFunctionID);
252  disablePass(&ShrinkWrapID);
253 
254  // NVVMReflectPass is added in addEarlyAsPossiblePasses, so hopefully running
255  // it here does nothing. But since we need it for correctness when lowering
256  // to NVPTX, run it here too, in case whoever built our pass pipeline didn't
257  // call addEarlyAsPossiblePasses.
258  const NVPTXSubtarget &ST = *getTM<NVPTXTargetMachine>().getSubtargetImpl();
259  addPass(createNVVMReflectPass(ST.getSmVersion()));
260 
261  if (getOptLevel() != CodeGenOpt::None)
264  addPass(createGenericToNVVMPass());
265 
266  // NVPTXLowerArgs is required for correctness and should be run right
267  // before the address space inference passes.
268  addPass(createNVPTXLowerArgsPass(&getNVPTXTargetMachine()));
269  if (getOptLevel() != CodeGenOpt::None) {
270  addAddressSpaceInferencePasses();
273  addStraightLineScalarOptimizationPasses();
274  }
275 
276  // === LSR and other generic IR passes ===
278  // EarlyCSE is not always strong enough to clean up what LSR produces. For
279  // example, GVN can combine
280  //
281  // %0 = add %a, %b
282  // %1 = add %b, %a
283  //
284  // and
285  //
286  // %0 = shl nsw %a, 2
287  // %1 = shl %a, 2
288  //
289  // but EarlyCSE can do neither of them.
290  if (getOptLevel() != CodeGenOpt::None)
291  addEarlyCSEOrGVNPass();
292 }
293 
294 bool NVPTXPassConfig::addInstSelector() {
295  const NVPTXSubtarget &ST = *getTM<NVPTXTargetMachine>().getSubtargetImpl();
296 
297  addPass(createLowerAggrCopies());
298  addPass(createAllocaHoisting());
299  addPass(createNVPTXISelDag(getNVPTXTargetMachine(), getOptLevel()));
300 
301  if (!ST.hasImageHandles())
303 
304  return false;
305 }
306 
307 void NVPTXPassConfig::addPreRegAlloc() {
308  // Remove Proxy Register pseudo instructions used to keep `callseq_end` alive.
310 }
311 
312 void NVPTXPassConfig::addPostRegAlloc() {
313  addPass(createNVPTXPrologEpilogPass(), false);
314  if (getOptLevel() != CodeGenOpt::None) {
315  // NVPTXPrologEpilogPass calculates frame object offset and replace frame
316  // index with VRFrame register. NVPTXPeephole need to be run after that and
317  // will replace VRFrame with VRFrameLocal when possible.
318  addPass(createNVPTXPeephole());
319  }
320 }
321 
322 FunctionPass *NVPTXPassConfig::createTargetRegisterAllocator(bool) {
323  return nullptr; // No reg alloc
324 }
325 
326 void NVPTXPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
327  assert(!RegAllocPass && "NVPTX uses no regalloc!");
328  addPass(&PHIEliminationID);
329  addPass(&TwoAddressInstructionPassID);
330 }
331 
332 void NVPTXPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
333  assert(!RegAllocPass && "NVPTX uses no regalloc!");
334 
335  addPass(&ProcessImplicitDefsID);
336  addPass(&LiveVariablesID);
337  addPass(&MachineLoopInfoID);
338  addPass(&PHIEliminationID);
339 
340  addPass(&TwoAddressInstructionPassID);
341  addPass(&RegisterCoalescerID);
342 
343  // PreRA instruction scheduling.
344  if (addPass(&MachineSchedulerID))
345  printAndVerify("After Machine Scheduling");
346 
347 
348  addPass(&StackSlotColoringID);
349 
350  // FIXME: Needs physical registers
351  //addPass(&MachineLICMID);
352 
353  printAndVerify("After StackSlotColoring");
354 }
355 
356 void NVPTXPassConfig::addMachineSSAOptimization() {
357  // Pre-ra tail duplication.
358  if (addPass(&EarlyTailDuplicateID))
359  printAndVerify("After Pre-RegAlloc TailDuplicate");
360 
361  // Optimize PHIs before DCE: removing dead PHI cycles may make more
362  // instructions dead.
363  addPass(&OptimizePHIsID);
364 
365  // This pass merges large allocas. StackSlotColoring is a different pass
366  // which merges spill slots.
367  addPass(&StackColoringID);
368 
369  // If the target requests it, assign local variables to stack slots relative
370  // to one another and simplify frame index references where possible.
371  addPass(&LocalStackSlotAllocationID);
372 
373  // With optimization, dead code should already be eliminated. However
374  // there is one known exception: lowered code for arguments that are only
375  // used by tail calls, where the tail calls reuse the incoming stack
376  // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
378  printAndVerify("After codegen DCE pass");
379 
380  // Allow targets to insert passes that improve instruction level parallelism,
381  // like if-conversion. Such passes will typically need dominator trees and
382  // loop info, just like LICM and CSE below.
383  if (addILPOpts())
384  printAndVerify("After ILP optimizations");
385 
386  addPass(&EarlyMachineLICMID);
387  addPass(&MachineCSEID);
388 
389  addPass(&MachineSinkingID);
390  printAndVerify("After Machine LICM, CSE and Sinking passes");
391 
392  addPass(&PeepholeOptimizerID);
393  printAndVerify("After codegen peephole optimization pass");
394 }
FunctionPass * createSpeculativeExecutionPass()
FunctionPass * createStraightLineStrengthReducePass()
FunctionPass * createGVNPass(bool NoLoads=false)
Create a legacy GVN pass.
Definition: GVN.cpp:2599
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
void initializeNVPTXLowerArgsPass(PassRegistry &)
CodeModel::Model getEffectiveCodeModel(Optional< CodeModel::Model > CM, CodeModel::Model Default)
Helper method for getting the code model, returning Default if CM does not have a value...
MachineFunctionPass * createNVPTXProxyRegErasurePass()
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
This class represents lattice values for constants.
Definition: AllocatorList.h:24
void LLVMInitializeNVPTXTarget()
virtual void addIRPasses()
Add common target configurable passes that perform LLVM IR to IR transforms following machine indepen...
OSType getOS() const
getOS - Get the parsed operating system type of this triple.
Definition: Triple.h:299
ModulePass * createNVPTXAssignValidGlobalNamesPass()
char & FuncletLayoutID
This pass lays out funclets contiguously.
FunctionPass * createAllocaHoisting()
static cl::opt< bool > DisableRequireStructuredCFG("disable-nvptx-require-structured-cfg", cl::desc("Transitional flag to turn off NVPTX's requirement on preserving " "structured CFG. The requirement should be disabled only when " "unexpected regressions happen."), cl::init(false), cl::Hidden)
char & RegisterCoalescerID
RegisterCoalescer - This pass merges live ranges to eliminate copies.
virtual void add(Pass *P)=0
Add a pass to the queue of passes to run.
MachineFunctionPass * createNVPTXPrologEpilogPass()
F(f)
char & MachineSchedulerID
MachineScheduler - This pass schedules machine instructions.
block Block Frequency true
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&... args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
Definition: STLExtras.h:1349
ModulePass * createGenericToNVVMPass()
char & ProcessImplicitDefsID
ProcessImpicitDefs pass - This pass removes IMPLICIT_DEFs.
void initializeNVPTXAssignValidGlobalNamesPass(PassRegistry &)
FunctionPass * createNVVMReflectPass(unsigned int SmVersion)
Definition: NVVMReflect.cpp:63
NVPTXTargetMachine64(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Optional< Reloc::Model > RM, Optional< CodeModel::Model > CM, CodeGenOpt::Level OL, bool JIT)
bool hasImageHandles() const
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
char & StackColoringID
StackSlotColoring - This pass performs stack coloring and merging.
Target-Independent Code Generator Pass Configuration Options.
Target & getTheNVPTXTarget64()
static cl::opt< bool > UseShortPointersOpt("nvptx-short-ptr", cl::desc("Use 32-bit pointers for accessing const/local/shared address spaces."), cl::init(false), cl::Hidden)
char & EarlyTailDuplicateID
Duplicate blocks with unconditional branches into tails of their predecessors.
RegisterTargetMachine - Helper template for registering a target machine implementation, for use in the target machine initialization function.
char & MachineCSEID
MachineCSE - This pass performs global CSE on machine instructions.
Definition: MachineCSE.cpp:134
char & StackSlotColoringID
StackSlotColoring - This pass performs stack slot coloring.
char & DeadMachineInstructionElimID
DeadMachineInstructionElim - This pass removes dead machine instructions.
Pass * createLoadStoreVectorizerPass()
Create a legacy pass manager instance of the LoadStoreVectorizer pass.
TargetPassConfig * createPassConfig(PassManagerBase &PM) override
Create a pass configuration object to be used by addPassToEmitX methods for generating a pipeline of ...
FunctionPass * createNVPTXImageOptimizerPass()
void initializeNVVMIntrRangePass(PassRegistry &)
TargetTransformInfo getTargetTransformInfo(const Function &F) override
Get a TargetTransformInfo implementation for the target.
char & PHIEliminationID
PHIElimination - This pass eliminates machine instruction PHI nodes by inserting copy instructions...
Target & getTheNVPTXTarget32()
char & LiveVariablesID
LiveVariables pass - This pass computes the set of blocks in which each variable is life and sets mac...
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:423
This file a TargetTransformInfo::Concept conforming object specific to the NVPTX target machine...
CodeGenOpt::Level getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
static std::string computeDataLayout(bool is64Bit, bool UseShortPointers)
void initializeNVPTXLowerAggrCopiesPass(PassRegistry &)
void initializeNVVMReflectPass(PassRegistry &)
NVPTXTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Optional< Reloc::Model > RM, Optional< CodeModel::Model > CM, CodeGenOpt::Level OP, bool is64bit)
This file provides the interface for LLVM&#39;s Global Value Numbering pass which eliminates fully redund...
static bool is64Bit(const char *name)
MachineFunctionPass * createNVPTXReplaceImageHandlesPass()
char & PostRAMachineSinkingID
This pass perform post-ra machine sink for COPY instructions.
char & LiveDebugValuesID
LiveDebugValues pass.
This class describes a target machine that is implemented with the LLVM target-independent code gener...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
void initializeNVPTXAllocaHoistingPass(PassRegistry &)
char & MachineCopyPropagationID
MachineCopyPropagation - This pass performs copy propagation on machine instructions.
char & TwoAddressInstructionPassID
TwoAddressInstruction - This pass reduces two-address instructions to use two operands.
void initializeGenericToNVVMPass(PassRegistry &)
EP_EarlyAsPossible - This extension point allows adding passes before any other transformations, allowing them to see the code as it is coming out of the frontend.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
char & PostRASchedulerID
createPostRAScheduler - This pass performs post register allocation scheduling.
void initializeNVPTXLowerAllocaPass(PassRegistry &)
NVPTXTargetMachine32(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Optional< Reloc::Model > RM, Optional< CodeModel::Model > CM, CodeGenOpt::Level OL, bool JIT)
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
BasicBlockPass * createNVPTXLowerAllocaPass()
PassManagerBase - An abstract interface to allow code to add passes to a pass manager without having ...
char & StackMapLivenessID
StackMapLiveness - This pass analyses the register live-out set of stackmap/patchpoint intrinsics and...
char & TailDuplicateID
TailDuplicate - Duplicate blocks with unconditional branches into tails of their predecessors.
char & MachineSinkingID
MachineSinking - This pass performs sinking on machine instructions.
void setRequiresStructuredCFG(bool Value)
char & EarlyMachineLICMID
This pass performs loop invariant code motion on machine instructions.
char & OptimizePHIsID
OptimizePHIs - This pass optimizes machine instruction PHIs to take advantage of opportunities create...
FunctionPass * createSeparateConstOffsetFromGEPPass(bool LowerGEP=false)
Target - Wrapper for Target specific information.
char & PeepholeOptimizerID
PeepholeOptimizer - This pass performs peephole optimizations - like extension and comparison elimina...
void initializeNVPTXProxyRegErasurePass(PassRegistry &)
char & PrologEpilogCodeInserterID
PrologEpilogCodeInserter - This pass inserts prolog and epilog code, and eliminates abstract frame re...
char & PatchableFunctionID
This pass implements the "patchable-function" attribute.
FunctionPass * createInferAddressSpacesPass()
NVPTXTargetMachine.
MachineFunctionPass * createNVPTXPeephole()
FunctionPass * createNVPTXISelDag(NVPTXTargetMachine &TM, llvm::CodeGenOpt::Level OptLevel)
createNVPTXISelDag - This pass converts a legalized DAG into a NVPTX-specific DAG, ready for instruction scheduling.
~NVPTXTargetMachine() override
FunctionPass * createNVVMIntrRangePass(unsigned int SmVersion)
FunctionPass * createNVPTXLowerArgsPass(const NVPTXTargetMachine *TM)
FunctionPass * createLowerAggrCopies()
TargetOptions Options
Definition: TargetMachine.h:97
void adjustPassManager(PassManagerBuilder &) override
Allow the target to modify the pass manager, e.g.
FunctionPass * createSROAPass()
Definition: SROA.cpp:4585
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const NVPTXSubtarget * getSubtargetImpl() const
unsigned int getSmVersion() const
FunctionPass * createEarlyCSEPass(bool UseMemorySSA=false)
Definition: EarlyCSE.cpp:1320
static cl::opt< bool > DisableLoadStoreVectorizer("disable-nvptx-load-store-vectorizer", cl::desc("Disable load/store vectorizer"), cl::init(false), cl::Hidden)
char & ShrinkWrapID
ShrinkWrap pass. Look for the best place to insert save and restore.
Definition: ShrinkWrap.cpp:250
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
PassRegistry - This class manages the registration and intitialization of the pass subsystem as appli...
Definition: PassRegistry.h:39
This pass exposes codegen information to IR-level passes.
void addExtension(ExtensionPointTy Ty, ExtensionFn Fn)
char & LocalStackSlotAllocationID
LocalStackSlotAllocation - This pass assigns local frame indices to stack slots relative to one anoth...
FunctionPass * createNaryReassociatePass()