xref: /petsc/config/BuildSystem/config/types.py (revision a95d84e0230cb0d652d808aead973c41ec535430)
1import config.base
2
3import os
4import re
5
6class Configure(config.base.Configure):
7  def __init__(self, framework):
8    config.base.Configure.__init__(self, framework)
9    self.headerPrefix = ''
10    self.substPrefix  = ''
11    self.sizes = {}
12    self.c99_complex = 0
13    self.cxx_complex = 0
14    return
15
16  def setupHelp(self, help):
17    import nargs
18    help.addArgument('Types', '-known-endian=<big or little>', nargs.Arg(None, None, 'Are bytes stored in big or little endian?'))
19    help.addArgument('Visibility', '-with-visibility=<bool>', nargs.Arg(None, 0, 'Use compiler visibility flags to limit symbol visibility'))
20    return
21
22  def setupDependencies(self, framework):
23    config.base.Configure.setupDependencies(self, framework)
24    self.compilers = framework.require('config.compilers', self)
25    self.headers   = framework.require('config.headers', self)
26    return
27
28  def check(self, typeName, defaultType = None, includes = []):
29    '''Checks that "typeName" exists, and if not defines it to "defaultType" if given'''
30    self.framework.log.write('Checking for type: '+typeName+'\n')
31    include = '''
32#include <sys/types.h>
33#if STDC_HEADERS
34#include <stdlib.h>
35#include <stddef.h>
36%s
37#endif
38    ''' % ('\n'.join(['#include<%s>' % inc for inc in includes]))
39    found = self.checkCompile(include,typeName+' a;')
40    if not found and defaultType:
41      self.addTypedef(defaultType, typeName)
42    else:
43      self.framework.log.write(typeName+' found\n')
44    return found
45
46  def check_siginfo_t(self):
47    '''Checks if siginfo_t exists in signal.h. This check is for windows, and C89 check.'''
48    if self.check('siginfo_t', includes = ['signal.h']):
49      self.addDefine('HAVE_SIGINFO_T',1)
50    return
51
52  def check__int64(self):
53    '''Checks if __int64 exists. This is primarily for windows.'''
54    if self.check('__int64'):
55      self.addDefine('HAVE___INT64',1)
56    return
57
58  def checkSizeTypes(self):
59    '''Checks for types associated with sizes, such as size_t.'''
60    self.check('size_t', 'int')
61    return
62
63  def checkIntegerTypes(self):
64    '''Checks for types associated with integers, such as int32_t.'''
65    self.check('int32_t', 'int')
66    return
67
68  def checkFileTypes(self):
69    '''Checks for types associated with files, such as mode_t, off_t, etc.'''
70    self.check('mode_t', 'int')
71    self.check('off_t', 'int')
72    return
73
74  def checkPID(self):
75    '''Checks for pid_t, and defines it if necessary'''
76    return self.check('pid_t', 'int')
77
78  def checkUID(self):
79    '''Checks for uid_t and gid_t, and defines them if necessary'''
80    if self.outputPreprocess('#include <sys/types.h>').find('uid_t') < 0:
81      self.addDefine('uid_t', 'int')
82      self.addDefine('gid_t', 'int')
83    return
84
85  def checkSignal(self):
86    '''Checks the return type of signal() and defines RETSIGTYPE to that type name'''
87    includes = '''
88#include <sys/types.h>
89#include <signal.h>
90#ifdef signal
91#undef signal
92#endif
93#ifdef __cplusplus
94extern "C" void (*signal (int, void(*)(int)))(int);
95#else
96void (*signal())();
97#endif
98    '''
99    if self.checkCompile(includes, ''):
100      returnType = 'void'
101    else:
102      returnType = 'int'
103    self.addDefine('RETSIGTYPE', returnType)
104    return
105
106  def checkC99Complex(self):
107    '''Check for complex numbers in in C99 std
108       Note that since PETSc source code uses _Complex we test specifically for that, not complex'''
109    includes = '#include <complex.h>\n'
110    body     = 'double _Complex x;\n x = I;\n'
111    if not self.checkCompile(includes, body): return    # checkLink can succeed even if checkCompile fails
112    if self.checkLink(includes, body):
113      self.addDefine('HAVE_C99_COMPLEX', 1)
114      self.c99_complex = 1
115    return
116
117  def checkCxxComplex(self):
118    '''Check for complex numbers in namespace std'''
119    self.pushLanguage('C++')
120    includes = '#include <complex>\n'
121    body     = 'std::complex<double> x;\n'
122    if self.checkLink(includes, body):
123      self.addDefine('HAVE_CXX_COMPLEX', 1)
124      self.cxx_complex = 1
125    self.popLanguage()
126    return
127
128  def checkFortranStar(self):
129    '''Checks whether integer*4, etc. is handled in Fortran, and if not defines MISSING_FORTRANSTAR'''
130    self.pushLanguage('FC')
131    body = '        integer*4 i\n        real*8 d\n'
132    if not self.checkCompile('', body):
133      self.addDefine('MISSING_FORTRANSTAR', 1)
134    self.popLanguage()
135    return
136
137# reverse of the above - but more standard thing to do for F90 compilers
138  def checkFortranKind(self):
139    '''Checks whether selected_int_kind etc work USE_FORTRANKIND'''
140    self.pushLanguage('FC')
141    body = '''
142        integer(kind=selected_int_kind(10)) i
143        real(kind=selected_real_kind(10)) d
144'''
145    if self.checkCompile('', body):
146      self.addDefine('USE_FORTRANKIND', 1)
147    self.popLanguage()
148    return
149
150  def checkFortranDReal(self):
151    '''Checks whether dreal is provided in Fortran, and if not defines MISSING_DREAL'''
152    self.pushLanguage('FC')
153    if not self.checkLink('', '      double precision d\n      d = dreal(3.0)'):
154      self.addDefine('MISSING_DREAL', 1)
155    self.popLanguage()
156    return
157
158  def checkConst(self):
159    '''Checks for working const, and if not found defines it to empty string'''
160    body = '''
161    /* Ultrix mips cc rejects this.  */
162    typedef int charset[2]; const charset x;
163    /* SunOS 4.1.1 cc rejects this.  */
164    char const *const *ccp;
165    char **p;
166    /* NEC SVR4.0.2 mips cc rejects this.  */
167    struct point {int x, y;};
168    static struct point const zero = {0,0};
169    /* AIX XL C 1.02.0.0 rejects this.
170    It does not let you subtract one const X* pointer from another in an arm
171    of an if-expression whose if-part is not a constant expression */
172    const char *g = "string";
173    ccp = &g + (g ? g-g : 0);
174    /* HPUX 7.0 cc rejects these. */
175    ++ccp;
176    p = (char**) ccp;
177    ccp = (char const *const *) p;
178    /* This section avoids unused variable warnings */
179    if (zero.x);
180    if (x[0]);
181    { /* SCO 3.2v4 cc rejects this.  */
182      char *t;
183      char const *s = 0 ? (char *) 0 : (char const *) 0;
184
185      *t++ = 0;
186      if (*s);
187    }
188    { /* Someone thinks the Sun supposedly-ANSI compiler will reject this.  */
189      int x[] = {25, 17};
190      const int *foo = &x[0];
191      ++foo;
192    }
193    { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
194      typedef const int *iptr;
195      iptr p = 0;
196      ++p;
197    }
198    { /* AIX XL C 1.02.0.0 rejects this saying
199      "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
200      struct s { int j; const int *ap[3]; };
201      struct s *b; b->j = 5;
202    }
203    { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
204      const int foo = 10;
205
206      /* Get rid of unused variable warning */
207      if (foo);
208    }
209    '''
210    if not self.checkCompile('', body):
211      self.addDefine('const', '')
212    return
213
214  def checkEndian(self):
215    '''If the machine is big endian, defines WORDS_BIGENDIAN'''
216    if 'known-endian' in self.framework.argDB:
217      endian = self.framework.argDB['known-endian']
218    else:
219      # See if sys/param.h defines the BYTE_ORDER macro
220      includes = '#include <sys/types.h>\n#ifdef HAVE_SYS_PARAM_H\n  #include <sys/param.h>\n#endif\n'
221      body     = '''
222#if !BYTE_ORDER || !BIG_ENDIAN || !LITTLE_ENDIAN
223  bogus endian macros
224#endif
225      '''
226      if self.checkCompile(includes, body):
227        # It does, so check whether it is defined to BIG_ENDIAN or not
228        body = '''
229#if BYTE_ORDER != BIG_ENDIAN
230  not big endian
231#endif
232        '''
233        if self.checkCompile(includes, body):
234          endian = 'big'
235        else:
236          endian = 'little'
237      else:
238        if not self.framework.argDB['with-batch']:
239          body = '''
240          /* Are we little or big endian?  From Harbison&Steele. */
241          union
242          {
243            long l;
244            char c[sizeof(long)];
245          } u;
246          u.l = 1;
247          exit(u.c[sizeof(long) - 1] == 1);
248          '''
249          self.pushLanguage('C')
250          if self.checkRun('#include <stdlib.h>\n', body, defaultArg = 'isLittleEndian'):
251            endian = 'little'
252          else:
253            endian = 'big'
254          self.popLanguage()
255        else:
256          self.framework.addBatchBody(['{',
257                                       '  union {long l; char c[sizeof(long)];} u;',
258                                       '  u.l = 1;',
259                                       '  fprintf(output, " \'--known-endian=%s\',\\n", (u.c[sizeof(long) - 1] == 1) ? "big" : "little");',
260                                       '}'])
261          # Dummy value
262          endian = 'little'
263    if endian == 'big':
264      self.addDefine('WORDS_BIGENDIAN', 1)
265    return
266
267  def checkSizeof(self, typeName, otherInclude = None):
268    '''Determines the size of type "typeName", and defines SIZEOF_"typeName" to be the size'''
269    self.framework.log.write('Checking for size of type: '+typeName+'\n')
270    filename = 'conftestval'
271    includes = '''
272#include <sys/types.h>
273#if STDC_HEADERS
274#include <stdlib.h>
275#include <stdio.h>
276#include <stddef.h>
277#endif\n'''
278    mpiFix = '''
279#define MPICH_IGNORE_CXX_SEEK
280#define MPICH_SKIP_MPICXX 1
281#define OMPI_SKIP_MPICXX 1\n'''
282    if otherInclude:
283      if otherInclude == 'mpi.h':
284        includes += mpiFix
285      includes += '#include <'+otherInclude+'>\n'
286    body     = 'FILE *f = fopen("'+filename+'", "w");\n\nif (!f) exit(1);\nfprintf(f, "%lu\\n", (unsigned long)sizeof('+typeName+'));\n'
287    typename = typeName.replace(' ', '-').replace('*', 'p')
288    if not 'known-sizeof-'+typename in self.framework.argDB:
289      if not self.framework.argDB['with-batch']:
290        self.pushLanguage('C')
291        if self.checkRun(includes, body) and os.path.exists(filename):
292          f    = file(filename)
293          size = int(f.read())
294          f.close()
295          os.remove(filename)
296        elif not typename == 'long-long':
297          msg = 'Cannot run executable to determine size of '+typeName+'. If this machine uses a batch system \nto submit jobs you will need to configure using ./configure with the additional option  --with-batch.\n Otherwise there is problem with the compilers. Can you compile and run code with your C/C++ (and maybe Fortran) compilers?\n'
298          raise RuntimeError(msg)
299        else:
300          self.framework.log.write('Compiler does not support long long\n')
301          size = 0
302        self.popLanguage()
303      else:
304        self.framework.addBatchInclude(['#include <stdlib.h>', '#include <stdio.h>', '#include <sys/types.h>'])
305        if otherInclude:
306          if otherInclude == 'mpi.h':
307            self.framework.addBatchInclude(mpiFix)
308          self.framework.addBatchInclude('#include <'+otherInclude+'>')
309        self.framework.addBatchBody('fprintf(output, "  \'--known-sizeof-'+typename+'=%d\',\\n", sizeof('+typeName+'));')
310        # dummy value
311        size = 4
312    else:
313      size = self.framework.argDB['known-sizeof-'+typename]
314    self.sizes['known-sizeof-'+typename] = int(size)
315    self.addDefine('SIZEOF_'+typeName.replace(' ', '_').replace('*', 'p').upper(), size)
316    return size
317
318  def checkBitsPerByte(self):
319    '''Determine the nubmer of bits per byte and define BITS_PER_BYTE'''
320    filename = 'conftestval'
321    includes = '''
322#if STDC_HEADERS
323#include <stdlib.h>
324#include <stdio.h>
325#endif\n'''
326    body     = 'FILE *f = fopen("'+filename+'", "w");\n'+'''
327    char val[2];
328    int i = 0;
329
330    if (!f) exit(1);
331    val[0]=\'\\1\';
332    val[1]=\'\\0\';
333    while(val[0]) {val[0] <<= 1; i++;}
334    fprintf(f, "%d\\n", i);\n
335    '''
336    if 'known-bits-per-byte' in self.framework.argDB:
337      bits = self.framework.argDB['known-bits-per-byte']
338    elif not self.framework.argDB['with-batch']:
339      if self.checkRun(includes, body) and os.path.exists(filename):
340        f    = file(filename)
341        bits = int(f.read())
342        f.close()
343        os.remove(filename)
344      else:
345         msg = 'Cannot run executable to determine bits per bit. If this machine uses a batch system \nto submit jobs you will need to configure using ./configure with the additional option  --with-batch.\n Otherwise there is problem with the compilers. Can you compile and run code with your C/C++ (and maybe Fortran) compilers?\n'
346         raise RuntimeError(msg)
347    else:
348      self.framework.addBatchBody(['{',
349                                   '  int i = 0;',
350                                   '  char val[2];',
351                                   '  val[0]=\'\\1\';',
352                                   '  val[1]=\'\\0\';',
353                                   '  while(val[0]) {val[0] <<= 1; i++;}',
354                                   '  fprintf(output, "  \'--known-bits-per-byte=%d\',\\n", i);',
355                                   '}'])
356      # dummy value
357      bits = 8
358
359    self.bits_per_byte = int(bits)
360    self.addDefine('BITS_PER_BYTE', bits)
361    return
362
363
364  def checkVisibility(self):
365    if self.framework.argDB['with-visibility']:
366      if not self.checkCompile('','__attribute__((visibility ("default"))) int foo(void);'):
367        raise RuntimeError('Cannot use visibility attributes')
368      self.addDefine('USE_VISIBILITY',1)
369
370  def configure(self):
371    self.executeTest(self.check_siginfo_t)
372    self.executeTest(self.check__int64)
373    self.executeTest(self.checkSizeTypes)
374    self.executeTest(self.checkFileTypes)
375    self.executeTest(self.checkIntegerTypes)
376    self.executeTest(self.checkPID)
377    self.executeTest(self.checkUID)
378    self.executeTest(self.checkSignal)
379    self.executeTest(self.checkC99Complex)
380    if hasattr(self.compilers, 'CXX'):
381      self.executeTest(self.checkCxxComplex)
382    if hasattr(self.compilers, 'FC'):
383      #self.executeTest(self.checkFortranStar)
384      self.executeTest(self.checkFortranKind)
385      self.executeTest(self.checkFortranDReal)
386    self.executeTest(self.checkConst)
387    self.executeTest(self.checkEndian)
388    map(lambda type: self.executeTest(self.checkSizeof, type), ['char','void *', 'short', 'int', 'long', 'long long', 'float', 'double', 'size_t'])
389    self.executeTest(self.checkBitsPerByte)
390    self.executeTest(self.checkVisibility)
391    return
392