ccompiler_opt.py 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659
  1. """Provides the `CCompilerOpt` class, used for handling the CPU/hardware
  2. optimization, starting from parsing the command arguments, to managing the
  3. relation between the CPU baseline and dispatch-able features,
  4. also generating the required C headers and ending with compiling
  5. the sources with proper compiler's flags.
  6. `CCompilerOpt` doesn't provide runtime detection for the CPU features,
  7. instead only focuses on the compiler side, but it creates abstract C headers
  8. that can be used later for the final runtime dispatching process."""
  9. import atexit
  10. import inspect
  11. import os
  12. import pprint
  13. import re
  14. import subprocess
  15. import textwrap
  16. # These flags are used to compile any C++ source within Numpy.
  17. # They are chosen to have very few runtime dependencies.
  18. NPY_CXX_FLAGS = [
  19. '-std=c++11', # Minimal standard version
  20. '-D__STDC_VERSION__=0', # for compatibility with C headers
  21. '-fno-exceptions', # no exception support
  22. '-fno-rtti'] # no runtime type information
  23. class _Config:
  24. """An abstract class holds all configurable attributes of `CCompilerOpt`,
  25. these class attributes can be used to change the default behavior
  26. of `CCompilerOpt` in order to fit other requirements.
  27. Attributes
  28. ----------
  29. conf_nocache : bool
  30. Set True to disable memory and file cache.
  31. Default is False.
  32. conf_noopt : bool
  33. Set True to forces the optimization to be disabled,
  34. in this case `CCompilerOpt` tends to generate all
  35. expected headers in order to 'not' break the build.
  36. Default is False.
  37. conf_cache_factors : list
  38. Add extra factors to the primary caching factors. The caching factors
  39. are utilized to determine if there are changes had happened that
  40. requires to discard the cache and re-updating it. The primary factors
  41. are the arguments of `CCompilerOpt` and `CCompiler`'s properties(type, flags, etc).
  42. Default is list of two items, containing the time of last modification
  43. of `ccompiler_opt` and value of attribute "conf_noopt"
  44. conf_tmp_path : str,
  45. The path of temporary directory. Default is auto-created
  46. temporary directory via ``tempfile.mkdtemp()``.
  47. conf_check_path : str
  48. The path of testing files. Each added CPU feature must have a
  49. **C** source file contains at least one intrinsic or instruction that
  50. related to this feature, so it can be tested against the compiler.
  51. Default is ``./distutils/checks``.
  52. conf_target_groups : dict
  53. Extra tokens that can be reached from dispatch-able sources through
  54. the special mark ``@targets``. Default is an empty dictionary.
  55. **Notes**:
  56. - case-insensitive for tokens and group names
  57. - sign '#' must stick in the begin of group name and only within ``@targets``
  58. **Example**:
  59. .. code-block:: console
  60. $ "@targets #avx_group other_tokens" > group_inside.c
  61. >>> CCompilerOpt.conf_target_groups["avx_group"] = \\
  62. "$werror $maxopt avx2 avx512f avx512_skx"
  63. >>> cco = CCompilerOpt(cc_instance)
  64. >>> cco.try_dispatch(["group_inside.c"])
  65. conf_c_prefix : str
  66. The prefix of public C definitions. Default is ``"NPY_"``.
  67. conf_c_prefix_ : str
  68. The prefix of internal C definitions. Default is ``"NPY__"``.
  69. conf_cc_flags : dict
  70. Nested dictionaries defining several compiler flags
  71. that linked to some major functions, the main key
  72. represent the compiler name and sub-keys represent
  73. flags names. Default is already covers all supported
  74. **C** compilers.
  75. Sub-keys explained as follows:
  76. "native": str or None
  77. used by argument option `native`, to detect the current
  78. machine support via the compiler.
  79. "werror": str or None
  80. utilized to treat warning as errors during testing CPU features
  81. against the compiler and also for target's policy `$werror`
  82. via dispatch-able sources.
  83. "maxopt": str or None
  84. utilized for target's policy '$maxopt' and the value should
  85. contains the maximum acceptable optimization by the compiler.
  86. e.g. in gcc `'-O3'`
  87. **Notes**:
  88. * case-sensitive for compiler names and flags
  89. * use space to separate multiple flags
  90. * any flag will tested against the compiler and it will skipped
  91. if it's not applicable.
  92. conf_min_features : dict
  93. A dictionary defines the used CPU features for
  94. argument option `'min'`, the key represent the CPU architecture
  95. name e.g. `'x86'`. Default values provide the best effort
  96. on wide range of users platforms.
  97. **Note**: case-sensitive for architecture names.
  98. conf_features : dict
  99. Nested dictionaries used for identifying the CPU features.
  100. the primary key is represented as a feature name or group name
  101. that gathers several features. Default values covers all
  102. supported features but without the major options like "flags",
  103. these undefined options handle it by method `conf_features_partial()`.
  104. Default value is covers almost all CPU features for *X86*, *IBM/Power64*
  105. and *ARM 7/8*.
  106. Sub-keys explained as follows:
  107. "implies" : str or list, optional,
  108. List of CPU feature names to be implied by it,
  109. the feature name must be defined within `conf_features`.
  110. Default is None.
  111. "flags": str or list, optional
  112. List of compiler flags. Default is None.
  113. "detect": str or list, optional
  114. List of CPU feature names that required to be detected
  115. in runtime. By default, its the feature name or features
  116. in "group" if its specified.
  117. "implies_detect": bool, optional
  118. If True, all "detect" of implied features will be combined.
  119. Default is True. see `feature_detect()`.
  120. "group": str or list, optional
  121. Same as "implies" but doesn't require the feature name to be
  122. defined within `conf_features`.
  123. "interest": int, required
  124. a key for sorting CPU features
  125. "headers": str or list, optional
  126. intrinsics C header file
  127. "disable": str, optional
  128. force disable feature, the string value should contains the
  129. reason of disabling.
  130. "autovec": bool or None, optional
  131. True or False to declare that CPU feature can be auto-vectorized
  132. by the compiler.
  133. By default(None), treated as True if the feature contains at
  134. least one applicable flag. see `feature_can_autovec()`
  135. "extra_checks": str or list, optional
  136. Extra test case names for the CPU feature that need to be tested
  137. against the compiler.
  138. Each test case must have a C file named ``extra_xxxx.c``, where
  139. ``xxxx`` is the case name in lower case, under 'conf_check_path'.
  140. It should contain at least one intrinsic or function related to the test case.
  141. If the compiler able to successfully compile the C file then `CCompilerOpt`
  142. will add a C ``#define`` for it into the main dispatch header, e.g.
  143. ``#define {conf_c_prefix}_XXXX`` where ``XXXX`` is the case name in upper case.
  144. **NOTES**:
  145. * space can be used as separator with options that supports "str or list"
  146. * case-sensitive for all values and feature name must be in upper-case.
  147. * if flags aren't applicable, its will skipped rather than disable the
  148. CPU feature
  149. * the CPU feature will disabled if the compiler fail to compile
  150. the test file
  151. """
  152. conf_nocache = False
  153. conf_noopt = False
  154. conf_cache_factors = None
  155. conf_tmp_path = None
  156. conf_check_path = os.path.join(
  157. os.path.dirname(os.path.realpath(__file__)), "checks"
  158. )
  159. conf_target_groups = {}
  160. conf_c_prefix = 'NPY_'
  161. conf_c_prefix_ = 'NPY__'
  162. conf_cc_flags = dict(
  163. gcc = dict(
  164. # native should always fail on arm and ppc64,
  165. # native usually works only with x86
  166. native = '-march=native',
  167. opt = '-O3',
  168. werror = '-Werror',
  169. ),
  170. clang = dict(
  171. native = '-march=native',
  172. opt = "-O3",
  173. # One of the following flags needs to be applicable for Clang to
  174. # guarantee the sanity of the testing process, however in certain
  175. # cases `-Werror` gets skipped during the availability test due to
  176. # "unused arguments" warnings.
  177. # see https://github.com/numpy/numpy/issues/19624
  178. werror = '-Werror=switch -Werror',
  179. ),
  180. icc = dict(
  181. native = '-xHost',
  182. opt = '-O3',
  183. werror = '-Werror',
  184. ),
  185. iccw = dict(
  186. native = '/QxHost',
  187. opt = '/O3',
  188. werror = '/Werror',
  189. ),
  190. msvc = dict(
  191. native = None,
  192. opt = '/O2',
  193. werror = '/WX',
  194. )
  195. )
  196. conf_min_features = dict(
  197. x86 = "SSE SSE2",
  198. x64 = "SSE SSE2 SSE3",
  199. ppc64 = '', # play it safe
  200. ppc64le = "VSX VSX2",
  201. s390x = '',
  202. armhf = '', # play it safe
  203. aarch64 = "NEON NEON_FP16 NEON_VFPV4 ASIMD"
  204. )
  205. conf_features = dict(
  206. # X86
  207. SSE = dict(
  208. interest=1, headers="xmmintrin.h",
  209. # enabling SSE without SSE2 is useless also
  210. # it's non-optional for x86_64
  211. implies="SSE2"
  212. ),
  213. SSE2 = dict(interest=2, implies="SSE", headers="emmintrin.h"),
  214. SSE3 = dict(interest=3, implies="SSE2", headers="pmmintrin.h"),
  215. SSSE3 = dict(interest=4, implies="SSE3", headers="tmmintrin.h"),
  216. SSE41 = dict(interest=5, implies="SSSE3", headers="smmintrin.h"),
  217. POPCNT = dict(interest=6, implies="SSE41", headers="popcntintrin.h"),
  218. SSE42 = dict(interest=7, implies="POPCNT"),
  219. AVX = dict(
  220. interest=8, implies="SSE42", headers="immintrin.h",
  221. implies_detect=False
  222. ),
  223. XOP = dict(interest=9, implies="AVX", headers="x86intrin.h"),
  224. FMA4 = dict(interest=10, implies="AVX", headers="x86intrin.h"),
  225. F16C = dict(interest=11, implies="AVX"),
  226. FMA3 = dict(interest=12, implies="F16C"),
  227. AVX2 = dict(interest=13, implies="F16C"),
  228. AVX512F = dict(
  229. interest=20, implies="FMA3 AVX2", implies_detect=False,
  230. extra_checks="AVX512F_REDUCE"
  231. ),
  232. AVX512CD = dict(interest=21, implies="AVX512F"),
  233. AVX512_KNL = dict(
  234. interest=40, implies="AVX512CD", group="AVX512ER AVX512PF",
  235. detect="AVX512_KNL", implies_detect=False
  236. ),
  237. AVX512_KNM = dict(
  238. interest=41, implies="AVX512_KNL",
  239. group="AVX5124FMAPS AVX5124VNNIW AVX512VPOPCNTDQ",
  240. detect="AVX512_KNM", implies_detect=False
  241. ),
  242. AVX512_SKX = dict(
  243. interest=42, implies="AVX512CD", group="AVX512VL AVX512BW AVX512DQ",
  244. detect="AVX512_SKX", implies_detect=False,
  245. extra_checks="AVX512BW_MASK AVX512DQ_MASK"
  246. ),
  247. AVX512_CLX = dict(
  248. interest=43, implies="AVX512_SKX", group="AVX512VNNI",
  249. detect="AVX512_CLX"
  250. ),
  251. AVX512_CNL = dict(
  252. interest=44, implies="AVX512_SKX", group="AVX512IFMA AVX512VBMI",
  253. detect="AVX512_CNL", implies_detect=False
  254. ),
  255. AVX512_ICL = dict(
  256. interest=45, implies="AVX512_CLX AVX512_CNL",
  257. group="AVX512VBMI2 AVX512BITALG AVX512VPOPCNTDQ",
  258. detect="AVX512_ICL", implies_detect=False
  259. ),
  260. # IBM/Power
  261. ## Power7/ISA 2.06
  262. VSX = dict(interest=1, headers="altivec.h", extra_checks="VSX_ASM"),
  263. ## Power8/ISA 2.07
  264. VSX2 = dict(interest=2, implies="VSX", implies_detect=False),
  265. ## Power9/ISA 3.00
  266. VSX3 = dict(interest=3, implies="VSX2", implies_detect=False),
  267. ## Power10/ISA 3.1
  268. VSX4 = dict(interest=4, implies="VSX3", implies_detect=False,
  269. extra_checks="VSX4_MMA"),
  270. # IBM/Z
  271. ## VX(z13) support
  272. VX = dict(interest=1, headers="vecintrin.h"),
  273. ## Vector-Enhancements Facility
  274. VXE = dict(interest=2, implies="VX", implies_detect=False),
  275. ## Vector-Enhancements Facility 2
  276. VXE2 = dict(interest=3, implies="VXE", implies_detect=False),
  277. # ARM
  278. NEON = dict(interest=1, headers="arm_neon.h"),
  279. NEON_FP16 = dict(interest=2, implies="NEON"),
  280. ## FMA
  281. NEON_VFPV4 = dict(interest=3, implies="NEON_FP16"),
  282. ## Advanced SIMD
  283. ASIMD = dict(interest=4, implies="NEON_FP16 NEON_VFPV4", implies_detect=False),
  284. ## ARMv8.2 half-precision & vector arithm
  285. ASIMDHP = dict(interest=5, implies="ASIMD"),
  286. ## ARMv8.2 dot product
  287. ASIMDDP = dict(interest=6, implies="ASIMD"),
  288. ## ARMv8.2 Single & half-precision Multiply
  289. ASIMDFHM = dict(interest=7, implies="ASIMDHP"),
  290. )
  291. def conf_features_partial(self):
  292. """Return a dictionary of supported CPU features by the platform,
  293. and accumulate the rest of undefined options in `conf_features`,
  294. the returned dict has same rules and notes in
  295. class attribute `conf_features`, also its override
  296. any options that been set in 'conf_features'.
  297. """
  298. if self.cc_noopt:
  299. # optimization is disabled
  300. return {}
  301. on_x86 = self.cc_on_x86 or self.cc_on_x64
  302. is_unix = self.cc_is_gcc or self.cc_is_clang
  303. if on_x86 and is_unix: return dict(
  304. SSE = dict(flags="-msse"),
  305. SSE2 = dict(flags="-msse2"),
  306. SSE3 = dict(flags="-msse3"),
  307. SSSE3 = dict(flags="-mssse3"),
  308. SSE41 = dict(flags="-msse4.1"),
  309. POPCNT = dict(flags="-mpopcnt"),
  310. SSE42 = dict(flags="-msse4.2"),
  311. AVX = dict(flags="-mavx"),
  312. F16C = dict(flags="-mf16c"),
  313. XOP = dict(flags="-mxop"),
  314. FMA4 = dict(flags="-mfma4"),
  315. FMA3 = dict(flags="-mfma"),
  316. AVX2 = dict(flags="-mavx2"),
  317. AVX512F = dict(flags="-mavx512f -mno-mmx"),
  318. AVX512CD = dict(flags="-mavx512cd"),
  319. AVX512_KNL = dict(flags="-mavx512er -mavx512pf"),
  320. AVX512_KNM = dict(
  321. flags="-mavx5124fmaps -mavx5124vnniw -mavx512vpopcntdq"
  322. ),
  323. AVX512_SKX = dict(flags="-mavx512vl -mavx512bw -mavx512dq"),
  324. AVX512_CLX = dict(flags="-mavx512vnni"),
  325. AVX512_CNL = dict(flags="-mavx512ifma -mavx512vbmi"),
  326. AVX512_ICL = dict(
  327. flags="-mavx512vbmi2 -mavx512bitalg -mavx512vpopcntdq"
  328. )
  329. )
  330. if on_x86 and self.cc_is_icc: return dict(
  331. SSE = dict(flags="-msse"),
  332. SSE2 = dict(flags="-msse2"),
  333. SSE3 = dict(flags="-msse3"),
  334. SSSE3 = dict(flags="-mssse3"),
  335. SSE41 = dict(flags="-msse4.1"),
  336. POPCNT = {},
  337. SSE42 = dict(flags="-msse4.2"),
  338. AVX = dict(flags="-mavx"),
  339. F16C = {},
  340. XOP = dict(disable="Intel Compiler doesn't support it"),
  341. FMA4 = dict(disable="Intel Compiler doesn't support it"),
  342. # Intel Compiler doesn't support AVX2 or FMA3 independently
  343. FMA3 = dict(
  344. implies="F16C AVX2", flags="-march=core-avx2"
  345. ),
  346. AVX2 = dict(implies="FMA3", flags="-march=core-avx2"),
  347. # Intel Compiler doesn't support AVX512F or AVX512CD independently
  348. AVX512F = dict(
  349. implies="AVX2 AVX512CD", flags="-march=common-avx512"
  350. ),
  351. AVX512CD = dict(
  352. implies="AVX2 AVX512F", flags="-march=common-avx512"
  353. ),
  354. AVX512_KNL = dict(flags="-xKNL"),
  355. AVX512_KNM = dict(flags="-xKNM"),
  356. AVX512_SKX = dict(flags="-xSKYLAKE-AVX512"),
  357. AVX512_CLX = dict(flags="-xCASCADELAKE"),
  358. AVX512_CNL = dict(flags="-xCANNONLAKE"),
  359. AVX512_ICL = dict(flags="-xICELAKE-CLIENT"),
  360. )
  361. if on_x86 and self.cc_is_iccw: return dict(
  362. SSE = dict(flags="/arch:SSE"),
  363. SSE2 = dict(flags="/arch:SSE2"),
  364. SSE3 = dict(flags="/arch:SSE3"),
  365. SSSE3 = dict(flags="/arch:SSSE3"),
  366. SSE41 = dict(flags="/arch:SSE4.1"),
  367. POPCNT = {},
  368. SSE42 = dict(flags="/arch:SSE4.2"),
  369. AVX = dict(flags="/arch:AVX"),
  370. F16C = {},
  371. XOP = dict(disable="Intel Compiler doesn't support it"),
  372. FMA4 = dict(disable="Intel Compiler doesn't support it"),
  373. # Intel Compiler doesn't support FMA3 or AVX2 independently
  374. FMA3 = dict(
  375. implies="F16C AVX2", flags="/arch:CORE-AVX2"
  376. ),
  377. AVX2 = dict(
  378. implies="FMA3", flags="/arch:CORE-AVX2"
  379. ),
  380. # Intel Compiler doesn't support AVX512F or AVX512CD independently
  381. AVX512F = dict(
  382. implies="AVX2 AVX512CD", flags="/Qx:COMMON-AVX512"
  383. ),
  384. AVX512CD = dict(
  385. implies="AVX2 AVX512F", flags="/Qx:COMMON-AVX512"
  386. ),
  387. AVX512_KNL = dict(flags="/Qx:KNL"),
  388. AVX512_KNM = dict(flags="/Qx:KNM"),
  389. AVX512_SKX = dict(flags="/Qx:SKYLAKE-AVX512"),
  390. AVX512_CLX = dict(flags="/Qx:CASCADELAKE"),
  391. AVX512_CNL = dict(flags="/Qx:CANNONLAKE"),
  392. AVX512_ICL = dict(flags="/Qx:ICELAKE-CLIENT")
  393. )
  394. if on_x86 and self.cc_is_msvc: return dict(
  395. SSE = dict(flags="/arch:SSE") if self.cc_on_x86 else {},
  396. SSE2 = dict(flags="/arch:SSE2") if self.cc_on_x86 else {},
  397. SSE3 = {},
  398. SSSE3 = {},
  399. SSE41 = {},
  400. POPCNT = dict(headers="nmmintrin.h"),
  401. SSE42 = {},
  402. AVX = dict(flags="/arch:AVX"),
  403. F16C = {},
  404. XOP = dict(headers="ammintrin.h"),
  405. FMA4 = dict(headers="ammintrin.h"),
  406. # MSVC doesn't support FMA3 or AVX2 independently
  407. FMA3 = dict(
  408. implies="F16C AVX2", flags="/arch:AVX2"
  409. ),
  410. AVX2 = dict(
  411. implies="F16C FMA3", flags="/arch:AVX2"
  412. ),
  413. # MSVC doesn't support AVX512F or AVX512CD independently,
  414. # always generate instructions belong to (VL/VW/DQ)
  415. AVX512F = dict(
  416. implies="AVX2 AVX512CD AVX512_SKX", flags="/arch:AVX512"
  417. ),
  418. AVX512CD = dict(
  419. implies="AVX512F AVX512_SKX", flags="/arch:AVX512"
  420. ),
  421. AVX512_KNL = dict(
  422. disable="MSVC compiler doesn't support it"
  423. ),
  424. AVX512_KNM = dict(
  425. disable="MSVC compiler doesn't support it"
  426. ),
  427. AVX512_SKX = dict(flags="/arch:AVX512"),
  428. AVX512_CLX = {},
  429. AVX512_CNL = {},
  430. AVX512_ICL = {}
  431. )
  432. on_power = self.cc_on_ppc64le or self.cc_on_ppc64
  433. if on_power:
  434. partial = dict(
  435. VSX = dict(
  436. implies=("VSX2" if self.cc_on_ppc64le else ""),
  437. flags="-mvsx"
  438. ),
  439. VSX2 = dict(
  440. flags="-mcpu=power8", implies_detect=False
  441. ),
  442. VSX3 = dict(
  443. flags="-mcpu=power9 -mtune=power9", implies_detect=False
  444. ),
  445. VSX4 = dict(
  446. flags="-mcpu=power10 -mtune=power10", implies_detect=False
  447. )
  448. )
  449. if self.cc_is_clang:
  450. partial["VSX"]["flags"] = "-maltivec -mvsx"
  451. partial["VSX2"]["flags"] = "-mpower8-vector"
  452. partial["VSX3"]["flags"] = "-mpower9-vector"
  453. partial["VSX4"]["flags"] = "-mpower10-vector"
  454. return partial
  455. on_zarch = self.cc_on_s390x
  456. if on_zarch:
  457. partial = dict(
  458. VX = dict(
  459. flags="-march=arch11 -mzvector"
  460. ),
  461. VXE = dict(
  462. flags="-march=arch12", implies_detect=False
  463. ),
  464. VXE2 = dict(
  465. flags="-march=arch13", implies_detect=False
  466. )
  467. )
  468. return partial
  469. if self.cc_on_aarch64 and is_unix: return dict(
  470. NEON = dict(
  471. implies="NEON_FP16 NEON_VFPV4 ASIMD", autovec=True
  472. ),
  473. NEON_FP16 = dict(
  474. implies="NEON NEON_VFPV4 ASIMD", autovec=True
  475. ),
  476. NEON_VFPV4 = dict(
  477. implies="NEON NEON_FP16 ASIMD", autovec=True
  478. ),
  479. ASIMD = dict(
  480. implies="NEON NEON_FP16 NEON_VFPV4", autovec=True
  481. ),
  482. ASIMDHP = dict(
  483. flags="-march=armv8.2-a+fp16"
  484. ),
  485. ASIMDDP = dict(
  486. flags="-march=armv8.2-a+dotprod"
  487. ),
  488. ASIMDFHM = dict(
  489. flags="-march=armv8.2-a+fp16fml"
  490. ),
  491. )
  492. if self.cc_on_armhf and is_unix: return dict(
  493. NEON = dict(
  494. flags="-mfpu=neon"
  495. ),
  496. NEON_FP16 = dict(
  497. flags="-mfpu=neon-fp16 -mfp16-format=ieee"
  498. ),
  499. NEON_VFPV4 = dict(
  500. flags="-mfpu=neon-vfpv4",
  501. ),
  502. ASIMD = dict(
  503. flags="-mfpu=neon-fp-armv8 -march=armv8-a+simd",
  504. ),
  505. ASIMDHP = dict(
  506. flags="-march=armv8.2-a+fp16"
  507. ),
  508. ASIMDDP = dict(
  509. flags="-march=armv8.2-a+dotprod",
  510. ),
  511. ASIMDFHM = dict(
  512. flags="-march=armv8.2-a+fp16fml"
  513. )
  514. )
  515. # TODO: ARM MSVC
  516. return {}
  517. def __init__(self):
  518. if self.conf_tmp_path is None:
  519. import shutil
  520. import tempfile
  521. tmp = tempfile.mkdtemp()
  522. def rm_temp():
  523. try:
  524. shutil.rmtree(tmp)
  525. except OSError:
  526. pass
  527. atexit.register(rm_temp)
  528. self.conf_tmp_path = tmp
  529. if self.conf_cache_factors is None:
  530. self.conf_cache_factors = [
  531. os.path.getmtime(__file__),
  532. self.conf_nocache
  533. ]
  534. class _Distutils:
  535. """A helper class that provides a collection of fundamental methods
  536. implemented in a top of Python and NumPy Distutils.
  537. The idea behind this class is to gather all methods that it may
  538. need to override in case of reuse 'CCompilerOpt' in environment
  539. different than of what NumPy has.
  540. Parameters
  541. ----------
  542. ccompiler : `CCompiler`
  543. The generate instance that returned from `distutils.ccompiler.new_compiler()`.
  544. """
  545. def __init__(self, ccompiler):
  546. self._ccompiler = ccompiler
  547. def dist_compile(self, sources, flags, ccompiler=None, **kwargs):
  548. """Wrap CCompiler.compile()"""
  549. assert(isinstance(sources, list))
  550. assert(isinstance(flags, list))
  551. flags = kwargs.pop("extra_postargs", []) + flags
  552. if not ccompiler:
  553. ccompiler = self._ccompiler
  554. return ccompiler.compile(sources, extra_postargs=flags, **kwargs)
  555. def dist_test(self, source, flags, macros=[]):
  556. """Return True if 'CCompiler.compile()' able to compile
  557. a source file with certain flags.
  558. """
  559. assert(isinstance(source, str))
  560. from distutils.errors import CompileError
  561. cc = self._ccompiler;
  562. bk_spawn = getattr(cc, 'spawn', None)
  563. if bk_spawn:
  564. cc_type = getattr(self._ccompiler, "compiler_type", "")
  565. if cc_type in ("msvc",):
  566. setattr(cc, 'spawn', self._dist_test_spawn_paths)
  567. else:
  568. setattr(cc, 'spawn', self._dist_test_spawn)
  569. test = False
  570. try:
  571. self.dist_compile(
  572. [source], flags, macros=macros, output_dir=self.conf_tmp_path
  573. )
  574. test = True
  575. except CompileError as e:
  576. self.dist_log(str(e), stderr=True)
  577. if bk_spawn:
  578. setattr(cc, 'spawn', bk_spawn)
  579. return test
  580. def dist_info(self):
  581. """
  582. Return a tuple containing info about (platform, compiler, extra_args),
  583. required by the abstract class '_CCompiler' for discovering the
  584. platform environment. This is also used as a cache factor in order
  585. to detect any changes happening from outside.
  586. """
  587. if hasattr(self, "_dist_info"):
  588. return self._dist_info
  589. cc_type = getattr(self._ccompiler, "compiler_type", '')
  590. if cc_type in ("intelem", "intelemw"):
  591. platform = "x86_64"
  592. elif cc_type in ("intel", "intelw", "intele"):
  593. platform = "x86"
  594. else:
  595. from distutils.util import get_platform
  596. platform = get_platform()
  597. cc_info = getattr(self._ccompiler, "compiler", getattr(self._ccompiler, "compiler_so", ''))
  598. if not cc_type or cc_type == "unix":
  599. if hasattr(cc_info, "__iter__"):
  600. compiler = cc_info[0]
  601. else:
  602. compiler = str(cc_info)
  603. else:
  604. compiler = cc_type
  605. if hasattr(cc_info, "__iter__") and len(cc_info) > 1:
  606. extra_args = ' '.join(cc_info[1:])
  607. else:
  608. extra_args = os.environ.get("CFLAGS", "")
  609. extra_args += os.environ.get("CPPFLAGS", "")
  610. self._dist_info = (platform, compiler, extra_args)
  611. return self._dist_info
  612. @staticmethod
  613. def dist_error(*args):
  614. """Raise a compiler error"""
  615. from distutils.errors import CompileError
  616. raise CompileError(_Distutils._dist_str(*args))
  617. @staticmethod
  618. def dist_fatal(*args):
  619. """Raise a distutils error"""
  620. from distutils.errors import DistutilsError
  621. raise DistutilsError(_Distutils._dist_str(*args))
  622. @staticmethod
  623. def dist_log(*args, stderr=False):
  624. """Print a console message"""
  625. from numpy.distutils import log
  626. out = _Distutils._dist_str(*args)
  627. if stderr:
  628. log.warn(out)
  629. else:
  630. log.info(out)
  631. @staticmethod
  632. def dist_load_module(name, path):
  633. """Load a module from file, required by the abstract class '_Cache'."""
  634. from .misc_util import exec_mod_from_location
  635. try:
  636. return exec_mod_from_location(name, path)
  637. except Exception as e:
  638. _Distutils.dist_log(e, stderr=True)
  639. return None
  640. @staticmethod
  641. def _dist_str(*args):
  642. """Return a string to print by log and errors."""
  643. def to_str(arg):
  644. if not isinstance(arg, str) and hasattr(arg, '__iter__'):
  645. ret = []
  646. for a in arg:
  647. ret.append(to_str(a))
  648. return '('+ ' '.join(ret) + ')'
  649. return str(arg)
  650. stack = inspect.stack()[2]
  651. start = "CCompilerOpt.%s[%d] : " % (stack.function, stack.lineno)
  652. out = ' '.join([
  653. to_str(a)
  654. for a in (*args,)
  655. ])
  656. return start + out
  657. def _dist_test_spawn_paths(self, cmd, display=None):
  658. """
  659. Fix msvc SDK ENV path same as distutils do
  660. without it we get c1: fatal error C1356: unable to find mspdbcore.dll
  661. """
  662. if not hasattr(self._ccompiler, "_paths"):
  663. self._dist_test_spawn(cmd)
  664. return
  665. old_path = os.getenv("path")
  666. try:
  667. os.environ["path"] = self._ccompiler._paths
  668. self._dist_test_spawn(cmd)
  669. finally:
  670. os.environ["path"] = old_path
  671. _dist_warn_regex = re.compile(
  672. # intel and msvc compilers don't raise
  673. # fatal errors when flags are wrong or unsupported
  674. ".*("
  675. "warning D9002|" # msvc, it should be work with any language.
  676. "invalid argument for option" # intel
  677. ").*"
  678. )
  679. @staticmethod
  680. def _dist_test_spawn(cmd, display=None):
  681. try:
  682. o = subprocess.check_output(cmd, stderr=subprocess.STDOUT,
  683. text=True)
  684. if o and re.match(_Distutils._dist_warn_regex, o):
  685. _Distutils.dist_error(
  686. "Flags in command", cmd ,"aren't supported by the compiler"
  687. ", output -> \n%s" % o
  688. )
  689. except subprocess.CalledProcessError as exc:
  690. o = exc.output
  691. s = exc.returncode
  692. except OSError as e:
  693. o = e
  694. s = 127
  695. else:
  696. return None
  697. _Distutils.dist_error(
  698. "Command", cmd, "failed with exit status %d output -> \n%s" % (
  699. s, o
  700. ))
  701. _share_cache = {}
  702. class _Cache:
  703. """An abstract class handles caching functionality, provides two
  704. levels of caching, in-memory by share instances attributes among
  705. each other and by store attributes into files.
  706. **Note**:
  707. any attributes that start with ``_`` or ``conf_`` will be ignored.
  708. Parameters
  709. ----------
  710. cache_path : str or None
  711. The path of cache file, if None then cache in file will disabled.
  712. *factors :
  713. The caching factors that need to utilize next to `conf_cache_factors`.
  714. Attributes
  715. ----------
  716. cache_private : set
  717. Hold the attributes that need be skipped from "in-memory cache".
  718. cache_infile : bool
  719. Utilized during initializing this class, to determine if the cache was able
  720. to loaded from the specified cache path in 'cache_path'.
  721. """
  722. # skip attributes from cache
  723. _cache_ignore = re.compile("^(_|conf_)")
  724. def __init__(self, cache_path=None, *factors):
  725. self.cache_me = {}
  726. self.cache_private = set()
  727. self.cache_infile = False
  728. self._cache_path = None
  729. if self.conf_nocache:
  730. self.dist_log("cache is disabled by `Config`")
  731. return
  732. self._cache_hash = self.cache_hash(*factors, *self.conf_cache_factors)
  733. self._cache_path = cache_path
  734. if cache_path:
  735. if os.path.exists(cache_path):
  736. self.dist_log("load cache from file ->", cache_path)
  737. cache_mod = self.dist_load_module("cache", cache_path)
  738. if not cache_mod:
  739. self.dist_log(
  740. "unable to load the cache file as a module",
  741. stderr=True
  742. )
  743. elif not hasattr(cache_mod, "hash") or \
  744. not hasattr(cache_mod, "data"):
  745. self.dist_log("invalid cache file", stderr=True)
  746. elif self._cache_hash == cache_mod.hash:
  747. self.dist_log("hit the file cache")
  748. for attr, val in cache_mod.data.items():
  749. setattr(self, attr, val)
  750. self.cache_infile = True
  751. else:
  752. self.dist_log("miss the file cache")
  753. if not self.cache_infile:
  754. other_cache = _share_cache.get(self._cache_hash)
  755. if other_cache:
  756. self.dist_log("hit the memory cache")
  757. for attr, val in other_cache.__dict__.items():
  758. if attr in other_cache.cache_private or \
  759. re.match(self._cache_ignore, attr):
  760. continue
  761. setattr(self, attr, val)
  762. _share_cache[self._cache_hash] = self
  763. atexit.register(self.cache_flush)
  764. def __del__(self):
  765. for h, o in _share_cache.items():
  766. if o == self:
  767. _share_cache.pop(h)
  768. break
  769. def cache_flush(self):
  770. """
  771. Force update the cache.
  772. """
  773. if not self._cache_path:
  774. return
  775. # TODO: don't write if the cache doesn't change
  776. self.dist_log("write cache to path ->", self._cache_path)
  777. cdict = self.__dict__.copy()
  778. for attr in self.__dict__.keys():
  779. if re.match(self._cache_ignore, attr):
  780. cdict.pop(attr)
  781. d = os.path.dirname(self._cache_path)
  782. if not os.path.exists(d):
  783. os.makedirs(d)
  784. repr_dict = pprint.pformat(cdict, compact=True)
  785. with open(self._cache_path, "w") as f:
  786. f.write(textwrap.dedent("""\
  787. # AUTOGENERATED DON'T EDIT
  788. # Please make changes to the code generator \
  789. (distutils/ccompiler_opt.py)
  790. hash = {}
  791. data = \\
  792. """).format(self._cache_hash))
  793. f.write(repr_dict)
  794. def cache_hash(self, *factors):
  795. # is there a built-in non-crypto hash?
  796. # sdbm
  797. chash = 0
  798. for f in factors:
  799. for char in str(f):
  800. chash = ord(char) + (chash << 6) + (chash << 16) - chash
  801. chash &= 0xFFFFFFFF
  802. return chash
  803. @staticmethod
  804. def me(cb):
  805. """
  806. A static method that can be treated as a decorator to
  807. dynamically cache certain methods.
  808. """
  809. def cache_wrap_me(self, *args, **kwargs):
  810. # good for normal args
  811. cache_key = str((
  812. cb.__name__, *args, *kwargs.keys(), *kwargs.values()
  813. ))
  814. if cache_key in self.cache_me:
  815. return self.cache_me[cache_key]
  816. ccb = cb(self, *args, **kwargs)
  817. self.cache_me[cache_key] = ccb
  818. return ccb
  819. return cache_wrap_me
  820. class _CCompiler:
  821. """A helper class for `CCompilerOpt` containing all utilities that
  822. related to the fundamental compiler's functions.
  823. Attributes
  824. ----------
  825. cc_on_x86 : bool
  826. True when the target architecture is 32-bit x86
  827. cc_on_x64 : bool
  828. True when the target architecture is 64-bit x86
  829. cc_on_ppc64 : bool
  830. True when the target architecture is 64-bit big-endian powerpc
  831. cc_on_ppc64le : bool
  832. True when the target architecture is 64-bit litle-endian powerpc
  833. cc_on_s390x : bool
  834. True when the target architecture is IBM/ZARCH on linux
  835. cc_on_armhf : bool
  836. True when the target architecture is 32-bit ARMv7+
  837. cc_on_aarch64 : bool
  838. True when the target architecture is 64-bit Armv8-a+
  839. cc_on_noarch : bool
  840. True when the target architecture is unknown or not supported
  841. cc_is_gcc : bool
  842. True if the compiler is GNU or
  843. if the compiler is unknown
  844. cc_is_clang : bool
  845. True if the compiler is Clang
  846. cc_is_icc : bool
  847. True if the compiler is Intel compiler (unix like)
  848. cc_is_iccw : bool
  849. True if the compiler is Intel compiler (msvc like)
  850. cc_is_nocc : bool
  851. True if the compiler isn't supported directly,
  852. Note: that cause a fail-back to gcc
  853. cc_has_debug : bool
  854. True if the compiler has debug flags
  855. cc_has_native : bool
  856. True if the compiler has native flags
  857. cc_noopt : bool
  858. True if the compiler has definition 'DISABLE_OPT*',
  859. or 'cc_on_noarch' is True
  860. cc_march : str
  861. The target architecture name, or "unknown" if
  862. the architecture isn't supported
  863. cc_name : str
  864. The compiler name, or "unknown" if the compiler isn't supported
  865. cc_flags : dict
  866. Dictionary containing the initialized flags of `_Config.conf_cc_flags`
  867. """
  868. def __init__(self):
  869. if hasattr(self, "cc_is_cached"):
  870. return
  871. # attr regex compiler-expression
  872. detect_arch = (
  873. ("cc_on_x64", ".*(x|x86_|amd)64.*", ""),
  874. ("cc_on_x86", ".*(win32|x86|i386|i686).*", ""),
  875. ("cc_on_ppc64le", ".*(powerpc|ppc)64(el|le).*|.*powerpc.*",
  876. "defined(__powerpc64__) && "
  877. "defined(__LITTLE_ENDIAN__)"),
  878. ("cc_on_ppc64", ".*(powerpc|ppc).*|.*powerpc.*",
  879. "defined(__powerpc64__) && "
  880. "defined(__BIG_ENDIAN__)"),
  881. ("cc_on_aarch64", ".*(aarch64|arm64).*", ""),
  882. ("cc_on_armhf", ".*arm.*", "defined(__ARM_ARCH_7__) || "
  883. "defined(__ARM_ARCH_7A__)"),
  884. ("cc_on_s390x", ".*s390x.*", ""),
  885. # undefined platform
  886. ("cc_on_noarch", "", ""),
  887. )
  888. detect_compiler = (
  889. ("cc_is_gcc", r".*(gcc|gnu\-g).*", ""),
  890. ("cc_is_clang", ".*clang.*", ""),
  891. # intel msvc like
  892. ("cc_is_iccw", ".*(intelw|intelemw|iccw).*", ""),
  893. ("cc_is_icc", ".*(intel|icc).*", ""), # intel unix like
  894. ("cc_is_msvc", ".*msvc.*", ""),
  895. # undefined compiler will be treat it as gcc
  896. ("cc_is_nocc", "", ""),
  897. )
  898. detect_args = (
  899. ("cc_has_debug", ".*(O0|Od|ggdb|coverage|debug:full).*", ""),
  900. ("cc_has_native", ".*(-march=native|-xHost|/QxHost).*", ""),
  901. # in case if the class run with -DNPY_DISABLE_OPTIMIZATION
  902. ("cc_noopt", ".*DISABLE_OPT.*", ""),
  903. )
  904. dist_info = self.dist_info()
  905. platform, compiler_info, extra_args = dist_info
  906. # set False to all attrs
  907. for section in (detect_arch, detect_compiler, detect_args):
  908. for attr, rgex, cexpr in section:
  909. setattr(self, attr, False)
  910. for detect, searchin in ((detect_arch, platform), (detect_compiler, compiler_info)):
  911. for attr, rgex, cexpr in detect:
  912. if rgex and not re.match(rgex, searchin, re.IGNORECASE):
  913. continue
  914. if cexpr and not self.cc_test_cexpr(cexpr):
  915. continue
  916. setattr(self, attr, True)
  917. break
  918. for attr, rgex, cexpr in detect_args:
  919. if rgex and not re.match(rgex, extra_args, re.IGNORECASE):
  920. continue
  921. if cexpr and not self.cc_test_cexpr(cexpr):
  922. continue
  923. setattr(self, attr, True)
  924. if self.cc_on_noarch:
  925. self.dist_log(
  926. "unable to detect CPU architecture which lead to disable the optimization. "
  927. f"check dist_info:<<\n{dist_info}\n>>",
  928. stderr=True
  929. )
  930. self.cc_noopt = True
  931. if self.conf_noopt:
  932. self.dist_log("Optimization is disabled by the Config", stderr=True)
  933. self.cc_noopt = True
  934. if self.cc_is_nocc:
  935. """
  936. mingw can be treated as a gcc, and also xlc even if it based on clang,
  937. but still has the same gcc optimization flags.
  938. """
  939. self.dist_log(
  940. "unable to detect compiler type which leads to treating it as GCC. "
  941. "this is a normal behavior if you're using gcc-like compiler such as MinGW or IBM/XLC."
  942. f"check dist_info:<<\n{dist_info}\n>>",
  943. stderr=True
  944. )
  945. self.cc_is_gcc = True
  946. self.cc_march = "unknown"
  947. for arch in ("x86", "x64", "ppc64", "ppc64le",
  948. "armhf", "aarch64", "s390x"):
  949. if getattr(self, "cc_on_" + arch):
  950. self.cc_march = arch
  951. break
  952. self.cc_name = "unknown"
  953. for name in ("gcc", "clang", "iccw", "icc", "msvc"):
  954. if getattr(self, "cc_is_" + name):
  955. self.cc_name = name
  956. break
  957. self.cc_flags = {}
  958. compiler_flags = self.conf_cc_flags.get(self.cc_name)
  959. if compiler_flags is None:
  960. self.dist_fatal(
  961. "undefined flag for compiler '%s', "
  962. "leave an empty dict instead" % self.cc_name
  963. )
  964. for name, flags in compiler_flags.items():
  965. self.cc_flags[name] = nflags = []
  966. if flags:
  967. assert(isinstance(flags, str))
  968. flags = flags.split()
  969. for f in flags:
  970. if self.cc_test_flags([f]):
  971. nflags.append(f)
  972. self.cc_is_cached = True
  973. @_Cache.me
  974. def cc_test_flags(self, flags):
  975. """
  976. Returns True if the compiler supports 'flags'.
  977. """
  978. assert(isinstance(flags, list))
  979. self.dist_log("testing flags", flags)
  980. test_path = os.path.join(self.conf_check_path, "test_flags.c")
  981. test = self.dist_test(test_path, flags)
  982. if not test:
  983. self.dist_log("testing failed", stderr=True)
  984. return test
  985. @_Cache.me
  986. def cc_test_cexpr(self, cexpr, flags=[]):
  987. """
  988. Same as the above but supports compile-time expressions.
  989. """
  990. self.dist_log("testing compiler expression", cexpr)
  991. test_path = os.path.join(self.conf_tmp_path, "npy_dist_test_cexpr.c")
  992. with open(test_path, "w") as fd:
  993. fd.write(textwrap.dedent(f"""\
  994. #if !({cexpr})
  995. #error "unsupported expression"
  996. #endif
  997. int dummy;
  998. """))
  999. test = self.dist_test(test_path, flags)
  1000. if not test:
  1001. self.dist_log("testing failed", stderr=True)
  1002. return test
  1003. def cc_normalize_flags(self, flags):
  1004. """
  1005. Remove the conflicts that caused due gathering implied features flags.
  1006. Parameters
  1007. ----------
  1008. 'flags' list, compiler flags
  1009. flags should be sorted from the lowest to the highest interest.
  1010. Returns
  1011. -------
  1012. list, filtered from any conflicts.
  1013. Examples
  1014. --------
  1015. >>> self.cc_normalize_flags(['-march=armv8.2-a+fp16', '-march=armv8.2-a+dotprod'])
  1016. ['armv8.2-a+fp16+dotprod']
  1017. >>> self.cc_normalize_flags(
  1018. ['-msse', '-msse2', '-msse3', '-mssse3', '-msse4.1', '-msse4.2', '-mavx', '-march=core-avx2']
  1019. )
  1020. ['-march=core-avx2']
  1021. """
  1022. assert(isinstance(flags, list))
  1023. if self.cc_is_gcc or self.cc_is_clang or self.cc_is_icc:
  1024. return self._cc_normalize_unix(flags)
  1025. if self.cc_is_msvc or self.cc_is_iccw:
  1026. return self._cc_normalize_win(flags)
  1027. return flags
  1028. _cc_normalize_unix_mrgx = re.compile(
  1029. # 1- to check the highest of
  1030. r"^(-mcpu=|-march=|-x[A-Z0-9\-])"
  1031. )
  1032. _cc_normalize_unix_frgx = re.compile(
  1033. # 2- to remove any flags starts with
  1034. # -march, -mcpu, -x(INTEL) and '-m' without '='
  1035. r"^(?!(-mcpu=|-march=|-x[A-Z0-9\-]|-m[a-z0-9\-\.]*.$))|"
  1036. # exclude:
  1037. r"(?:-mzvector)"
  1038. )
  1039. _cc_normalize_unix_krgx = re.compile(
  1040. # 3- keep only the highest of
  1041. r"^(-mfpu|-mtune)"
  1042. )
  1043. _cc_normalize_arch_ver = re.compile(
  1044. r"[0-9.]"
  1045. )
  1046. def _cc_normalize_unix(self, flags):
  1047. def ver_flags(f):
  1048. # arch ver subflag
  1049. # -march=armv8.2-a+fp16fml
  1050. tokens = f.split('+')
  1051. ver = float('0' + ''.join(
  1052. re.findall(self._cc_normalize_arch_ver, tokens[0])
  1053. ))
  1054. return ver, tokens[0], tokens[1:]
  1055. if len(flags) <= 1:
  1056. return flags
  1057. # get the highest matched flag
  1058. for i, cur_flag in enumerate(reversed(flags)):
  1059. if not re.match(self._cc_normalize_unix_mrgx, cur_flag):
  1060. continue
  1061. lower_flags = flags[:-(i+1)]
  1062. upper_flags = flags[-i:]
  1063. filterd = list(filter(
  1064. self._cc_normalize_unix_frgx.search, lower_flags
  1065. ))
  1066. # gather subflags
  1067. ver, arch, subflags = ver_flags(cur_flag)
  1068. if ver > 0 and len(subflags) > 0:
  1069. for xflag in lower_flags:
  1070. xver, _, xsubflags = ver_flags(xflag)
  1071. if ver == xver:
  1072. subflags = xsubflags + subflags
  1073. cur_flag = arch + '+' + '+'.join(subflags)
  1074. flags = filterd + [cur_flag]
  1075. if i > 0:
  1076. flags += upper_flags
  1077. break
  1078. # to remove overridable flags
  1079. final_flags = []
  1080. matched = set()
  1081. for f in reversed(flags):
  1082. match = re.match(self._cc_normalize_unix_krgx, f)
  1083. if not match:
  1084. pass
  1085. elif match[0] in matched:
  1086. continue
  1087. else:
  1088. matched.add(match[0])
  1089. final_flags.insert(0, f)
  1090. return final_flags
  1091. _cc_normalize_win_frgx = re.compile(
  1092. r"^(?!(/arch\:|/Qx\:))"
  1093. )
  1094. _cc_normalize_win_mrgx = re.compile(
  1095. r"^(/arch|/Qx:)"
  1096. )
  1097. def _cc_normalize_win(self, flags):
  1098. for i, f in enumerate(reversed(flags)):
  1099. if not re.match(self._cc_normalize_win_mrgx, f):
  1100. continue
  1101. i += 1
  1102. return list(filter(
  1103. self._cc_normalize_win_frgx.search, flags[:-i]
  1104. )) + flags[-i:]
  1105. return flags
  1106. class _Feature:
  1107. """A helper class for `CCompilerOpt` that managing CPU features.
  1108. Attributes
  1109. ----------
  1110. feature_supported : dict
  1111. Dictionary containing all CPU features that supported
  1112. by the platform, according to the specified values in attribute
  1113. `_Config.conf_features` and `_Config.conf_features_partial()`
  1114. feature_min : set
  1115. The minimum support of CPU features, according to
  1116. the specified values in attribute `_Config.conf_min_features`.
  1117. """
  1118. def __init__(self):
  1119. if hasattr(self, "feature_is_cached"):
  1120. return
  1121. self.feature_supported = pfeatures = self.conf_features_partial()
  1122. for feature_name in list(pfeatures.keys()):
  1123. feature = pfeatures[feature_name]
  1124. cfeature = self.conf_features[feature_name]
  1125. feature.update({
  1126. k:v for k,v in cfeature.items() if k not in feature
  1127. })
  1128. disabled = feature.get("disable")
  1129. if disabled is not None:
  1130. pfeatures.pop(feature_name)
  1131. self.dist_log(
  1132. "feature '%s' is disabled," % feature_name,
  1133. disabled, stderr=True
  1134. )
  1135. continue
  1136. # list is used internally for these options
  1137. for option in (
  1138. "implies", "group", "detect", "headers", "flags", "extra_checks"
  1139. ) :
  1140. oval = feature.get(option)
  1141. if isinstance(oval, str):
  1142. feature[option] = oval.split()
  1143. self.feature_min = set()
  1144. min_f = self.conf_min_features.get(self.cc_march, "")
  1145. for F in min_f.upper().split():
  1146. if F in self.feature_supported:
  1147. self.feature_min.add(F)
  1148. self.feature_is_cached = True
  1149. def feature_names(self, names=None, force_flags=None, macros=[]):
  1150. """
  1151. Returns a set of CPU feature names that supported by platform and the **C** compiler.
  1152. Parameters
  1153. ----------
  1154. names : sequence or None, optional
  1155. Specify certain CPU features to test it against the **C** compiler.
  1156. if None(default), it will test all current supported features.
  1157. **Note**: feature names must be in upper-case.
  1158. force_flags : list or None, optional
  1159. If None(default), default compiler flags for every CPU feature will
  1160. be used during the test.
  1161. macros : list of tuples, optional
  1162. A list of C macro definitions.
  1163. """
  1164. assert(
  1165. names is None or (
  1166. not isinstance(names, str) and
  1167. hasattr(names, "__iter__")
  1168. )
  1169. )
  1170. assert(force_flags is None or isinstance(force_flags, list))
  1171. if names is None:
  1172. names = self.feature_supported.keys()
  1173. supported_names = set()
  1174. for f in names:
  1175. if self.feature_is_supported(
  1176. f, force_flags=force_flags, macros=macros
  1177. ):
  1178. supported_names.add(f)
  1179. return supported_names
  1180. def feature_is_exist(self, name):
  1181. """
  1182. Returns True if a certain feature is exist and covered within
  1183. `_Config.conf_features`.
  1184. Parameters
  1185. ----------
  1186. 'name': str
  1187. feature name in uppercase.
  1188. """
  1189. assert(name.isupper())
  1190. return name in self.conf_features
  1191. def feature_sorted(self, names, reverse=False):
  1192. """
  1193. Sort a list of CPU features ordered by the lowest interest.
  1194. Parameters
  1195. ----------
  1196. 'names': sequence
  1197. sequence of supported feature names in uppercase.
  1198. 'reverse': bool, optional
  1199. If true, the sorted features is reversed. (highest interest)
  1200. Returns
  1201. -------
  1202. list, sorted CPU features
  1203. """
  1204. def sort_cb(k):
  1205. if isinstance(k, str):
  1206. return self.feature_supported[k]["interest"]
  1207. # multiple features
  1208. rank = max([self.feature_supported[f]["interest"] for f in k])
  1209. # FIXME: that's not a safe way to increase the rank for
  1210. # multi targets
  1211. rank += len(k) -1
  1212. return rank
  1213. return sorted(names, reverse=reverse, key=sort_cb)
  1214. def feature_implies(self, names, keep_origins=False):
  1215. """
  1216. Return a set of CPU features that implied by 'names'
  1217. Parameters
  1218. ----------
  1219. names : str or sequence of str
  1220. CPU feature name(s) in uppercase.
  1221. keep_origins : bool
  1222. if False(default) then the returned set will not contain any
  1223. features from 'names'. This case happens only when two features
  1224. imply each other.
  1225. Examples
  1226. --------
  1227. >>> self.feature_implies("SSE3")
  1228. {'SSE', 'SSE2'}
  1229. >>> self.feature_implies("SSE2")
  1230. {'SSE'}
  1231. >>> self.feature_implies("SSE2", keep_origins=True)
  1232. # 'SSE2' found here since 'SSE' and 'SSE2' imply each other
  1233. {'SSE', 'SSE2'}
  1234. """
  1235. def get_implies(name, _caller=set()):
  1236. implies = set()
  1237. d = self.feature_supported[name]
  1238. for i in d.get("implies", []):
  1239. implies.add(i)
  1240. if i in _caller:
  1241. # infinity recursive guard since
  1242. # features can imply each other
  1243. continue
  1244. _caller.add(name)
  1245. implies = implies.union(get_implies(i, _caller))
  1246. return implies
  1247. if isinstance(names, str):
  1248. implies = get_implies(names)
  1249. names = [names]
  1250. else:
  1251. assert(hasattr(names, "__iter__"))
  1252. implies = set()
  1253. for n in names:
  1254. implies = implies.union(get_implies(n))
  1255. if not keep_origins:
  1256. implies.difference_update(names)
  1257. return implies
  1258. def feature_implies_c(self, names):
  1259. """same as feature_implies() but combining 'names'"""
  1260. if isinstance(names, str):
  1261. names = set((names,))
  1262. else:
  1263. names = set(names)
  1264. return names.union(self.feature_implies(names))
  1265. def feature_ahead(self, names):
  1266. """
  1267. Return list of features in 'names' after remove any
  1268. implied features and keep the origins.
  1269. Parameters
  1270. ----------
  1271. 'names': sequence
  1272. sequence of CPU feature names in uppercase.
  1273. Returns
  1274. -------
  1275. list of CPU features sorted as-is 'names'
  1276. Examples
  1277. --------
  1278. >>> self.feature_ahead(["SSE2", "SSE3", "SSE41"])
  1279. ["SSE41"]
  1280. # assume AVX2 and FMA3 implies each other and AVX2
  1281. # is the highest interest
  1282. >>> self.feature_ahead(["SSE2", "SSE3", "SSE41", "AVX2", "FMA3"])
  1283. ["AVX2"]
  1284. # assume AVX2 and FMA3 don't implies each other
  1285. >>> self.feature_ahead(["SSE2", "SSE3", "SSE41", "AVX2", "FMA3"])
  1286. ["AVX2", "FMA3"]
  1287. """
  1288. assert(
  1289. not isinstance(names, str)
  1290. and hasattr(names, '__iter__')
  1291. )
  1292. implies = self.feature_implies(names, keep_origins=True)
  1293. ahead = [n for n in names if n not in implies]
  1294. if len(ahead) == 0:
  1295. # return the highest interested feature
  1296. # if all features imply each other
  1297. ahead = self.feature_sorted(names, reverse=True)[:1]
  1298. return ahead
  1299. def feature_untied(self, names):
  1300. """
  1301. same as 'feature_ahead()' but if both features implied each other
  1302. and keep the highest interest.
  1303. Parameters
  1304. ----------
  1305. 'names': sequence
  1306. sequence of CPU feature names in uppercase.
  1307. Returns
  1308. -------
  1309. list of CPU features sorted as-is 'names'
  1310. Examples
  1311. --------
  1312. >>> self.feature_untied(["SSE2", "SSE3", "SSE41"])
  1313. ["SSE2", "SSE3", "SSE41"]
  1314. # assume AVX2 and FMA3 implies each other
  1315. >>> self.feature_untied(["SSE2", "SSE3", "SSE41", "FMA3", "AVX2"])
  1316. ["SSE2", "SSE3", "SSE41", "AVX2"]
  1317. """
  1318. assert(
  1319. not isinstance(names, str)
  1320. and hasattr(names, '__iter__')
  1321. )
  1322. final = []
  1323. for n in names:
  1324. implies = self.feature_implies(n)
  1325. tied = [
  1326. nn for nn in final
  1327. if nn in implies and n in self.feature_implies(nn)
  1328. ]
  1329. if tied:
  1330. tied = self.feature_sorted(tied + [n])
  1331. if n not in tied[1:]:
  1332. continue
  1333. final.remove(tied[:1][0])
  1334. final.append(n)
  1335. return final
  1336. def feature_get_til(self, names, keyisfalse):
  1337. """
  1338. same as `feature_implies_c()` but stop collecting implied
  1339. features when feature's option that provided through
  1340. parameter 'keyisfalse' is False, also sorting the returned
  1341. features.
  1342. """
  1343. def til(tnames):
  1344. # sort from highest to lowest interest then cut if "key" is False
  1345. tnames = self.feature_implies_c(tnames)
  1346. tnames = self.feature_sorted(tnames, reverse=True)
  1347. for i, n in enumerate(tnames):
  1348. if not self.feature_supported[n].get(keyisfalse, True):
  1349. tnames = tnames[:i+1]
  1350. break
  1351. return tnames
  1352. if isinstance(names, str) or len(names) <= 1:
  1353. names = til(names)
  1354. # normalize the sort
  1355. names.reverse()
  1356. return names
  1357. names = self.feature_ahead(names)
  1358. names = {t for n in names for t in til(n)}
  1359. return self.feature_sorted(names)
  1360. def feature_detect(self, names):
  1361. """
  1362. Return a list of CPU features that required to be detected
  1363. sorted from the lowest to highest interest.
  1364. """
  1365. names = self.feature_get_til(names, "implies_detect")
  1366. detect = []
  1367. for n in names:
  1368. d = self.feature_supported[n]
  1369. detect += d.get("detect", d.get("group", [n]))
  1370. return detect
  1371. @_Cache.me
  1372. def feature_flags(self, names):
  1373. """
  1374. Return a list of CPU features flags sorted from the lowest
  1375. to highest interest.
  1376. """
  1377. names = self.feature_sorted(self.feature_implies_c(names))
  1378. flags = []
  1379. for n in names:
  1380. d = self.feature_supported[n]
  1381. f = d.get("flags", [])
  1382. if not f or not self.cc_test_flags(f):
  1383. continue
  1384. flags += f
  1385. return self.cc_normalize_flags(flags)
  1386. @_Cache.me
  1387. def feature_test(self, name, force_flags=None, macros=[]):
  1388. """
  1389. Test a certain CPU feature against the compiler through its own
  1390. check file.
  1391. Parameters
  1392. ----------
  1393. name : str
  1394. Supported CPU feature name.
  1395. force_flags : list or None, optional
  1396. If None(default), the returned flags from `feature_flags()`
  1397. will be used.
  1398. macros : list of tuples, optional
  1399. A list of C macro definitions.
  1400. """
  1401. if force_flags is None:
  1402. force_flags = self.feature_flags(name)
  1403. self.dist_log(
  1404. "testing feature '%s' with flags (%s)" % (
  1405. name, ' '.join(force_flags)
  1406. ))
  1407. # Each CPU feature must have C source code contains at
  1408. # least one intrinsic or instruction related to this feature.
  1409. test_path = os.path.join(
  1410. self.conf_check_path, "cpu_%s.c" % name.lower()
  1411. )
  1412. if not os.path.exists(test_path):
  1413. self.dist_fatal("feature test file is not exist", test_path)
  1414. test = self.dist_test(
  1415. test_path, force_flags + self.cc_flags["werror"], macros=macros
  1416. )
  1417. if not test:
  1418. self.dist_log("testing failed", stderr=True)
  1419. return test
  1420. @_Cache.me
  1421. def feature_is_supported(self, name, force_flags=None, macros=[]):
  1422. """
  1423. Check if a certain CPU feature is supported by the platform and compiler.
  1424. Parameters
  1425. ----------
  1426. name : str
  1427. CPU feature name in uppercase.
  1428. force_flags : list or None, optional
  1429. If None(default), default compiler flags for every CPU feature will
  1430. be used during test.
  1431. macros : list of tuples, optional
  1432. A list of C macro definitions.
  1433. """
  1434. assert(name.isupper())
  1435. assert(force_flags is None or isinstance(force_flags, list))
  1436. supported = name in self.feature_supported
  1437. if supported:
  1438. for impl in self.feature_implies(name):
  1439. if not self.feature_test(impl, force_flags, macros=macros):
  1440. return False
  1441. if not self.feature_test(name, force_flags, macros=macros):
  1442. return False
  1443. return supported
  1444. @_Cache.me
  1445. def feature_can_autovec(self, name):
  1446. """
  1447. check if the feature can be auto-vectorized by the compiler
  1448. """
  1449. assert(isinstance(name, str))
  1450. d = self.feature_supported[name]
  1451. can = d.get("autovec", None)
  1452. if can is None:
  1453. valid_flags = [
  1454. self.cc_test_flags([f]) for f in d.get("flags", [])
  1455. ]
  1456. can = valid_flags and any(valid_flags)
  1457. return can
  1458. @_Cache.me
  1459. def feature_extra_checks(self, name):
  1460. """
  1461. Return a list of supported extra checks after testing them against
  1462. the compiler.
  1463. Parameters
  1464. ----------
  1465. names : str
  1466. CPU feature name in uppercase.
  1467. """
  1468. assert isinstance(name, str)
  1469. d = self.feature_supported[name]
  1470. extra_checks = d.get("extra_checks", [])
  1471. if not extra_checks:
  1472. return []
  1473. self.dist_log("Testing extra checks for feature '%s'" % name, extra_checks)
  1474. flags = self.feature_flags(name)
  1475. available = []
  1476. not_available = []
  1477. for chk in extra_checks:
  1478. test_path = os.path.join(
  1479. self.conf_check_path, "extra_%s.c" % chk.lower()
  1480. )
  1481. if not os.path.exists(test_path):
  1482. self.dist_fatal("extra check file does not exist", test_path)
  1483. is_supported = self.dist_test(test_path, flags + self.cc_flags["werror"])
  1484. if is_supported:
  1485. available.append(chk)
  1486. else:
  1487. not_available.append(chk)
  1488. if not_available:
  1489. self.dist_log("testing failed for checks", not_available, stderr=True)
  1490. return available
  1491. def feature_c_preprocessor(self, feature_name, tabs=0):
  1492. """
  1493. Generate C preprocessor definitions and include headers of a CPU feature.
  1494. Parameters
  1495. ----------
  1496. 'feature_name': str
  1497. CPU feature name in uppercase.
  1498. 'tabs': int
  1499. if > 0, align the generated strings to the right depend on number of tabs.
  1500. Returns
  1501. -------
  1502. str, generated C preprocessor
  1503. Examples
  1504. --------
  1505. >>> self.feature_c_preprocessor("SSE3")
  1506. /** SSE3 **/
  1507. #define NPY_HAVE_SSE3 1
  1508. #include <pmmintrin.h>
  1509. """
  1510. assert(feature_name.isupper())
  1511. feature = self.feature_supported.get(feature_name)
  1512. assert(feature is not None)
  1513. prepr = [
  1514. "/** %s **/" % feature_name,
  1515. "#define %sHAVE_%s 1" % (self.conf_c_prefix, feature_name)
  1516. ]
  1517. prepr += [
  1518. "#include <%s>" % h for h in feature.get("headers", [])
  1519. ]
  1520. extra_defs = feature.get("group", [])
  1521. extra_defs += self.feature_extra_checks(feature_name)
  1522. for edef in extra_defs:
  1523. # Guard extra definitions in case of duplicate with
  1524. # another feature
  1525. prepr += [
  1526. "#ifndef %sHAVE_%s" % (self.conf_c_prefix, edef),
  1527. "\t#define %sHAVE_%s 1" % (self.conf_c_prefix, edef),
  1528. "#endif",
  1529. ]
  1530. if tabs > 0:
  1531. prepr = [('\t'*tabs) + l for l in prepr]
  1532. return '\n'.join(prepr)
  1533. class _Parse:
  1534. """A helper class that parsing main arguments of `CCompilerOpt`,
  1535. also parsing configuration statements in dispatch-able sources.
  1536. Parameters
  1537. ----------
  1538. cpu_baseline : str or None
  1539. minimal set of required CPU features or special options.
  1540. cpu_dispatch : str or None
  1541. dispatched set of additional CPU features or special options.
  1542. Special options can be:
  1543. - **MIN**: Enables the minimum CPU features that utilized via `_Config.conf_min_features`
  1544. - **MAX**: Enables all supported CPU features by the Compiler and platform.
  1545. - **NATIVE**: Enables all CPU features that supported by the current machine.
  1546. - **NONE**: Enables nothing
  1547. - **Operand +/-**: remove or add features, useful with options **MAX**, **MIN** and **NATIVE**.
  1548. NOTE: operand + is only added for nominal reason.
  1549. NOTES:
  1550. - Case-insensitive among all CPU features and special options.
  1551. - Comma or space can be used as a separator.
  1552. - If the CPU feature is not supported by the user platform or compiler,
  1553. it will be skipped rather than raising a fatal error.
  1554. - Any specified CPU features to 'cpu_dispatch' will be skipped if its part of CPU baseline features
  1555. - 'cpu_baseline' force enables implied features.
  1556. Attributes
  1557. ----------
  1558. parse_baseline_names : list
  1559. Final CPU baseline's feature names(sorted from low to high)
  1560. parse_baseline_flags : list
  1561. Compiler flags of baseline features
  1562. parse_dispatch_names : list
  1563. Final CPU dispatch-able feature names(sorted from low to high)
  1564. parse_target_groups : dict
  1565. Dictionary containing initialized target groups that configured
  1566. through class attribute `conf_target_groups`.
  1567. The key is represent the group name and value is a tuple
  1568. contains three items :
  1569. - bool, True if group has the 'baseline' option.
  1570. - list, list of CPU features.
  1571. - list, list of extra compiler flags.
  1572. """
  1573. def __init__(self, cpu_baseline, cpu_dispatch):
  1574. self._parse_policies = dict(
  1575. # POLICY NAME, (HAVE, NOT HAVE, [DEB])
  1576. KEEP_BASELINE = (
  1577. None, self._parse_policy_not_keepbase,
  1578. []
  1579. ),
  1580. KEEP_SORT = (
  1581. self._parse_policy_keepsort,
  1582. self._parse_policy_not_keepsort,
  1583. []
  1584. ),
  1585. MAXOPT = (
  1586. self._parse_policy_maxopt, None,
  1587. []
  1588. ),
  1589. WERROR = (
  1590. self._parse_policy_werror, None,
  1591. []
  1592. ),
  1593. AUTOVEC = (
  1594. self._parse_policy_autovec, None,
  1595. ["MAXOPT"]
  1596. )
  1597. )
  1598. if hasattr(self, "parse_is_cached"):
  1599. return
  1600. self.parse_baseline_names = []
  1601. self.parse_baseline_flags = []
  1602. self.parse_dispatch_names = []
  1603. self.parse_target_groups = {}
  1604. if self.cc_noopt:
  1605. # skip parsing baseline and dispatch args and keep parsing target groups
  1606. cpu_baseline = cpu_dispatch = None
  1607. self.dist_log("check requested baseline")
  1608. if cpu_baseline is not None:
  1609. cpu_baseline = self._parse_arg_features("cpu_baseline", cpu_baseline)
  1610. baseline_names = self.feature_names(cpu_baseline)
  1611. self.parse_baseline_flags = self.feature_flags(baseline_names)
  1612. self.parse_baseline_names = self.feature_sorted(
  1613. self.feature_implies_c(baseline_names)
  1614. )
  1615. self.dist_log("check requested dispatch-able features")
  1616. if cpu_dispatch is not None:
  1617. cpu_dispatch_ = self._parse_arg_features("cpu_dispatch", cpu_dispatch)
  1618. cpu_dispatch = {
  1619. f for f in cpu_dispatch_
  1620. if f not in self.parse_baseline_names
  1621. }
  1622. conflict_baseline = cpu_dispatch_.difference(cpu_dispatch)
  1623. self.parse_dispatch_names = self.feature_sorted(
  1624. self.feature_names(cpu_dispatch)
  1625. )
  1626. if len(conflict_baseline) > 0:
  1627. self.dist_log(
  1628. "skip features", conflict_baseline, "since its part of baseline"
  1629. )
  1630. self.dist_log("initialize targets groups")
  1631. for group_name, tokens in self.conf_target_groups.items():
  1632. self.dist_log("parse target group", group_name)
  1633. GROUP_NAME = group_name.upper()
  1634. if not tokens or not tokens.strip():
  1635. # allow empty groups, useful in case if there's a need
  1636. # to disable certain group since '_parse_target_tokens()'
  1637. # requires at least one valid target
  1638. self.parse_target_groups[GROUP_NAME] = (
  1639. False, [], []
  1640. )
  1641. continue
  1642. has_baseline, features, extra_flags = \
  1643. self._parse_target_tokens(tokens)
  1644. self.parse_target_groups[GROUP_NAME] = (
  1645. has_baseline, features, extra_flags
  1646. )
  1647. self.parse_is_cached = True
  1648. def parse_targets(self, source):
  1649. """
  1650. Fetch and parse configuration statements that required for
  1651. defining the targeted CPU features, statements should be declared
  1652. in the top of source in between **C** comment and start
  1653. with a special mark **@targets**.
  1654. Configuration statements are sort of keywords representing
  1655. CPU features names, group of statements and policies, combined
  1656. together to determine the required optimization.
  1657. Parameters
  1658. ----------
  1659. source : str
  1660. the path of **C** source file.
  1661. Returns
  1662. -------
  1663. - bool, True if group has the 'baseline' option
  1664. - list, list of CPU features
  1665. - list, list of extra compiler flags
  1666. """
  1667. self.dist_log("looking for '@targets' inside -> ", source)
  1668. # get lines between /*@targets and */
  1669. with open(source) as fd:
  1670. tokens = ""
  1671. max_to_reach = 1000 # good enough, isn't?
  1672. start_with = "@targets"
  1673. start_pos = -1
  1674. end_with = "*/"
  1675. end_pos = -1
  1676. for current_line, line in enumerate(fd):
  1677. if current_line == max_to_reach:
  1678. self.dist_fatal("reached the max of lines")
  1679. break
  1680. if start_pos == -1:
  1681. start_pos = line.find(start_with)
  1682. if start_pos == -1:
  1683. continue
  1684. start_pos += len(start_with)
  1685. tokens += line
  1686. end_pos = line.find(end_with)
  1687. if end_pos != -1:
  1688. end_pos += len(tokens) - len(line)
  1689. break
  1690. if start_pos == -1:
  1691. self.dist_fatal("expected to find '%s' within a C comment" % start_with)
  1692. if end_pos == -1:
  1693. self.dist_fatal("expected to end with '%s'" % end_with)
  1694. tokens = tokens[start_pos:end_pos]
  1695. return self._parse_target_tokens(tokens)
  1696. _parse_regex_arg = re.compile(r'\s|,|([+-])')
  1697. def _parse_arg_features(self, arg_name, req_features):
  1698. if not isinstance(req_features, str):
  1699. self.dist_fatal("expected a string in '%s'" % arg_name)
  1700. final_features = set()
  1701. # space and comma can be used as a separator
  1702. tokens = list(filter(None, re.split(self._parse_regex_arg, req_features)))
  1703. append = True # append is the default
  1704. for tok in tokens:
  1705. if tok[0] in ("#", "$"):
  1706. self.dist_fatal(
  1707. arg_name, "target groups and policies "
  1708. "aren't allowed from arguments, "
  1709. "only from dispatch-able sources"
  1710. )
  1711. if tok == '+':
  1712. append = True
  1713. continue
  1714. if tok == '-':
  1715. append = False
  1716. continue
  1717. TOK = tok.upper() # we use upper-case internally
  1718. features_to = set()
  1719. if TOK == "NONE":
  1720. pass
  1721. elif TOK == "NATIVE":
  1722. native = self.cc_flags["native"]
  1723. if not native:
  1724. self.dist_fatal(arg_name,
  1725. "native option isn't supported by the compiler"
  1726. )
  1727. features_to = self.feature_names(
  1728. force_flags=native, macros=[("DETECT_FEATURES", 1)]
  1729. )
  1730. elif TOK == "MAX":
  1731. features_to = self.feature_supported.keys()
  1732. elif TOK == "MIN":
  1733. features_to = self.feature_min
  1734. else:
  1735. if TOK in self.feature_supported:
  1736. features_to.add(TOK)
  1737. else:
  1738. if not self.feature_is_exist(TOK):
  1739. self.dist_fatal(arg_name,
  1740. ", '%s' isn't a known feature or option" % tok
  1741. )
  1742. if append:
  1743. final_features = final_features.union(features_to)
  1744. else:
  1745. final_features = final_features.difference(features_to)
  1746. append = True # back to default
  1747. return final_features
  1748. _parse_regex_target = re.compile(r'\s|[*,/]|([()])')
  1749. def _parse_target_tokens(self, tokens):
  1750. assert(isinstance(tokens, str))
  1751. final_targets = [] # to keep it sorted as specified
  1752. extra_flags = []
  1753. has_baseline = False
  1754. skipped = set()
  1755. policies = set()
  1756. multi_target = None
  1757. tokens = list(filter(None, re.split(self._parse_regex_target, tokens)))
  1758. if not tokens:
  1759. self.dist_fatal("expected one token at least")
  1760. for tok in tokens:
  1761. TOK = tok.upper()
  1762. ch = tok[0]
  1763. if ch in ('+', '-'):
  1764. self.dist_fatal(
  1765. "+/- are 'not' allowed from target's groups or @targets, "
  1766. "only from cpu_baseline and cpu_dispatch parms"
  1767. )
  1768. elif ch == '$':
  1769. if multi_target is not None:
  1770. self.dist_fatal(
  1771. "policies aren't allowed inside multi-target '()'"
  1772. ", only CPU features"
  1773. )
  1774. policies.add(self._parse_token_policy(TOK))
  1775. elif ch == '#':
  1776. if multi_target is not None:
  1777. self.dist_fatal(
  1778. "target groups aren't allowed inside multi-target '()'"
  1779. ", only CPU features"
  1780. )
  1781. has_baseline, final_targets, extra_flags = \
  1782. self._parse_token_group(TOK, has_baseline, final_targets, extra_flags)
  1783. elif ch == '(':
  1784. if multi_target is not None:
  1785. self.dist_fatal("unclosed multi-target, missing ')'")
  1786. multi_target = set()
  1787. elif ch == ')':
  1788. if multi_target is None:
  1789. self.dist_fatal("multi-target opener '(' wasn't found")
  1790. targets = self._parse_multi_target(multi_target)
  1791. if targets is None:
  1792. skipped.add(tuple(multi_target))
  1793. else:
  1794. if len(targets) == 1:
  1795. targets = targets[0]
  1796. if targets and targets not in final_targets:
  1797. final_targets.append(targets)
  1798. multi_target = None # back to default
  1799. else:
  1800. if TOK == "BASELINE":
  1801. if multi_target is not None:
  1802. self.dist_fatal("baseline isn't allowed inside multi-target '()'")
  1803. has_baseline = True
  1804. continue
  1805. if multi_target is not None:
  1806. multi_target.add(TOK)
  1807. continue
  1808. if not self.feature_is_exist(TOK):
  1809. self.dist_fatal("invalid target name '%s'" % TOK)
  1810. is_enabled = (
  1811. TOK in self.parse_baseline_names or
  1812. TOK in self.parse_dispatch_names
  1813. )
  1814. if is_enabled:
  1815. if TOK not in final_targets:
  1816. final_targets.append(TOK)
  1817. continue
  1818. skipped.add(TOK)
  1819. if multi_target is not None:
  1820. self.dist_fatal("unclosed multi-target, missing ')'")
  1821. if skipped:
  1822. self.dist_log(
  1823. "skip targets", skipped,
  1824. "not part of baseline or dispatch-able features"
  1825. )
  1826. final_targets = self.feature_untied(final_targets)
  1827. # add polices dependencies
  1828. for p in list(policies):
  1829. _, _, deps = self._parse_policies[p]
  1830. for d in deps:
  1831. if d in policies:
  1832. continue
  1833. self.dist_log(
  1834. "policy '%s' force enables '%s'" % (
  1835. p, d
  1836. ))
  1837. policies.add(d)
  1838. # release policies filtrations
  1839. for p, (have, nhave, _) in self._parse_policies.items():
  1840. func = None
  1841. if p in policies:
  1842. func = have
  1843. self.dist_log("policy '%s' is ON" % p)
  1844. else:
  1845. func = nhave
  1846. if not func:
  1847. continue
  1848. has_baseline, final_targets, extra_flags = func(
  1849. has_baseline, final_targets, extra_flags
  1850. )
  1851. return has_baseline, final_targets, extra_flags
  1852. def _parse_token_policy(self, token):
  1853. """validate policy token"""
  1854. if len(token) <= 1 or token[-1:] == token[0]:
  1855. self.dist_fatal("'$' must stuck in the begin of policy name")
  1856. token = token[1:]
  1857. if token not in self._parse_policies:
  1858. self.dist_fatal(
  1859. "'%s' is an invalid policy name, available policies are" % token,
  1860. self._parse_policies.keys()
  1861. )
  1862. return token
  1863. def _parse_token_group(self, token, has_baseline, final_targets, extra_flags):
  1864. """validate group token"""
  1865. if len(token) <= 1 or token[-1:] == token[0]:
  1866. self.dist_fatal("'#' must stuck in the begin of group name")
  1867. token = token[1:]
  1868. ghas_baseline, gtargets, gextra_flags = self.parse_target_groups.get(
  1869. token, (False, None, [])
  1870. )
  1871. if gtargets is None:
  1872. self.dist_fatal(
  1873. "'%s' is an invalid target group name, " % token + \
  1874. "available target groups are",
  1875. self.parse_target_groups.keys()
  1876. )
  1877. if ghas_baseline:
  1878. has_baseline = True
  1879. # always keep sorting as specified
  1880. final_targets += [f for f in gtargets if f not in final_targets]
  1881. extra_flags += [f for f in gextra_flags if f not in extra_flags]
  1882. return has_baseline, final_targets, extra_flags
  1883. def _parse_multi_target(self, targets):
  1884. """validate multi targets that defined between parentheses()"""
  1885. # remove any implied features and keep the origins
  1886. if not targets:
  1887. self.dist_fatal("empty multi-target '()'")
  1888. if not all([
  1889. self.feature_is_exist(tar) for tar in targets
  1890. ]) :
  1891. self.dist_fatal("invalid target name in multi-target", targets)
  1892. if not all([
  1893. (
  1894. tar in self.parse_baseline_names or
  1895. tar in self.parse_dispatch_names
  1896. )
  1897. for tar in targets
  1898. ]) :
  1899. return None
  1900. targets = self.feature_ahead(targets)
  1901. if not targets:
  1902. return None
  1903. # force sort multi targets, so it can be comparable
  1904. targets = self.feature_sorted(targets)
  1905. targets = tuple(targets) # hashable
  1906. return targets
  1907. def _parse_policy_not_keepbase(self, has_baseline, final_targets, extra_flags):
  1908. """skip all baseline features"""
  1909. skipped = []
  1910. for tar in final_targets[:]:
  1911. is_base = False
  1912. if isinstance(tar, str):
  1913. is_base = tar in self.parse_baseline_names
  1914. else:
  1915. # multi targets
  1916. is_base = all([
  1917. f in self.parse_baseline_names
  1918. for f in tar
  1919. ])
  1920. if is_base:
  1921. skipped.append(tar)
  1922. final_targets.remove(tar)
  1923. if skipped:
  1924. self.dist_log("skip baseline features", skipped)
  1925. return has_baseline, final_targets, extra_flags
  1926. def _parse_policy_keepsort(self, has_baseline, final_targets, extra_flags):
  1927. """leave a notice that $keep_sort is on"""
  1928. self.dist_log(
  1929. "policy 'keep_sort' is on, dispatch-able targets", final_targets, "\n"
  1930. "are 'not' sorted depend on the highest interest but"
  1931. "as specified in the dispatch-able source or the extra group"
  1932. )
  1933. return has_baseline, final_targets, extra_flags
  1934. def _parse_policy_not_keepsort(self, has_baseline, final_targets, extra_flags):
  1935. """sorted depend on the highest interest"""
  1936. final_targets = self.feature_sorted(final_targets, reverse=True)
  1937. return has_baseline, final_targets, extra_flags
  1938. def _parse_policy_maxopt(self, has_baseline, final_targets, extra_flags):
  1939. """append the compiler optimization flags"""
  1940. if self.cc_has_debug:
  1941. self.dist_log("debug mode is detected, policy 'maxopt' is skipped.")
  1942. elif self.cc_noopt:
  1943. self.dist_log("optimization is disabled, policy 'maxopt' is skipped.")
  1944. else:
  1945. flags = self.cc_flags["opt"]
  1946. if not flags:
  1947. self.dist_log(
  1948. "current compiler doesn't support optimization flags, "
  1949. "policy 'maxopt' is skipped", stderr=True
  1950. )
  1951. else:
  1952. extra_flags += flags
  1953. return has_baseline, final_targets, extra_flags
  1954. def _parse_policy_werror(self, has_baseline, final_targets, extra_flags):
  1955. """force warnings to treated as errors"""
  1956. flags = self.cc_flags["werror"]
  1957. if not flags:
  1958. self.dist_log(
  1959. "current compiler doesn't support werror flags, "
  1960. "warnings will 'not' treated as errors", stderr=True
  1961. )
  1962. else:
  1963. self.dist_log("compiler warnings are treated as errors")
  1964. extra_flags += flags
  1965. return has_baseline, final_targets, extra_flags
  1966. def _parse_policy_autovec(self, has_baseline, final_targets, extra_flags):
  1967. """skip features that has no auto-vectorized support by compiler"""
  1968. skipped = []
  1969. for tar in final_targets[:]:
  1970. if isinstance(tar, str):
  1971. can = self.feature_can_autovec(tar)
  1972. else: # multiple target
  1973. can = all([
  1974. self.feature_can_autovec(t)
  1975. for t in tar
  1976. ])
  1977. if not can:
  1978. final_targets.remove(tar)
  1979. skipped.append(tar)
  1980. if skipped:
  1981. self.dist_log("skip non auto-vectorized features", skipped)
  1982. return has_baseline, final_targets, extra_flags
  1983. class CCompilerOpt(_Config, _Distutils, _Cache, _CCompiler, _Feature, _Parse):
  1984. """
  1985. A helper class for `CCompiler` aims to provide extra build options
  1986. to effectively control of compiler optimizations that are directly
  1987. related to CPU features.
  1988. """
  1989. def __init__(self, ccompiler, cpu_baseline="min", cpu_dispatch="max", cache_path=None):
  1990. _Config.__init__(self)
  1991. _Distutils.__init__(self, ccompiler)
  1992. _Cache.__init__(self, cache_path, self.dist_info(), cpu_baseline, cpu_dispatch)
  1993. _CCompiler.__init__(self)
  1994. _Feature.__init__(self)
  1995. if not self.cc_noopt and self.cc_has_native:
  1996. self.dist_log(
  1997. "native flag is specified through environment variables. "
  1998. "force cpu-baseline='native'"
  1999. )
  2000. cpu_baseline = "native"
  2001. _Parse.__init__(self, cpu_baseline, cpu_dispatch)
  2002. # keep the requested features untouched, need it later for report
  2003. # and trace purposes
  2004. self._requested_baseline = cpu_baseline
  2005. self._requested_dispatch = cpu_dispatch
  2006. # key is the dispatch-able source and value is a tuple
  2007. # contains two items (has_baseline[boolean], dispatched-features[list])
  2008. self.sources_status = getattr(self, "sources_status", {})
  2009. # every instance should has a separate one
  2010. self.cache_private.add("sources_status")
  2011. # set it at the end to make sure the cache writing was done after init
  2012. # this class
  2013. self.hit_cache = hasattr(self, "hit_cache")
  2014. def is_cached(self):
  2015. """
  2016. Returns True if the class loaded from the cache file
  2017. """
  2018. return self.cache_infile and self.hit_cache
  2019. def cpu_baseline_flags(self):
  2020. """
  2021. Returns a list of final CPU baseline compiler flags
  2022. """
  2023. return self.parse_baseline_flags
  2024. def cpu_baseline_names(self):
  2025. """
  2026. return a list of final CPU baseline feature names
  2027. """
  2028. return self.parse_baseline_names
  2029. def cpu_dispatch_names(self):
  2030. """
  2031. return a list of final CPU dispatch feature names
  2032. """
  2033. return self.parse_dispatch_names
  2034. def try_dispatch(self, sources, src_dir=None, ccompiler=None, **kwargs):
  2035. """
  2036. Compile one or more dispatch-able sources and generates object files,
  2037. also generates abstract C config headers and macros that
  2038. used later for the final runtime dispatching process.
  2039. The mechanism behind it is to takes each source file that specified
  2040. in 'sources' and branching it into several files depend on
  2041. special configuration statements that must be declared in the
  2042. top of each source which contains targeted CPU features,
  2043. then it compiles every branched source with the proper compiler flags.
  2044. Parameters
  2045. ----------
  2046. sources : list
  2047. Must be a list of dispatch-able sources file paths,
  2048. and configuration statements must be declared inside
  2049. each file.
  2050. src_dir : str
  2051. Path of parent directory for the generated headers and wrapped sources.
  2052. If None(default) the files will generated in-place.
  2053. ccompiler : CCompiler
  2054. Distutils `CCompiler` instance to be used for compilation.
  2055. If None (default), the provided instance during the initialization
  2056. will be used instead.
  2057. **kwargs : any
  2058. Arguments to pass on to the `CCompiler.compile()`
  2059. Returns
  2060. -------
  2061. list : generated object files
  2062. Raises
  2063. ------
  2064. CompileError
  2065. Raises by `CCompiler.compile()` on compiling failure.
  2066. DistutilsError
  2067. Some errors during checking the sanity of configuration statements.
  2068. See Also
  2069. --------
  2070. parse_targets :
  2071. Parsing the configuration statements of dispatch-able sources.
  2072. """
  2073. to_compile = {}
  2074. baseline_flags = self.cpu_baseline_flags()
  2075. include_dirs = kwargs.setdefault("include_dirs", [])
  2076. for src in sources:
  2077. output_dir = os.path.dirname(src)
  2078. if src_dir:
  2079. if not output_dir.startswith(src_dir):
  2080. output_dir = os.path.join(src_dir, output_dir)
  2081. if output_dir not in include_dirs:
  2082. # To allow including the generated config header(*.dispatch.h)
  2083. # by the dispatch-able sources
  2084. include_dirs.append(output_dir)
  2085. has_baseline, targets, extra_flags = self.parse_targets(src)
  2086. nochange = self._generate_config(output_dir, src, targets, has_baseline)
  2087. for tar in targets:
  2088. tar_src = self._wrap_target(output_dir, src, tar, nochange=nochange)
  2089. flags = tuple(extra_flags + self.feature_flags(tar))
  2090. to_compile.setdefault(flags, []).append(tar_src)
  2091. if has_baseline:
  2092. flags = tuple(extra_flags + baseline_flags)
  2093. to_compile.setdefault(flags, []).append(src)
  2094. self.sources_status[src] = (has_baseline, targets)
  2095. # For these reasons, the sources are compiled in a separate loop:
  2096. # - Gathering all sources with the same flags to benefit from
  2097. # the parallel compiling as much as possible.
  2098. # - To generate all config headers of the dispatchable sources,
  2099. # before the compilation in case if there are dependency relationships
  2100. # among them.
  2101. objects = []
  2102. for flags, srcs in to_compile.items():
  2103. objects += self.dist_compile(
  2104. srcs, list(flags), ccompiler=ccompiler, **kwargs
  2105. )
  2106. return objects
  2107. def generate_dispatch_header(self, header_path):
  2108. """
  2109. Generate the dispatch header which contains the #definitions and headers
  2110. for platform-specific instruction-sets for the enabled CPU baseline and
  2111. dispatch-able features.
  2112. Its highly recommended to take a look at the generated header
  2113. also the generated source files via `try_dispatch()`
  2114. in order to get the full picture.
  2115. """
  2116. self.dist_log("generate CPU dispatch header: (%s)" % header_path)
  2117. baseline_names = self.cpu_baseline_names()
  2118. dispatch_names = self.cpu_dispatch_names()
  2119. baseline_len = len(baseline_names)
  2120. dispatch_len = len(dispatch_names)
  2121. header_dir = os.path.dirname(header_path)
  2122. if not os.path.exists(header_dir):
  2123. self.dist_log(
  2124. f"dispatch header dir {header_dir} does not exist, creating it",
  2125. stderr=True
  2126. )
  2127. os.makedirs(header_dir)
  2128. with open(header_path, 'w') as f:
  2129. baseline_calls = ' \\\n'.join([
  2130. (
  2131. "\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))"
  2132. ) % (self.conf_c_prefix, f)
  2133. for f in baseline_names
  2134. ])
  2135. dispatch_calls = ' \\\n'.join([
  2136. (
  2137. "\t%sWITH_CPU_EXPAND_(MACRO_TO_CALL(%s, __VA_ARGS__))"
  2138. ) % (self.conf_c_prefix, f)
  2139. for f in dispatch_names
  2140. ])
  2141. f.write(textwrap.dedent("""\
  2142. /*
  2143. * AUTOGENERATED DON'T EDIT
  2144. * Please make changes to the code generator (distutils/ccompiler_opt.py)
  2145. */
  2146. #define {pfx}WITH_CPU_BASELINE "{baseline_str}"
  2147. #define {pfx}WITH_CPU_DISPATCH "{dispatch_str}"
  2148. #define {pfx}WITH_CPU_BASELINE_N {baseline_len}
  2149. #define {pfx}WITH_CPU_DISPATCH_N {dispatch_len}
  2150. #define {pfx}WITH_CPU_EXPAND_(X) X
  2151. #define {pfx}WITH_CPU_BASELINE_CALL(MACRO_TO_CALL, ...) \\
  2152. {baseline_calls}
  2153. #define {pfx}WITH_CPU_DISPATCH_CALL(MACRO_TO_CALL, ...) \\
  2154. {dispatch_calls}
  2155. """).format(
  2156. pfx=self.conf_c_prefix, baseline_str=" ".join(baseline_names),
  2157. dispatch_str=" ".join(dispatch_names), baseline_len=baseline_len,
  2158. dispatch_len=dispatch_len, baseline_calls=baseline_calls,
  2159. dispatch_calls=dispatch_calls
  2160. ))
  2161. baseline_pre = ''
  2162. for name in baseline_names:
  2163. baseline_pre += self.feature_c_preprocessor(name, tabs=1) + '\n'
  2164. dispatch_pre = ''
  2165. for name in dispatch_names:
  2166. dispatch_pre += textwrap.dedent("""\
  2167. #ifdef {pfx}CPU_TARGET_{name}
  2168. {pre}
  2169. #endif /*{pfx}CPU_TARGET_{name}*/
  2170. """).format(
  2171. pfx=self.conf_c_prefix_, name=name, pre=self.feature_c_preprocessor(
  2172. name, tabs=1
  2173. ))
  2174. f.write(textwrap.dedent("""\
  2175. /******* baseline features *******/
  2176. {baseline_pre}
  2177. /******* dispatch features *******/
  2178. {dispatch_pre}
  2179. """).format(
  2180. pfx=self.conf_c_prefix_, baseline_pre=baseline_pre,
  2181. dispatch_pre=dispatch_pre
  2182. ))
  2183. def report(self, full=False):
  2184. report = []
  2185. platform_rows = []
  2186. baseline_rows = []
  2187. dispatch_rows = []
  2188. report.append(("Platform", platform_rows))
  2189. report.append(("", ""))
  2190. report.append(("CPU baseline", baseline_rows))
  2191. report.append(("", ""))
  2192. report.append(("CPU dispatch", dispatch_rows))
  2193. ########## platform ##########
  2194. platform_rows.append(("Architecture", (
  2195. "unsupported" if self.cc_on_noarch else self.cc_march)
  2196. ))
  2197. platform_rows.append(("Compiler", (
  2198. "unix-like" if self.cc_is_nocc else self.cc_name)
  2199. ))
  2200. ########## baseline ##########
  2201. if self.cc_noopt:
  2202. baseline_rows.append(("Requested", "optimization disabled"))
  2203. else:
  2204. baseline_rows.append(("Requested", repr(self._requested_baseline)))
  2205. baseline_names = self.cpu_baseline_names()
  2206. baseline_rows.append((
  2207. "Enabled", (' '.join(baseline_names) if baseline_names else "none")
  2208. ))
  2209. baseline_flags = self.cpu_baseline_flags()
  2210. baseline_rows.append((
  2211. "Flags", (' '.join(baseline_flags) if baseline_flags else "none")
  2212. ))
  2213. extra_checks = []
  2214. for name in baseline_names:
  2215. extra_checks += self.feature_extra_checks(name)
  2216. baseline_rows.append((
  2217. "Extra checks", (' '.join(extra_checks) if extra_checks else "none")
  2218. ))
  2219. ########## dispatch ##########
  2220. if self.cc_noopt:
  2221. baseline_rows.append(("Requested", "optimization disabled"))
  2222. else:
  2223. dispatch_rows.append(("Requested", repr(self._requested_dispatch)))
  2224. dispatch_names = self.cpu_dispatch_names()
  2225. dispatch_rows.append((
  2226. "Enabled", (' '.join(dispatch_names) if dispatch_names else "none")
  2227. ))
  2228. ########## Generated ##########
  2229. # TODO:
  2230. # - collect object names from 'try_dispatch()'
  2231. # then get size of each object and printed
  2232. # - give more details about the features that not
  2233. # generated due compiler support
  2234. # - find a better output's design.
  2235. #
  2236. target_sources = {}
  2237. for source, (_, targets) in self.sources_status.items():
  2238. for tar in targets:
  2239. target_sources.setdefault(tar, []).append(source)
  2240. if not full or not target_sources:
  2241. generated = ""
  2242. for tar in self.feature_sorted(target_sources):
  2243. sources = target_sources[tar]
  2244. name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar)
  2245. generated += name + "[%d] " % len(sources)
  2246. dispatch_rows.append(("Generated", generated[:-1] if generated else "none"))
  2247. else:
  2248. dispatch_rows.append(("Generated", ''))
  2249. for tar in self.feature_sorted(target_sources):
  2250. sources = target_sources[tar]
  2251. pretty_name = tar if isinstance(tar, str) else '(%s)' % ' '.join(tar)
  2252. flags = ' '.join(self.feature_flags(tar))
  2253. implies = ' '.join(self.feature_sorted(self.feature_implies(tar)))
  2254. detect = ' '.join(self.feature_detect(tar))
  2255. extra_checks = []
  2256. for name in ((tar,) if isinstance(tar, str) else tar):
  2257. extra_checks += self.feature_extra_checks(name)
  2258. extra_checks = (' '.join(extra_checks) if extra_checks else "none")
  2259. dispatch_rows.append(('', ''))
  2260. dispatch_rows.append((pretty_name, implies))
  2261. dispatch_rows.append(("Flags", flags))
  2262. dispatch_rows.append(("Extra checks", extra_checks))
  2263. dispatch_rows.append(("Detect", detect))
  2264. for src in sources:
  2265. dispatch_rows.append(("", src))
  2266. ###############################
  2267. # TODO: add support for 'markdown' format
  2268. text = []
  2269. secs_len = [len(secs) for secs, _ in report]
  2270. cols_len = [len(col) for _, rows in report for col, _ in rows]
  2271. tab = ' ' * 2
  2272. pad = max(max(secs_len), max(cols_len))
  2273. for sec, rows in report:
  2274. if not sec:
  2275. text.append("") # empty line
  2276. continue
  2277. sec += ' ' * (pad - len(sec))
  2278. text.append(sec + tab + ': ')
  2279. for col, val in rows:
  2280. col += ' ' * (pad - len(col))
  2281. text.append(tab + col + ': ' + val)
  2282. return '\n'.join(text)
  2283. def _wrap_target(self, output_dir, dispatch_src, target, nochange=False):
  2284. assert(isinstance(target, (str, tuple)))
  2285. if isinstance(target, str):
  2286. ext_name = target_name = target
  2287. else:
  2288. # multi-target
  2289. ext_name = '.'.join(target)
  2290. target_name = '__'.join(target)
  2291. wrap_path = os.path.join(output_dir, os.path.basename(dispatch_src))
  2292. wrap_path = "{0}.{2}{1}".format(*os.path.splitext(wrap_path), ext_name.lower())
  2293. if nochange and os.path.exists(wrap_path):
  2294. return wrap_path
  2295. self.dist_log("wrap dispatch-able target -> ", wrap_path)
  2296. # sorting for readability
  2297. features = self.feature_sorted(self.feature_implies_c(target))
  2298. target_join = "#define %sCPU_TARGET_" % self.conf_c_prefix_
  2299. target_defs = [target_join + f for f in features]
  2300. target_defs = '\n'.join(target_defs)
  2301. with open(wrap_path, "w") as fd:
  2302. fd.write(textwrap.dedent("""\
  2303. /**
  2304. * AUTOGENERATED DON'T EDIT
  2305. * Please make changes to the code generator \
  2306. (distutils/ccompiler_opt.py)
  2307. */
  2308. #define {pfx}CPU_TARGET_MODE
  2309. #define {pfx}CPU_TARGET_CURRENT {target_name}
  2310. {target_defs}
  2311. #include "{path}"
  2312. """).format(
  2313. pfx=self.conf_c_prefix_, target_name=target_name,
  2314. path=os.path.abspath(dispatch_src), target_defs=target_defs
  2315. ))
  2316. return wrap_path
  2317. def _generate_config(self, output_dir, dispatch_src, targets, has_baseline=False):
  2318. config_path = os.path.basename(dispatch_src)
  2319. config_path = os.path.splitext(config_path)[0] + '.h'
  2320. config_path = os.path.join(output_dir, config_path)
  2321. # check if targets didn't change to avoid recompiling
  2322. cache_hash = self.cache_hash(targets, has_baseline)
  2323. try:
  2324. with open(config_path) as f:
  2325. last_hash = f.readline().split("cache_hash:")
  2326. if len(last_hash) == 2 and int(last_hash[1]) == cache_hash:
  2327. return True
  2328. except OSError:
  2329. pass
  2330. os.makedirs(os.path.dirname(config_path), exist_ok=True)
  2331. self.dist_log("generate dispatched config -> ", config_path)
  2332. dispatch_calls = []
  2333. for tar in targets:
  2334. if isinstance(tar, str):
  2335. target_name = tar
  2336. else: # multi target
  2337. target_name = '__'.join([t for t in tar])
  2338. req_detect = self.feature_detect(tar)
  2339. req_detect = '&&'.join([
  2340. "CHK(%s)" % f for f in req_detect
  2341. ])
  2342. dispatch_calls.append(
  2343. "\t%sCPU_DISPATCH_EXPAND_(CB((%s), %s, __VA_ARGS__))" % (
  2344. self.conf_c_prefix_, req_detect, target_name
  2345. ))
  2346. dispatch_calls = ' \\\n'.join(dispatch_calls)
  2347. if has_baseline:
  2348. baseline_calls = (
  2349. "\t%sCPU_DISPATCH_EXPAND_(CB(__VA_ARGS__))"
  2350. ) % self.conf_c_prefix_
  2351. else:
  2352. baseline_calls = ''
  2353. with open(config_path, "w") as fd:
  2354. fd.write(textwrap.dedent("""\
  2355. // cache_hash:{cache_hash}
  2356. /**
  2357. * AUTOGENERATED DON'T EDIT
  2358. * Please make changes to the code generator (distutils/ccompiler_opt.py)
  2359. */
  2360. #ifndef {pfx}CPU_DISPATCH_EXPAND_
  2361. #define {pfx}CPU_DISPATCH_EXPAND_(X) X
  2362. #endif
  2363. #undef {pfx}CPU_DISPATCH_BASELINE_CALL
  2364. #undef {pfx}CPU_DISPATCH_CALL
  2365. #define {pfx}CPU_DISPATCH_BASELINE_CALL(CB, ...) \\
  2366. {baseline_calls}
  2367. #define {pfx}CPU_DISPATCH_CALL(CHK, CB, ...) \\
  2368. {dispatch_calls}
  2369. """).format(
  2370. pfx=self.conf_c_prefix_, baseline_calls=baseline_calls,
  2371. dispatch_calls=dispatch_calls, cache_hash=cache_hash
  2372. ))
  2373. return False
  2374. def new_ccompiler_opt(compiler, dispatch_hpath, **kwargs):
  2375. """
  2376. Create a new instance of 'CCompilerOpt' and generate the dispatch header
  2377. which contains the #definitions and headers of platform-specific instruction-sets for
  2378. the enabled CPU baseline and dispatch-able features.
  2379. Parameters
  2380. ----------
  2381. compiler : CCompiler instance
  2382. dispatch_hpath : str
  2383. path of the dispatch header
  2384. **kwargs: passed as-is to `CCompilerOpt(...)`
  2385. Returns
  2386. -------
  2387. new instance of CCompilerOpt
  2388. """
  2389. opt = CCompilerOpt(compiler, **kwargs)
  2390. if not os.path.exists(dispatch_hpath) or not opt.is_cached():
  2391. opt.generate_dispatch_header(dispatch_hpath)
  2392. return opt