xref: /petsc/config/PETSc/Configure.py (revision 5d4804778dfa45ea00bcad8aabdb3eca36eaeac3)
1import config.base
2
3import os
4import re
5
6# The sorted() builtin is not available with python-2.3
7try: sorted
8except NameError:
9  def sorted(lst):
10    lst.sort()
11    return lst
12
13class Configure(config.base.Configure):
14  def __init__(self, framework):
15    config.base.Configure.__init__(self, framework)
16    self.headerPrefix = 'PETSC'
17    self.substPrefix  = 'PETSC'
18    return
19
20  def __str2__(self):
21    desc = []
22    desc.append('xxx=========================================================================xxx')
23    desc.append('   Configure stage complete. Now build PETSc libraries with:')
24    desc.append('   make PETSC_DIR='+self.petscdir.dir+' PETSC_ARCH='+self.arch.arch+' all')
25    desc.append(' or:')
26    desc.append('   PETSC_DIR='+self.petscdir.dir+' PETSC_ARCH='+self.arch.arch+' ./config/builder.py')
27    desc.append('xxx=========================================================================xxx')
28    return '\n'.join(desc)+'\n'
29
30  def setupHelp(self, help):
31    import nargs
32    help.addArgument('PETSc',  '-prefix=<dir>',                  nargs.Arg(None, '', 'Specifiy location to install PETSc (eg. /usr/local)'))
33    help.addArgument('Windows','-with-windows-graphics=<bool>',   nargs.ArgBool(None, 1,'Enable check for Windows Graphics'))
34    help.addArgument('PETSc', '-with-default-arch=<bool>',        nargs.ArgBool(None, 1, 'Allow using the last configured arch without setting PETSC_ARCH'))
35    help.addArgument('PETSc','-with-single-library=<bool>',       nargs.ArgBool(None, 1,'Put all PETSc code into the single -lpetsc library'))
36    help.addArgument('PETSc', '-with-iphone=<bool>',              nargs.ArgBool(None, 0, 'Build an iPhone version of PETSc'))
37    return
38
39  def setupDependencies(self, framework):
40    config.base.Configure.setupDependencies(self, framework)
41    self.setCompilers  = framework.require('config.setCompilers',      self)
42    self.arch          = framework.require('PETSc.utilities.arch',     self.setCompilers)
43    self.petscdir      = framework.require('PETSc.utilities.petscdir', self.setCompilers)
44    self.languages     = framework.require('PETSc.utilities.languages',self.setCompilers)
45    self.debugging     = framework.require('PETSc.utilities.debugging',self.setCompilers)
46    self.CHUD          = framework.require('PETSc.utilities.CHUD',     self)
47    self.compilers     = framework.require('config.compilers',         self)
48    self.types         = framework.require('config.types',             self)
49    self.headers       = framework.require('config.headers',           self)
50    self.functions     = framework.require('config.functions',         self)
51    self.libraries     = framework.require('config.libraries',         self)
52    if os.path.isdir(os.path.join('config', 'PETSc')):
53      for d in ['utilities', 'packages']:
54        for utility in os.listdir(os.path.join('config', 'PETSc', d)):
55          (utilityName, ext) = os.path.splitext(utility)
56          if not utilityName.startswith('.') and not utilityName.startswith('#') and ext == '.py' and not utilityName == '__init__':
57            utilityObj                    = self.framework.require('PETSc.'+d+'.'+utilityName, self)
58            utilityObj.headerPrefix       = self.headerPrefix
59            utilityObj.archProvider       = self.arch
60            utilityObj.languageProvider   = self.languages
61            utilityObj.installDirProvider = self.petscdir
62            setattr(self, utilityName.lower(), utilityObj)
63
64    for package in config.packages.all:
65      if not package == 'PETSc':
66        packageObj                    = framework.require('config.packages.'+package, self)
67        packageObj.archProvider       = self.arch
68        packageObj.languageProvider   = self.languages
69        packageObj.installDirProvider = self.petscdir
70        setattr(self, package.lower(), packageObj)
71    # Force blaslapack to depend on scalarType so precision is set before BlasLapack is built
72    framework.require('PETSc.utilities.scalarTypes', self.blaslapack)
73    self.blaslapack.precisionProvider = self.scalartypes
74
75    self.compilers.headerPrefix  = self.headerPrefix
76    self.types.headerPrefix      = self.headerPrefix
77    self.headers.headerPrefix    = self.headerPrefix
78    self.functions.headerPrefix  = self.headerPrefix
79    self.libraries.headerPrefix  = self.headerPrefix
80    self.blaslapack.headerPrefix = self.headerPrefix
81    self.mpi.headerPrefix        = self.headerPrefix
82    headersC = map(lambda name: name+'.h', ['dos', 'endian', 'fcntl', 'float', 'io', 'limits', 'malloc', 'pwd', 'search', 'strings',
83                                            'unistd', 'machine/endian', 'sys/param', 'sys/procfs', 'sys/resource',
84                                            'sys/systeminfo', 'sys/times', 'sys/utsname','string', 'stdlib','memory',
85                                            'sys/socket','sys/wait','netinet/in','netdb','Direct','time','Ws2tcpip','sys/types',
86                                            'WindowsX', 'cxxabi','float','ieeefp','stdint','fenv'])
87    functions = ['access', '_access', 'clock', 'drand48', 'getcwd', '_getcwd', 'getdomainname', 'gethostname', 'getpwuid',
88                 'gettimeofday', 'getwd', 'memalign', 'memmove', 'mkstemp', 'popen', 'PXFGETARG', 'rand', 'getpagesize',
89                 'readlink', 'realpath',  'sigaction', 'signal', 'sigset', 'nanosleep', 'usleep', 'sleep', '_sleep', 'socket',
90                 'times', 'gethostbyname', 'uname','snprintf','_snprintf','_fullpath','lseek','_lseek','time','fork','stricmp',
91                 'strcasecmp', 'bzero', 'dlopen', 'dlsym', 'dlclose', 'dlerror',
92                 '_intel_fast_memcpy','_intel_fast_memset']
93    libraries1 = [(['socket', 'nsl'], 'socket'), (['fpe'], 'handle_sigfpes')]
94    self.headers.headers.extend(headersC)
95    self.functions.functions.extend(functions)
96    self.libraries.libraries.extend(libraries1)
97
98    return
99
100  def Dump(self):
101    ''' Actually put the values into the configuration files '''
102    # eventually everything between -- should be gone
103#-----------------------------------------------------------------------------------------------------
104
105    # Sometimes we need C compiler, even if built with C++
106    self.setCompilers.pushLanguage('C')
107    self.addMakeMacro('CC_FLAGS',self.setCompilers.getCompilerFlags())
108    self.setCompilers.popLanguage()
109
110    # C preprocessor values
111    self.addMakeMacro('CPP_FLAGS',self.setCompilers.CPPFLAGS+self.CHUD.CPPFLAGS)
112
113    # compiler values
114    self.setCompilers.pushLanguage(self.languages.clanguage)
115    self.addMakeMacro('PCC',self.setCompilers.getCompiler())
116    self.addMakeMacro('PCC_FLAGS',self.setCompilers.getCompilerFlags())
117    self.setCompilers.popLanguage()
118    # .o or .obj
119    self.addMakeMacro('CC_SUFFIX','o')
120
121    # executable linker values
122    self.setCompilers.pushLanguage(self.languages.clanguage)
123    pcc_linker = self.setCompilers.getLinker()
124    self.addMakeMacro('PCC_LINKER',pcc_linker)
125    self.addMakeMacro('PCC_LINKER_FLAGS',self.setCompilers.getLinkerFlags())
126    self.setCompilers.popLanguage()
127    # '' for Unix, .exe for Windows
128    self.addMakeMacro('CC_LINKER_SUFFIX','')
129
130    if hasattr(self.compilers, 'FC'):
131      self.setCompilers.pushLanguage('FC')
132      # need FPPFLAGS in config/setCompilers
133      self.addDefine('HAVE_FORTRAN','1')
134      self.addMakeMacro('FPP_FLAGS',self.setCompilers.CPPFLAGS)
135
136      # compiler values
137      self.addMakeMacro('FC_FLAGS',self.setCompilers.getCompilerFlags())
138      self.setCompilers.popLanguage()
139      # .o or .obj
140      self.addMakeMacro('FC_SUFFIX','o')
141
142      # executable linker values
143      self.setCompilers.pushLanguage('FC')
144      # Cannot have NAG f90 as the linker - so use pcc_linker as fc_linker
145      fc_linker = self.setCompilers.getLinker()
146      if config.setCompilers.Configure.isNAG(fc_linker):
147        self.addMakeMacro('FC_LINKER',pcc_linker)
148      else:
149        self.addMakeMacro('FC_LINKER',fc_linker)
150      self.addMakeMacro('FC_LINKER_FLAGS',self.setCompilers.getLinkerFlags())
151      # apple requires this shared library linker flag on SOME versions of the os
152      if self.setCompilers.getLinkerFlags().find('-Wl,-commons,use_dylibs') > -1:
153        self.addMakeMacro('DARWIN_COMMONS_USE_DYLIBS',' -Wl,-commons,use_dylibs ')
154      self.setCompilers.popLanguage()
155
156      # F90 Modules
157      if self.setCompilers.fortranModuleIncludeFlag:
158        self.addMakeMacro('FC_MODULE_FLAG', self.setCompilers.fortranModuleIncludeFlag)
159      else: # for non-f90 compilers like g77
160        self.addMakeMacro('FC_MODULE_FLAG', '-I')
161      if self.setCompilers.fortranModuleIncludeFlag:
162        self.addMakeMacro('FC_MODULE_OUTPUT_FLAG', self.setCompilers.fortranModuleOutputFlag)
163    else:
164      self.addMakeMacro('FC','')
165
166    if hasattr(self.compilers, 'CUDAC'):
167      self.setCompilers.pushLanguage('CUDA')
168      self.addMakeMacro('CUDAC_FLAGS',self.setCompilers.getCompilerFlags())
169      self.setCompilers.popLanguage()
170
171    # shared library linker values
172    self.setCompilers.pushLanguage(self.languages.clanguage)
173    # need to fix BuildSystem to collect these separately
174    self.addMakeMacro('SL_LINKER',self.setCompilers.getLinker())
175    self.addMakeMacro('SL_LINKER_FLAGS','${PCC_LINKER_FLAGS}')
176    self.setCompilers.popLanguage()
177    # One of 'a', 'so', 'lib', 'dll', 'dylib' (perhaps others also?) depending on the library generator and architecture
178    # Note: . is not included in this macro, consistent with AR_LIB_SUFFIX
179    if self.setCompilers.sharedLibraryExt == self.setCompilers.AR_LIB_SUFFIX:
180      self.addMakeMacro('SL_LINKER_SUFFIX', '')
181      self.addDefine('SLSUFFIX','""')
182    else:
183      self.addMakeMacro('SL_LINKER_SUFFIX', self.setCompilers.sharedLibraryExt)
184      self.addDefine('SLSUFFIX','"'+self.setCompilers.sharedLibraryExt+'"')
185
186    self.addMakeMacro('SL_LINKER_LIBS','${PETSC_EXTERNAL_LIB_BASIC}')
187
188#-----------------------------------------------------------------------------------------------------
189
190    # CONLY or CPP. We should change the PETSc makefiles to do this better
191    if self.languages.clanguage == 'C': lang = 'CONLY'
192    else: lang = 'CXXONLY'
193    self.addMakeMacro('PETSC_LANGUAGE',lang)
194
195    # real or complex
196    self.addMakeMacro('PETSC_SCALAR',self.scalartypes.scalartype)
197    # double or float
198    self.addMakeMacro('PETSC_PRECISION',self.scalartypes.precision)
199
200    if self.framework.argDB['with-batch']:
201      self.addMakeMacro('PETSC_WITH_BATCH','1')
202
203    # Test for compiler-specific macros that need to be defined.
204    if self.setCompilers.isCrayVector('CC'):
205      self.addDefine('HAVE_CRAY_VECTOR','1')
206
207#-----------------------------------------------------------------------------------------------------
208    if self.functions.haveFunction('gethostbyname') and self.functions.haveFunction('socket'):
209      self.addDefine('USE_SOCKET_VIEWER','1')
210
211#-----------------------------------------------------------------------------------------------------
212    # print include and lib for makefiles
213    self.framework.packages.reverse()
214    includes = [os.path.join(self.petscdir.dir,'include'),os.path.join(self.petscdir.dir,self.arch.arch,'include')]
215    libs = []
216    for i in self.framework.packages:
217      if i.useddirectly:
218        self.addDefine('HAVE_'+i.PACKAGE, 1)  # ONLY list package if it is used directly by PETSc (and not only by another package)
219      if not isinstance(i.lib, list):
220        i.lib = [i.lib]
221      libs.extend(i.lib)
222      self.addMakeMacro(i.PACKAGE+'_LIB', self.libraries.toStringNoDupes(i.lib))
223      if hasattr(i,'include'):
224        if not isinstance(i.include,list):
225          i.include = [i.include]
226        includes.extend(i.include)
227        self.addMakeMacro(i.PACKAGE+'_INCLUDE',self.headers.toStringNoDupes(i.include))
228    if self.framework.argDB['with-single-library']:
229      self.addMakeMacro('PETSC_WITH_EXTERNAL_LIB',self.libraries.toStringNoDupes(['-L'+os.path.join(self.petscdir.dir,self.arch.arch,'lib'),' -lpetsc']+libs+self.libraries.math+self.compilers.flibs+self.compilers.cxxlibs+self.compilers.LIBS.split(' '))+self.CHUD.LIBS)
230    self.addMakeMacro('PETSC_EXTERNAL_LIB_BASIC',self.libraries.toStringNoDupes(libs+self.libraries.math+self.compilers.flibs+self.compilers.cxxlibs+self.compilers.LIBS.split(' '))+self.CHUD.LIBS)
231    self.PETSC_EXTERNAL_LIB_BASIC = self.libraries.toStringNoDupes(libs+self.libraries.math+self.compilers.flibs+self.compilers.cxxlibs+self.compilers.LIBS.split(' '))+self.CHUD.LIBS
232    self.addMakeMacro('PETSC_CC_INCLUDES',self.headers.toStringNoDupes(includes))
233    self.PETSC_CC_INCLUDES = self.headers.toStringNoDupes(includes)
234    if hasattr(self.compilers, 'FC'):
235      if self.compilers.fortranIsF90:
236        self.addMakeMacro('PETSC_FC_INCLUDES',self.headers.toStringNoDupes(includes,includes))
237      else:
238        self.addMakeMacro('PETSC_FC_INCLUDES',self.headers.toStringNoDupes(includes))
239
240    self.addMakeMacro('DESTDIR',self.installdir)
241    self.addDefine('LIB_DIR','"'+os.path.join(self.installdir,'lib')+'"')
242
243    if self.framework.argDB['with-single-library']:
244      # overrides the values set in conf/variables
245      self.addMakeMacro('LIBNAME','${INSTALL_LIB_DIR}/libpetsc.${AR_LIB_SUFFIX}')
246      self.addMakeMacro('SHLIBS','libpetsc')
247      self.addMakeMacro('PETSC_LIB_BASIC','-lpetsc')
248      self.addMakeMacro('PETSC_KSP_LIB_BASIC','-lpetsc')
249      self.addMakeMacro('PETSC_TS_LIB_BASIC','-lpetsc')
250      self.addDefine('USE_SINGLE_LIBRARY', '1')
251      if self.sharedlibraries.useShared:
252        self.addMakeMacro('PETSC_SYS_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
253        self.addMakeMacro('PETSC_VEC_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
254        self.addMakeMacro('PETSC_MAT_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
255        self.addMakeMacro('PETSC_DM_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
256        self.addMakeMacro('PETSC_KSP_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
257        self.addMakeMacro('PETSC_SNES_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
258        self.addMakeMacro('PETSC_TS_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
259        self.addMakeMacro('PETSC_CHARACTERISTIC_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
260        self.addMakeMacro('PETSC_LIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
261        self.addMakeMacro('PETSC_CONTRIB','${C_SH_LIB_PATH} ${PETSC_WITH_EXTERNAL_LIB}')
262      else:
263        self.addMakeMacro('PETSC_SYS_LIB','${PETSC_WITH_EXTERNAL_LIB}')
264        self.addMakeMacro('PETSC_VEC_LIB','${PETSC_WITH_EXTERNAL_LIB}')
265        self.addMakeMacro('PETSC_MAT_LIB','${PETSC_WITH_EXTERNAL_LIB}')
266        self.addMakeMacro('PETSC_DM_LIB','${PETSC_WITH_EXTERNAL_LIB}')
267        self.addMakeMacro('PETSC_KSP_LIB','${PETSC_WITH_EXTERNAL_LIB}')
268        self.addMakeMacro('PETSC_SNES_LIB','${PETSC_WITH_EXTERNAL_LIB}')
269        self.addMakeMacro('PETSC_TS_LIB','${PETSC_WITH_EXTERNAL_LIB}')
270        self.addMakeMacro('PETSC_CHARACTERISTIC_LIB','${PETSC_WITH_EXTERNAL_LIB}')
271        self.addMakeMacro('PETSC_LIB','${PETSC_WITH_EXTERNAL_LIB}')
272        self.addMakeMacro('PETSC_CONTRIB','${PETSC_WITH_EXTERNAL_LIB}')
273
274    if not os.path.exists(os.path.join(self.petscdir.dir,self.arch.arch,'lib')):
275      os.makedirs(os.path.join(self.petscdir.dir,self.arch.arch,'lib'))
276
277    # add a makefile entry for configure options
278    self.addMakeMacro('CONFIGURE_OPTIONS', self.framework.getOptionsString(['configModules', 'optionsModule']).replace('\"','\\"'))
279    return
280
281  def dumpConfigInfo(self):
282    import time
283    fd = file(os.path.join(self.arch.arch,'include','petscconfiginfo.h'),'w')
284    fd.write('static const char *petscconfigureruntime = "'+time.ctime(time.time())+'";\n')
285    fd.write('static const char *petscconfigureoptions = "'+self.framework.getOptionsString(['configModules', 'optionsModule']).replace('\"','\\"')+'";\n')
286    fd.close()
287    return
288
289  def dumpMachineInfo(self):
290    import platform
291    import time
292    import script
293    fd = file(os.path.join(self.arch.arch,'include','petscmachineinfo.h'),'w')
294    fd.write('static const char *petscmachineinfo = \"\\n\"\n')
295    fd.write('\"-----------------------------------------\\n\"\n')
296    fd.write('\"Libraries compiled on %s on %s \\n\"\n' % (time.ctime(time.time()), platform.node()))
297    fd.write('\"Machine characteristics: %s\\n\"\n' % (platform.platform()))
298    fd.write('\"Using PETSc directory: %s\\n\"\n' % (self.petscdir.dir))
299    fd.write('\"Using PETSc arch: %s\\n\"\n' % (self.arch.arch))
300    fd.write('\"-----------------------------------------\\n\";\n')
301    fd.write('static const char *petsccompilerinfo = \"\\n\"\n')
302    self.setCompilers.pushLanguage(self.languages.clanguage)
303    fd.write('\"Using C compiler: %s %s ${COPTFLAGS} ${CFLAGS}\\n\"\n' % (self.setCompilers.getCompiler(), self.setCompilers.getCompilerFlags()))
304    self.setCompilers.popLanguage()
305    if hasattr(self.compilers, 'FC'):
306      self.setCompilers.pushLanguage('FC')
307      fd.write('\"Using Fortran compiler: %s %s ${FOPTFLAGS} ${FFLAGS} %s\\n\"\n' % (self.setCompilers.getCompiler(), self.setCompilers.getCompilerFlags(), self.setCompilers.CPPFLAGS))
308      self.setCompilers.popLanguage()
309    fd.write('\"-----------------------------------------\\n\";\n')
310    fd.write('static const char *petsccompilerflagsinfo = \"\\n\"\n')
311    fd.write('\"Using include paths: %s %s %s\\n\"\n' % ('-I'+os.path.join(self.petscdir.dir, self.arch.arch, 'include'), '-I'+os.path.join(self.petscdir.dir, 'include'), self.PETSC_CC_INCLUDES))
312    fd.write('\"-----------------------------------------\\n\";\n')
313    fd.write('static const char *petsclinkerinfo = \"\\n\"\n')
314    self.setCompilers.pushLanguage(self.languages.clanguage)
315    fd.write('\"Using C linker: %s\\n\"\n' % (self.setCompilers.getLinker()))
316    self.setCompilers.popLanguage()
317    if hasattr(self.compilers, 'FC'):
318      self.setCompilers.pushLanguage('FC')
319      fd.write('\"Using Fortran linker: %s\\n\"\n' % (self.setCompilers.getLinker()))
320      self.setCompilers.popLanguage()
321    fd.write('\"Using libraries: %s%s -L%s %s %s\\n\"\n' % (self.setCompilers.CSharedLinkerFlag, os.path.join(self.petscdir.dir, self.arch.arch, 'lib'), os.path.join(self.petscdir.dir, self.arch.arch, 'lib'), '-lpetscts -lpetscsnes -lpetscksp -lpetscdm -lpetscmat -lpetscvec -lpetscsys', self.PETSC_EXTERNAL_LIB_BASIC))
322    fd.write('\"-----------------------------------------\\n\";\n')
323    fd.close()
324    return
325
326  def dumpCMakeConfig(self):
327    '''
328    Writes configuration-specific values to ${PETSC_ARCH}/conf/PETScConfig.cmake.
329    This file is private to PETSc and should not be included by third parties
330    (a suitable file can be produced later by CMake, but this is not it).
331    '''
332    def cmakeset(fd,key,val=True):
333      if val == True: val = 'YES'
334      if val == False: val = 'NO'
335      fd.write('set (' + key + ' ' + val + ')\n')
336    def ensurelist(a):
337      if isinstance(a,list):
338        return a
339      else:
340        return [a]
341    def libpath(lib):
342      'Returns a search path if that is what this item provides, else "" which will be cleaned out later'
343      if not isinstance(lib,str): return ''
344      if lib.startswith('-L'): return lib[2:]
345      if lib.startswith('-R'): return lib[2:]
346      if lib.startswith('-Wl,-rpath,'):
347        # This case occurs when an external package needs a specific system library that is normally provided by the compiler.
348        # In other words, the -L path is builtin to the wrapper or compiler, here we provide it so that CMake can locate the
349        # corresponding library.
350        return lib[len('-Wl,-rpath,'):]
351      if lib.startswith('-'): return ''
352      return os.path.dirname(lib)
353    def cleanlib(lib):
354      'Returns a library name if that is what this item provides, else "" which will be cleaned out later'
355      if not isinstance(lib,str): return ''
356      if lib.startswith('-l'):  return lib[2:]
357      if lib.startswith('-Wl') or lib.startswith('-L'): return ''
358      lib = os.path.splitext(os.path.basename(lib))[0]
359      if lib.startswith('lib'): return lib[3:]
360      return lib
361    def nub(lst):
362      'Return a list containing the first occurrence of each unique element'
363      unique = []
364      for elem in lst:
365        if elem not in unique and elem != '':
366          unique.append(elem)
367      return unique
368    try: reversed # reversed was added in Python-2.4
369    except NameError:
370      def reversed(lst): return lst[::-1]
371    def nublast(lst):
372      'Return a list containing the last occurrence of each unique entry in a list'
373      return reversed(nub(reversed(lst)))
374    def cmakeexpand(varname):
375      return r'"${' + varname + r'}"'
376    def uniqextend(lst,new):
377      for x in ensurelist(new):
378        if x not in lst:
379          lst.append(x)
380    def notstandardinclude(path):
381      return path not in '/usr/include /usr/local/include'.split()
382    def writeMacroDefinitions(fd):
383      if self.mpi.usingMPIUni:
384        cmakeset(fd,'PETSC_HAVE_MPIUNI')
385      for pkg in self.framework.packages:
386        if pkg.useddirectly:
387          cmakeset(fd,'PETSC_HAVE_' + pkg.PACKAGE)
388      for name,val in self.functions.defines.items():
389        cmakeset(fd,'PETSC_'+name,val)
390      for dct in [self.defines, self.libraryoptions.defines]:
391        for k,v in dct.items():
392          if k.startswith('USE_'):
393            cmakeset(fd,'PETSC_' + k, v)
394      cmakeset(fd,'PETSC_USE_COMPLEX', self.scalartypes.scalartype == 'complex')
395      cmakeset(fd,'PETSC_USE_REAL_' + self.scalartypes.precision.upper())
396      cmakeset(fd,'PETSC_CLANGUAGE_'+self.languages.clanguage)
397      if hasattr(self.compilers, 'FC'):
398        cmakeset(fd,'PETSC_HAVE_FORTRAN')
399        if self.compilers.fortranIsF90:
400          cmakeset(fd,'PETSC_USING_F90')
401      if self.sharedlibraries.useShared:
402        cmakeset(fd,'BUILD_SHARED_LIBS')
403    def writeBuildFlags(fd):
404      def extendby(lib):
405        libs = ensurelist(lib)
406        lib_paths.extend(map(libpath,libs))
407        lib_libs.extend(map(cleanlib,libs))
408        uniqextend(includes,pkg.include)
409      lib_paths = []
410      lib_libs  = []
411      includes  = []
412      libvars   = []
413      for pkg in self.framework.packages:
414        extendby(pkg.lib)
415      extendby(self.libraries.math)
416      extendby(self.libraries.rt)
417      extendby(self.compilers.flibs)
418      extendby(self.compilers.cxxlibs)
419      extendby(self.compilers.LIBS.split())
420      for libname in nublast(lib_libs):
421        libvar = 'PETSC_' + libname.upper() + '_LIB'
422        addpath = ''
423        for lpath in nublast(lib_paths):
424          addpath += '"' + str(lpath) + '" '
425        fd.write('find_library (' + libvar + ' ' + libname + ' HINTS ' + addpath + ')\n')
426        libvars.append(libvar)
427      fd.write('mark_as_advanced (' + ' '.join(libvars) + ')\n')
428      fd.write('set (PETSC_PACKAGE_LIBS ' + ' '.join(map(cmakeexpand,libvars)) + ')\n')
429      fd.write('set (PETSC_PACKAGE_INCLUDES ' + ' '.join(map(lambda i: '"'+i+'"',filter(notstandardinclude,includes))) + ')\n')
430    fd = open(os.path.join(self.arch.arch,'conf','PETScConfig.cmake'), 'w')
431    writeMacroDefinitions(fd)
432    writeBuildFlags(fd)
433    fd.close()
434    return
435
436  def dumpCMakeLists(self):
437    import sys
438    if sys.version_info >= (2,5):
439      import cmakegen
440      try:
441        cmakegen.main(self.petscdir.dir)
442      except (OSError), e:
443        self.framework.logPrint('Generating CMakeLists.txt failed:\n' + str(e))
444
445  def cmakeBoot(self):
446    import sys
447    if sys.version_info >= (2,5) and hasattr(self.cmake,'cmake'):
448      try:
449        import cmakeboot
450        cmakeboot.main(petscdir=self.petscdir.dir,petscarch=self.arch.arch,argDB=self.argDB,framework=self.framework,log=self.framework.log)
451      except (OSError), e:
452        self.framework.logPrint('Booting CMake in PETSC_ARCH failed:\n' + str(e))
453      except (ImportError, KeyError), e:
454        self.framework.logPrint('Importing cmakeboot failed:\n' + str(e))
455    return
456
457  def configurePrefetch(self):
458    '''Sees if there are any prefetch functions supported'''
459    if config.setCompilers.Configure.isSolaris() or self.framework.argDB['with-iphone'] or self.framework.argDB['with-cuda']:
460      self.addDefine('Prefetch(a,b,c)', ' ')
461      return
462    self.pushLanguage(self.languages.clanguage)
463    if self.checkLink('#include <xmmintrin.h>', 'void *v = 0;_mm_prefetch((const char*)v,_MM_HINT_NTA);\n'):
464      # The Intel Intrinsics manual [1] specifies the prototype
465      #
466      #   void _mm_prefetch(char const *a, int sel);
467      #
468      # but other vendors seem to insist on using subtly different
469      # prototypes, including void* for the pointer, and an enum for
470      # sel.  These are both reasonable changes, but negatively impact
471      # portability.
472      #
473      # [1] http://software.intel.com/file/6373
474      self.addDefine('HAVE_XMMINTRIN_H', 1)
475      self.addDefine('Prefetch(a,b,c)', '_mm_prefetch((const char*)(a),(c))')
476      self.addDefine('PREFETCH_HINT_NTA', '_MM_HINT_NTA')
477      self.addDefine('PREFETCH_HINT_T0',  '_MM_HINT_T0')
478      self.addDefine('PREFETCH_HINT_T1',  '_MM_HINT_T1')
479      self.addDefine('PREFETCH_HINT_T2',  '_MM_HINT_T2')
480    elif self.checkLink('#include <xmmintrin.h>', 'void *v = 0;_mm_prefetch(v,_MM_HINT_NTA);\n'):
481      self.addDefine('HAVE_XMMINTRIN_H', 1)
482      self.addDefine('Prefetch(a,b,c)', '_mm_prefetch((const void*)(a),(c))')
483      self.addDefine('PREFETCH_HINT_NTA', '_MM_HINT_NTA')
484      self.addDefine('PREFETCH_HINT_T0',  '_MM_HINT_T0')
485      self.addDefine('PREFETCH_HINT_T1',  '_MM_HINT_T1')
486      self.addDefine('PREFETCH_HINT_T2',  '_MM_HINT_T2')
487    elif self.checkLink('', 'void *v = 0;__builtin_prefetch(v,0,0);\n'):
488      # From GCC docs: void __builtin_prefetch(const void *addr,int rw,int locality)
489      #
490      #   The value of rw is a compile-time constant one or zero; one
491      #   means that the prefetch is preparing for a write to the memory
492      #   address and zero, the default, means that the prefetch is
493      #   preparing for a read. The value locality must be a compile-time
494      #   constant integer between zero and three. A value of zero means
495      #   that the data has no temporal locality, so it need not be left
496      #   in the cache after the access. A value of three means that the
497      #   data has a high degree of temporal locality and should be left
498      #   in all levels of cache possible. Values of one and two mean,
499      #   respectively, a low or moderate degree of temporal locality.
500      #
501      # Here we adopt Intel's x86/x86-64 naming scheme for the locality
502      # hints.  Using macros for these values in necessary since some
503      # compilers require an enum.
504      self.addDefine('Prefetch(a,b,c)', '__builtin_prefetch((a),(b),(c))')
505      self.addDefine('PREFETCH_HINT_NTA', '0')
506      self.addDefine('PREFETCH_HINT_T0',  '3')
507      self.addDefine('PREFETCH_HINT_T1',  '2')
508      self.addDefine('PREFETCH_HINT_T2',  '1')
509    else:
510      self.addDefine('Prefetch(a,b,c)', ' ')
511    self.popLanguage()
512
513  def configureUnused(self):
514    '''Sees if __attribute((unused)) is supported'''
515    if self.framework.argDB['with-iphone'] or self.framework.argDB['with-cuda']:
516      self.addDefine('UNUSED', ' ')
517      return
518    self.pushLanguage(self.languages.clanguage)
519    if self.checkLink('__attribute((unused)) static int myfunc(void){ return 1;}', 'int i = myfunc();\n'):
520      self.addDefine('UNUSED', '__attribute((unused))')
521    else:
522      self.addDefine('UNUSED', ' ')
523    self.popLanguage()
524
525  def configureExpect(self):
526    '''Sees if the __builtin_expect directive is supported'''
527    self.pushLanguage(self.languages.clanguage)
528    if self.checkLink('', 'if (__builtin_expect(0,1)) return 1;'):
529      self.addDefine('HAVE_BUILTIN_EXPECT', 1)
530    self.popLanguage()
531
532  def configureFunctionName(self):
533    '''Sees if the compiler supports __func__ or a variant.  Falls back
534    on __FUNCT__ which PETSc source defines, but most users do not, thus
535    stack traces through user code are better when the compiler's
536    variant is used.'''
537    def getFunctionName(lang):
538      name = '__FUNCT__'
539      self.pushLanguage(lang)
540      if self.checkLink('', "if (__func__[0] != 'm') return 1;"):
541        name = '__func__'
542      elif self.checkLink('', "if (__FUNCTION__[0] != 'm') return 1;"):
543        name = '__FUNCTION__'
544      self.popLanguage()
545      return name
546    langs = []
547
548    self.addDefine('FUNCTION_NAME_C', getFunctionName('C'))
549    if hasattr(self.compilers, 'CXX'):
550      self.addDefine('FUNCTION_NAME_CXX', getFunctionName('Cxx'))
551    else:
552      self.addDefine('FUNCTION_NAME_CXX', '__FUNCT__')
553
554  def configureIntptrt(self):
555    '''Determine what to use for uintptr_t'''
556    def staticAssertSizeMatchesVoidStar(inc,typename):
557      # The declaration is an error if either array size is negative.
558      # It should be okay to use an int that is too large, but it would be very unlikely for this to be the case
559      return self.checkCompile(inc, ('#define STATIC_ASSERT(cond) char negative_length_if_false[2*(!!(cond))-1]\n'
560                                     + 'STATIC_ASSERT(sizeof(void*) == sizeof(%s));'%typename))
561    self.pushLanguage(self.languages.clanguage)
562    if self.checkCompile('#include <stdint.h>', 'int x; uintptr_t i = (uintptr_t)&x;'):
563      self.addDefine('UINTPTR_T', 'uintptr_t')
564    elif staticAssertSizeMatchesVoidStar('','unsigned long long'):
565      self.addDefine('UINTPTR_T', 'unsigned long long')
566    elif staticAssertSizeMatchesVoidStar('#include <stdlib.h>','size_t') or staticAssertSizeMatchesVoidStar('#include <string.h>', 'size_t'):
567      self.addDefine('UINTPTR_T', 'size_t')
568    elif staticAssertSizeMatchesVoidStar('','unsigned long'):
569      self.addDefine('UINTPTR_T', 'unsigned long')
570    elif staticAssertSizeMatchesVoidStar('','unsigned'):
571      self.addDefine('UINTPTR_T', 'unsigned')
572    else:
573      raise RuntimeError('Could not find any unsigned integer type matching void*')
574    self.popLanguage()
575
576  def configureInline(self):
577    '''Get a generic inline keyword, depending on the language'''
578    if self.languages.clanguage == 'C':
579      self.addDefine('STATIC_INLINE', self.compilers.cStaticInlineKeyword)
580      self.addDefine('RESTRICT', self.compilers.cRestrict)
581    elif self.languages.clanguage == 'Cxx':
582      self.addDefine('STATIC_INLINE', self.compilers.cxxStaticInlineKeyword)
583      self.addDefine('RESTRICT', self.compilers.cxxRestrict)
584
585    if self.checkCompile('#include <dlfcn.h>\n void *ptr =  RTLD_DEFAULT;'):
586      self.addDefine('RTLD_DEFAULT','1')
587    return
588
589  def configureSolaris(self):
590    '''Solaris specific stuff'''
591    if os.path.isdir(os.path.join('/usr','ucblib')):
592      try:
593        flag = getattr(self.setCompilers, self.language[-1]+'SharedLinkerFlag')
594      except AttributeError:
595        flag = None
596      if flag is None:
597        self.compilers.LIBS += ' -L/usr/ucblib'
598      else:
599        self.compilers.LIBS += ' '+flag+'/usr/ucblib'
600    return
601
602  def configureLinux(self):
603    '''Linux specific stuff'''
604    # TODO: Test for this by mallocing an odd number of floats and checking the address
605    self.addDefine('HAVE_DOUBLE_ALIGN_MALLOC', 1)
606    return
607
608  def configureWin32(self):
609    '''Win32 non-cygwin specific stuff'''
610    kernel32=0
611    if self.libraries.add('Kernel32.lib','GetComputerName',prototype='#include <Windows.h>', call='GetComputerName(NULL,NULL);'):
612      self.addDefine('HAVE_WINDOWS_H',1)
613      self.addDefine('HAVE_GETCOMPUTERNAME',1)
614      kernel32=1
615    elif self.libraries.add('kernel32','GetComputerName',prototype='#include <Windows.h>', call='GetComputerName(NULL,NULL);'):
616      self.addDefine('HAVE_WINDOWS_H',1)
617      self.addDefine('HAVE_GETCOMPUTERNAME',1)
618      kernel32=1
619    if kernel32:
620      if self.framework.argDB['with-windows-graphics']:
621        self.addDefine('USE_WINDOWS_GRAPHICS',1)
622      if self.checkLink('#include <Windows.h>','LoadLibrary(0)'):
623        self.addDefine('HAVE_LOADLIBRARY',1)
624      if self.checkLink('#include <Windows.h>','GetProcAddress(0,0)'):
625        self.addDefine('HAVE_GETPROCADDRESS',1)
626      if self.checkLink('#include <Windows.h>','FreeLibrary(0)'):
627        self.addDefine('HAVE_FREELIBRARY',1)
628      if self.checkLink('#include <Windows.h>','GetLastError()'):
629        self.addDefine('HAVE_GETLASTERROR',1)
630      if self.checkLink('#include <Windows.h>','SetLastError(0)'):
631        self.addDefine('HAVE_SETLASTERROR',1)
632      if self.checkLink('#include <Windows.h>\n','QueryPerformanceCounter(0);\n'):
633        self.addDefine('USE_NT_TIME',1)
634    if self.libraries.add('Advapi32.lib','GetUserName',prototype='#include <Windows.h>', call='GetUserName(NULL,NULL);'):
635      self.addDefine('HAVE_GET_USER_NAME',1)
636    elif self.libraries.add('advapi32','GetUserName',prototype='#include <Windows.h>', call='GetUserName(NULL,NULL);'):
637      self.addDefine('HAVE_GET_USER_NAME',1)
638
639    if not self.libraries.add('User32.lib','GetDC',prototype='#include <Windows.h>',call='GetDC(0);'):
640      self.libraries.add('user32','GetDC',prototype='#include <Windows.h>',call='GetDC(0);')
641    if not self.libraries.add('Gdi32.lib','CreateCompatibleDC',prototype='#include <Windows.h>',call='CreateCompatibleDC(0);'):
642      self.libraries.add('gdi32','CreateCompatibleDC',prototype='#include <Windows.h>',call='CreateCompatibleDC(0);')
643
644    self.types.check('int32_t', 'int')
645    if not self.checkCompile('#include <sys/types.h>\n','uid_t u;\n'):
646      self.addTypedef('int', 'uid_t')
647      self.addTypedef('int', 'gid_t')
648    if not self.checkLink('#if defined(PETSC_HAVE_UNISTD_H)\n#include <unistd.h>\n#endif\n','int a=R_OK;\n'):
649      self.framework.addDefine('R_OK', '04')
650      self.framework.addDefine('W_OK', '02')
651      self.framework.addDefine('X_OK', '01')
652    if not self.checkLink('#include <sys/stat.h>\n','int a=0;\nif (S_ISDIR(a)){}\n'):
653      self.framework.addDefine('S_ISREG(a)', '(((a)&_S_IFMT) == _S_IFREG)')
654      self.framework.addDefine('S_ISDIR(a)', '(((a)&_S_IFMT) == _S_IFDIR)')
655    if self.checkCompile('#include <Windows.h>\n','LARGE_INTEGER a;\nDWORD b=a.u.HighPart;\n'):
656      self.addDefine('HAVE_LARGE_INTEGER_U',1)
657
658    # Windows requires a Binary file creation flag when creating/opening binary files.  Is a better test in order?
659    if self.checkCompile('#include <Windows.h>\n', 'int flags = O_BINARY;'):
660      self.addDefine('HAVE_O_BINARY',1)
661
662    if self.compilers.CC.find('win32fe') >= 0:
663      self.addDefine('PATH_SEPARATOR','\';\'')
664      self.addDefine('DIR_SEPARATOR','\'\\\\\'')
665      self.addDefine('REPLACE_DIR_SEPARATOR','\'/\'')
666      self.addDefine('CANNOT_START_DEBUGGER',1)
667    else:
668      self.addDefine('PATH_SEPARATOR','\':\'')
669      self.addDefine('REPLACE_DIR_SEPARATOR','\'\\\\\'')
670      self.addDefine('DIR_SEPARATOR','\'/\'')
671
672    return
673
674#-----------------------------------------------------------------------------------------------------
675  def configureDefaultArch(self):
676    conffile = os.path.join('conf', 'petscvariables')
677    if self.framework.argDB['with-default-arch']:
678      fd = file(conffile, 'w')
679      fd.write('PETSC_ARCH='+self.arch.arch+'\n')
680      fd.write('PETSC_DIR='+self.petscdir.dir+'\n')
681      fd.write('include ${PETSC_DIR}/${PETSC_ARCH}/conf/petscvariables\n')
682      fd.close()
683      self.framework.actions.addArgument('PETSc', 'Build', 'Set default architecture to '+self.arch.arch+' in '+conffile)
684    elif os.path.isfile(conffile):
685      try:
686        os.unlink(conffile)
687      except:
688        raise RuntimeError('Unable to remove file '+conffile+'. Did a different user create it?')
689    return
690
691#-----------------------------------------------------------------------------------------------------
692  def configureScript(self):
693    '''Output a script in the conf directory which will reproduce the configuration'''
694    import nargs
695    import sys
696    scriptName = os.path.join(self.arch.arch,'conf', 'reconfigure-'+self.arch.arch+'.py')
697    args = dict([(nargs.Arg.parseArgument(arg)[0], arg) for arg in self.framework.clArgs])
698    if 'configModules' in args:
699      if nargs.Arg.parseArgument(args['configModules'])[1] == 'PETSc.Configure':
700        del args['configModules']
701    if 'optionsModule' in args:
702      if nargs.Arg.parseArgument(args['optionsModule'])[1] == 'PETSc.compilerOptions':
703        del args['optionsModule']
704    if not 'PETSC_ARCH' in args:
705      args['PETSC_ARCH'] = 'PETSC_ARCH='+str(self.arch.arch)
706    f = file(scriptName, 'w')
707    f.write('#!'+sys.executable+'\n')
708    f.write('if __name__ == \'__main__\':\n')
709    f.write('  import sys\n')
710    f.write('  import os\n')
711    f.write('  sys.path.insert(0, os.path.abspath(\'config\'))\n')
712    f.write('  import configure\n')
713    # pretty print repr(args.values())
714    f.write('  configure_options = [\n')
715    for itm in sorted(args.values()):
716      f.write('    \''+str(itm)+'\',\n')
717    f.write('  ]\n')
718    f.write('  configure.petsc_configure(configure_options)\n')
719    f.close()
720    try:
721      os.chmod(scriptName, 0775)
722    except OSError, e:
723      self.framework.logPrint('Unable to make reconfigure script executable:\n'+str(e))
724    self.framework.actions.addArgument('PETSc', 'File creation', 'Created '+scriptName+' for automatic reconfiguration')
725    return
726
727  def configureInstall(self):
728    '''Setup the directories for installation'''
729    if self.framework.argDB['prefix']:
730      self.installdir = self.framework.argDB['prefix']
731      self.addMakeRule('shared_install','',['-@echo "Now to install the libraries do:"',\
732                                              '-@echo "make PETSC_DIR=${PETSC_DIR} PETSC_ARCH=${PETSC_ARCH} install"',\
733                                              '-@echo "========================================="'])
734    else:
735      self.installdir = os.path.join(self.petscdir.dir,self.arch.arch)
736      self.addMakeRule('shared_install','',['-@echo "Now to check if the libraries are working do:"',\
737                                              '-@echo "make PETSC_DIR=${PETSC_DIR} PETSC_ARCH=${PETSC_ARCH} test"',\
738                                              '-@echo "========================================="'])
739      return
740
741  def configureGCOV(self):
742    if self.framework.argDB['with-gcov']:
743      self.addDefine('USE_GCOV','1')
744    return
745
746  def configureFortranFlush(self):
747    if hasattr(self.compilers, 'FC'):
748      for baseName in ['flush','flush_']:
749        if self.libraries.check('', baseName, otherLibs = self.compilers.flibs, fortranMangle = 1):
750          self.addDefine('HAVE_'+baseName.upper(), 1)
751          return
752
753
754  def configure(self):
755    if not os.path.samefile(self.petscdir.dir, os.getcwd()):
756      raise RuntimeError('Wrong PETSC_DIR option specified: '+str(self.petscdir.dir) + '\n  Configure invoked in: '+os.path.realpath(os.getcwd()))
757    if self.framework.argDB['prefix'] and os.path.isdir(self.framework.argDB['prefix']) and os.path.samefile(self.framework.argDB['prefix'],self.petscdir.dir):
758      raise RuntimeError('Incorrect option --prefix='+self.framework.argDB['prefix']+' specified. It cannot be same as PETSC_DIR!')
759    if self.framework.argDB['prefix'] and os.path.isdir(self.framework.argDB['prefix']) and os.path.samefile(self.framework.argDB['prefix'],os.path.join(self.petscdir.dir,self.arch.arch)):
760      raise RuntimeError('Incorrect option --prefix='+self.framework.argDB['prefix']+' specified. It cannot be same as PETSC_DIR/PETSC_ARCH!')
761    self.framework.header          = os.path.join(self.arch.arch,'include','petscconf.h')
762    self.framework.cHeader         = os.path.join(self.arch.arch,'include','petscfix.h')
763    self.framework.makeMacroHeader = os.path.join(self.arch.arch,'conf','petscvariables')
764    self.framework.makeRuleHeader  = os.path.join(self.arch.arch,'conf','petscrules')
765    if self.libraries.math is None:
766      raise RuntimeError('PETSc requires a functional math library. Please send configure.log to petsc-maint@mcs.anl.gov.')
767    if self.languages.clanguage == 'Cxx' and not hasattr(self.compilers, 'CXX'):
768      raise RuntimeError('Cannot set C language to C++ without a functional C++ compiler.')
769    self.executeTest(self.configureInline)
770    self.executeTest(self.configurePrefetch)
771    self.executeTest(self.configureUnused)
772    self.executeTest(self.configureExpect);
773    self.executeTest(self.configureFunctionName);
774    self.executeTest(self.configureIntptrt);
775    self.executeTest(self.configureSolaris)
776    self.executeTest(self.configureLinux)
777    self.executeTest(self.configureWin32)
778    self.executeTest(self.configureDefaultArch)
779    self.executeTest(self.configureScript)
780    self.executeTest(self.configureInstall)
781    self.executeTest(self.configureGCOV)
782    self.executeTest(self.configureFortranFlush)
783    # dummy rules, always needed except for remote builds
784    self.addMakeRule('remote','')
785    self.addMakeRule('remoteclean','')
786
787    self.Dump()
788    self.dumpConfigInfo()
789    self.dumpMachineInfo()
790    self.dumpCMakeConfig()
791    self.dumpCMakeLists()
792    self.cmakeBoot()
793    self.framework.log.write('================================================================================\n')
794    self.logClear()
795    return
796