1# - Tools for building CUDA C files: libraries and build dependencies.
2# This script locates the NVIDIA CUDA C tools. It should work on linux, windows,
3# and mac and should be reasonably up to date with CUDA C releases.
4#
5# This script makes use of the standard find_package arguments of <VERSION>,
6# REQUIRED and QUIET.  CUDA_FOUND will report if an acceptable version of CUDA
7# was found.
8#
9# The script will prompt the user to specify CUDA_TOOLKIT_ROOT_DIR if the prefix
10# cannot be determined by the location of nvcc in the system path and REQUIRED
11# is specified to find_package(). To use a different installed version of the
12# toolkit set the environment variable CUDA_BIN_PATH before running cmake
13# (e.g. CUDA_BIN_PATH=/usr/local/cuda1.0 instead of the default /usr/local/cuda)
14# or set CUDA_TOOLKIT_ROOT_DIR after configuring.  If you change the value of
15# CUDA_TOOLKIT_ROOT_DIR, various components that depend on the path will be
16# relocated.
17#
18# It might be necessary to set CUDA_TOOLKIT_ROOT_DIR manually on certain
19# platforms, or to use a cuda runtime not installed in the default location. In
20# newer versions of the toolkit the cuda library is included with the graphics
21# driver- be sure that the driver version matches what is needed by the cuda
22# runtime version.
23#
24# The following variables affect the behavior of the macros in the script (in
25# alphebetical order).  Note that any of these flags can be changed multiple
26# times in the same directory before calling CUDA_ADD_EXECUTABLE,
27# CUDA_ADD_LIBRARY, CUDA_COMPILE, CUDA_COMPILE_PTX or CUDA_WRAP_SRCS.
28#
29#  CUDA_64_BIT_DEVICE_CODE (Default matches host bit size)
30#  -- Set to ON to compile for 64 bit device code, OFF for 32 bit device code.
31#     Note that making this different from the host code when generating object
32#     or C files from CUDA code just won't work, because size_t gets defined by
33#     nvcc in the generated source.  If you compile to PTX and then load the
34#     file yourself, you can mix bit sizes between device and host.
35#
36#  CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE (Default ON)
37#  -- Set to ON if you want the custom build rule to be attached to the source
38#     file in Visual Studio.  Turn OFF if you add the same cuda file to multiple
39#     targets.
40#
41#     This allows the user to build the target from the CUDA file; however, bad
42#     things can happen if the CUDA source file is added to multiple targets.
43#     When performing parallel builds it is possible for the custom build
44#     command to be run more than once and in parallel causing cryptic build
45#     errors.  VS runs the rules for every source file in the target, and a
46#     source can have only one rule no matter how many projects it is added to.
47#     When the rule is run from multiple targets race conditions can occur on
48#     the generated file.  Eventually everything will get built, but if the user
49#     is unaware of this behavior, there may be confusion.  It would be nice if
50#     this script could detect the reuse of source files across multiple targets
51#     and turn the option off for the user, but no good solution could be found.
52#
53#  CUDA_BUILD_CUBIN (Default OFF)
54#  -- Set to ON to enable and extra compilation pass with the -cubin option in
55#     Device mode. The output is parsed and register, shared memory usage is
56#     printed during build.
57#
58#  CUDA_BUILD_EMULATION (Default OFF for device mode)
59#  -- Set to ON for Emulation mode. -D_DEVICEEMU is defined for CUDA C files
60#     when CUDA_BUILD_EMULATION is TRUE.
61#
62#  CUDA_GENERATED_OUTPUT_DIR (Default CMAKE_CURRENT_BINARY_DIR)
63#  -- Set to the path you wish to have the generated files placed.  If it is
64#     blank output files will be placed in CMAKE_CURRENT_BINARY_DIR.
65#     Intermediate files will always be placed in
66#     CMAKE_CURRENT_BINARY_DIR/CMakeFiles.
67#
68#  CUDA_HOST_COMPILATION_CPP (Default ON)
69#  -- Set to OFF for C compilation of host code.
70#
71#  CUDA_NVCC_FLAGS
72#  CUDA_NVCC_FLAGS_<CONFIG>
73#  -- Additional NVCC command line arguments.  NOTE: multiple arguments must be
74#     semi-colon delimited (e.g. --compiler-options;-Wall)
75#
76#  CUDA_PROPAGATE_HOST_FLAGS (Default ON)
77#  -- Set to ON to propagate CMAKE_{C,CXX}_FLAGS and their configuration
78#     dependent counterparts (e.g. CMAKE_C_FLAGS_DEBUG) automatically to the
79#     host compiler through nvcc's -Xcompiler flag.  This helps make the
80#     generated host code match the rest of the system better.  Sometimes
81#     certain flags give nvcc problems, and this will help you turn the flag
82#     propagation off.  This does not affect the flags supplied directly to nvcc
83#     via CUDA_NVCC_FLAGS or through the OPTION flags specified through
84#     CUDA_ADD_LIBRARY, CUDA_ADD_EXECUTABLE, or CUDA_WRAP_SRCS.  Flags used for
85#     shared library compilation are not affected by this flag.
86#
87#  CUDA_VERBOSE_BUILD (Default OFF)
88#  -- Set to ON to see all the commands used when building the CUDA file.  When
89#     using a Makefile generator the value defaults to VERBOSE (run make
90#     VERBOSE=1 to see output), although setting CUDA_VERBOSE_BUILD to ON will
91#     always print the output.
92#
93# The script creates the following macros (in alphebetical order):
94#
95#  CUDA_ADD_CUFFT_TO_TARGET( cuda_target )
96#  -- Adds the cufft library to the target (can be any target).  Handles whether
97#     you are in emulation mode or not.
98#
99#  CUDA_ADD_CUBLAS_TO_TARGET( cuda_target )
100#  -- Adds the cublas library to the target (can be any target).  Handles
101#     whether you are in emulation mode or not.
102#
103#  CUDA_ADD_EXECUTABLE( cuda_target file0 file1 ...
104#                       [WIN32] [MACOSX_BUNDLE] [EXCLUDE_FROM_ALL] [OPTIONS ...] )
105#  -- Creates an executable "cuda_target" which is made up of the files
106#     specified.  All of the non CUDA C files are compiled using the standard
107#     build rules specified by CMAKE and the cuda files are compiled to object
108#     files using nvcc and the host compiler.  In addition CUDA_INCLUDE_DIRS is
109#     added automatically to include_directories().  Some standard CMake target
110#     calls can be used on the target after calling this macro
111#     (e.g. set_target_properties and target_link_libraries), but setting
112#     properties that adjust compilation flags will not affect code compiled by
113#     nvcc.  Such flags should be modified before calling CUDA_ADD_EXECUTABLE,
114#     CUDA_ADD_LIBRARY or CUDA_WRAP_SRCS.
115#
116#  CUDA_ADD_LIBRARY( cuda_target file0 file1 ...
117#                    [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] [OPTIONS ...] )
118#  -- Same as CUDA_ADD_EXECUTABLE except that a library is created.
119#
120#  CUDA_BUILD_CLEAN_TARGET()
121#  -- Creates a convience target that deletes all the dependency files
122#     generated.  You should make clean after running this target to ensure the
123#     dependency files get regenerated.
124#
125#  CUDA_COMPILE( generated_files file0 file1 ... [STATIC | SHARED | MODULE]
126#                [OPTIONS ...] )
127#  -- Returns a list of generated files from the input source files to be used
128#     with ADD_LIBRARY or ADD_EXECUTABLE.
129#
130#  CUDA_COMPILE_PTX( generated_files file0 file1 ... [OPTIONS ...] )
131#  -- Returns a list of PTX files generated from the input source files.
132#
133#  CUDA_INCLUDE_DIRECTORIES( path0 path1 ... )
134#  -- Sets the directories that should be passed to nvcc
135#     (e.g. nvcc -Ipath0 -Ipath1 ... ). These paths usually contain other .cu
136#     files.
137#
138#  CUDA_WRAP_SRCS ( cuda_target format generated_files file0 file1 ...
139#                   [STATIC | SHARED | MODULE] [OPTIONS ...] )
140#  -- This is where all the magic happens.  CUDA_ADD_EXECUTABLE,
141#     CUDA_ADD_LIBRARY, CUDA_COMPILE, and CUDA_COMPILE_PTX all call this
142#     function under the hood.
143#
144#     Given the list of files (file0 file1 ... fileN) this macro generates
145#     custom commands that generate either PTX or linkable objects (use "PTX" or
146#     "OBJ" for the format argument to switch).  Files that don't end with .cu
147#     or have the HEADER_FILE_ONLY property are ignored.
148#
149#     The arguments passed in after OPTIONS are extra command line options to
150#     give to nvcc.  You can also specify per configuration options by
151#     specifying the name of the configuration followed by the options.  General
152#     options must preceed configuration specific options.  Not all
153#     configurations need to be specified, only the ones provided will be used.
154#
155#        OPTIONS -DFLAG=2 "-DFLAG_OTHER=space in flag"
156#        DEBUG -g
157#        RELEASE --use_fast_math
158#        RELWITHDEBINFO --use_fast_math;-g
159#        MINSIZEREL --use_fast_math
160#
161#     For certain configurations (namely VS generating object files with
162#     CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE set to ON), no generated file will
163#     be produced for the given cuda file.  This is because when you add the
164#     cuda file to Visual Studio it knows that this file produces an object file
165#     and will link in the resulting object file automatically.
166#
167#     This script will also generate a separate cmake script that is used at
168#     build time to invoke nvcc.  This is for several reasons.
169#
170#       1. nvcc can return negative numbers as return values which confuses
171#       Visual Studio into thinking that the command succeeded.  The script now
172#       checks the error codes and produces errors when there was a problem.
173#
174#       2. nvcc has been known to not delete incomplete results when it
175#       encounters problems.  This confuses build systems into thinking the
176#       target was generated when in fact an unusable file exists.  The script
177#       now deletes the output files if there was an error.
178#
179#       3. By putting all the options that affect the build into a file and then
180#       make the build rule dependent on the file, the output files will be
181#       regenerated when the options change.
182#
183#     This script also looks at optional arguments STATIC, SHARED, or MODULE to
184#     determine when to target the object compilation for a shared library.
185#     BUILD_SHARED_LIBS is ignored in CUDA_WRAP_SRCS, but it is respected in
186#     CUDA_ADD_LIBRARY.  On some systems special flags are added for building
187#     objects intended for shared libraries.  A preprocessor macro,
188#     <target_name>_EXPORTS is defined when a shared library compilation is
189#     detected.
190#
191#     Flags passed into add_definitions with -D or /D are passed along to nvcc.
192#
193# The script defines the following variables:
194#
195#  CUDA_VERSION_MAJOR    -- The major version of cuda as reported by nvcc.
196#  CUDA_VERSION_MINOR    -- The minor version.
197#  CUDA_VERSION
198#  CUDA_VERSION_STRING   -- CUDA_VERSION_MAJOR.CUDA_VERSION_MINOR
199#
200#  CUDA_TOOLKIT_ROOT_DIR -- Path to the CUDA Toolkit (defined if not set).
201#  CUDA_SDK_ROOT_DIR     -- Path to the CUDA SDK.  Use this to find files in the
202#                           SDK.  This script will not directly support finding
203#                           specific libraries or headers, as that isn't
204#                           supported by NVIDIA.  If you want to change
205#                           libraries when the path changes see the
206#                           FindCUDA.cmake script for an example of how to clear
207#                           these variables.  There are also examples of how to
208#                           use the CUDA_SDK_ROOT_DIR to locate headers or
209#                           libraries, if you so choose (at your own risk).
210#  CUDA_INCLUDE_DIRS     -- Include directory for cuda headers.  Added automatically
211#                           for CUDA_ADD_EXECUTABLE and CUDA_ADD_LIBRARY.
212#  CUDA_LIBRARIES        -- Cuda RT library.
213#  CUDA_CUFFT_LIBRARIES  -- Device or emulation library for the Cuda FFT
214#                           implementation (alternative to:
215#                           CUDA_ADD_CUFFT_TO_TARGET macro)
216#  CUDA_CUBLAS_LIBRARIES -- Device or emulation library for the Cuda BLAS
217#                           implementation (alterative to:
218#                           CUDA_ADD_CUBLAS_TO_TARGET macro).
219#
220#
221#  James Bigler, NVIDIA Corp (nvidia.com - jbigler)
222#  Abe Stephens, SCI Institute -- http://www.sci.utah.edu/~abe/FindCuda.html
223#
224#  Copyright (c) 2008 - 2009 NVIDIA Corporation.  All rights reserved.
225#
226#  Copyright (c) 2007-2009
227#  Scientific Computing and Imaging Institute, University of Utah
228#
229#  This code is licensed under the MIT License.  See the FindCUDA.cmake script
230#  for the text of the license.
231
232# The MIT License
233#
234# License for the specific language governing rights and limitations under
235# Permission is hereby granted, free of charge, to any person obtaining a
236# copy of this software and associated documentation files (the "Software"),
237# to deal in the Software without restriction, including without limitation
238# the rights to use, copy, modify, merge, publish, distribute, sublicense,
239# and/or sell copies of the Software, and to permit persons to whom the
240# Software is furnished to do so, subject to the following conditions:
241#
242# The above copyright notice and this permission notice shall be included
243# in all copies or substantial portions of the Software.
244#
245# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
246# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
247# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
248# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
249# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
250# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
251# DEALINGS IN THE SOFTWARE.
252#
253###############################################################################
254
255# FindCUDA.cmake
256
257# We need to have at least this version to support the VERSION_LESS argument to 'if' (2.6.2) and unset (2.6.3)
258cmake_policy(PUSH)
259cmake_minimum_required(VERSION 2.6.3)
260cmake_policy(POP)
261
262# This macro helps us find the location of helper files we will need the full path to
263macro(CUDA_FIND_HELPER_FILE _name _extension)
264  set(_full_name "${_name}.${_extension}")
265  # CMAKE_CURRENT_LIST_FILE contains the full path to the file currently being
266  # processed.  Using this variable, we can pull out the current path, and
267  # provide a way to get access to the other files we need local to here.
268  get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
269  find_file(CUDA_${_name} ${_full_name} PATHS ${CMAKE_CURRENT_LIST_DIR}/FindCUDA NO_DEFAULT_PATH)
270  if(NOT CUDA_${_name})
271    set(error_message "${_full_name} not found in CMAKE_MODULE_PATH")
272    if(CUDA_FIND_REQUIRED)
273      message(FATAL_ERROR "${error_message}")
274    else(CUDA_FIND_REQUIRED)
275      if(NOT CUDA_FIND_QUIETLY)
276        message(STATUS "${error_message}")
277      endif(NOT CUDA_FIND_QUIETLY)
278    endif(CUDA_FIND_REQUIRED)
279  endif(NOT CUDA_${_name})
280  # Set this variable as internal, so the user isn't bugged with it.
281  set(CUDA_${_name} ${CUDA_${_name}} CACHE INTERNAL "Location of ${_full_name}" FORCE)
282endmacro(CUDA_FIND_HELPER_FILE)
283
284#####################################################################
285## CUDA_INCLUDE_NVCC_DEPENDENCIES
286##
287
288# So we want to try and include the dependency file if it exists.  If
289# it doesn't exist then we need to create an empty one, so we can
290# include it.
291
292# If it does exist, then we need to check to see if all the files it
293# depends on exist.  If they don't then we should clear the dependency
294# file and regenerate it later.  This covers the case where a header
295# file has disappeared or moved.
296
297macro(CUDA_INCLUDE_NVCC_DEPENDENCIES dependency_file)
298  set(CUDA_NVCC_DEPEND)
299  set(CUDA_NVCC_DEPEND_REGENERATE FALSE)
300
301
302  # Include the dependency file.  Create it first if it doesn't exist .  The
303  # INCLUDE puts a dependency that will force CMake to rerun and bring in the
304  # new info when it changes.  DO NOT REMOVE THIS (as I did and spent a few
305  # hours figuring out why it didn't work.
306  if(NOT EXISTS ${dependency_file})
307    file(WRITE ${dependency_file} "#FindCUDA.cmake generated file.  Do not edit.\n")
308  endif()
309  # Always include this file to force CMake to run again next
310  # invocation and rebuild the dependencies.
311  #message("including dependency_file = ${dependency_file}")
312  include(${dependency_file})
313
314  # Now we need to verify the existence of all the included files
315  # here.  If they aren't there we need to just blank this variable and
316  # make the file regenerate again.
317#   if(DEFINED CUDA_NVCC_DEPEND)
318#     message("CUDA_NVCC_DEPEND set")
319#   else()
320#     message("CUDA_NVCC_DEPEND NOT set")
321#   endif()
322  if(CUDA_NVCC_DEPEND)
323    #message("CUDA_NVCC_DEPEND true")
324    foreach(f ${CUDA_NVCC_DEPEND})
325      #message("searching for ${f}")
326      if(NOT EXISTS ${f})
327        #message("file ${f} not found")
328        set(CUDA_NVCC_DEPEND_REGENERATE TRUE)
329      endif()
330    endforeach(f)
331  else(CUDA_NVCC_DEPEND)
332    #message("CUDA_NVCC_DEPEND false")
333    # No dependencies, so regenerate the file.
334    set(CUDA_NVCC_DEPEND_REGENERATE TRUE)
335  endif(CUDA_NVCC_DEPEND)
336
337  #message("CUDA_NVCC_DEPEND_REGENERATE = ${CUDA_NVCC_DEPEND_REGENERATE}")
338  # No incoming dependencies, so we need to generate them.  Make the
339  # output depend on the dependency file itself, which should cause the
340  # rule to re-run.
341  if(CUDA_NVCC_DEPEND_REGENERATE)
342    file(WRITE ${dependency_file} "#FindCUDA.cmake generated file.  Do not edit.\n")
343  endif(CUDA_NVCC_DEPEND_REGENERATE)
344
345endmacro(CUDA_INCLUDE_NVCC_DEPENDENCIES)
346
347###############################################################################
348###############################################################################
349# Setup variables' defaults
350###############################################################################
351###############################################################################
352
353# Allow the user to specify if the device code is supposed to be 32 or 64 bit.
354if(CMAKE_SIZEOF_VOID_P EQUAL 8)
355  set(CUDA_64_BIT_DEVICE_CODE_DEFAULT ON)
356else()
357  set(CUDA_64_BIT_DEVICE_CODE_DEFAULT OFF)
358endif()
359option(CUDA_64_BIT_DEVICE_CODE "Compile device code in 64 bit mode" ${CUDA_64_BIT_DEVICE_CODE_DEFAULT})
360
361# Attach the build rule to the source file in VS.  This option
362option(CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE "Attach the build rule to the CUDA source file.  Enable only when the CUDA source file is added to at most one target." ON)
363
364# Prints out extra information about the cuda file during compilation
365option(CUDA_BUILD_CUBIN "Generate and parse .cubin files in Device mode." OFF)
366
367# Set whether we are using emulation or device mode.
368option(CUDA_BUILD_EMULATION "Build in Emulation mode" OFF)
369
370# Where to put the generated output.
371set(CUDA_GENERATED_OUTPUT_DIR "" CACHE PATH "Directory to put all the output files.  If blank it will default to the CMAKE_CURRENT_BINARY_DIR")
372
373# Parse HOST_COMPILATION mode.
374option(CUDA_HOST_COMPILATION_CPP "Generated file extension" ON)
375
376# Extra user settable flags
377set(CUDA_NVCC_FLAGS "" CACHE STRING "Semi-colon delimit multiple arguments.")
378
379# Propagate the host flags to the host compiler via -Xcompiler
380option(CUDA_PROPAGATE_HOST_FLAGS "Propage C/CXX_FLAGS and friends to the host compiler via -Xcompile" ON)
381
382# Specifies whether the commands used when compiling the .cu file will be printed out.
383option(CUDA_VERBOSE_BUILD "Print out the commands run while compiling the CUDA source file.  With the Makefile generator this defaults to VERBOSE variable specified on the command line, but can be forced on with this option." OFF)
384
385mark_as_advanced(
386  CUDA_64_BIT_DEVICE_CODE
387  CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE
388  CUDA_GENERATED_OUTPUT_DIR
389  CUDA_HOST_COMPILATION_CPP
390  CUDA_NVCC_FLAGS
391  CUDA_PROPAGATE_HOST_FLAGS
392  )
393
394# Makefile and similar generators don't define CMAKE_CONFIGURATION_TYPES, so we
395# need to add another entry for the CMAKE_BUILD_TYPE.  We also need to add the
396# standerd set of 4 build types (Debug, MinSizeRel, Release, and RelWithDebInfo)
397# for completeness.  We need run this loop in order to accomodate the addition
398# of extra configuration types.  Duplicate entries will be removed by
399# REMOVE_DUPLICATES.
400set(CUDA_configuration_types ${CMAKE_CONFIGURATION_TYPES} ${CMAKE_BUILD_TYPE} Debug MinSizeRel Release RelWithDebInfo)
401list(REMOVE_DUPLICATES CUDA_configuration_types)
402foreach(config ${CUDA_configuration_types})
403    string(TOUPPER ${config} config_upper)
404    set(CUDA_NVCC_FLAGS_${config_upper} "" CACHE STRING "Semi-colon delimit multiple arguments.")
405    mark_as_advanced(CUDA_NVCC_FLAGS_${config_upper})
406endforeach()
407
408###############################################################################
409###############################################################################
410# Locate CUDA, Set Build Type, etc.
411###############################################################################
412###############################################################################
413
414# Check to see if the CUDA_TOOLKIT_ROOT_DIR and CUDA_SDK_ROOT_DIR have changed,
415# if they have then clear the cache variables, so that will be detected again.
416if(NOT "${CUDA_TOOLKIT_ROOT_DIR}" STREQUAL "${CUDA_TOOLKIT_ROOT_DIR_INTERNAL}")
417  unset(CUDA_NVCC_EXECUTABLE CACHE)
418  unset(CUDA_VERSION CACHE)
419  unset(CUDA_TOOLKIT_INCLUDE CACHE)
420  unset(CUDA_CUDART_LIBRARY CACHE)
421  if(CUDA_VERSION VERSION_EQUAL "3.0")
422    # This only existed in the 3.0 version of the CUDA toolkit
423    unset(CUDA_CUDARTEMU_LIBRARY CACHE)
424  endif()
425  unset(CUDA_CUDA_LIBRARY CACHE)
426  unset(CUDA_cublas_LIBRARY CACHE)
427  unset(CUDA_cublasemu_LIBRARY CACHE)
428  unset(CUDA_cufft_LIBRARY CACHE)
429  unset(CUDA_cufftemu_LIBRARY CACHE)
430endif()
431
432if(NOT "${CUDA_SDK_ROOT_DIR}" STREQUAL "${CUDA_SDK_ROOT_DIR_INTERNAL}")
433  # No specific variables to catch.  Use this kind of code before calling
434  # find_package(CUDA) to clean up any variables that may depend on this path.
435
436  #   unset(MY_SPECIAL_CUDA_SDK_INCLUDE_DIR CACHE)
437  #   unset(MY_SPECIAL_CUDA_SDK_LIBRARY CACHE)
438endif()
439
440# Search for the cuda distribution.
441if(NOT CUDA_TOOLKIT_ROOT_DIR)
442
443  # Search in the CUDA_BIN_PATH first.
444  find_path(CUDA_TOOLKIT_ROOT_DIR
445    NAMES nvcc nvcc.exe
446    PATHS ENV CUDA_BIN_PATH
447    DOC "Toolkit location."
448    NO_DEFAULT_PATH
449    )
450  # Now search default paths
451  find_path(CUDA_TOOLKIT_ROOT_DIR
452    NAMES nvcc nvcc.exe
453    PATHS /usr/local/bin
454          /usr/local/cuda/bin
455    DOC "Toolkit location."
456    )
457
458  if (CUDA_TOOLKIT_ROOT_DIR)
459    string(REGEX REPLACE "[/\\\\]?bin[64]*[/\\\\]?$" "" CUDA_TOOLKIT_ROOT_DIR ${CUDA_TOOLKIT_ROOT_DIR})
460    # We need to force this back into the cache.
461    set(CUDA_TOOLKIT_ROOT_DIR ${CUDA_TOOLKIT_ROOT_DIR} CACHE PATH "Toolkit location." FORCE)
462  endif(CUDA_TOOLKIT_ROOT_DIR)
463  if (NOT EXISTS ${CUDA_TOOLKIT_ROOT_DIR})
464    if(CUDA_FIND_REQUIRED)
465      message(FATAL_ERROR "Specify CUDA_TOOLKIT_ROOT_DIR")
466    elseif(NOT CUDA_FIND_QUIETLY)
467      message("CUDA_TOOLKIT_ROOT_DIR not found or specified")
468    endif()
469  endif (NOT EXISTS ${CUDA_TOOLKIT_ROOT_DIR})
470endif (NOT CUDA_TOOLKIT_ROOT_DIR)
471
472# CUDA_NVCC_EXECUTABLE
473find_program(CUDA_NVCC_EXECUTABLE
474  NAMES nvcc
475  PATHS "${CUDA_TOOLKIT_ROOT_DIR}/bin"
476        "${CUDA_TOOLKIT_ROOT_DIR}/bin64"
477  ENV CUDA_BIN_PATH
478  NO_DEFAULT_PATH
479  )
480# Search default search paths, after we search our own set of paths.
481find_program(CUDA_NVCC_EXECUTABLE nvcc)
482mark_as_advanced(CUDA_NVCC_EXECUTABLE)
483
484if(CUDA_NVCC_EXECUTABLE AND NOT CUDA_VERSION)
485  # Compute the version.
486  execute_process (COMMAND ${CUDA_NVCC_EXECUTABLE} "--version" OUTPUT_VARIABLE NVCC_OUT)
487  string(REGEX REPLACE ".*release ([0-9]+)\\.([0-9]+).*" "\\1" CUDA_VERSION_MAJOR ${NVCC_OUT})
488  string(REGEX REPLACE ".*release ([0-9]+)\\.([0-9]+).*" "\\2" CUDA_VERSION_MINOR ${NVCC_OUT})
489  set(CUDA_VERSION "${CUDA_VERSION_MAJOR}.${CUDA_VERSION_MINOR}" CACHE STRING "Version of CUDA as computed from nvcc.")
490  mark_as_advanced(CUDA_VERSION)
491else()
492  # Need to set these based off of the cached value
493  string(REGEX REPLACE "([0-9]+)\\.([0-9]+).*" "\\1" CUDA_VERSION_MAJOR "${CUDA_VERSION}")
494  string(REGEX REPLACE "([0-9]+)\\.([0-9]+).*" "\\2" CUDA_VERSION_MINOR "${CUDA_VERSION}")
495endif()
496
497# Always set this convenience variable
498set(CUDA_VERSION_STRING "${CUDA_VERSION}")
499
500# Here we need to determine if the version we found is acceptable.  We will
501# assume that is unless CUDA_FIND_VERSION_EXACT or CUDA_FIND_VERSION is
502# specified.  The presence of either of these options checks the version
503# string and signals if the version is acceptable or not.
504set(_cuda_version_acceptable TRUE)
505#
506if(CUDA_FIND_VERSION_EXACT AND NOT CUDA_VERSION VERSION_EQUAL CUDA_FIND_VERSION)
507  set(_cuda_version_acceptable FALSE)
508endif()
509#
510if(CUDA_FIND_VERSION       AND     CUDA_VERSION VERSION_LESS  CUDA_FIND_VERSION)
511  set(_cuda_version_acceptable FALSE)
512endif()
513#
514if(NOT _cuda_version_acceptable)
515  set(_cuda_error_message "Requested CUDA version ${CUDA_FIND_VERSION}, but found unacceptable version ${CUDA_VERSION}")
516  if(CUDA_FIND_REQUIRED)
517    message("${_cuda_error_message}")
518  elseif(NOT CUDA_FIND_QUIETLY)
519    message("${_cuda_error_message}")
520  endif()
521endif()
522
523# CUDA_TOOLKIT_INCLUDE
524find_path(CUDA_TOOLKIT_INCLUDE
525  device_functions.h # Header included in toolkit
526  PATHS "${CUDA_TOOLKIT_ROOT_DIR}/include"
527  ENV CUDA_INC_PATH
528  NO_DEFAULT_PATH
529  )
530# Search default search paths, after we search our own set of paths.
531find_path(CUDA_TOOLKIT_INCLUDE device_functions.h)
532mark_as_advanced(CUDA_TOOLKIT_INCLUDE)
533
534# Set the user list of include dir to nothing to initialize it.
535set (CUDA_NVCC_INCLUDE_ARGS_USER "")
536set (CUDA_INCLUDE_DIRS ${CUDA_TOOLKIT_INCLUDE})
537
538macro(FIND_LIBRARY_LOCAL_FIRST _var _names _doc)
539  if(CMAKE_SIZEOF_VOID_P EQUAL 8)
540    # CUDA 3.2+ on Windows moved the library directoryies, so we need the new
541    # and old paths.
542    set(_cuda_64bit_lib_dir
543      "${CUDA_TOOLKIT_ROOT_DIR}/lib/x64"
544      "${CUDA_TOOLKIT_ROOT_DIR}/lib64"
545      )
546  endif()
547  # CUDA 3.2+ on Windows moved the library directories, so we need to new
548  # (lib/Win32) and the old path (lib).
549  find_library(${_var}
550    NAMES ${_names}
551    PATHS ${_cuda_64bit_lib_dir}
552          "${CUDA_TOOLKIT_ROOT_DIR}/lib/Win32"
553          "${CUDA_TOOLKIT_ROOT_DIR}/lib"
554    ENV CUDA_LIB_PATH
555    DOC ${_doc}
556    NO_DEFAULT_PATH
557    )
558  # Search default search paths, after we search our own set of paths.
559  find_library(${_var} NAMES ${_names} DOC ${_doc})
560endmacro()
561
562# CUDA_LIBRARIES
563find_library_local_first(CUDA_CUDART_LIBRARY cudart "\"cudart\" library")
564if(CUDA_VERSION VERSION_EQUAL "3.0")
565  # The cudartemu library only existed for the 3.0 version of CUDA.
566  find_library_local_first(CUDA_CUDARTEMU_LIBRARY cudartemu "\"cudartemu\" library")
567  mark_as_advanced(
568    CUDA_CUDARTEMU_LIBRARY
569    )
570endif()
571# If we are using emulation mode and we found the cudartemu library then use
572# that one instead of cudart.
573if(CUDA_BUILD_EMULATION AND CUDA_CUDARTEMU_LIBRARY)
574  set(CUDA_LIBRARIES ${CUDA_CUDARTEMU_LIBRARY})
575else()
576  set(CUDA_LIBRARIES ${CUDA_CUDART_LIBRARY})
577endif()
578if(APPLE)
579  # We need to add the path to cudart to the linker using rpath, since the
580  # library name for the cuda libraries is prepended with @rpath.
581  if(CUDA_BUILD_EMULATION AND CUDA_CUDARTEMU_LIBRARY)
582    get_filename_component(_cuda_path_to_cudart "${CUDA_CUDARTEMU_LIBRARY}" PATH)
583  else()
584    get_filename_component(_cuda_path_to_cudart "${CUDA_CUDART_LIBRARY}" PATH)
585  endif()
586  if(_cuda_path_to_cudart)
587    list(APPEND CUDA_LIBRARIES -Wl,-rpath "-Wl,${_cuda_path_to_cudart}")
588  endif()
589endif()
590
591# 1.1 toolkit on linux doesn't appear to have a separate library on
592# some platforms.
593find_library_local_first(CUDA_CUDA_LIBRARY cuda "\"cuda\" library (older versions only).")
594
595# Add cuda library to the link line only if it is found.
596if (CUDA_CUDA_LIBRARY)
597  set(CUDA_LIBRARIES ${CUDA_LIBRARIES} ${CUDA_CUDA_LIBRARY})
598endif(CUDA_CUDA_LIBRARY)
599
600mark_as_advanced(
601  CUDA_CUDA_LIBRARY
602  CUDA_CUDART_LIBRARY
603  )
604
605#######################
606# Look for some of the toolkit helper libraries
607macro(FIND_CUDA_HELPER_LIBS _name)
608  find_library_local_first(CUDA_${_name}_LIBRARY ${_name} "\"${_name}\" library")
609  mark_as_advanced(CUDA_${_name}_LIBRARY)
610endmacro(FIND_CUDA_HELPER_LIBS)
611
612#######################
613# Disable emulation for v3.1 onward
614if(CUDA_VERSION VERSION_GREATER "3.0")
615  if(CUDA_BUILD_EMULATION)
616    message(FATAL_ERROR "CUDA_BUILD_EMULATION is not supported in version 3.1 and onwards.  You must disable it to proceed.  You have version ${CUDA_VERSION}.")
617  endif()
618endif()
619
620# Search for cufft and cublas libraries.
621if(CUDA_VERSION VERSION_LESS "3.1")
622  # Emulation libraries aren't available in version 3.1 onward.
623  find_cuda_helper_libs(cufftemu)
624  find_cuda_helper_libs(cublasemu)
625endif()
626find_cuda_helper_libs(cufft)
627find_cuda_helper_libs(cublas)
628
629if (CUDA_BUILD_EMULATION)
630  set(CUDA_CUFFT_LIBRARIES ${CUDA_cufftemu_LIBRARY})
631  set(CUDA_CUBLAS_LIBRARIES ${CUDA_cublasemu_LIBRARY})
632else()
633  set(CUDA_CUFFT_LIBRARIES ${CUDA_cufft_LIBRARY})
634  set(CUDA_CUBLAS_LIBRARIES ${CUDA_cublas_LIBRARY})
635endif()
636
637########################
638# Look for the SDK stuff.  As of CUDA 3.0 NVSDKCUDA_ROOT has been replaced with
639# NVSDKCOMPUTE_ROOT with the old CUDA C contents moved into the C subdirectory
640find_path(CUDA_SDK_ROOT_DIR common/inc/cutil.h
641  "$ENV{NVSDKCOMPUTE_ROOT}/C"
642  "$ENV{NVSDKCUDA_ROOT}"
643  "[HKEY_LOCAL_MACHINE\\SOFTWARE\\NVIDIA Corporation\\Installed Products\\NVIDIA SDK 10\\Compute;InstallDir]"
644  "/Developer/GPU\ Computing/C"
645  )
646
647# Keep the CUDA_SDK_ROOT_DIR first in order to be able to override the
648# environment variables.
649set(CUDA_SDK_SEARCH_PATH
650  "${CUDA_SDK_ROOT_DIR}"
651  "${CUDA_TOOLKIT_ROOT_DIR}/local/NVSDK0.2"
652  "${CUDA_TOOLKIT_ROOT_DIR}/NVSDK0.2"
653  "${CUDA_TOOLKIT_ROOT_DIR}/NV_CUDA_SDK"
654  "$ENV{HOME}/NVIDIA_CUDA_SDK"
655  "$ENV{HOME}/NVIDIA_CUDA_SDK_MACOSX"
656  "$ENV{HOME}/NVIDIA_GPU_Computing_SDK/C"
657  "/Developer/CUDA"
658  )
659
660# Example of how to find an include file from the CUDA_SDK_ROOT_DIR
661
662find_path(CUDA_CUT_INCLUDE_DIR
663  cutil.h
664  PATHS ${CUDA_SDK_SEARCH_PATH}
665  PATH_SUFFIXES "common/inc"
666  DOC "Location of cutil.h"
667  NO_DEFAULT_PATH
668  )
669# Now search system paths
670find_path(CUDA_CUT_INCLUDE_DIR cutil.h DOC "Location of cutil.h")
671
672mark_as_advanced(CUDA_CUT_INCLUDE_DIR)
673
674
675# Example of how to find a library in the CUDA_SDK_ROOT_DIR
676
677# cutil library is called cutil64 for 64 bit builds on windows.  We don't want
678# to get these confused, so we are setting the name based on the word size of
679# the build.
680
681if (CMAKE_HOST_WIN32)
682  if(CMAKE_SIZEOF_VOID_P EQUAL 8)
683    set(cuda_cutil_name cutil64)
684  else(CMAKE_SIZEOF_VOID_P EQUAL 8)
685    set(cuda_cutil_name cutil32)
686  endif(CMAKE_SIZEOF_VOID_P EQUAL 8)
687else (CMAKE_HOST_WIN32)
688  if(CMAKE_SIZEOF_VOID_P EQUAL 4)
689    set(cuda_cutil_name cutil_i386)
690  else(CMAKE_SIZEOF_VOID_P EQUAL 4)
691    set(cuda_cutil_name cutil_x86_64)
692  endif(CMAKE_SIZEOF_VOID_P EQUAL 4)
693endif (CMAKE_HOST_WIN32)
694
695find_library(CUDA_CUT_LIBRARY
696  NAMES cutil ${cuda_cutil_name}
697  PATHS ${CUDA_SDK_SEARCH_PATH}
698  # The new version of the sdk shows up in common/lib, but the old one is in lib
699  PATH_SUFFIXES "common/lib" "lib"
700  DOC "Location of cutil library"
701  NO_DEFAULT_PATH
702  )
703# Now search system paths
704find_library(CUDA_CUT_LIBRARY NAMES cutil ${cuda_cutil_name} DOC "Location of cutil library")
705mark_as_advanced(CUDA_CUT_LIBRARY)
706set(CUDA_CUT_LIBRARIES ${CUDA_CUT_LIBRARY})
707
708
709
710#############################
711# Check for required components
712set(CUDA_FOUND TRUE)
713
714set(CUDA_TOOLKIT_ROOT_DIR_INTERNAL "${CUDA_TOOLKIT_ROOT_DIR}" CACHE INTERNAL
715  "This is the value of the last time CUDA_TOOLKIT_ROOT_DIR was set successfully." FORCE)
716set(CUDA_SDK_ROOT_DIR_INTERNAL "${CUDA_SDK_ROOT_DIR}" CACHE INTERNAL
717  "This is the value of the last time CUDA_SDK_ROOT_DIR was set successfully." FORCE)
718
719include(FindPackageHandleStandardArgs)
720find_package_handle_standard_args(CUDA DEFAULT_MSG
721  CUDA_TOOLKIT_ROOT_DIR
722  CUDA_NVCC_EXECUTABLE
723  CUDA_INCLUDE_DIRS
724  CUDA_CUDART_LIBRARY
725  _cuda_version_acceptable
726  )
727
728
729
730###############################################################################
731###############################################################################
732# Macros
733###############################################################################
734###############################################################################
735
736###############################################################################
737# Add include directories to pass to the nvcc command.
738macro(CUDA_INCLUDE_DIRECTORIES)
739  foreach(dir ${ARGN})
740    list(APPEND CUDA_NVCC_INCLUDE_ARGS_USER "-I${dir}")
741  endforeach(dir ${ARGN})
742endmacro(CUDA_INCLUDE_DIRECTORIES)
743
744
745##############################################################################
746cuda_find_helper_file(parse_cubin cmake)
747cuda_find_helper_file(make2cmake cmake)
748cuda_find_helper_file(run_nvcc cmake)
749
750##############################################################################
751# Separate the OPTIONS out from the sources
752#
753macro(CUDA_GET_SOURCES_AND_OPTIONS _sources _cmake_options _options)
754  set( ${_sources} )
755  set( ${_cmake_options} )
756  set( ${_options} )
757  set( _found_options FALSE )
758  foreach(arg ${ARGN})
759    if(arg STREQUAL "OPTIONS")
760      set( _found_options TRUE )
761    elseif(
762        arg STREQUAL "WIN32" OR
763        arg STREQUAL "MACOSX_BUNDLE" OR
764        arg STREQUAL "EXCLUDE_FROM_ALL" OR
765        arg STREQUAL "STATIC" OR
766        arg STREQUAL "SHARED" OR
767        arg STREQUAL "MODULE"
768        )
769      list(APPEND ${_cmake_options} "${arg}")
770    else()
771      if ( _found_options )
772        list(APPEND ${_options} "${arg}")
773      else()
774        # Assume this is a file
775        list(APPEND ${_sources} "${arg}")
776      endif()
777    endif()
778  endforeach()
779endmacro()
780
781##############################################################################
782# Parse the OPTIONS from ARGN and set the variables prefixed by _option_prefix
783#
784macro(CUDA_PARSE_NVCC_OPTIONS _option_prefix)
785  set( _found_config )
786  foreach(arg ${ARGN})
787    # Determine if we are dealing with a perconfiguration flag
788    foreach(config ${CUDA_configuration_types})
789      string(TOUPPER ${config} config_upper)
790      if (arg STREQUAL "${config_upper}")
791        set( _found_config _${arg})
792        # Set arg to nothing to keep it from being processed further
793        set( arg )
794      endif()
795    endforeach()
796
797    if ( arg )
798      list(APPEND ${_option_prefix}${_found_config} "${arg}")
799    endif()
800  endforeach()
801endmacro()
802
803##############################################################################
804# Helper to add the include directory for CUDA only once
805function(CUDA_ADD_CUDA_INCLUDE_ONCE)
806  get_directory_property(_include_directories INCLUDE_DIRECTORIES)
807  set(_add TRUE)
808  if(_include_directories)
809    foreach(dir ${_include_directories})
810      if("${dir}" STREQUAL "${CUDA_INCLUDE_DIRS}")
811        set(_add FALSE)
812      endif()
813    endforeach()
814  endif()
815  if(_add)
816    include_directories(${CUDA_INCLUDE_DIRS})
817  endif()
818endfunction()
819
820function(CUDA_BUILD_SHARED_LIBRARY shared_flag)
821  set(cmake_args ${ARGN})
822  # If SHARED, MODULE, or STATIC aren't already in the list of arguments, then
823  # add SHARED or STATIC based on the value of BUILD_SHARED_LIBS.
824  list(FIND cmake_args SHARED _cuda_found_SHARED)
825  list(FIND cmake_args MODULE _cuda_found_MODULE)
826  list(FIND cmake_args STATIC _cuda_found_STATIC)
827  if( _cuda_found_SHARED GREATER -1 OR
828      _cuda_found_MODULE GREATER -1 OR
829      _cuda_found_STATIC GREATER -1)
830    set(_cuda_build_shared_libs)
831  else()
832    if (BUILD_SHARED_LIBS)
833      set(_cuda_build_shared_libs SHARED)
834    else()
835      set(_cuda_build_shared_libs STATIC)
836    endif()
837  endif()
838  set(${shared_flag} ${_cuda_build_shared_libs} PARENT_SCOPE)
839endfunction()
840
841##############################################################################
842# This helper macro populates the following variables and setups up custom
843# commands and targets to invoke the nvcc compiler to generate C or PTX source
844# dependent upon the format parameter.  The compiler is invoked once with -M
845# to generate a dependency file and a second time with -cuda or -ptx to generate
846# a .cpp or .ptx file.
847# INPUT:
848#   cuda_target         - Target name
849#   format              - PTX or OBJ
850#   FILE1 .. FILEN      - The remaining arguments are the sources to be wrapped.
851#   OPTIONS             - Extra options to NVCC
852# OUTPUT:
853#   generated_files     - List of generated files
854##############################################################################
855##############################################################################
856
857macro(CUDA_WRAP_SRCS cuda_target format generated_files)
858
859  if( ${format} MATCHES "PTX" )
860    set( compile_to_ptx ON )
861  elseif( ${format} MATCHES "OBJ")
862    set( compile_to_ptx OFF )
863  else()
864    message( FATAL_ERROR "Invalid format flag passed to CUDA_WRAP_SRCS: '${format}'.  Use OBJ or PTX.")
865  endif()
866
867  # Set up all the command line flags here, so that they can be overriden on a per target basis.
868
869  set(nvcc_flags "")
870
871  # Emulation if the card isn't present.
872  if (CUDA_BUILD_EMULATION)
873    # Emulation.
874    set(nvcc_flags ${nvcc_flags} --device-emulation -D_DEVICEEMU -g)
875  else(CUDA_BUILD_EMULATION)
876    # Device mode.  No flags necessary.
877  endif(CUDA_BUILD_EMULATION)
878
879  if(CUDA_HOST_COMPILATION_CPP)
880    set(CUDA_C_OR_CXX CXX)
881  else(CUDA_HOST_COMPILATION_CPP)
882    if(CUDA_VERSION VERSION_LESS "3.0")
883      set(nvcc_flags ${nvcc_flags} --host-compilation C)
884    else()
885      message(WARNING "--host-compilation flag is deprecated in CUDA version >= 3.0.  Removing --host-compilation C flag" )
886    endif()
887    set(CUDA_C_OR_CXX C)
888  endif(CUDA_HOST_COMPILATION_CPP)
889
890  set(generated_extension ${CMAKE_${CUDA_C_OR_CXX}_OUTPUT_EXTENSION})
891
892  if(CUDA_64_BIT_DEVICE_CODE)
893    set(nvcc_flags ${nvcc_flags} -m64)
894  else()
895    set(nvcc_flags ${nvcc_flags} -m32)
896  endif()
897
898  # This needs to be passed in at this stage, because VS needs to fill out the
899  # value of VCInstallDir from within VS.
900  if(CMAKE_GENERATOR MATCHES "Visual Studio")
901    if( CMAKE_SIZEOF_VOID_P EQUAL 8 )
902      # Add nvcc flag for 64b Windows
903      set(ccbin_flags -D "\"CCBIN:PATH=$(VCInstallDir)bin\"" )
904    endif()
905  endif()
906
907  # Figure out which configure we will use and pass that in as an argument to
908  # the script.  We need to defer the decision until compilation time, because
909  # for VS projects we won't know if we are making a debug or release build
910  # until build time.
911  if(CMAKE_GENERATOR MATCHES "Visual Studio")
912    set( CUDA_build_configuration "$(ConfigurationName)" )
913  else()
914    set( CUDA_build_configuration "${CMAKE_BUILD_TYPE}")
915  endif()
916
917  # Initialize our list of includes with the user ones followed by the CUDA system ones.
918  set(CUDA_NVCC_INCLUDE_ARGS ${CUDA_NVCC_INCLUDE_ARGS_USER} "-I${CUDA_INCLUDE_DIRS}")
919  # Get the include directories for this directory and use them for our nvcc command.
920  get_directory_property(CUDA_NVCC_INCLUDE_DIRECTORIES INCLUDE_DIRECTORIES)
921  if(CUDA_NVCC_INCLUDE_DIRECTORIES)
922    foreach(dir ${CUDA_NVCC_INCLUDE_DIRECTORIES})
923      list(APPEND CUDA_NVCC_INCLUDE_ARGS "-I${dir}")
924    endforeach()
925  endif()
926
927  # Reset these variables
928  set(CUDA_WRAP_OPTION_NVCC_FLAGS)
929  foreach(config ${CUDA_configuration_types})
930    string(TOUPPER ${config} config_upper)
931    set(CUDA_WRAP_OPTION_NVCC_FLAGS_${config_upper})
932  endforeach()
933
934  CUDA_GET_SOURCES_AND_OPTIONS(_cuda_wrap_sources _cuda_wrap_cmake_options _cuda_wrap_options ${ARGN})
935  CUDA_PARSE_NVCC_OPTIONS(CUDA_WRAP_OPTION_NVCC_FLAGS ${_cuda_wrap_options})
936
937  # Figure out if we are building a shared library.  BUILD_SHARED_LIBS is
938  # respected in CUDA_ADD_LIBRARY.
939  set(_cuda_build_shared_libs FALSE)
940  # SHARED, MODULE
941  list(FIND _cuda_wrap_cmake_options SHARED _cuda_found_SHARED)
942  list(FIND _cuda_wrap_cmake_options MODULE _cuda_found_MODULE)
943  if(_cuda_found_SHARED GREATER -1 OR _cuda_found_MODULE GREATER -1)
944    set(_cuda_build_shared_libs TRUE)
945  endif()
946  # STATIC
947  list(FIND _cuda_wrap_cmake_options STATIC _cuda_found_STATIC)
948  if(_cuda_found_STATIC GREATER -1)
949    set(_cuda_build_shared_libs FALSE)
950  endif()
951
952  # CUDA_HOST_FLAGS
953  if(_cuda_build_shared_libs)
954    # If we are setting up code for a shared library, then we need to add extra flags for
955    # compiling objects for shared libraries.
956    set(CUDA_HOST_SHARED_FLAGS ${CMAKE_SHARED_LIBRARY_${CUDA_C_OR_CXX}_FLAGS})
957  else()
958    set(CUDA_HOST_SHARED_FLAGS)
959  endif()
960  # Only add the CMAKE_{C,CXX}_FLAGS if we are propagating host flags.  We
961  # always need to set the SHARED_FLAGS, though.
962  if(CUDA_PROPAGATE_HOST_FLAGS)
963    set(CUDA_HOST_FLAGS "set(CMAKE_HOST_FLAGS ${CMAKE_${CUDA_C_OR_CXX}_FLAGS} ${CUDA_HOST_SHARED_FLAGS})")
964  else()
965    set(CUDA_HOST_FLAGS "set(CMAKE_HOST_FLAGS ${CUDA_HOST_SHARED_FLAGS})")
966  endif()
967
968  set(CUDA_NVCC_FLAGS_CONFIG "# Build specific configuration flags")
969  # Loop over all the configuration types to generate appropriate flags for run_nvcc.cmake
970  foreach(config ${CUDA_configuration_types})
971    string(TOUPPER ${config} config_upper)
972    # CMAKE_FLAGS are strings and not lists.  By not putting quotes around CMAKE_FLAGS
973    # we convert the strings to lists (like we want).
974
975    if(CUDA_PROPAGATE_HOST_FLAGS)
976      # nvcc chokes on -g3 in versions previous to 3.0, so replace it with -g
977      if(CMAKE_COMPILER_IS_GNUCC AND CUDA_VERSION VERSION_LESS "3.0")
978        string(REPLACE "-g3" "-g" _cuda_C_FLAGS "${CMAKE_${CUDA_C_OR_CXX}_FLAGS_${config_upper}}")
979      else()
980        set(_cuda_C_FLAGS "${CMAKE_${CUDA_C_OR_CXX}_FLAGS_${config_upper}}")
981      endif()
982
983      set(CUDA_HOST_FLAGS "${CUDA_HOST_FLAGS}\nset(CMAKE_HOST_FLAGS_${config_upper} ${_cuda_C_FLAGS})")
984    endif()
985
986    # Note that if we ever want CUDA_NVCC_FLAGS_<CONFIG> to be string (instead of a list
987    # like it is currently), we can remove the quotes around the
988    # ${CUDA_NVCC_FLAGS_${config_upper}} variable like the CMAKE_HOST_FLAGS_<CONFIG> variable.
989    set(CUDA_NVCC_FLAGS_CONFIG "${CUDA_NVCC_FLAGS_CONFIG}\nset(CUDA_NVCC_FLAGS_${config_upper} \"${CUDA_NVCC_FLAGS_${config_upper}};;${CUDA_WRAP_OPTION_NVCC_FLAGS_${config_upper}}\")")
990  endforeach()
991
992  if(compile_to_ptx)
993    # Don't use any of the host compilation flags for PTX targets.
994    set(CUDA_HOST_FLAGS)
995    set(CUDA_NVCC_FLAGS_CONFIG)
996  endif()
997
998  # Get the list of definitions from the directory property
999  get_directory_property(CUDA_NVCC_DEFINITIONS COMPILE_DEFINITIONS)
1000  if(CUDA_NVCC_DEFINITIONS)
1001    foreach(_definition ${CUDA_NVCC_DEFINITIONS})
1002      list(APPEND nvcc_flags "-D${_definition}")
1003    endforeach()
1004  endif()
1005
1006  if(_cuda_build_shared_libs)
1007    list(APPEND nvcc_flags "-D${cuda_target}_EXPORTS")
1008  endif()
1009
1010  # Determine output directory
1011  if(CUDA_GENERATED_OUTPUT_DIR)
1012    set(cuda_compile_output_dir "${CUDA_GENERATED_OUTPUT_DIR}")
1013  else()
1014    set(cuda_compile_output_dir "${CMAKE_CURRENT_BINARY_DIR}")
1015  endif()
1016
1017  # Reset the output variable
1018  set(_cuda_wrap_generated_files "")
1019
1020  # Iterate over the macro arguments and create custom
1021  # commands for all the .cu files.
1022  foreach(file ${ARGN})
1023    # Ignore any file marked as a HEADER_FILE_ONLY
1024    get_source_file_property(_is_header ${file} HEADER_FILE_ONLY)
1025    if(${file} MATCHES ".*\\.cu$" AND NOT _is_header)
1026
1027      # Add a custom target to generate a c or ptx file. ######################
1028
1029      get_filename_component( basename ${file} NAME )
1030      if( compile_to_ptx )
1031        set(generated_file_path "${cuda_compile_output_dir}")
1032        set(generated_file_basename "${cuda_target}_generated_${basename}.ptx")
1033        set(format_flag "-ptx")
1034        file(MAKE_DIRECTORY "${cuda_compile_output_dir}")
1035      else( compile_to_ptx )
1036        set(generated_file_path "${cuda_compile_output_dir}/${CMAKE_CFG_INTDIR}")
1037        set(generated_file_basename "${cuda_target}_generated_${basename}${generated_extension}")
1038        set(format_flag "-c")
1039      endif( compile_to_ptx )
1040
1041      # Set all of our file names.  Make sure that whatever filenames that have
1042      # generated_file_path in them get passed in through as a command line
1043      # argument, so that the ${CMAKE_CFG_INTDIR} gets expanded at run time
1044      # instead of configure time.
1045      set(generated_file "${generated_file_path}/${generated_file_basename}")
1046      set(cmake_dependency_file "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${generated_file_basename}.depend")
1047      set(NVCC_generated_dependency_file "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${generated_file_basename}.NVCC-depend")
1048      set(generated_cubin_file "${generated_file_path}/${generated_file_basename}.cubin.txt")
1049      set(custom_target_script "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/${generated_file_basename}.cmake")
1050
1051      # Setup properties for obj files:
1052      if( NOT compile_to_ptx )
1053        set_source_files_properties("${generated_file}"
1054          PROPERTIES
1055          EXTERNAL_OBJECT true # This is an object file not to be compiled, but only be linked.
1056          )
1057      endif()
1058
1059      # Don't add CMAKE_CURRENT_SOURCE_DIR if the path is already an absolute path.
1060      get_filename_component(file_path "${file}" PATH)
1061      if(IS_ABSOLUTE "${file_path}")
1062        set(source_file "${file}")
1063      else()
1064        set(source_file "${CMAKE_CURRENT_SOURCE_DIR}/${file}")
1065      endif()
1066
1067      # Bring in the dependencies.  Creates a variable CUDA_NVCC_DEPEND #######
1068      cuda_include_nvcc_dependencies(${cmake_dependency_file})
1069
1070      # Convience string for output ###########################################
1071      if(CUDA_BUILD_EMULATION)
1072        set(cuda_build_type "Emulation")
1073      else(CUDA_BUILD_EMULATION)
1074        set(cuda_build_type "Device")
1075      endif(CUDA_BUILD_EMULATION)
1076
1077      # Build the NVCC made dependency file ###################################
1078      set(build_cubin OFF)
1079      if ( NOT CUDA_BUILD_EMULATION AND CUDA_BUILD_CUBIN )
1080         if ( NOT compile_to_ptx )
1081           set ( build_cubin ON )
1082         endif( NOT compile_to_ptx )
1083      endif( NOT CUDA_BUILD_EMULATION AND CUDA_BUILD_CUBIN )
1084
1085      # Configure the build script
1086      configure_file("${CUDA_run_nvcc}" "${custom_target_script}" @ONLY)
1087
1088      # So if a user specifies the same cuda file as input more than once, you
1089      # can have bad things happen with dependencies.  Here we check an option
1090      # to see if this is the behavior they want.
1091      if(CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE)
1092        set(main_dep MAIN_DEPENDENCY ${source_file})
1093      else()
1094        set(main_dep DEPENDS ${source_file})
1095      endif()
1096
1097      if(CUDA_VERBOSE_BUILD)
1098        set(verbose_output ON)
1099      elseif(CMAKE_GENERATOR MATCHES "Makefiles")
1100        set(verbose_output "$(VERBOSE)")
1101      else()
1102        set(verbose_output OFF)
1103      endif()
1104
1105      # Create up the comment string
1106      file(RELATIVE_PATH generated_file_relative_path "${CMAKE_BINARY_DIR}" "${generated_file}")
1107      if(compile_to_ptx)
1108        set(cuda_build_comment_string "Building NVCC ptx file ${generated_file_relative_path}")
1109      else()
1110        set(cuda_build_comment_string "Building NVCC (${cuda_build_type}) object ${generated_file_relative_path}")
1111      endif()
1112
1113      # Build the generated file and dependency file ##########################
1114      add_custom_command(
1115        OUTPUT ${generated_file}
1116        # These output files depend on the source_file and the contents of cmake_dependency_file
1117        ${main_dep}
1118        DEPENDS ${CUDA_NVCC_DEPEND}
1119        DEPENDS ${custom_target_script}
1120        # Make sure the output directory exists before trying to write to it.
1121        COMMAND ${CMAKE_COMMAND} -E make_directory "${generated_file_path}"
1122        COMMAND ${CMAKE_COMMAND} ARGS
1123          -D verbose:BOOL=${verbose_output}
1124          ${ccbin_flags}
1125          -D build_configuration:STRING=${CUDA_build_configuration}
1126          -D "generated_file:STRING=${generated_file}"
1127          -D "generated_cubin_file:STRING=${generated_cubin_file}"
1128          -P "${custom_target_script}"
1129        COMMENT "${cuda_build_comment_string}"
1130        )
1131
1132      # Make sure the build system knows the file is generated.
1133      set_source_files_properties(${generated_file} PROPERTIES GENERATED TRUE)
1134
1135      # Don't add the object file to the list of generated files if we are using
1136      # visual studio and we are attaching the build rule to the cuda file.  VS
1137      # will add our object file to the linker automatically for us.
1138      set(cuda_add_generated_file TRUE)
1139
1140      if(NOT compile_to_ptx AND CMAKE_GENERATOR MATCHES "Visual Studio" AND CUDA_ATTACH_VS_BUILD_RULE_TO_CUDA_FILE)
1141        # Visual Studio 8 crashes when you close the solution when you don't add the object file.
1142        if(NOT CMAKE_GENERATOR MATCHES "Visual Studio 8")
1143          #message("Not adding ${generated_file}")
1144          set(cuda_add_generated_file FALSE)
1145        endif()
1146      endif()
1147
1148      if(cuda_add_generated_file)
1149        list(APPEND _cuda_wrap_generated_files ${generated_file})
1150      endif()
1151
1152      # Add the other files that we want cmake to clean on a cleanup ##########
1153      list(APPEND CUDA_ADDITIONAL_CLEAN_FILES "${cmake_dependency_file}")
1154      list(REMOVE_DUPLICATES CUDA_ADDITIONAL_CLEAN_FILES)
1155      set(CUDA_ADDITIONAL_CLEAN_FILES ${CUDA_ADDITIONAL_CLEAN_FILES} CACHE INTERNAL "List of intermediate files that are part of the cuda dependency scanning.")
1156
1157    endif(${file} MATCHES ".*\\.cu$" AND NOT _is_header)
1158  endforeach(file)
1159
1160  # Set the return parameter
1161  set(${generated_files} ${_cuda_wrap_generated_files})
1162endmacro(CUDA_WRAP_SRCS)
1163
1164
1165###############################################################################
1166###############################################################################
1167# ADD LIBRARY
1168###############################################################################
1169###############################################################################
1170macro(CUDA_ADD_LIBRARY cuda_target)
1171
1172  CUDA_ADD_CUDA_INCLUDE_ONCE()
1173
1174  # Separate the sources from the options
1175  CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
1176  CUDA_BUILD_SHARED_LIBRARY(_cuda_shared_flag ${ARGN})
1177  # Create custom commands and targets for each file.
1178  CUDA_WRAP_SRCS( ${cuda_target} OBJ _generated_files ${_sources}
1179    ${_cmake_options} ${_cuda_shared_flag}
1180    OPTIONS ${_options} )
1181
1182  # Add the library.
1183  add_library(${cuda_target} ${_cmake_options}
1184    ${_generated_files}
1185    ${_sources}
1186    )
1187
1188  target_link_libraries(${cuda_target}
1189    ${CUDA_LIBRARIES}
1190    )
1191
1192  # We need to set the linker language based on what the expected generated file
1193  # would be. CUDA_C_OR_CXX is computed based on CUDA_HOST_COMPILATION_CPP.
1194  set_target_properties(${cuda_target}
1195    PROPERTIES
1196    LINKER_LANGUAGE ${CUDA_C_OR_CXX}
1197    )
1198
1199endmacro(CUDA_ADD_LIBRARY cuda_target)
1200
1201
1202###############################################################################
1203###############################################################################
1204# ADD EXECUTABLE
1205###############################################################################
1206###############################################################################
1207macro(CUDA_ADD_EXECUTABLE cuda_target)
1208
1209  CUDA_ADD_CUDA_INCLUDE_ONCE()
1210
1211  # Separate the sources from the options
1212  CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
1213  # Create custom commands and targets for each file.
1214  CUDA_WRAP_SRCS( ${cuda_target} OBJ _generated_files ${_sources} OPTIONS ${_options} )
1215
1216  # Add the library.
1217  add_executable(${cuda_target} ${_cmake_options}
1218    ${_generated_files}
1219    ${_sources}
1220    )
1221
1222  target_link_libraries(${cuda_target}
1223    ${CUDA_LIBRARIES}
1224    )
1225
1226  # We need to set the linker language based on what the expected generated file
1227  # would be. CUDA_C_OR_CXX is computed based on CUDA_HOST_COMPILATION_CPP.
1228  set_target_properties(${cuda_target}
1229    PROPERTIES
1230    LINKER_LANGUAGE ${CUDA_C_OR_CXX}
1231    )
1232
1233endmacro(CUDA_ADD_EXECUTABLE cuda_target)
1234
1235
1236###############################################################################
1237###############################################################################
1238# CUDA COMPILE
1239###############################################################################
1240###############################################################################
1241macro(CUDA_COMPILE generated_files)
1242
1243  # Separate the sources from the options
1244  CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
1245  # Create custom commands and targets for each file.
1246  CUDA_WRAP_SRCS( cuda_compile OBJ _generated_files ${_sources} ${_cmake_options}
1247    OPTIONS ${_options} )
1248
1249  set( ${generated_files} ${_generated_files})
1250
1251endmacro(CUDA_COMPILE)
1252
1253
1254###############################################################################
1255###############################################################################
1256# CUDA COMPILE PTX
1257###############################################################################
1258###############################################################################
1259macro(CUDA_COMPILE_PTX generated_files)
1260
1261  # Separate the sources from the options
1262  CUDA_GET_SOURCES_AND_OPTIONS(_sources _cmake_options _options ${ARGN})
1263  # Create custom commands and targets for each file.
1264  CUDA_WRAP_SRCS( cuda_compile_ptx PTX _generated_files ${_sources} ${_cmake_options}
1265    OPTIONS ${_options} )
1266
1267  set( ${generated_files} ${_generated_files})
1268
1269endmacro(CUDA_COMPILE_PTX)
1270
1271###############################################################################
1272###############################################################################
1273# CUDA ADD CUFFT TO TARGET
1274###############################################################################
1275###############################################################################
1276macro(CUDA_ADD_CUFFT_TO_TARGET target)
1277  if (CUDA_BUILD_EMULATION)
1278    target_link_libraries(${target} ${CUDA_cufftemu_LIBRARY})
1279  else()
1280    target_link_libraries(${target} ${CUDA_cufft_LIBRARY})
1281  endif()
1282endmacro()
1283
1284###############################################################################
1285###############################################################################
1286# CUDA ADD CUBLAS TO TARGET
1287###############################################################################
1288###############################################################################
1289macro(CUDA_ADD_CUBLAS_TO_TARGET target)
1290  if (CUDA_BUILD_EMULATION)
1291    target_link_libraries(${target} ${CUDA_cublasemu_LIBRARY})
1292  else()
1293    target_link_libraries(${target} ${CUDA_cublas_LIBRARY})
1294  endif()
1295endmacro()
1296
1297###############################################################################
1298###############################################################################
1299# CUDA BUILD CLEAN TARGET
1300###############################################################################
1301###############################################################################
1302macro(CUDA_BUILD_CLEAN_TARGET)
1303  # Call this after you add all your CUDA targets, and you will get a convience
1304  # target.  You should also make clean after running this target to get the
1305  # build system to generate all the code again.
1306
1307  set(cuda_clean_target_name clean_cuda_depends)
1308  if (CMAKE_GENERATOR MATCHES "Visual Studio")
1309    string(TOUPPER ${cuda_clean_target_name} cuda_clean_target_name)
1310  endif()
1311  add_custom_target(${cuda_clean_target_name}
1312    COMMAND ${CMAKE_COMMAND} -E remove ${CUDA_ADDITIONAL_CLEAN_FILES})
1313
1314  # Clear out the variable, so the next time we configure it will be empty.
1315  # This is useful so that the files won't persist in the list after targets
1316  # have been removed.
1317  set(CUDA_ADDITIONAL_CLEAN_FILES "" CACHE INTERNAL "List of intermediate files that are part of the cuda dependency scanning.")
1318endmacro(CUDA_BUILD_CLEAN_TARGET)
1319