build_clib.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. """ Modified version of build_clib that handles fortran source files.
  2. """
  3. import os
  4. from glob import glob
  5. import shutil
  6. from distutils.command.build_clib import build_clib as old_build_clib
  7. from distutils.errors import DistutilsSetupError, DistutilsError, \
  8. DistutilsFileError
  9. from numpy.distutils import log
  10. from distutils.dep_util import newer_group
  11. from numpy.distutils.misc_util import (
  12. filter_sources, get_lib_source_files, get_numpy_include_dirs,
  13. has_cxx_sources, has_f_sources, is_sequence
  14. )
  15. from numpy.distutils.ccompiler_opt import new_ccompiler_opt
  16. # Fix Python distutils bug sf #1718574:
  17. _l = old_build_clib.user_options
  18. for _i in range(len(_l)):
  19. if _l[_i][0] in ['build-clib', 'build-temp']:
  20. _l[_i] = (_l[_i][0] + '=',) + _l[_i][1:]
  21. #
  22. class build_clib(old_build_clib):
  23. description = "build C/C++/F libraries used by Python extensions"
  24. user_options = old_build_clib.user_options + [
  25. ('fcompiler=', None,
  26. "specify the Fortran compiler type"),
  27. ('inplace', 'i', 'Build in-place'),
  28. ('parallel=', 'j',
  29. "number of parallel jobs"),
  30. ('warn-error', None,
  31. "turn all warnings into errors (-Werror)"),
  32. ('cpu-baseline=', None,
  33. "specify a list of enabled baseline CPU optimizations"),
  34. ('cpu-dispatch=', None,
  35. "specify a list of dispatched CPU optimizations"),
  36. ('disable-optimization', None,
  37. "disable CPU optimized code(dispatch,simd,fast...)"),
  38. ]
  39. boolean_options = old_build_clib.boolean_options + \
  40. ['inplace', 'warn-error', 'disable-optimization']
  41. def initialize_options(self):
  42. old_build_clib.initialize_options(self)
  43. self.fcompiler = None
  44. self.inplace = 0
  45. self.parallel = None
  46. self.warn_error = None
  47. self.cpu_baseline = None
  48. self.cpu_dispatch = None
  49. self.disable_optimization = None
  50. def finalize_options(self):
  51. if self.parallel:
  52. try:
  53. self.parallel = int(self.parallel)
  54. except ValueError as e:
  55. raise ValueError("--parallel/-j argument must be an integer") from e
  56. old_build_clib.finalize_options(self)
  57. self.set_undefined_options('build',
  58. ('parallel', 'parallel'),
  59. ('warn_error', 'warn_error'),
  60. ('cpu_baseline', 'cpu_baseline'),
  61. ('cpu_dispatch', 'cpu_dispatch'),
  62. ('disable_optimization', 'disable_optimization')
  63. )
  64. def have_f_sources(self):
  65. for (lib_name, build_info) in self.libraries:
  66. if has_f_sources(build_info.get('sources', [])):
  67. return True
  68. return False
  69. def have_cxx_sources(self):
  70. for (lib_name, build_info) in self.libraries:
  71. if has_cxx_sources(build_info.get('sources', [])):
  72. return True
  73. return False
  74. def run(self):
  75. if not self.libraries:
  76. return
  77. # Make sure that library sources are complete.
  78. languages = []
  79. # Make sure that extension sources are complete.
  80. self.run_command('build_src')
  81. for (lib_name, build_info) in self.libraries:
  82. l = build_info.get('language', None)
  83. if l and l not in languages:
  84. languages.append(l)
  85. from distutils.ccompiler import new_compiler
  86. self.compiler = new_compiler(compiler=self.compiler,
  87. dry_run=self.dry_run,
  88. force=self.force)
  89. self.compiler.customize(self.distribution,
  90. need_cxx=self.have_cxx_sources())
  91. if self.warn_error:
  92. self.compiler.compiler.append('-Werror')
  93. self.compiler.compiler_so.append('-Werror')
  94. libraries = self.libraries
  95. self.libraries = None
  96. self.compiler.customize_cmd(self)
  97. self.libraries = libraries
  98. self.compiler.show_customization()
  99. if not self.disable_optimization:
  100. dispatch_hpath = os.path.join("numpy", "distutils", "include", "npy_cpu_dispatch_config.h")
  101. dispatch_hpath = os.path.join(self.get_finalized_command("build_src").build_src, dispatch_hpath)
  102. opt_cache_path = os.path.abspath(
  103. os.path.join(self.build_temp, 'ccompiler_opt_cache_clib.py')
  104. )
  105. if hasattr(self, "compiler_opt"):
  106. # By default `CCompilerOpt` update the cache at the exit of
  107. # the process, which may lead to duplicate building
  108. # (see build_extension()/force_rebuild) if run() called
  109. # multiple times within the same os process/thread without
  110. # giving the chance the previous instances of `CCompilerOpt`
  111. # to update the cache.
  112. self.compiler_opt.cache_flush()
  113. self.compiler_opt = new_ccompiler_opt(
  114. compiler=self.compiler, dispatch_hpath=dispatch_hpath,
  115. cpu_baseline=self.cpu_baseline, cpu_dispatch=self.cpu_dispatch,
  116. cache_path=opt_cache_path
  117. )
  118. def report(copt):
  119. log.info("\n########### CLIB COMPILER OPTIMIZATION ###########")
  120. log.info(copt.report(full=True))
  121. import atexit
  122. atexit.register(report, self.compiler_opt)
  123. if self.have_f_sources():
  124. from numpy.distutils.fcompiler import new_fcompiler
  125. self._f_compiler = new_fcompiler(compiler=self.fcompiler,
  126. verbose=self.verbose,
  127. dry_run=self.dry_run,
  128. force=self.force,
  129. requiref90='f90' in languages,
  130. c_compiler=self.compiler)
  131. if self._f_compiler is not None:
  132. self._f_compiler.customize(self.distribution)
  133. libraries = self.libraries
  134. self.libraries = None
  135. self._f_compiler.customize_cmd(self)
  136. self.libraries = libraries
  137. self._f_compiler.show_customization()
  138. else:
  139. self._f_compiler = None
  140. self.build_libraries(self.libraries)
  141. if self.inplace:
  142. for l in self.distribution.installed_libraries:
  143. libname = self.compiler.library_filename(l.name)
  144. source = os.path.join(self.build_clib, libname)
  145. target = os.path.join(l.target_dir, libname)
  146. self.mkpath(l.target_dir)
  147. shutil.copy(source, target)
  148. def get_source_files(self):
  149. self.check_library_list(self.libraries)
  150. filenames = []
  151. for lib in self.libraries:
  152. filenames.extend(get_lib_source_files(lib))
  153. return filenames
  154. def build_libraries(self, libraries):
  155. for (lib_name, build_info) in libraries:
  156. self.build_a_library(build_info, lib_name, libraries)
  157. def assemble_flags(self, in_flags):
  158. """ Assemble flags from flag list
  159. Parameters
  160. ----------
  161. in_flags : None or sequence
  162. None corresponds to empty list. Sequence elements can be strings
  163. or callables that return lists of strings. Callable takes `self` as
  164. single parameter.
  165. Returns
  166. -------
  167. out_flags : list
  168. """
  169. if in_flags is None:
  170. return []
  171. out_flags = []
  172. for in_flag in in_flags:
  173. if callable(in_flag):
  174. out_flags += in_flag(self)
  175. else:
  176. out_flags.append(in_flag)
  177. return out_flags
  178. def build_a_library(self, build_info, lib_name, libraries):
  179. # default compilers
  180. compiler = self.compiler
  181. fcompiler = self._f_compiler
  182. sources = build_info.get('sources')
  183. if sources is None or not is_sequence(sources):
  184. raise DistutilsSetupError(("in 'libraries' option (library '%s'), " +
  185. "'sources' must be present and must be " +
  186. "a list of source filenames") % lib_name)
  187. sources = list(sources)
  188. c_sources, cxx_sources, f_sources, fmodule_sources \
  189. = filter_sources(sources)
  190. requiref90 = not not fmodule_sources or \
  191. build_info.get('language', 'c') == 'f90'
  192. # save source type information so that build_ext can use it.
  193. source_languages = []
  194. if c_sources:
  195. source_languages.append('c')
  196. if cxx_sources:
  197. source_languages.append('c++')
  198. if requiref90:
  199. source_languages.append('f90')
  200. elif f_sources:
  201. source_languages.append('f77')
  202. build_info['source_languages'] = source_languages
  203. lib_file = compiler.library_filename(lib_name,
  204. output_dir=self.build_clib)
  205. depends = sources + build_info.get('depends', [])
  206. force_rebuild = self.force
  207. if not self.disable_optimization and not self.compiler_opt.is_cached():
  208. log.debug("Detected changes on compiler optimizations")
  209. force_rebuild = True
  210. if not (force_rebuild or newer_group(depends, lib_file, 'newer')):
  211. log.debug("skipping '%s' library (up-to-date)", lib_name)
  212. return
  213. else:
  214. log.info("building '%s' library", lib_name)
  215. config_fc = build_info.get('config_fc', {})
  216. if fcompiler is not None and config_fc:
  217. log.info('using additional config_fc from setup script '
  218. 'for fortran compiler: %s'
  219. % (config_fc,))
  220. from numpy.distutils.fcompiler import new_fcompiler
  221. fcompiler = new_fcompiler(compiler=fcompiler.compiler_type,
  222. verbose=self.verbose,
  223. dry_run=self.dry_run,
  224. force=self.force,
  225. requiref90=requiref90,
  226. c_compiler=self.compiler)
  227. if fcompiler is not None:
  228. dist = self.distribution
  229. base_config_fc = dist.get_option_dict('config_fc').copy()
  230. base_config_fc.update(config_fc)
  231. fcompiler.customize(base_config_fc)
  232. # check availability of Fortran compilers
  233. if (f_sources or fmodule_sources) and fcompiler is None:
  234. raise DistutilsError("library %s has Fortran sources"
  235. " but no Fortran compiler found" % (lib_name))
  236. if fcompiler is not None:
  237. fcompiler.extra_f77_compile_args = build_info.get(
  238. 'extra_f77_compile_args') or []
  239. fcompiler.extra_f90_compile_args = build_info.get(
  240. 'extra_f90_compile_args') or []
  241. macros = build_info.get('macros')
  242. if macros is None:
  243. macros = []
  244. include_dirs = build_info.get('include_dirs')
  245. if include_dirs is None:
  246. include_dirs = []
  247. # Flags can be strings, or callables that return a list of strings.
  248. extra_postargs = self.assemble_flags(
  249. build_info.get('extra_compiler_args'))
  250. extra_cflags = self.assemble_flags(
  251. build_info.get('extra_cflags'))
  252. extra_cxxflags = self.assemble_flags(
  253. build_info.get('extra_cxxflags'))
  254. include_dirs.extend(get_numpy_include_dirs())
  255. # where compiled F90 module files are:
  256. module_dirs = build_info.get('module_dirs') or []
  257. module_build_dir = os.path.dirname(lib_file)
  258. if requiref90:
  259. self.mkpath(module_build_dir)
  260. if compiler.compiler_type == 'msvc':
  261. # this hack works around the msvc compiler attributes
  262. # problem, msvc uses its own convention :(
  263. c_sources += cxx_sources
  264. cxx_sources = []
  265. # filtering C dispatch-table sources when optimization is not disabled,
  266. # otherwise treated as normal sources.
  267. copt_c_sources = []
  268. copt_cxx_sources = []
  269. copt_baseline_flags = []
  270. copt_macros = []
  271. if not self.disable_optimization:
  272. bsrc_dir = self.get_finalized_command("build_src").build_src
  273. dispatch_hpath = os.path.join("numpy", "distutils", "include")
  274. dispatch_hpath = os.path.join(bsrc_dir, dispatch_hpath)
  275. include_dirs.append(dispatch_hpath)
  276. copt_build_src = None if self.inplace else bsrc_dir
  277. for _srcs, _dst, _ext in (
  278. ((c_sources,), copt_c_sources, ('.dispatch.c',)),
  279. ((c_sources, cxx_sources), copt_cxx_sources,
  280. ('.dispatch.cpp', '.dispatch.cxx'))
  281. ):
  282. for _src in _srcs:
  283. _dst += [
  284. _src.pop(_src.index(s))
  285. for s in _src[:] if s.endswith(_ext)
  286. ]
  287. copt_baseline_flags = self.compiler_opt.cpu_baseline_flags()
  288. else:
  289. copt_macros.append(("NPY_DISABLE_OPTIMIZATION", 1))
  290. objects = []
  291. if copt_cxx_sources:
  292. log.info("compiling C++ dispatch-able sources")
  293. objects += self.compiler_opt.try_dispatch(
  294. copt_c_sources,
  295. output_dir=self.build_temp,
  296. src_dir=copt_build_src,
  297. macros=macros + copt_macros,
  298. include_dirs=include_dirs,
  299. debug=self.debug,
  300. extra_postargs=extra_postargs + extra_cxxflags,
  301. ccompiler=cxx_compiler
  302. )
  303. if copt_c_sources:
  304. log.info("compiling C dispatch-able sources")
  305. objects += self.compiler_opt.try_dispatch(
  306. copt_c_sources,
  307. output_dir=self.build_temp,
  308. src_dir=copt_build_src,
  309. macros=macros + copt_macros,
  310. include_dirs=include_dirs,
  311. debug=self.debug,
  312. extra_postargs=extra_postargs + extra_cflags)
  313. if c_sources:
  314. log.info("compiling C sources")
  315. objects += compiler.compile(
  316. c_sources,
  317. output_dir=self.build_temp,
  318. macros=macros + copt_macros,
  319. include_dirs=include_dirs,
  320. debug=self.debug,
  321. extra_postargs=(extra_postargs +
  322. copt_baseline_flags +
  323. extra_cflags))
  324. if cxx_sources:
  325. log.info("compiling C++ sources")
  326. cxx_compiler = compiler.cxx_compiler()
  327. cxx_objects = cxx_compiler.compile(
  328. cxx_sources,
  329. output_dir=self.build_temp,
  330. macros=macros + copt_macros,
  331. include_dirs=include_dirs,
  332. debug=self.debug,
  333. extra_postargs=(extra_postargs +
  334. copt_baseline_flags +
  335. extra_cxxflags))
  336. objects.extend(cxx_objects)
  337. if f_sources or fmodule_sources:
  338. extra_postargs = []
  339. f_objects = []
  340. if requiref90:
  341. if fcompiler.module_dir_switch is None:
  342. existing_modules = glob('*.mod')
  343. extra_postargs += fcompiler.module_options(
  344. module_dirs, module_build_dir)
  345. if fmodule_sources:
  346. log.info("compiling Fortran 90 module sources")
  347. f_objects += fcompiler.compile(fmodule_sources,
  348. output_dir=self.build_temp,
  349. macros=macros,
  350. include_dirs=include_dirs,
  351. debug=self.debug,
  352. extra_postargs=extra_postargs)
  353. if requiref90 and self._f_compiler.module_dir_switch is None:
  354. # move new compiled F90 module files to module_build_dir
  355. for f in glob('*.mod'):
  356. if f in existing_modules:
  357. continue
  358. t = os.path.join(module_build_dir, f)
  359. if os.path.abspath(f) == os.path.abspath(t):
  360. continue
  361. if os.path.isfile(t):
  362. os.remove(t)
  363. try:
  364. self.move_file(f, module_build_dir)
  365. except DistutilsFileError:
  366. log.warn('failed to move %r to %r'
  367. % (f, module_build_dir))
  368. if f_sources:
  369. log.info("compiling Fortran sources")
  370. f_objects += fcompiler.compile(f_sources,
  371. output_dir=self.build_temp,
  372. macros=macros,
  373. include_dirs=include_dirs,
  374. debug=self.debug,
  375. extra_postargs=extra_postargs)
  376. else:
  377. f_objects = []
  378. if f_objects and not fcompiler.can_ccompiler_link(compiler):
  379. # Default linker cannot link Fortran object files, and results
  380. # need to be wrapped later. Instead of creating a real static
  381. # library, just keep track of the object files.
  382. listfn = os.path.join(self.build_clib,
  383. lib_name + '.fobjects')
  384. with open(listfn, 'w') as f:
  385. f.write("\n".join(os.path.abspath(obj) for obj in f_objects))
  386. listfn = os.path.join(self.build_clib,
  387. lib_name + '.cobjects')
  388. with open(listfn, 'w') as f:
  389. f.write("\n".join(os.path.abspath(obj) for obj in objects))
  390. # create empty "library" file for dependency tracking
  391. lib_fname = os.path.join(self.build_clib,
  392. lib_name + compiler.static_lib_extension)
  393. with open(lib_fname, 'wb') as f:
  394. pass
  395. else:
  396. # assume that default linker is suitable for
  397. # linking Fortran object files
  398. objects.extend(f_objects)
  399. compiler.create_static_lib(objects, lib_name,
  400. output_dir=self.build_clib,
  401. debug=self.debug)
  402. # fix library dependencies
  403. clib_libraries = build_info.get('libraries', [])
  404. for lname, binfo in libraries:
  405. if lname in clib_libraries:
  406. clib_libraries.extend(binfo.get('libraries', []))
  407. if clib_libraries:
  408. build_info['libraries'] = clib_libraries