xref: /petsc/config/BuildSystem/config/compilerFlags.py (revision b63c620b66da884efdf690e70d6f9f5511a4e974)
1import config.base
2import re
3import os
4
5class Configure(config.base.Configure):
6  def __init__(self, framework):
7    config.base.Configure.__init__(self, framework)
8    self.headerPrefix = ''
9    self.substPrefix  = ''
10    self.version = {}
11    self.rejected = {}
12    self.text = ''
13    return
14
15  def __str__(self):
16    return self.text
17
18  def setupHelp(self, help):
19    import nargs
20    help.addArgument('Compiler Flags', '-optionsModule=<module name>', nargs.Arg(None, 'config.compilerOptions', 'The Python module used to determine compiler options and versions'))
21    help.addArgument('Compiler Flags', '-with-debugging=<bool>', nargs.ArgBool(None, 1, 'Specify debugging version of libraries'))
22    help.addArgument('Compiler Flags', '-C_VERSION=<string>',   nargs.Arg(None, 'Unknown', 'The version of the C compiler'))
23    help.addArgument('Compiler Flags', '-CXX_VERSION=<string>', nargs.Arg(None, 'Unknown', 'The version of the C++ compiler'))
24    help.addArgument('Compiler Flags', '-FC_VERSION=<string>',  nargs.Arg(None, 'Unknown', 'The version of the Fortran compiler'))
25    help.addArgument('Compiler Flags', '-CUDA_VERSION=<string>',nargs.Arg(None, 'Unknown', 'The version of the CUDA compiler'))
26    help.addArgument('Compiler Flags', '-HIP_VERSION=<string>',nargs.Arg(None, 'Unknown', 'The version of the HIP compiler'))
27    help.addArgument('Compiler Flags', '-SYCL_VERSION=<string>',nargs.Arg(None, 'Unknown', 'The version of the SYCL compiler'))
28    help.addArgument('Compiler Flags', '-COPTFLAGS=<string>',   nargs.Arg(None, None, 'Override the debugging/optimization flags for the C compiler'))
29    help.addArgument('Compiler Flags', '-CXXOPTFLAGS=<string>', nargs.Arg(None, None, 'Override the debugging/optimization flags for the C++ compiler'))
30    help.addArgument('Compiler Flags', '-FOPTFLAGS=<string>',   nargs.Arg(None, None, 'Override the debugging/optimization flags for the Fortran compiler'))
31    help.addArgument('Compiler Flags', '-CUDAOPTFLAGS=<string>',   nargs.Arg(None, None, 'Override the debugging/optimization flags for the CUDA compiler'))
32    help.addArgument('Compiler Flags', '-HIPOPTFLAGS=<string>',   nargs.Arg(None, None, 'Override the debugging/optimization flags for the HIP compiler'))
33    help.addArgument('Compiler Flags', '-SYCLOPTFLAGS=<string>',   nargs.Arg(None, None, 'Override the debugging/optimization flags for the SYCL compiler'))
34    help.addArgument('Compiler Flags', '-with-gcov=<bool>', nargs.ArgBool(None, value=None, help='Specify that GNUs coverage tool gcov is used', deprecated='--with-coverage'))
35    return
36
37  def setupDependencies(self, framework):
38    config.base.Configure.setupDependencies(self, framework)
39    self.setCompilers = framework.require('config.setCompilers', self)
40    return
41
42  def getOptionalFlagsName(self, language, compilerOnly = 0):
43    if language == 'C':
44      flagsArg = 'COPTFLAGS'
45    elif language == 'Cxx':
46      if compilerOnly:
47        flagsArg = 'CXX_CXXOPTFLAGS'
48      else:
49        flagsArg = 'CXXOPTFLAGS'
50    elif language == 'FC':
51      flagsArg = 'FOPTFLAGS'
52    elif language == 'CUDA':
53      flagsArg = 'CUDAOPTFLAGS'
54    elif language == 'HIP':
55      flagsArg = 'HIPOPTFLAGS'
56    elif language == 'SYCL':
57      flagsArg = 'SYCLOPTFLAGS'
58    else:
59      raise RuntimeError('Unknown language: '+language)
60    return flagsArg
61
62  def findOptFlags(self, flags):
63    if isinstance(flags, str):
64      flags = flags.split()
65
66    return [f for f in flags if f.startswith('-g') or f.startswith('-O') or f in {'-fast'}]
67
68  def hasOptFlags(self,flags):
69    return len(self.findOptFlags(flags)) > 0
70
71  def getOptionsObject(self):
72    '''Get a configure object which will return default options for each compiler'''
73    options = None
74    try:
75      mod     = __import__(self.argDB['optionsModule'], locals(), globals(), ['CompilerOptions'])
76      options = mod.CompilerOptions(self.framework)
77      options.setup()
78    except ImportError:
79      self.logPrint('ERROR: Failed to load user options module '+str(self.argDB['optionsModule']))
80    return options
81
82  def configureCompilerFlags(self):
83    '''Get the default compiler flags'''
84    self.debugging = self.argDB['with-debugging']
85    bopts = ['', '+']
86    if self.debugging:
87      bopts.append('g')
88    else:
89      bopts.append('O')
90
91    options = self.getOptionsObject()
92    if not options:
93      return
94    options.saveLog()
95    for language, compiler in [('C', 'CC'), ('Cxx', 'CXX'), ('FC', 'FC'), ('CUDA', 'CUDAC'), ('HIP', 'HIPC'), ('SYCL', 'SYCLC')]:
96      if not hasattr(self.setCompilers, compiler):
97        continue
98      self.setCompilers.pushLanguage(language)
99      flagsName = config.base.Configure.getCompilerFlagsName(language)
100      try:
101        self.version[language] = self.argDB[language.upper()+'_VERSION']
102        if self.version[language] == 'Unknown':
103          self.version[language] = options.getCompilerVersion(language, self.setCompilers.getCompiler())
104      except RuntimeError:
105        pass
106      self.rejected[language] = []
107      for bopt in bopts:
108        userflags = 0
109        userlangflags = 0
110        if bopt in ['g','O'] and self.getOptionalFlagsName(language) in self.argDB: # check --COPTFLAGS etc
111          # treat user supplied options as single option - as it could include options separated by spaces '-tp k8-64'
112          flags = [self.argDB[self.getOptionalFlagsName(language)]]
113          userflags = 1
114        elif bopt in ['g','O'] and self.hasOptFlags(getattr(self.setCompilers,flagsName)): # check --CFLAGS etc
115          self.logPrint('Optimization options found in '+flagsName+ '. Skipping setting defaults')
116          flags = []
117        elif bopt == '' and flagsName in self.argDB:
118          self.logPrint('Ignoring default options which were overridden using --'+flagsName+ ' ' + self.argDB[flagsName])
119          flags = []
120        elif bopt == '+' and flagsName+'+' in self.argDB:
121          flags = [self.argDB[flagsName+'+']]
122          userlangflags = 1
123        elif not bopt == '+':
124          flags = options.getCompilerFlags(language, self.setCompilers.getCompiler(), bopt)
125
126        for testFlag in flags:
127          if isinstance(testFlag, (tuple, list)):
128            testFlag = ' '.join(testFlag)
129          self.logPrint('Trying '+language+' compiler flag '+testFlag)
130          try:
131            self.setCompilers.addCompilerFlag(testFlag)
132          except RuntimeError:
133            if userflags:
134              raise RuntimeError('User provided flags for language '+language+' with '+self.getOptionalFlagsName(language)+': '+self.argDB[self.getOptionalFlagsName(language)]+' are not correct for the compiler')
135            if userlangflags:
136              raise RuntimeError('User provided flags for language '+language+' with '+flagsName+'+: '+self.argDB[flagsName+'+']+' are not correct for the compiler')
137            self.logPrint('Rejected '+language+' compiler flag '+testFlag)
138            self.rejected[language].append(testFlag)
139      self.setCompilers.popLanguage()
140    return
141
142  def outputCompilerMacros(self):
143    '''Cannot use the regular outputCompile because it swallows the output into the -o file'''
144    command = self.getCompilerCmd()
145    if self.compilerDefines: self.framework.outputHeader(self.compilerDefines)
146    self.framework.outputCHeader(self.compilerFixes)
147    f = open(self.compilerSource, 'w')
148    f.close()
149    try:
150      command = command + ' -E -dM '
151      start = command.find('-o ')
152      end = start + 3 + command[start+3:].find(' ')
153      command = command[:start-1]+command[end:]
154      (out, err, ret) = Configure.executeShellCommand(command, log = self.log)
155      if out.find('__AVX2__') > -1 and out.find('__FMA__') > -1:
156        self.text = self.text + 'Intel instruction sets utilizable by compiler:\n'
157        self.text = self.text + '  AVX2\n'
158      if out.find('__AVX512') > -1:
159        self.text = self.text + '  AVX512: '
160        self.text = self.text + ' '.join([i for i in out.split('__') if i.startswith('AVX512')])
161        self.text = self.text + '\n'
162    except:
163      pass
164    for filename in [self.compilerDefines, self.compilerFixes, self.compilerSource, self.compilerObj]:
165      if os.path.isfile(filename): os.remove(filename)
166
167  def checkCompilerMacros(self):
168    '''Save the list of CPP macros defined by the C and C++ compiler, does not work for all compilers'''
169    '''The values will depends on the flags passed to the compiler'''
170    self.outputCompilerMacros()
171    if hasattr(self.setCompilers, 'CXX'):
172      with self.Language('Cxx'):
173        self.outputCompilerMacros()
174    return
175
176  def checkIntelHardwareSupport(self):
177    '''Use Linux/macOS commands to determine what operations the hardware supports'''
178    try:
179      (out, err, ret) = Configure.executeShellCommand('lscpu', log = self.log)
180    except:
181      out = ''
182    if out.find(' avx2 ') > -1 and out.find(' fma ') > -1:
183      self.text = self.text + 'Intel instruction sets found on CPU:\n'
184      self.text = self.text + '  AVX2\n'
185    if out.find(' avx512') > -1:
186      self.text = self.text + '  AVX512: '
187      self.text = self.text + ' '.join([i for i in out.split(' ') if i.startswith('avx512')])
188      self.text = self.text + '\n'
189    return
190
191  def configure(self):
192    self.executeTest(self.configureCompilerFlags)
193    self.executeTest(self.checkIntelHardwareSupport)
194    self.executeTest(self.checkCompilerMacros)
195    return
196