~ubuntu-branches/ubuntu/vivid/emscripten/vivid

« back to all changes in this revision

Viewing changes to emcc

  • Committer: Package Import Robot
  • Author(s): Sylvestre Ledru
  • Date: 2013-05-02 13:11:51 UTC
  • Revision ID: package-import@ubuntu.com-20130502131151-q8dvteqr1ef2x7xz
Tags: upstream-1.4.1~20130504~adb56cb
ImportĀ upstreamĀ versionĀ 1.4.1~20130504~adb56cb

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python2
 
2
# -*- Mode: python -*-
 
3
 
 
4
'''
 
5
emcc - compiler helper script
 
6
=============================
 
7
 
 
8
emcc is a drop-in replacement for a compiler like gcc or clang.
 
9
 
 
10
Tell your build system to use this instead of the compiler, and similarly
 
11
use emar, emranlib etc. instead of the same command without 'em'.
 
12
 
 
13
Example uses:
 
14
 
 
15
 * For configure, instead of ./configure, cmake, etc., run emconfigure.py
 
16
   with that command as an argument, for example
 
17
 
 
18
    emconfigure.py ./configure [options]
 
19
 
 
20
   emconfigure.py is a tiny script that just sets some environment vars
 
21
   as a convenience. The command just shown is equivalent to
 
22
 
 
23
    EMMAKEN_JUST_CONFIGURE=1 RANLIB=PATH/emranlib AR=PATH/emar CXX=PATH/em++ CC=PATH/emcc ./configure [options]
 
24
 
 
25
   where PATH is the path to this file.
 
26
 
 
27
   EMMAKEN_JUST_CONFIGURE tells emcc that it is being run in ./configure,
 
28
   so it should relay everything to gcc/g++. You should not define that when
 
29
   running make, of course.
 
30
 
 
31
 * With CMake, the same command will work (with cmake instead of ./configure). You may also be
 
32
   able to do the following in your CMakeLists.txt:
 
33
 
 
34
    SET(CMAKE_C_COMPILER "PATH/emcc")
 
35
    SET(CMAKE_CXX_COMPILER "PATH/em++")
 
36
    SET(CMAKE_LINKER "PATH/emcc")
 
37
    SET(CMAKE_CXX_LINKER "PATH/emcc")
 
38
    SET(CMAKE_C_LINK_EXECUTABLE "PATH/emcc")
 
39
    SET(CMAKE_CXX_LINK_EXECUTABLE "PATH/emcc")
 
40
    SET(CMAKE_AR "PATH/emar")
 
41
    SET(CMAKE_RANLIB "PATH/emranlib")
 
42
 
 
43
 * For SCons the shared.py can be imported like so:
 
44
    __file__ = str(Dir('#/project_path_to_emscripten/dummy/dummy'))
 
45
    __rootpath__ = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 
46
    def path_from_root(*pathelems):
 
47
      return os.path.join(__rootpath__, *pathelems)
 
48
    sys.path += [path_from_root('')]
 
49
    from tools.shared import *
 
50
 
 
51
   For using the Emscripten compilers/linkers/etc. you can do:
 
52
    env = Environment()
 
53
    ...
 
54
    env.Append(CCFLAGS = COMPILER_OPTS)
 
55
    env.Replace(LINK = LLVM_LD)
 
56
    env.Replace(LD   = LLVM_LD)
 
57
   TODO: Document all relevant setup changes
 
58
 
 
59
After setting that up, run your build system normally.
 
60
 
 
61
Note the appearance of em++ instead of emcc
 
62
for the C++ compiler. This is needed for cases where we get
 
63
a C++ file with a C extension, in which case CMake can be told
 
64
to run g++ on it despite the .c extension, see
 
65
 
 
66
  https://github.com/kripken/emscripten/issues/6
 
67
 
 
68
(If a similar situation occurs with ./configure, you can do the same there too.)
 
69
 
 
70
emcc can be influenced by a few environment variables:
 
71
 
 
72
  EMMAKEN_NO_SDK - Will tell emcc *not* to use the emscripten headers. Instead
 
73
                   your system headers will be used.
 
74
 
 
75
  EMMAKEN_COMPILER - The compiler to be used, if you don't want the default clang.
 
76
'''
 
77
 
 
78
import os, sys, shutil, tempfile, subprocess, shlex, time, re
 
79
from subprocess import PIPE, STDOUT
 
80
from tools import shared
 
81
from tools.shared import Compression, execute, suffix, unsuffixed, unsuffixed_basename
 
82
from tools.response_file import read_response_file
 
83
 
 
84
# Mapping of emcc opt levels to llvm opt levels. We use llvm opt level 3 in emcc opt
 
85
# levels 2 and 3 (emcc 3 is unsafe opts, so unsuitable for the only level to get
 
86
# llvm opt level 3, and speed-wise emcc level 2 is already the slowest/most optimizing
 
87
# level)
 
88
LLVM_OPT_LEVEL = {
 
89
  0: 0,
 
90
  1: 1,
 
91
  2: 3,
 
92
  3: 3,
 
93
}
 
94
 
 
95
DEBUG = os.environ.get('EMCC_DEBUG')
 
96
if DEBUG == "0":
 
97
  DEBUG = None
 
98
 
 
99
TEMP_DIR = os.environ.get('EMCC_TEMP_DIR')
 
100
LEAVE_INPUTS_RAW = os.environ.get('EMCC_LEAVE_INPUTS_RAW') # Do not compile .ll files into .bc, just compile them with emscripten directly
 
101
                                                           # Not recommended, this is mainly for the test runner, or if you have some other
 
102
                                                           # specific need.
 
103
                                                           # One major limitation with this mode is that libc and libc++ cannot be
 
104
                                                           # added in. Also, LLVM optimizations will not be done, nor dead code elimination
 
105
AUTODEBUG = os.environ.get('EMCC_AUTODEBUG') # If set to 1, we will run the autodebugger (the automatic debugging tool, see tools/autodebugger).
 
106
                                             # Note that this will disable inclusion of libraries. This is useful because including
 
107
                                             # dlmalloc makes it hard to compare native and js builds
 
108
EMCC_CFLAGS = os.environ.get('EMCC_CFLAGS') # Additional compiler flags that we treat as if they were passed to us on the commandline
 
109
 
 
110
if DEBUG: print >> sys.stderr, '\nemcc invocation: ', ' '.join(sys.argv), (' + ' + EMCC_CFLAGS if EMCC_CFLAGS else '')
 
111
if EMCC_CFLAGS: sys.argv.append(EMCC_CFLAGS)
 
112
 
 
113
if DEBUG and LEAVE_INPUTS_RAW: print >> sys.stderr, 'emcc: leaving inputs raw'
 
114
 
 
115
stdout = PIPE if not DEBUG else None # suppress output of child processes
 
116
stderr = PIPE if not DEBUG else None # unless we are in DEBUG mode
 
117
 
 
118
shared.check_sanity(force=DEBUG)
 
119
 
 
120
# Handle some global flags
 
121
 
 
122
if len(sys.argv) == 1:
 
123
  print 'emcc: no input files'
 
124
  exit(1)
 
125
 
 
126
# read response files very early on
 
127
response_file = True
 
128
while response_file:
 
129
  response_file = None
 
130
  for index in range(1, len(sys.argv)):
 
131
    if sys.argv[index][0] == '@':
 
132
      # found one, loop again next time
 
133
      response_file = True
 
134
      extra_args = read_response_file(sys.argv[index])
 
135
      # slice in extra_args in place of the response file arg
 
136
      sys.argv[index:index+1] = extra_args
 
137
      break
 
138
 
 
139
if sys.argv[1] == '--version':
 
140
  revision = '(unknown revision)'
 
141
  here = os.getcwd()
 
142
  os.chdir(shared.path_from_root())
 
143
  try:
 
144
    revision = execute(['git', 'show'], stdout=PIPE, stderr=PIPE)[0].split('\n')[0]
 
145
  except:
 
146
    pass
 
147
  finally:
 
148
    os.chdir(here)
 
149
  print '''emcc (Emscripten GCC-like replacement) %s (%s)
 
150
Copyright (C) 2013 the Emscripten authors (see AUTHORS.txt)
 
151
This is free and open source software under the MIT license.
 
152
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
153
  ''' % (shared.EMSCRIPTEN_VERSION, revision)
 
154
  exit(0)
 
155
elif sys.argv[1] == '--help':
 
156
  this = os.path.basename('em++' if os.environ.get('EMMAKEN_CXX') else 'emcc')
 
157
 
 
158
  print '''%s [options] file...
 
159
 
 
160
Most normal gcc/g++ options will work, for example:
 
161
  --help                   Display this information
 
162
  --version                Display compiler version information
 
163
 
 
164
Options that are modified or new in %s include:
 
165
  -O0                      No optimizations (default)
 
166
  -O1                      Simple optimizations, including asm.js, LLVM -O1
 
167
                           optimizations, and no runtime assertions
 
168
                           or C++ exception catching (to re-enable
 
169
                           C++ exception catching, use
 
170
                           -s DISABLE_EXCEPTION_CATCHING=0 ).
 
171
                           (For details on the affects of different
 
172
                           opt levels, see apply_opt_level() in
 
173
                           tools/shared.py and also src/settings.js.)
 
174
                           Note: Optimizations are only done when
 
175
                           compiling to JavaScript, not to intermediate
 
176
                           bitcode, *unless* you build with
 
177
                           EMCC_OPTIMIZE_NORMALLY=1 (not recommended
 
178
                           unless you know what you are doing!)
 
179
  -O2                      As -O1, plus the relooper (loop recreation),
 
180
                           plus LLVM -O2 optimizations
 
181
  -O3                      As -O2, plus dangerous optimizations that may
 
182
                           break the generated code! This adds
 
183
 
 
184
                              -s DOUBLE_MODE=0
 
185
                              -s PRECISE_I64_MATH=0
 
186
                              --closure 1
 
187
                              --llvm-lto 1
 
188
 
 
189
                           This is not recommended at all. A better idea
 
190
                           is to try each of these separately on top of
 
191
                           -O2 to see what works. See the wiki for more
 
192
                           information.
 
193
 
 
194
  -s OPTION=VALUE          JavaScript code generation option passed
 
195
                           into the emscripten compiler. For the
 
196
                           available options, see src/settings.js
 
197
                           Note that for options that are lists, you
 
198
                           need quotation marks in most shells, for
 
199
                           example
 
200
 
 
201
                            -s RUNTIME_LINKED_LIBS="['liblib.so']"
 
202
 
 
203
                           or
 
204
 
 
205
                            -s "RUNTIME_LINKED_LIBS=['liblib.so']"
 
206
 
 
207
                           (without the external "s in either of those,
 
208
                           you would get an error)
 
209
 
 
210
                           You can also specify a file from which the
 
211
                           value would be read, for example,
 
212
 
 
213
                            -s DEAD_FUNCTIONS=@/path/to/file
 
214
 
 
215
                           The contents of /path/to/file will be read,
 
216
                           JSON.parsed and set into DEAD_FUNCTIONS (so
 
217
                           the file could contain
 
218
 
 
219
                            ["_func1", "func2"]
 
220
 
 
221
                           ). Note that the path must be absolute, not
 
222
                           relative.
 
223
 
 
224
  -g                       Use debug info. Note that you need this during
 
225
                           the last compilation phase from bitcode to
 
226
                           JavaScript, or else we will remove it by
 
227
                           default in -O1 and above.
 
228
                           In -O0, line numbers wil be shown in the
 
229
                           generated code. In -O1 and above, the optimizer
 
230
                           removes those comments. This flag does however
 
231
                           have the effect of disabling anything that
 
232
                           causes name mangling or minification (closure
 
233
                           or the registerize pass).
 
234
 
 
235
  --typed-arrays <mode>    0: No typed arrays
 
236
                           1: Parallel typed arrays
 
237
                           2: Shared (C-like) typed arrays (default)
 
238
 
 
239
  --llvm-opts <level>      0: No LLVM optimizations (default in -O0)
 
240
                           1: -O1 LLVM optimizations (default in -O1)
 
241
                           2: -O2 LLVM optimizations
 
242
                           3: -O3 LLVM optimizations (default in -O2+)
 
243
 
 
244
  --llvm-lto <level>       0: No LLVM LTO (default in -O2 and below)
 
245
                           1: LLVM LTO (default in -O3)
 
246
                           Note: If LLVM optimizations are not run
 
247
                           (see --llvm-opts), setting this to 1 has no
 
248
                           effect.
 
249
 
 
250
  --closure <on>           0: No closure compiler (default in -O2 and below)
 
251
                           1: Run closure compiler. This greatly reduces
 
252
                           code size and may in some cases increase
 
253
                           runtime speed (although the opposite can also
 
254
                           occur). Note that it takes time to run, and
 
255
                           may require some changes to the code. This
 
256
                           is run by default in -O3.
 
257
 
 
258
                           Note: If closure compiler hits an out-of-memory,
 
259
                           try adjusting JAVA_HEAP_SIZE in the environment
 
260
                           (for example, to 4096m for 4GB).
 
261
 
 
262
  --js-transform <cmd>     <cmd> will be called on the generated code
 
263
                           before it is optimized. This lets you modify
 
264
                           the JavaScript, for example adding some code
 
265
                           or removing some code, in a way that those
 
266
                           modifications will be optimized together with
 
267
                           the generated code properly. <cmd> will be
 
268
                           called with the filename of the generated
 
269
                           code as a parameter; to modify the code, you
 
270
                           can read the original data and then append to
 
271
                           it or overwrite it with the modified data.
 
272
                           <cmd> is interpreted as a space-separated
 
273
                           list of arguments, for example, <cmd> of
 
274
                           "python processor.py" will cause a python
 
275
                           script to be run.
 
276
 
 
277
  --pre-js <file>          A file whose contents are added before the
 
278
                           generated code. This is done *before*
 
279
                           optimization, so it will be minified
 
280
                           properly if closure compiler is run.
 
281
 
 
282
  --post-js <file>         A file whose contents are added after the
 
283
                           generated code This is done *before*
 
284
                           optimization, so it will be minified
 
285
                           properly if closure compiler is run.
 
286
 
 
287
  --embed-file <file>      A file to embed inside the generated
 
288
                           JavaScript. The compiled code will be able
 
289
                           to access the file in the current directory
 
290
                           with the same name as given here. So if
 
291
                           you do --embed-file dir/file.dat, then
 
292
                           (1) dir/file.dat must exist relative to
 
293
                           where you run emcc, and (2) your compiled
 
294
                           code will be able to find the file by
 
295
                           reading that same path, dir/file.dat.
 
296
                           If a directory is passed here, its entire
 
297
                           contents will be embedded.
 
298
 
 
299
  --preload-file <name>    A file to preload before running the
 
300
                           compiled code asynchronously. Otherwise
 
301
                           similar to --embed-file, except that this
 
302
                           option is only relevant when generating
 
303
                           HTML (it uses asynchronous binary XHRs),
 
304
                           or JS that will be used in a web page.
 
305
                           If a directory is passed here, its entire
 
306
                           contents will be preloaded.
 
307
                           Preloaded files are stored in filename.data,
 
308
                           where filename.html is the main file you
 
309
                           are compiling to. To run your code, you
 
310
                           will need both the .html and the .data.
 
311
 
 
312
                           emcc runs tools/file_packager.py to do the
 
313
                           actual packaging of embedded and preloaded
 
314
                           files. You can run the file packager yourself
 
315
                           if you want, see docs inside that file. You
 
316
                           should then put the output of the file packager
 
317
                           in an emcc --pre-js, so that it executes before
 
318
                           your main compiled code (or run it before in
 
319
                           some other way).
 
320
 
 
321
  --compression <codec>    Compress both the compiled code and embedded/
 
322
                           preloaded files. <codec> should be a triple,
 
323
 
 
324
                              <native_encoder>,<js_decoder>,<js_name>
 
325
 
 
326
                           where native_encoder is a native executable
 
327
                           that compresses stdin to stdout (the simplest
 
328
                           possible interface), js_decoder is a
 
329
                           JavaScript file that implements a decoder,
 
330
                           and js_name is the name of the function to
 
331
                           call in the decoder file (which should
 
332
                           receive an array/typed array and return
 
333
                           an array/typed array.
 
334
                           Compression only works when generating HTML.
 
335
                           When compression is on, all filed specified
 
336
                           to be preloaded are compressed in one big
 
337
                           archive, which is given the same name as the
 
338
                           output HTML but with suffix .data.compress
 
339
 
 
340
  --minify <on>            0: Do not minify the generated JavaScript's
 
341
                              whitespace (default in -O0, -O1, or if
 
342
                              -g is used)
 
343
                           1: Minify the generated JavaScript's
 
344
                              whitespace (default in -O2+, assuming
 
345
                              -g is not used)
 
346
 
 
347
  --split <size>           Splits the resulting javascript file into pieces
 
348
                           to ease debugging. This option only works if
 
349
                           Javascript is generated (target -o <name>.js).
 
350
                           Files with function declarations must be loaded
 
351
                           before main file upon execution.
 
352
 
 
353
                           Without "-g" option:
 
354
                              Creates files with function declarations up
 
355
                              to the given size with the suffix
 
356
                              "_functions.partxxx.js" and a main file with
 
357
                              the suffix ".js".
 
358
 
 
359
                           With "-g" option:
 
360
                              Recreates the directory structure of the C
 
361
                              source files and stores function declarations
 
362
                              in their respective C files with the suffix
 
363
                              ".js". If such a file exceeds the given size,
 
364
                              files with the suffix ".partxxx.js" are created.
 
365
                              The main file resides in the base directory and
 
366
                              has the suffix ".js".
 
367
 
 
368
  --bind                   Compiles the source code using the "embind"
 
369
                           bindings approach, which connects C/C++ and JS.
 
370
 
 
371
  --ignore-dynamic-linking Normally emcc will treat dynamic linking like
 
372
                           static linking, by linking in the code from
 
373
                           the dynamic library. This fails if the same
 
374
                           dynamic library is linked more than once.
 
375
                           With this option, dynamic linking is ignored,
 
376
                           which allows the build system to proceed without
 
377
                           errors. However, you will need to manually
 
378
                           link to the shared libraries later on yourself.
 
379
 
 
380
  --shell-file <path>      The path name to a skeleton HTML file used
 
381
                           when generating HTML output. The shell file
 
382
                           used needs to have this token inside it:
 
383
                           {{{ SCRIPT_CODE }}}
 
384
                           Note that this argument is ignored if a
 
385
                           target other than HTML is specified using
 
386
                           the -o option.
 
387
 
 
388
  --js-library <lib>       A JavaScript library to use in addition to
 
389
                           those in Emscripten's src/library_*
 
390
 
 
391
  -v                       Turns on verbose output. This will pass
 
392
                           -v to Clang, and also enable EMCC_DEBUG
 
393
                           to details emcc's operations
 
394
 
 
395
  --jcache                 Use a JavaScript cache. This is disabled by
 
396
                           default. When enabled, emcc will store the
 
397
                           results of compilation in a cache and check
 
398
                           the cache when compiling later, something
 
399
                           like what ccache does. This allows incremental
 
400
                           builds - where you are compiling a large
 
401
                           program but only modified a small part of it -
 
402
                           to be much faster (at the cost of more disk
 
403
                           IO for cache accesses). Note that you need
 
404
                           to enable --jcache for both loading and saving
 
405
                           of data, so you must enable it on a full build
 
406
                           for a later incremental build (where you also
 
407
                           enable it) to be sped up.
 
408
 
 
409
                           Caching works separately on 4 parts of compilation:
 
410
                           'pre' which is types and global variables; that
 
411
                           information is then fed into 'funcs' which are
 
412
                           the functions (which we parallelize), and then
 
413
                           'post' which adds final information based on
 
414
                           the functions (e.g., do we need long64 support
 
415
                           code). Finally, 'jsfuncs' are JavaScript-level
 
416
                           optimizations. Each of the 4 parts can be cached
 
417
                           separately, but note that they can affect each
 
418
                           other: If you recompile a single C++ file that
 
419
                           changes a global variable - e.g., adds, removes
 
420
                           or modifies a global variable, say by adding
 
421
                           a printf or by adding a compile-time timestamp,
 
422
                           then 'pre' cannot be loaded from the cache. And
 
423
                           since 'pre's output is sent to 'funcs' and 'post',
 
424
                           they will get invalidated as well, and only
 
425
                           'jsfuncs' will be cached. So avoid modifying
 
426
                           globals to let caching work fully.
 
427
 
 
428
                           To work around the problem mentioned in the
 
429
                           previous paragraph, you can use
 
430
 
 
431
                            emscripten_jcache_printf
 
432
 
 
433
                           when adding debug printfs to your code. That
 
434
                           function is specially preprocessed so that it
 
435
                           does not create a constant string global for
 
436
                           its first argument. See emscripten.h for more
 
437
                           details. Note in particular that you need to
 
438
                           already have a call to that function in your
 
439
                           code *before* you add one and do an incremental
 
440
                           build, so that adding an external reference
 
441
                           (also a global property) does not invalidate
 
442
                           everything.
 
443
 
 
444
                           Note that you should use -g during the linking
 
445
                           stage (bitcode to JS), for jcache to work
 
446
                           (otherwise, JS minification can confuse it).
 
447
 
 
448
  --clear-cache            Manually clears the cache of compiled
 
449
                           emscripten system libraries (libc++,
 
450
                           libc++abi, libc). This is normally
 
451
                           handled automatically, but if you update
 
452
                           llvm in-place (instead of having a different
 
453
                           directory for a new version), the caching
 
454
                           mechanism can get confused. Clearing the
 
455
                           cache can fix weird problems related to
 
456
                           cache incompatibilities, like clang failing
 
457
                           to link with library files. This also clears
 
458
                           other cached data like the jcache and
 
459
                           the bootstrapped relooper. After the cache
 
460
                           is cleared, this process will exit.
 
461
 
 
462
  --save-bc PATH           When compiling to JavaScript or HTML, this
 
463
                           option will save a copy of the bitcode to
 
464
                           the specified path. The bitcode will include
 
465
                           all files being linked, including standard
 
466
                           libraries, and after any link-time optimizations
 
467
                           (if any).
 
468
 
 
469
  --memory-init-file <on>  If on, we generate a separate memory initialization
 
470
                           file. This is more efficient than storing the
 
471
                           memory initialization data embedded inside
 
472
                           JavaScript as text. (default is off)
 
473
 
 
474
The target file, if specified (-o <target>), defines what will
 
475
be generated:
 
476
 
 
477
  <name>.js                JavaScript
 
478
  <name>.html              HTML with embedded JavaScript
 
479
  <name>.bc                LLVM bitcode (default)
 
480
  <name>.o                 LLVM bitcode (same as .bc)
 
481
 
 
482
(Note that if --memory-init-file is used, then in addition to a
 
483
.js or .html file that is generated, a .mem file will also appear.)
 
484
 
 
485
The -c option (which tells gcc not to run the linker) will
 
486
cause LLVM bitcode to be generated, as %s only generates
 
487
JavaScript in the final linking stage of building.
 
488
 
 
489
The input file(s) can be either source code files that
 
490
Clang can handle (C or C++), LLVM bitcode in binary form,
 
491
or LLVM assembly files in human-readable form.
 
492
 
 
493
emcc is affected by several environment variables. For details, view
 
494
the source of emcc (search for 'os.environ').
 
495
 
 
496
emcc: supported targets: llvm bitcode, javascript, NOT elf
 
497
(autoconf likes to see elf above to enable shared object support)
 
498
''' % (this, this, this)
 
499
  exit(0)
 
500
elif len(sys.argv) == 2 and sys.argv[1] == '-v': # -v with no inputs
 
501
  print 'emcc (Emscripten GCC-like replacement + linker emulating GNU ld ) 2.0'
 
502
  exit(subprocess.call([shared.CLANG, '-v']))
 
503
 
 
504
def is_minus_s_for_emcc(newargs,i):
 
505
  assert newargs[i] == '-s'
 
506
  if i+1 < len(newargs) and '=' in newargs[i+1]: # -s OPT=VALUE is for us, -s by itself is a linker option
 
507
    return True
 
508
  else:
 
509
    print >> sys.stderr, 'emcc: warning: treating -s as linker option and not as -s OPT=VALUE for js compilation'
 
510
    return False
 
511
 
 
512
# If this is a configure-type thing, do not compile to JavaScript, instead use clang
 
513
# to compile to a native binary (using our headers, so things make sense later)
 
514
CONFIGURE_CONFIG = (os.environ.get('EMMAKEN_JUST_CONFIGURE') or 'conftest.c' in sys.argv) and not os.environ.get('EMMAKEN_JUST_CONFIGURE_RECURSE')
 
515
CMAKE_CONFIG = 'CMakeFiles/cmTryCompileExec.dir' in ' '.join(sys.argv)# or 'CMakeCCompilerId' in ' '.join(sys.argv)
 
516
if CONFIGURE_CONFIG or CMAKE_CONFIG:
 
517
  debug_configure = 0 # XXX use this to debug configure stuff. ./configure's generally hide our normal output including stderr so we write to a file
 
518
  use_js = os.environ.get('EMCONFIGURE_JS') # whether we fake configure tests using clang - the local, native compiler - or not. if not we generate JS and use node with a shebang
 
519
                   # neither approach is perfect, you can try both, but may need to edit configure scripts in some cases
 
520
                   # XXX False is not fully tested yet
 
521
 
 
522
  if debug_configure:
 
523
    tempout = '/tmp/emscripten_temp/out'
 
524
    if not os.path.exists(tempout):
 
525
      open(tempout, 'w').write('//\n')
 
526
 
 
527
  src = None
 
528
  for i in range(len(sys.argv)):
 
529
    if sys.argv[i].endswith('.c'):
 
530
      try:
 
531
        src = open(sys.argv[i]).read()
 
532
        if debug_configure: open(tempout, 'a').write('============= ' + sys.argv[i] + '\n' + src + '\n=============\n\n')
 
533
      except:
 
534
        pass
 
535
    if sys.argv[i].endswith('.s'):
 
536
      if debug_configure: open(tempout, 'a').write('(compiling .s assembly, must use clang\n')
 
537
      use_js = 0
 
538
 
 
539
  if src:
 
540
    if 'fopen' in src and '"w"' in src:
 
541
      use_js = 0 # we cannot write to files from js!
 
542
      if debug_configure: open(tempout, 'a').write('Forcing clang since uses fopen to write\n')
 
543
 
 
544
  compiler = os.environ.get('CONFIGURE_CC') or (shared.CLANG if not use_js else shared.EMCC) # if CONFIGURE_CC is defined, use that. let's you use local gcc etc. if you need that
 
545
  if not ('CXXCompiler' in ' '.join(sys.argv) or os.environ.get('EMMAKEN_CXX')):
 
546
    compiler = shared.to_cc(compiler)
 
547
 
 
548
  def filter_emscripten_options(argv):
 
549
    idx = 0
 
550
    skip_next = False
 
551
    for el in argv:
 
552
      if skip_next:
 
553
        skip_next = False
 
554
        idx += 1
 
555
        continue
 
556
      if el == '-s' and is_minus_s_for_emcc(argv, idx):
 
557
        skip_next = True
 
558
      else:
 
559
        yield el
 
560
      idx += 1
 
561
 
 
562
  cmd = [compiler] + list(filter_emscripten_options(sys.argv[1:]))
 
563
  if not use_js: cmd += shared.EMSDK_OPTS + ['-DEMSCRIPTEN']
 
564
  if use_js: cmd += ['-s', 'ERROR_ON_UNDEFINED_SYMBOLS=1'] # configure tests should fail when an undefined symbol exists
 
565
 
 
566
  if DEBUG: print >> sys.stderr, 'emcc, just configuring: ', ' '.join(cmd)
 
567
  if debug_configure: open(tempout, 'a').write('emcc, just configuring: ' + ' '.join(cmd) + '\n\n')
 
568
 
 
569
  if not use_js:
 
570
    exit(subprocess.call(cmd))
 
571
  else:
 
572
    only_object = '-c' in cmd
 
573
    target = None
 
574
    for i in range(len(cmd)-1):
 
575
      if cmd[i] == '-o':
 
576
        if not only_object:
 
577
          cmd[i+1] += '.js'
 
578
        target = cmd[i+1]
 
579
        break
 
580
    print 't1', target
 
581
    if not target:
 
582
      target = 'a.out.js'
 
583
    print 't2', target, only_object
 
584
    os.environ['EMMAKEN_JUST_CONFIGURE_RECURSE'] = '1'
 
585
    ret = subprocess.call(cmd)
 
586
    os.environ['EMMAKEN_JUST_CONFIGURE_RECURSE'] = ''
 
587
    if not os.path.exists(target): exit(1)
 
588
    if target.endswith('.js'):
 
589
      shutil.copyfile(target, target[:-3])
 
590
      target = target[:-3]
 
591
    src = open(target).read()
 
592
    full_node = ' '.join(shared.listify(shared.NODE_JS))
 
593
    if os.path.sep not in full_node:
 
594
      full_node = '/usr/bin/' + full_node # TODO: use whereis etc. And how about non-*NIX?
 
595
    open(target, 'w').write('#!' + full_node + '\n' + src) # add shebang
 
596
    import stat
 
597
    os.chmod(target, stat.S_IMODE(os.stat(target).st_mode) | stat.S_IXUSR) # make executable
 
598
    exit(ret)
 
599
 
 
600
if os.environ.get('EMMAKEN_COMPILER'):
 
601
  CXX = os.environ['EMMAKEN_COMPILER']
 
602
else:
 
603
  CXX = shared.CLANG
 
604
 
 
605
CC = shared.to_cc(CXX)
 
606
 
 
607
# If we got here from a redirection through emmakenxx.py, then force a C++ compiler here
 
608
if os.environ.get('EMMAKEN_CXX'):
 
609
  CC = CXX
 
610
 
 
611
CC_ADDITIONAL_ARGS = shared.COMPILER_OPTS
 
612
 
 
613
EMMAKEN_CFLAGS = os.environ.get('EMMAKEN_CFLAGS')
 
614
if EMMAKEN_CFLAGS: CC_ADDITIONAL_ARGS += shlex.split(EMMAKEN_CFLAGS)
 
615
 
 
616
# ---------------- Utilities ---------------
 
617
 
 
618
SOURCE_SUFFIXES = ('.c', '.cpp', '.cxx', '.cc')
 
619
BITCODE_SUFFIXES = ('.bc', '.o', '.obj')
 
620
DYNAMICLIB_SUFFIXES = ('.dylib', '.so', '.dll')
 
621
STATICLIB_SUFFIXES = ('.a',)
 
622
ASSEMBLY_SUFFIXES = ('.ll',)
 
623
LIB_PREFIXES = ('', 'lib')
 
624
 
 
625
JS_CONTAINING_SUFFIXES = ('js', 'html')
 
626
 
 
627
seen_names = {}
 
628
def uniquename(name):
 
629
  if name not in seen_names:
 
630
    seen_names[name] = str(len(seen_names))
 
631
  return unsuffixed(name) + '_' + seen_names[name] + (('.' + suffix(name)) if suffix(name) else '')
 
632
 
 
633
# ---------------- End configs -------------
 
634
 
 
635
if len(sys.argv) == 1 or sys.argv[1] in ['x', 't']:
 
636
  # noop ar
 
637
  if DEBUG: print >> sys.stderr, 'emcc, just ar'
 
638
  sys.exit(0)
 
639
 
 
640
use_cxx = True
 
641
header = False # pre-compiled headers. We fake that by just copying the file
 
642
 
 
643
for i in range(1, len(sys.argv)):
 
644
  arg = sys.argv[i]
 
645
  if not arg.startswith('-'):
 
646
    if arg.endswith('.c'):
 
647
      use_cxx = False
 
648
    if arg.endswith('.h') and sys.argv[i-1] != '-include':
 
649
      header = True
 
650
 
 
651
if '-M' in sys.argv or '-MM' in sys.argv:
 
652
  # Just output dependencies, do not compile. Warning: clang and gcc behave differently with -MF! (clang seems to not recognize it)
 
653
  cmd = [CC] + shared.COMPILER_OPTS + sys.argv[1:]
 
654
  if DEBUG: print >> sys.stderr, 'emcc, just dependencies: ', ' '.join(cmd)
 
655
  exit(subprocess.call(cmd))
 
656
 
 
657
# Check if a target is specified
 
658
target = None
 
659
for i in range(len(sys.argv)-1):
 
660
  if sys.argv[i].startswith('-o='):
 
661
    raise Exception('Invalid syntax: do not use -o=X, use -o X')
 
662
 
 
663
  if sys.argv[i] == '-o':
 
664
    target = sys.argv[i+1]
 
665
    sys.argv = sys.argv[:i] + sys.argv[i+2:]
 
666
    break
 
667
 
 
668
specified_target = target
 
669
target = specified_target if specified_target is not None else 'a.out.js' # specified_target is the user-specified one, target is what we will generate
 
670
target_basename = unsuffixed_basename(target)
 
671
 
 
672
if '.' in target:
 
673
  final_suffix = target.split('.')[-1]
 
674
else:
 
675
  final_suffix = ''
 
676
 
 
677
if header: # header or such
 
678
  if len(sys.argv) >= 3: # if there is a source and a target, then copy, otherwise do nothing
 
679
    sys.argv = filter(lambda arg: not arg.startswith('-I'), sys.argv)
 
680
    if DEBUG: print >> sys.stderr, 'Just copy:', sys.argv[-1], target
 
681
    shutil.copy(sys.argv[-1], target)
 
682
  else:
 
683
    if DEBUG: print >> sys.stderr, 'No-op.'
 
684
  exit(0)
 
685
 
 
686
if TEMP_DIR:
 
687
  temp_dir = TEMP_DIR
 
688
  if os.path.exists(temp_dir):
 
689
    shutil.rmtree(temp_dir) # clear it
 
690
  os.makedirs(temp_dir)
 
691
else:
 
692
  temp_root = shared.TEMP_DIR
 
693
  if not os.path.exists(temp_root):
 
694
    os.makedirs(temp_root)
 
695
  temp_dir = tempfile.mkdtemp(dir=temp_root)
 
696
 
 
697
def in_temp(name):
 
698
  return os.path.join(temp_dir, os.path.basename(name))
 
699
 
 
700
try:
 
701
  call = CXX if use_cxx else CC
 
702
 
 
703
  ## Parse args
 
704
 
 
705
  newargs = sys.argv[1:]
 
706
 
 
707
  opt_level = 0
 
708
  llvm_opts = None
 
709
  llvm_lto = None
 
710
  closure = None
 
711
  js_transform = None
 
712
  pre_js = ''
 
713
  post_js = ''
 
714
  minify_whitespace = None
 
715
  split_js_file = None
 
716
  preload_files = []
 
717
  embed_files = []
 
718
  compression = None
 
719
  ignore_dynamic_linking = False
 
720
  shell_path = shared.path_from_root('src', 'shell.html')
 
721
  js_libraries = []
 
722
  keep_llvm_debug = False
 
723
  keep_js_debug = False
 
724
  bind = False
 
725
  jcache = False
 
726
  save_bc = False
 
727
  memory_init_file = False
 
728
  use_preload_cache = False
 
729
 
 
730
  if use_cxx:
 
731
    default_cxx_std = '-std=c++03' # Enforce a consistent C++ standard when compiling .cpp files, if user does not specify one on the cmdline.
 
732
  else:
 
733
    default_cxx_std = '' # Compiling C code with .c files, don't enforce a default C++ std.
 
734
 
 
735
  def check_bad_eq(arg):
 
736
    assert '=' not in arg, 'Invalid parameter (do not use "=" with "--" options)'
 
737
 
 
738
  absolute_warning_shown = False
 
739
 
 
740
  settings_changes = []
 
741
 
 
742
  for i in range(len(newargs)):
 
743
    newargs[i] = newargs[i].strip() # On Windows Vista (and possibly others), excessive spaces in the command line leak into the items in this array, so trim e.g. 'foo.cpp ' -> 'foo.cpp'
 
744
    if newargs[i].startswith('-O'):
 
745
      # Let -O default to -O2, which is what gcc does.
 
746
      requested_level = newargs[i][2:] or '2'
 
747
      if requested_level == 's':
 
748
        requested_level = 2
 
749
        settings_changes.append('INLINING_LIMIT=50')
 
750
      try:
 
751
        opt_level = int(requested_level)
 
752
        assert 0 <= opt_level <= 3
 
753
      except:
 
754
        raise Exception('Invalid optimization level: ' + newargs[i])
 
755
      newargs[i] = ''
 
756
    elif newargs[i].startswith('--llvm-opts'):
 
757
      check_bad_eq(newargs[i])
 
758
      llvm_opts = eval(newargs[i+1])
 
759
      newargs[i] = ''
 
760
      newargs[i+1] = ''
 
761
    elif newargs[i].startswith('--llvm-lto'):
 
762
      check_bad_eq(newargs[i])
 
763
      llvm_lto = eval(newargs[i+1])
 
764
      newargs[i] = ''
 
765
      newargs[i+1] = ''
 
766
    elif newargs[i].startswith('--closure'):
 
767
      check_bad_eq(newargs[i])
 
768
      closure = int(newargs[i+1])
 
769
      newargs[i] = ''
 
770
      newargs[i+1] = ''
 
771
    elif newargs[i].startswith('--js-transform'):
 
772
      check_bad_eq(newargs[i])
 
773
      js_transform = newargs[i+1]
 
774
      newargs[i] = ''
 
775
      newargs[i+1] = ''
 
776
    elif newargs[i].startswith('--pre-js'):
 
777
      check_bad_eq(newargs[i])
 
778
      pre_js += open(newargs[i+1]).read() + '\n'
 
779
      newargs[i] = ''
 
780
      newargs[i+1] = ''
 
781
    elif newargs[i].startswith('--post-js'):
 
782
      check_bad_eq(newargs[i])
 
783
      post_js += open(newargs[i+1]).read() + '\n'
 
784
      newargs[i] = ''
 
785
      newargs[i+1] = ''
 
786
    elif newargs[i].startswith('--minify'):
 
787
      check_bad_eq(newargs[i])
 
788
      minify_whitespace = int(newargs[i+1])
 
789
      newargs[i] = ''
 
790
      newargs[i+1] = ''
 
791
    elif newargs[i].startswith('--split'):
 
792
      check_bad_eq(newargs[i])
 
793
      split_js_file = int(newargs[i+1])
 
794
      newargs[i] = ''
 
795
      newargs[i+1] = ''
 
796
    elif newargs[i] == '-g':
 
797
      keep_llvm_debug = True
 
798
      keep_js_debug = True
 
799
    elif newargs[i] == '--bind':
 
800
      bind = True
 
801
      newargs[i] = ''
 
802
      if default_cxx_std:
 
803
        default_cxx_std = '-std=c++11' # Force C++11 for embind code, but only if user has not explicitly overridden a standard.
 
804
    elif newargs[i].startswith('-std='):
 
805
      default_cxx_std = '' # User specified a standard to use, clear Emscripten from specifying it.
 
806
    elif newargs[i].startswith('--embed-file'):
 
807
      check_bad_eq(newargs[i])
 
808
      embed_files.append(newargs[i+1])
 
809
      newargs[i] = ''
 
810
      newargs[i+1] = ''
 
811
    elif newargs[i].startswith('--preload-file'):
 
812
      check_bad_eq(newargs[i])
 
813
      preload_files.append(newargs[i+1])
 
814
      newargs[i] = ''
 
815
      newargs[i+1] = ''
 
816
    elif newargs[i].startswith('--compression'):
 
817
      check_bad_eq(newargs[i])
 
818
      parts = newargs[i+1].split(',')
 
819
      assert len(parts) == 3, '--compression requires specifying    native_encoder,js_decoder,js_name  - see emcc --help. got: %s' % newargs[i+1]
 
820
      Compression.encoder = parts[0]
 
821
      Compression.decoder = parts[1]
 
822
      Compression.js_name = parts[2]
 
823
      assert os.path.exists(Compression.encoder), 'native encoder %s does not exist' % Compression.encoder
 
824
      assert os.path.exists(Compression.decoder), 'js decoder %s does not exist' % Compression.decoder
 
825
      Compression.on = True
 
826
      newargs[i] = ''
 
827
      newargs[i+1] = ''
 
828
    elif newargs[i].startswith('--use-preload-cache'):
 
829
      use_preload_cache = True;
 
830
      newargs[i] = ''
 
831
    elif newargs[i] == '--ignore-dynamic-linking':
 
832
      ignore_dynamic_linking = True
 
833
      newargs[i] = ''
 
834
    elif newargs[i] == '-v':
 
835
      shared.COMPILER_OPTS += ['-v']
 
836
      DEBUG = 1
 
837
      os.environ['EMCC_DEBUG'] = '1' # send to child processes too
 
838
      newargs[i] = ''
 
839
    elif newargs[i].startswith('--shell-file'):
 
840
      check_bad_eq(newargs[i])
 
841
      shell_path = newargs[i+1]
 
842
      newargs[i] = ''
 
843
      newargs[i+1] = ''
 
844
    elif newargs[i].startswith('--js-library'):
 
845
      check_bad_eq(newargs[i])
 
846
      js_libraries.append(newargs[i+1])
 
847
      newargs[i] = ''
 
848
      newargs[i+1] = ''
 
849
    elif newargs[i] == '--remove-duplicates':
 
850
      print >> sys.stderr, 'emcc: warning: --remove-duplicates is deprecated as it is no longer needed. If you cannot link without it, file a bug with a testcase'
 
851
      newargs[i] = ''
 
852
    elif newargs[i] == '--jcache':
 
853
      jcache = True
 
854
      newargs[i] = ''
 
855
    elif newargs[i] == '--clear-cache':
 
856
      newargs[i] = ''
 
857
      print >> sys.stderr, 'emcc: clearing cache'
 
858
      shared.Cache.erase()
 
859
      sys.exit(0)
 
860
    elif newargs[i] == '--save-bc':
 
861
      check_bad_eq(newargs[i])
 
862
      save_bc = newargs[i+1]
 
863
      newargs[i] = ''
 
864
      newargs[i+1] = ''
 
865
    elif newargs[i] == '--memory-init-file':
 
866
      check_bad_eq(newargs[i])
 
867
      memory_init_file = int(newargs[i+1])
 
868
      newargs[i] = ''
 
869
      newargs[i+1] = ''
 
870
    elif newargs[i].startswith(('-I/', '-L/')):
 
871
      if not absolute_warning_shown:
 
872
        print >> sys.stderr, 'emcc: warning: -I or -L of an absolute path encountered. If this is to a local system header/library, it may cause problems (local system files make sense for compiling natively on your system, but not necessarily to JavaScript)' # Of course an absolute path to a non-system-specific library or header is fine, and you can ignore this warning. The danger are system headers that are e.g. x86 specific and nonportable. The emscripten bundled headers are modified to be portable, local system ones are generally not
 
873
        absolute_warning_shown = True
 
874
  newargs = [ arg for arg in newargs if arg is not '' ]
 
875
 
 
876
  # If user did not specify a default -std for C++ code, specify the emscripten default.
 
877
  if default_cxx_std:
 
878
    newargs = newargs + [default_cxx_std]
 
879
 
 
880
  if llvm_opts is None: llvm_opts = LLVM_OPT_LEVEL[opt_level]
 
881
  if llvm_lto is None: llvm_lto = opt_level >= 3
 
882
  if opt_level <= 0: keep_llvm_debug = keep_js_debug = True # always keep debug in -O0
 
883
  if opt_level > 0: keep_llvm_debug = False # JS optimizer wipes out llvm debug info from being visible
 
884
  if closure is None and opt_level == 3: closure = True
 
885
 
 
886
  if DEBUG: start_time = time.time() # done after parsing arguments, which might affect debug state
 
887
 
 
888
  if closure:
 
889
    assert os.path.exists(shared.CLOSURE_COMPILER), 'emcc: fatal: Closure compiler (%s) does not exist' % shared.CLOSURE_COMPILER
 
890
 
 
891
  for i in range(len(newargs)):
 
892
    if newargs[i] == '-s':
 
893
      if is_minus_s_for_emcc(newargs, i):
 
894
        settings_changes.append(newargs[i+1])
 
895
        newargs[i] = newargs[i+1] = ''
 
896
    elif newargs[i].startswith('--typed-arrays'):
 
897
      assert '=' not in newargs[i], 'Invalid typed arrays parameter (do not use "=")'
 
898
      settings_changes.append('USE_TYPED_ARRAYS=' + newargs[i+1])
 
899
      newargs[i] = ''
 
900
      newargs[i+1] = ''
 
901
  newargs = [ arg for arg in newargs if arg is not '' ]
 
902
 
 
903
  if split_js_file:
 
904
    settings_changes.append("PRINT_SPLIT_FILE_MARKER=1")
 
905
 
 
906
  # Find input files
 
907
 
 
908
  input_files = []
 
909
  has_source_inputs = False
 
910
  lib_dirs = [shared.path_from_root('system', 'local', 'lib'),
 
911
              shared.path_from_root('system', 'lib')]
 
912
  libs = []
 
913
  for i in range(len(newargs)): # find input files XXX this a simple heuristic. we should really analyze based on a full understanding of gcc params,
 
914
                                # right now we just assume that what is left contains no more |-x OPT| things
 
915
    arg = newargs[i]
 
916
 
 
917
    if i > 0:
 
918
      prev = newargs[i-1]
 
919
      if prev in ['-MT', '-install_name', '-I', '-L']: continue # ignore this gcc-style argument
 
920
 
 
921
    if not arg.startswith('-') and (arg.endswith(SOURCE_SUFFIXES + BITCODE_SUFFIXES + DYNAMICLIB_SUFFIXES + ASSEMBLY_SUFFIXES) or shared.Building.is_ar(arg)): # we already removed -o <target>, so all these should be inputs
 
922
      newargs[i] = ''
 
923
      if os.path.exists(arg):
 
924
        if arg.endswith(SOURCE_SUFFIXES):
 
925
          input_files.append(arg)
 
926
          has_source_inputs = True
 
927
        else:
 
928
          # this should be bitcode, make sure it is valid
 
929
          if arg.endswith(ASSEMBLY_SUFFIXES) or shared.Building.is_bitcode(arg):
 
930
            input_files.append(arg)
 
931
          elif arg.endswith(STATICLIB_SUFFIXES + DYNAMICLIB_SUFFIXES):
 
932
            # if it's not, and it's a library, just add it to libs to find later
 
933
            l = unsuffixed_basename(arg)
 
934
            for prefix in LIB_PREFIXES:
 
935
              if not prefix: continue
 
936
              if l.startswith(prefix):
 
937
                l = l[len(prefix):]
 
938
                break;
 
939
            libs.append(l)
 
940
            newargs[i] = ''
 
941
          else:
 
942
            print >> sys.stderr, 'emcc: %s: warning: Not valid LLVM bitcode' % arg
 
943
      else:
 
944
        print >> sys.stderr, 'emcc: %s: error: No such file or directory' % arg
 
945
        exit(1)
 
946
    elif arg.startswith('-L'):
 
947
      lib_dirs.append(arg[2:])
 
948
      newargs[i] = ''
 
949
    elif arg.startswith('-l'):
 
950
      libs.append(arg[2:])
 
951
      newargs[i] = ''
 
952
 
 
953
  original_input_files = input_files[:]
 
954
 
 
955
  newargs = [ arg for arg in newargs if arg is not '' ]
 
956
 
 
957
  # -c means do not link in gcc, and for us, the parallel is to not go all the way to JS, but stop at bitcode
 
958
  has_dash_c = '-c' in newargs
 
959
  if has_dash_c:
 
960
    assert has_source_inputs, 'Must have source code inputs to use -c'
 
961
    target = target_basename + '.o'
 
962
    final_suffix = 'o'
 
963
 
 
964
  # do not link in libs when just generating object code (not an 'executable', i.e. JS, or a library)
 
965
  if ('.' + final_suffix) in BITCODE_SUFFIXES and len(libs) > 0:
 
966
    print >> sys.stderr, 'emcc: warning: not linking against libraries since only compiling to bitcode'
 
967
    libs = []
 
968
 
 
969
  # Find library files
 
970
  for lib in libs:
 
971
    if DEBUG: print >> sys.stderr, 'emcc: looking for library "%s"' % lib
 
972
    found = False
 
973
    for prefix in LIB_PREFIXES:
 
974
      for suff in STATICLIB_SUFFIXES + DYNAMICLIB_SUFFIXES:
 
975
        name = prefix + lib + suff
 
976
        for lib_dir in lib_dirs:
 
977
          path = os.path.join(lib_dir, name)
 
978
          if os.path.exists(path):
 
979
            if DEBUG: print >> sys.stderr, 'emcc: found library "%s" at %s' % (lib, path)
 
980
            input_files.append(path)
 
981
            found = True
 
982
            break
 
983
        if found: break
 
984
      if found: break
 
985
 
 
986
  if ignore_dynamic_linking:
 
987
    input_files = filter(lambda input_file: not input_file.endswith(DYNAMICLIB_SUFFIXES), input_files)
 
988
 
 
989
  if len(input_files) == 0:
 
990
    print >> sys.stderr, 'emcc: no input files'
 
991
    print >> sys.stderr, 'note that input files without a known suffix are ignored, make sure your input files end with one of: ' + str(SOURCE_SUFFIXES + BITCODE_SUFFIXES + DYNAMICLIB_SUFFIXES + STATICLIB_SUFFIXES + ASSEMBLY_SUFFIXES)
 
992
    exit(0)
 
993
 
 
994
  newargs += CC_ADDITIONAL_ARGS
 
995
 
 
996
  assert not (Compression.on and final_suffix != 'html'), 'Compression only works when generating HTML'
 
997
 
 
998
  # If we are using embind and generating JS, now is the time to link in bind.cpp
 
999
  if bind and final_suffix in JS_CONTAINING_SUFFIXES:
 
1000
    input_files.append(shared.path_from_root('system', 'lib', 'embind', 'bind.cpp'))
 
1001
 
 
1002
  # Apply optimization level settings
 
1003
  shared.Settings.apply_opt_level(opt_level, noisy=True)
 
1004
 
 
1005
  # Apply -s settings in newargs here (after optimization levels, so they can override them)
 
1006
  for change in settings_changes:
 
1007
    key, value = change.split('=')
 
1008
    if value[0] == '@':
 
1009
      value = '"' + value + '"'
 
1010
    exec('shared.Settings.' + key + ' = ' + value)
 
1011
 
 
1012
  # Apply effects from settings
 
1013
  if shared.Settings.ASM_JS:
 
1014
    assert opt_level >= 1, 'asm.js requires -O1 or above'
 
1015
 
 
1016
    if bind:
 
1017
      shared.Settings.ASM_JS = 0
 
1018
      print >> sys.stderr, 'emcc: warning: disabling asm.js because it is not compatible with embind yet'
 
1019
    if closure:
 
1020
      print >> sys.stderr, 'emcc: warning: disabling closure because it is not compatible with asm.js code generation'
 
1021
      closure = False
 
1022
    if shared.Settings.CORRECT_SIGNS != 1:
 
1023
      print >> sys.stderr, 'emcc: warning: setting CORRECT_SIGNS to 1 for asm.js code generation'
 
1024
      shared.Settings.CORRECT_SIGNS = 1
 
1025
    if shared.Settings.CORRECT_OVERFLOWS != 1:
 
1026
      print >> sys.stderr, 'emcc: warning: setting CORRECT_OVERFLOWS to 1 for asm.js code generation'
 
1027
      shared.Settings.CORRECT_OVERFLOWS = 1
 
1028
    assert not shared.Settings.PGO, 'cannot run PGO in ASM_JS mode'
 
1029
 
 
1030
  if shared.Settings.CORRECT_SIGNS >= 2 or shared.Settings.CORRECT_OVERFLOWS >= 2 or shared.Settings.CORRECT_ROUNDINGS >= 2:
 
1031
    keep_llvm_debug = True # must keep debug info to do line-by-line operations
 
1032
 
 
1033
  if (keep_llvm_debug or keep_js_debug) and closure:
 
1034
    print >> sys.stderr, 'emcc: warning: disabling closure because debug info was requested'
 
1035
    closure = False
 
1036
 
 
1037
  if jcache and not keep_js_debug: print >> sys.stderr, 'emcc: warning: it is recommended to run jcache with -g when compiling bitcode to JS'
 
1038
 
 
1039
  if minify_whitespace is None:
 
1040
    minify_whitespace = opt_level >= 2 and not keep_js_debug
 
1041
 
 
1042
  assert shared.LLVM_TARGET in shared.COMPILER_OPTS
 
1043
  if shared.LLVM_TARGET == 'i386-pc-linux-gnu':
 
1044
    shared.Settings.TARGET_X86 = 1
 
1045
    shared.Settings.TARGET_LE32 = 0
 
1046
    assert 'le32-unknown-nacl' not in shared.COMPILER_OPTS
 
1047
  elif shared.LLVM_TARGET == 'le32-unknown-nacl':
 
1048
    shared.Settings.TARGET_LE32 = 1
 
1049
    shared.Settings.TARGET_X86 = 0
 
1050
    assert 'i386-pc-linux-gnu' not in shared.COMPILER_OPTS
 
1051
  else:
 
1052
    raise Exception('unknown llvm target: ' + str(shared.LLVM_TARGET))
 
1053
 
 
1054
  ## Compile source code to bitcode
 
1055
 
 
1056
  if DEBUG: print >> sys.stderr, 'emcc: compiling to bitcode'
 
1057
 
 
1058
  temp_files = []
 
1059
 
 
1060
  # First, generate LLVM bitcode. For each input file, we get base.o with bitcode
 
1061
  for input_file in input_files:
 
1062
    if input_file.endswith(SOURCE_SUFFIXES):
 
1063
      if DEBUG: print >> sys.stderr, 'emcc: compiling source file: ', input_file
 
1064
      input_file = shared.Building.preprocess(input_file, in_temp(uniquename(input_file)))
 
1065
      output_file = in_temp(unsuffixed(uniquename(input_file)) + '.o')
 
1066
      temp_files.append(output_file)
 
1067
      args = newargs + ['-emit-llvm', '-c', input_file, '-o', output_file]
 
1068
      if DEBUG: print >> sys.stderr, "emcc running:", call, ' '.join(args)
 
1069
      execute([call] + args) # let compiler frontend print directly, so colors are saved (PIPE kills that)
 
1070
      if not os.path.exists(output_file):
 
1071
        print >> sys.stderr, 'emcc: compiler frontend failed to generate LLVM bitcode, halting'
 
1072
        sys.exit(1)
 
1073
    else: # bitcode
 
1074
      if input_file.endswith(BITCODE_SUFFIXES):
 
1075
        if DEBUG: print >> sys.stderr, 'emcc: copying bitcode file: ', input_file
 
1076
        temp_file = in_temp(unsuffixed(uniquename(input_file)) + '.o')
 
1077
        shutil.copyfile(input_file, temp_file)
 
1078
        temp_files.append(temp_file)
 
1079
      elif input_file.endswith(DYNAMICLIB_SUFFIXES) or shared.Building.is_ar(input_file):
 
1080
        if DEBUG: print >> sys.stderr, 'emcc: copying library file: ', input_file
 
1081
        temp_file = in_temp(uniquename(input_file))
 
1082
        shutil.copyfile(input_file, temp_file)
 
1083
        temp_files.append(temp_file)
 
1084
      else: #.ll
 
1085
        if not LEAVE_INPUTS_RAW:
 
1086
          # Note that by assembling the .ll file, then disassembling it later, we will
 
1087
          # remove annotations which is a good thing for compilation time
 
1088
          if DEBUG: print >> sys.stderr, 'emcc: assembling assembly file: ', input_file
 
1089
          temp_file = in_temp(unsuffixed(uniquename(input_file)) + '.o')
 
1090
          shared.Building.llvm_as(input_file, temp_file)
 
1091
          temp_files.append(temp_file)
 
1092
 
 
1093
  if not LEAVE_INPUTS_RAW: assert len(temp_files) == len(input_files)
 
1094
 
 
1095
  # If we were just asked to generate bitcode, stop there
 
1096
  if final_suffix not in JS_CONTAINING_SUFFIXES:
 
1097
    if llvm_opts > 0:
 
1098
      if not os.environ.get('EMCC_OPTIMIZE_NORMALLY'):
 
1099
        print >> sys.stderr, 'emcc: warning: -Ox flags ignored, since not generating JavaScript'
 
1100
      else:
 
1101
        for input_file in input_files:
 
1102
          if input_file.endswith(SOURCE_SUFFIXES):
 
1103
            if DEBUG: print >> sys.stderr, 'emcc: optimizing %s with -O%d since EMCC_OPTIMIZE_NORMALLY defined' % (input_file, llvm_opts)
 
1104
            shared.Building.llvm_opt(in_temp(unsuffixed(uniquename(input_file)) + '.o'), llvm_opts)
 
1105
          else:
 
1106
            if DEBUG: print >> sys.stderr, 'emcc: not optimizing %s despite EMCC_OPTIMIZE_NORMALLY since not source code' % (input_file)
 
1107
    if not specified_target:
 
1108
      for input_file in input_files:
 
1109
        shutil.move(in_temp(unsuffixed(uniquename(input_file)) + '.o'), unsuffixed_basename(input_file) + '.' + final_suffix)
 
1110
    else:
 
1111
      if len(input_files) == 1:
 
1112
        shutil.move(in_temp(unsuffixed(uniquename(input_files[0])) + '.o'), specified_target)
 
1113
      else:
 
1114
        assert len(original_input_files) == 1 or not has_dash_c, 'fatal error: cannot specify -o with -c with multiple files' + str(sys.argv) + ':' + str(original_input_files)
 
1115
        # We have a specified target (-o <target>), which is not JavaScript or HTML, and
 
1116
        # we have multiple files: Link them
 
1117
        if DEBUG: print >> sys.stderr, 'emcc: link: ' + str(temp_files), specified_target
 
1118
        shared.Building.link(temp_files, specified_target)
 
1119
    exit(0)
 
1120
 
 
1121
  ## Continue on to create JavaScript
 
1122
 
 
1123
  if DEBUG: print >> sys.stderr, 'emcc: will generate JavaScript'
 
1124
 
 
1125
  extra_files_to_link = []
 
1126
 
 
1127
  if not LEAVE_INPUTS_RAW and not AUTODEBUG and \
 
1128
     not shared.Settings.BUILD_AS_SHARED_LIB == 2: # shared lib 2 use the library in the parent
 
1129
    # Check if we need to include some libraries that we compile. (We implement libc ourselves in js, but
 
1130
    # compile a malloc implementation and stdlibc++.)
 
1131
    # Note that we assume a single symbol is enough to know if we have/do not have dlmalloc etc. If you
 
1132
    # include just a few symbols but want the rest, this will not work.
 
1133
 
 
1134
    def read_symbols(path, exclude=None):
 
1135
      symbols = map(lambda line: line.strip().split(' ')[1], open(path).readlines())
 
1136
      if exclude:
 
1137
        symbols = filter(lambda symbol: symbol not in exclude, symbols)
 
1138
      return set(symbols)
 
1139
 
 
1140
    # XXX We also need to add libc symbols that use malloc, for example strdup. It's very rare to use just them and not
 
1141
    #     a normal malloc symbol (like free, after calling strdup), so we haven't hit this yet, but it is possible.
 
1142
    libc_symbols = read_symbols(shared.path_from_root('system', 'lib', 'libc.symbols'))
 
1143
    libcextra_symbols = read_symbols(shared.path_from_root('system', 'lib', 'libcextra.symbols'))
 
1144
    libcxx_symbols = read_symbols(shared.path_from_root('system', 'lib', 'libcxx', 'symbols'), exclude=libc_symbols)
 
1145
    libcxxabi_symbols = read_symbols(shared.path_from_root('system', 'lib', 'libcxxabi', 'symbols'), exclude=libc_symbols)
 
1146
 
 
1147
    def build_libc(lib_filename, files):
 
1148
      o_s = []
 
1149
      prev_cxx = os.environ.get('EMMAKEN_CXX')
 
1150
      if prev_cxx: os.environ['EMMAKEN_CXX'] = ''
 
1151
      musl_internal_includes = shared.path_from_root('system', 'lib', 'libc', 'musl', 'src', 'internal')
 
1152
      for src in files:
 
1153
        o = in_temp(os.path.basename(src) + '.o')
 
1154
        execute([shared.PYTHON, shared.EMCC, shared.path_from_root('system', 'lib', src), '-o', o, '-I', musl_internal_includes], stdout=stdout, stderr=stderr)
 
1155
        o_s.append(o)
 
1156
      if prev_cxx: os.environ['EMMAKEN_CXX'] = prev_cxx
 
1157
      shared.Building.link(o_s, in_temp(lib_filename))
 
1158
      return in_temp(lib_filename)
 
1159
 
 
1160
    def build_libcxx(src_dirname, lib_filename, files):
 
1161
      o_s = []
 
1162
      for src in files:
 
1163
        o = in_temp(src + '.o')
 
1164
        srcfile = shared.path_from_root(src_dirname, src)
 
1165
        execute([shared.PYTHON, shared.EMXX, srcfile, '-o', o, '-std=c++11'], stdout=stdout, stderr=stderr)
 
1166
        o_s.append(o)
 
1167
      shared.Building.link(o_s, in_temp(lib_filename))
 
1168
      return in_temp(lib_filename)
 
1169
 
 
1170
    # libc
 
1171
    def create_libc():
 
1172
      if DEBUG: print >> sys.stderr, 'emcc: building libc for cache'
 
1173
      libc_files = [
 
1174
        'dlmalloc.c',
 
1175
        os.path.join('libcxx', 'new.cpp'),
 
1176
        os.path.join('libc', 'stdlib', 'getopt_long.c'),
 
1177
        os.path.join('libc', 'gen', 'err.c'),
 
1178
        os.path.join('libc', 'gen', 'errx.c'),
 
1179
        os.path.join('libc', 'gen', 'warn.c'),
 
1180
        os.path.join('libc', 'gen', 'warnx.c'),
 
1181
        os.path.join('libc', 'gen', 'verr.c'),
 
1182
        os.path.join('libc', 'gen', 'verrx.c'),
 
1183
        os.path.join('libc', 'gen', 'vwarn.c'),
 
1184
        os.path.join('libc', 'gen', 'vwarnx.c'),
 
1185
        os.path.join('libc', 'stdlib', 'strtod.c'),
 
1186
      ];
 
1187
      return build_libc('libc.bc', libc_files)
 
1188
 
 
1189
    def fix_libc(need):
 
1190
      # libc needs some sign correction. # If we are in mode 0, switch to 2. We will add our lines
 
1191
      try:
 
1192
        if shared.Settings.CORRECT_SIGNS == 0: raise Exception('we need to change to 2')
 
1193
      except: # we fail if equal to 0 - so we need to switch to 2 - or if CORRECT_SIGNS is not even in Settings
 
1194
        shared.Settings.CORRECT_SIGNS = 2
 
1195
      if shared.Settings.CORRECT_SIGNS == 2:
 
1196
        shared.Settings.CORRECT_SIGNS_LINES = [shared.path_from_root('src', 'dlmalloc.c') + ':' + str(i+4) for i in [4816, 4191, 4246, 4199, 4205, 4235, 4227]]
 
1197
      # If we are in mode 1, we are correcting everything anyhow. If we are in mode 3, we will be corrected
 
1198
      # so all is well anyhow too.
 
1199
 
 
1200
    # libcextra
 
1201
    def create_libcextra():
 
1202
      if DEBUG: print >> sys.stderr, 'emcc: building libcextra for cache'
 
1203
      musl_files = [
 
1204
         ['ctype', [
 
1205
          'iswalnum.c',
 
1206
          'iswalpha.c',
 
1207
          'iswblank.c',
 
1208
          'iswcntrl.c',
 
1209
          'iswctype.c',
 
1210
          'iswdigit.c',
 
1211
          'iswgraph.c',
 
1212
          'iswlower.c',
 
1213
          'iswprint.c',
 
1214
          'iswpunct.c',
 
1215
          'iswspace.c',
 
1216
          'iswupper.c',
 
1217
          'iswxdigit.c',
 
1218
          'towctrans.c',
 
1219
          'wcswidth.c',
 
1220
          'wctrans.c',
 
1221
          'wcwidth.c',
 
1222
         ]],
 
1223
         ['multibyte', [
 
1224
          'btowc.c',
 
1225
          'mblen.c',
 
1226
          'mbrlen.c',
 
1227
          'mbrtowc.c',
 
1228
          'mbsinit.c',
 
1229
          'mbsnrtowcs.c',
 
1230
          'mbsrtowcs.c',
 
1231
          'mbstowcs.c',
 
1232
          'mbtowc.c',
 
1233
          'wcrtomb.c',
 
1234
          'wcsnrtombs.c',
 
1235
          'wcsrtombs.c',
 
1236
          'wcstombs.c',
 
1237
          'wctob.c',
 
1238
          'wctomb.c',
 
1239
         ]],
 
1240
         ['string', [
 
1241
           'wcpcpy.c',
 
1242
           'wcpncpy.c',
 
1243
           'wcscasecmp.c',
 
1244
           # 'wcscasecmp_l.c', # XXX: alltypes.h issue
 
1245
           'wcscat.c',
 
1246
           'wcschr.c',
 
1247
           'wcscmp.c',
 
1248
           'wcscpy.c',
 
1249
           'wcscspn.c',
 
1250
           'wcsdup.c',
 
1251
           'wcslen.c',
 
1252
           'wcsncasecmp.c',
 
1253
           # 'wcsncasecmp_l.c', # XXX: alltypes.h issue
 
1254
           'wcsncat.c',
 
1255
           'wcsncmp.c',
 
1256
           'wcsncpy.c',
 
1257
           'wcsnlen.c',
 
1258
           'wcspbrk.c',
 
1259
           'wcsrchr.c',
 
1260
           'wcsspn.c',
 
1261
           'wcsstr.c',
 
1262
           'wcstok.c',
 
1263
           'wcswcs.c',
 
1264
           'wmemchr.c',
 
1265
           'wmemcmp.c',
 
1266
           'wmemcpy.c',
 
1267
           'wmemmove.c',
 
1268
           'wmemset.c',
 
1269
         ]]
 
1270
      ]
 
1271
      libcextra_files = []
 
1272
      for directory, sources in musl_files:
 
1273
        libcextra_files += [os.path.join('libc', 'musl', 'src', directory, source) for source in sources]
 
1274
      return build_libc('libcextra.bc', libcextra_files)
 
1275
 
 
1276
    def fix_libcextra(need):
 
1277
      pass
 
1278
 
 
1279
    # libcxx
 
1280
    def create_libcxx():
 
1281
      if DEBUG: print >> sys.stderr, 'emcc: building libcxx for cache'
 
1282
      libcxx_files = [
 
1283
        'algorithm.cpp',
 
1284
        'condition_variable.cpp',
 
1285
        'future.cpp',
 
1286
        'iostream.cpp',
 
1287
        'memory.cpp',
 
1288
        'random.cpp',
 
1289
        'stdexcept.cpp',
 
1290
        'system_error.cpp',
 
1291
        'utility.cpp',
 
1292
        'bind.cpp',
 
1293
        'debug.cpp',
 
1294
        'hash.cpp',
 
1295
        'mutex.cpp',
 
1296
        'string.cpp',
 
1297
        'thread.cpp',
 
1298
        'valarray.cpp',
 
1299
        'chrono.cpp',
 
1300
        'exception.cpp',
 
1301
        'ios.cpp',
 
1302
        'locale.cpp',
 
1303
        'regex.cpp',
 
1304
        'strstream.cpp'
 
1305
      ]
 
1306
      return build_libcxx(os.path.join('system', 'lib', 'libcxx'), 'libcxx.bc', libcxx_files)
 
1307
 
 
1308
    def fix_libcxx(need):
 
1309
      assert shared.Settings.QUANTUM_SIZE == 4, 'We do not support libc++ with QUANTUM_SIZE == 1'
 
1310
      # libcxx might need corrections, so turn them all on. TODO: check which are actually needed
 
1311
      shared.Settings.CORRECT_SIGNS = shared.Settings.CORRECT_OVERFLOWS = shared.Settings.CORRECT_ROUNDINGS = 1
 
1312
      #print >> sys.stderr, 'emcc: info: using libcxx turns on CORRECT_* options'
 
1313
 
 
1314
    # libcxxabi - just for dynamic_cast for now
 
1315
    def create_libcxxabi():
 
1316
      if DEBUG: print >> sys.stderr, 'emcc: building libcxxabi for cache'
 
1317
      libcxxabi_files = [
 
1318
        'typeinfo.cpp',
 
1319
        'private_typeinfo.cpp'
 
1320
      ]
 
1321
      return build_libcxx(os.path.join('system', 'lib', 'libcxxabi', 'src'), 'libcxxabi.bc', libcxxabi_files)
 
1322
 
 
1323
    def fix_libcxxabi(need):
 
1324
      assert shared.Settings.QUANTUM_SIZE == 4, 'We do not support libc++abi with QUANTUM_SIZE == 1'
 
1325
      #print >> sys.stderr, 'emcc: info: using libcxxabi, this may need CORRECT_* options'
 
1326
      #shared.Settings.CORRECT_SIGNS = shared.Settings.CORRECT_OVERFLOWS = shared.Settings.CORRECT_ROUNDINGS = 1
 
1327
 
 
1328
    # If we have libcxx, we must force inclusion of libc, since libcxx uses new internally. Note: this is kind of hacky
 
1329
    # Settings this in the environment will avoid checking dependencies and make building big projects a little faster
 
1330
    force = os.environ.get('EMCC_FORCE_STDLIBS')
 
1331
    has = need = None
 
1332
    for name, create, fix, library_symbols in [('libcxx',    create_libcxx,    fix_libcxx,    libcxx_symbols),
 
1333
                                               ('libcextra', create_libcextra, fix_libcextra, libcextra_symbols),
 
1334
                                               ('libcxxabi', create_libcxxabi, fix_libcxxabi, libcxxabi_symbols),
 
1335
                                               ('libc',      create_libc,      fix_libc,      libc_symbols)]:
 
1336
      if not force:
 
1337
        need = set()
 
1338
        has = set()
 
1339
        for temp_file in temp_files:
 
1340
          symbols = shared.Building.llvm_nm(temp_file)
 
1341
          for library_symbol in library_symbols:
 
1342
            if library_symbol in symbols.undefs:
 
1343
              need.add(library_symbol)
 
1344
            if library_symbol in symbols.defs:
 
1345
              has.add(library_symbol)
 
1346
        for haz in has: # remove symbols that are supplied by another of the inputs
 
1347
          if haz in need:
 
1348
            need.remove(haz)
 
1349
        if DEBUG: print >> sys.stderr, 'emcc: considering including %s: we need %s and have %s' % (name, str(need), str(has))
 
1350
      if force or len(need) > 0:
 
1351
        # We need to build and link the library in
 
1352
        if DEBUG: print >> sys.stderr, 'emcc: including %s' % name
 
1353
        libfile = shared.Cache.get(name, create)
 
1354
        extra_files_to_link.append(libfile)
 
1355
        force = True
 
1356
        if fix and need:
 
1357
          fix(need)
 
1358
 
 
1359
  # First, combine the bitcode files if there are several. We must also link if we have a singleton .a
 
1360
  if len(input_files) + len(extra_files_to_link) > 1 or \
 
1361
     (not LEAVE_INPUTS_RAW and not (suffix(temp_files[0]) in BITCODE_SUFFIXES or suffix(temp_files[0]) in DYNAMICLIB_SUFFIXES) and shared.Building.is_ar(temp_files[0])):
 
1362
    linker_inputs = temp_files + extra_files_to_link
 
1363
    if DEBUG: print >> sys.stderr, 'emcc: linking: ', linker_inputs
 
1364
    t0 = time.time()
 
1365
    shared.Building.link(linker_inputs, in_temp(target_basename + '.bc'))
 
1366
    t1 = time.time()
 
1367
    if DEBUG: print >> sys.stderr, 'emcc:    linking took %.2f seconds' % (t1 - t0)
 
1368
    final = in_temp(target_basename + '.bc')
 
1369
  else:
 
1370
    if not LEAVE_INPUTS_RAW:
 
1371
      shutil.move(temp_files[0], in_temp(target_basename + '.bc'))
 
1372
      final = in_temp(target_basename + '.bc')
 
1373
    else:
 
1374
      final = in_temp(input_files[0])
 
1375
      shutil.copyfile(input_files[0], final)
 
1376
 
 
1377
  if DEBUG:
 
1378
    print >> sys.stderr, 'emcc: saving intermediate processing steps to %s' % shared.EMSCRIPTEN_TEMP_DIR
 
1379
 
 
1380
    intermediate_counter = 0
 
1381
    intermediate_time = None
 
1382
    def save_intermediate(name=None, suffix='js'):
 
1383
      global intermediate_counter, intermediate_time
 
1384
      shutil.copyfile(final, os.path.join(shared.EMSCRIPTEN_TEMP_DIR, 'emcc-%d%s.%s' % (intermediate_counter, '' if name is None else '-' + name, suffix)))
 
1385
      intermediate_counter += 1
 
1386
      now = time.time()
 
1387
      if intermediate_time:
 
1388
        print >> sys.stderr, 'emcc:    step took %.2f seconds' % (now - intermediate_time)
 
1389
      intermediate_time = now
 
1390
 
 
1391
    if not LEAVE_INPUTS_RAW: save_intermediate('basebc', 'bc')
 
1392
 
 
1393
  # Optimize, if asked to
 
1394
  if not LEAVE_INPUTS_RAW:
 
1395
    link_opts = [] if keep_llvm_debug else ['-strip-debug'] # remove LLVM debug info in -O1+, since the optimizer removes it anyhow
 
1396
    if llvm_opts > 0:
 
1397
      if not os.environ.get('EMCC_OPTIMIZE_NORMALLY'):
 
1398
        shared.Building.llvm_opt(in_temp(target_basename + '.bc'), llvm_opts)
 
1399
        if DEBUG: save_intermediate('opt', 'bc')
 
1400
        # Do LTO in a separate pass to work around LLVM bug XXX (see failure e.g. in cubescript)
 
1401
      else:
 
1402
        if DEBUG: print >> sys.stderr, 'emcc: not running opt because EMCC_OPTIMIZE_NORMALLY was specified, opt should have been run before'
 
1403
    if shared.Building.can_build_standalone():
 
1404
      # If we can LTO, do it before dce, since it opens up dce opportunities
 
1405
      if llvm_lto and shared.Building.can_use_unsafe_opts():
 
1406
        if not shared.Building.can_inline(): link_opts.append('-disable-inlining')
 
1407
        # do not internalize in std-link-opts - it ignores internalize-public-api-list - and add a manual internalize
 
1408
        link_opts += ['-disable-internalize'] + shared.Building.get_safe_internalize() + ['-std-link-opts']
 
1409
      else:
 
1410
        # At minimum remove dead functions etc., this potentially saves a lot in the size of the generated code (and the time to compile it)
 
1411
        link_opts += shared.Building.get_safe_internalize() + ['-globaldce']
 
1412
      shared.Building.llvm_opt(in_temp(target_basename + '.bc'), link_opts)
 
1413
      if DEBUG: save_intermediate('linktime', 'bc')
 
1414
 
 
1415
  if save_bc:
 
1416
    shutil.copyfile(final, save_bc)
 
1417
 
 
1418
  # Prepare .ll for Emscripten
 
1419
  if not LEAVE_INPUTS_RAW:
 
1420
    final = shared.Building.llvm_dis(final, final + '.ll')
 
1421
  else:
 
1422
    assert len(input_files) == 1
 
1423
  if DEBUG: save_intermediate('ll', 'll')
 
1424
 
 
1425
  if AUTODEBUG:
 
1426
    if DEBUG: print >> sys.stderr, 'emcc: autodebug'
 
1427
    execute([shared.PYTHON, shared.AUTODEBUGGER, final, final + '.ad.ll'])
 
1428
    final += '.ad.ll'
 
1429
    if DEBUG: save_intermediate('autodebug', 'll')
 
1430
 
 
1431
  # Emscripten
 
1432
  if DEBUG: print >> sys.stderr, 'emcc: LLVM => JS'
 
1433
  extra_args = [] if not js_libraries else ['--libraries', ','.join(map(os.path.abspath, js_libraries))]
 
1434
  if jcache: extra_args.append('--jcache')
 
1435
  final = shared.Building.emscripten(final, append_ext=False, extra_args=extra_args)
 
1436
  if DEBUG: save_intermediate('original')
 
1437
 
 
1438
  # Embed and preload files
 
1439
  if len(preload_files) + len(embed_files) > 0:
 
1440
    if DEBUG: print >> sys.stderr, 'emcc: setting up files'
 
1441
    file_args = []
 
1442
    if len(preload_files) > 0:
 
1443
      file_args.append('--preload')
 
1444
      file_args += preload_files
 
1445
    if len(embed_files) > 0:
 
1446
      file_args.append('--embed')
 
1447
      file_args += embed_files
 
1448
    if Compression.on:
 
1449
      file_args += ['--compress', Compression.encoder, Compression.decoder, Compression.js_name]
 
1450
    if use_preload_cache:
 
1451
      file_args.append('--use-preload-cache')
 
1452
    code = execute([shared.PYTHON, shared.FILE_PACKAGER, unsuffixed(target) + '.data'] + file_args, stdout=PIPE)[0]
 
1453
    src = open(final).read().replace('// {{PRE_RUN_ADDITIONS}}', '// {{PRE_RUN_ADDITIONS}}\n' + code)
 
1454
    final += '.files.js'
 
1455
    open(final, 'w').write(src)
 
1456
    if DEBUG: save_intermediate('files')
 
1457
 
 
1458
  # Apply pre and postjs files
 
1459
  if pre_js or post_js:
 
1460
    if DEBUG: print >> sys.stderr, 'emcc: applying pre/postjses'
 
1461
    src = open(final).read()
 
1462
    final += '.pp.js'
 
1463
    open(final, 'w').write(pre_js + src + post_js)
 
1464
    if DEBUG: save_intermediate('pre-post')
 
1465
 
 
1466
  # Add bindings glue if used
 
1467
  if bind:
 
1468
    if DEBUG: print >> sys.stderr, 'emcc: adding embind glue'
 
1469
    src = open(final).read().replace('// {{PRE_RUN_ADDITIONS}}', '// {{PRE_RUN_ADDITIONS}}\n' +
 
1470
            open(shared.path_from_root('src', 'embind', 'embind.js')).read() +
 
1471
            open(shared.path_from_root('src', 'embind', 'emval.js')).read()
 
1472
          )
 
1473
    final += '.bd.js'
 
1474
    open(final, 'w').write(src)
 
1475
    if DEBUG: save_intermediate('bind')
 
1476
 
 
1477
  # Apply a source code transformation, if requested
 
1478
  if js_transform:
 
1479
    shutil.copyfile(final, final + '.tr.js')
 
1480
    final += '.tr.js'
 
1481
    posix = True if not shared.WINDOWS else False
 
1482
    if DEBUG: print >> sys.stderr, 'emcc: applying transform: %s' % js_transform
 
1483
    execute(shlex.split(js_transform, posix=posix) + [os.path.abspath(final)])
 
1484
    if DEBUG: save_intermediate('transformed')
 
1485
 
 
1486
  # It is useful to run several js optimizer passes together, to save on unneeded unparsing/reparsing
 
1487
  js_optimizer_queue = []
 
1488
  def flush_js_optimizer_queue():
 
1489
    global final, js_optimizer_queue
 
1490
    if len(js_optimizer_queue) > 0 and not(len(js_optimizer_queue) == 1 and js_optimizer_queue[0] == 'last'):
 
1491
      if DEBUG != '2':
 
1492
        if shared.Settings.ASM_JS:
 
1493
          js_optimizer_queue = ['asm'] + js_optimizer_queue
 
1494
        if DEBUG: print >> sys.stderr, 'emcc: applying js optimization passes:', js_optimizer_queue
 
1495
        final = shared.Building.js_optimizer(final, js_optimizer_queue, jcache)
 
1496
        if DEBUG: save_intermediate('js_opts')
 
1497
      else:
 
1498
        for name in js_optimizer_queue:
 
1499
          passes = [name]
 
1500
          if shared.Settings.ASM_JS:
 
1501
            passes = ['asm'] + passes
 
1502
          print >> sys.stderr, 'emcc: applying js optimization pass:', passes
 
1503
          final = shared.Building.js_optimizer(final, passes, jcache)
 
1504
          save_intermediate(name)
 
1505
      js_optimizer_queue = []
 
1506
 
 
1507
  if opt_level >= 1:
 
1508
    if DEBUG: print >> sys.stderr, 'emcc: running pre-closure post-opts'
 
1509
 
 
1510
    if DEBUG == '2':
 
1511
      # Clean up the syntax a bit
 
1512
      final = shared.Building.js_optimizer(final, [], jcache)
 
1513
      if DEBUG: save_intermediate('pretty')
 
1514
 
 
1515
    def get_eliminate():
 
1516
      if shared.Settings.ALLOW_MEMORY_GROWTH:
 
1517
        return 'eliminateMemSafe'
 
1518
      else:
 
1519
        return 'eliminate'
 
1520
 
 
1521
    js_optimizer_queue += [get_eliminate(), 'simplifyExpressionsPre']
 
1522
 
 
1523
    if shared.Settings.RELOOP and not shared.Settings.ASM_JS:
 
1524
      js_optimizer_queue += ['optimizeShiftsAggressive', get_eliminate()] # aggressive shifts optimization requires loops, it breaks on switches
 
1525
 
 
1526
  if closure:
 
1527
    flush_js_optimizer_queue()
 
1528
 
 
1529
    if DEBUG: print >> sys.stderr, 'emcc: running closure'
 
1530
    final = shared.Building.closure_compiler(final)
 
1531
    if DEBUG: save_intermediate('closure')
 
1532
 
 
1533
  if opt_level >= 1:
 
1534
    if DEBUG: print >> sys.stderr, 'emcc: running post-closure post-opts'
 
1535
    js_optimizer_queue += ['simplifyExpressionsPost']
 
1536
 
 
1537
  if not closure and shared.Settings.RELOOP and not keep_js_debug:
 
1538
    # do this if closure is not enabled (it gives similar speedups), and we do not need to keep debug info around
 
1539
    js_optimizer_queue += ['registerize']
 
1540
 
 
1541
  if minify_whitespace:
 
1542
    js_optimizer_queue += ['compress']
 
1543
 
 
1544
  js_optimizer_queue += ['last']
 
1545
 
 
1546
  flush_js_optimizer_queue()
 
1547
 
 
1548
  # Remove some trivial whitespace # TODO: do not run when compress has already been done on all parts of the code
 
1549
  src = open(final).read()
 
1550
  src = re.sub(r'\n+[ \n]*\n+', '\n', src)
 
1551
  open(final, 'w').write(src)
 
1552
 
 
1553
  if memory_init_file:
 
1554
    if shared.Settings.USE_TYPED_ARRAYS != 2:
 
1555
      if type(memory_init_file) == int: print >> sys.stderr, 'emcc: warning: memory init file requires typed arrays mode 2'
 
1556
    else:
 
1557
      memfile = target + '.mem'
 
1558
      shared.try_delete(memfile)
 
1559
      def repl(m):
 
1560
        # handle chunking of the memory initializer
 
1561
        s = re.sub('[\[\]\n\(\)\. ]', '', m.groups(0)[0])
 
1562
        s = s.replace('concat', ',')
 
1563
        if s[-1] == ',': s = s[:-1]
 
1564
        open(memfile, 'wb').write(''.join(map(lambda x: chr(int(x or '0')), s.split(','))))
 
1565
        if DEBUG:
 
1566
          # Copy into temp dir as well, so can be run there too
 
1567
          temp_memfile = os.path.join(shared.EMSCRIPTEN_TEMP_DIR, os.path.basename(memfile))
 
1568
          if os.path.abspath(memfile) != os.path.abspath(memfile):
 
1569
            shutil.copyfile(memfile, temp_memfile)
 
1570
        return 'loadMemoryInitializer("%s");' % os.path.basename(memfile)
 
1571
      src = re.sub('/\* memory initializer \*/ allocate\(([\d,\.concat\(\)\[\]\\n ]+)"i8", ALLOC_NONE, TOTAL_STACK\)', repl, src, count=1)
 
1572
      open(final + '.mem.js', 'w').write(src)
 
1573
      final += '.mem.js'
 
1574
      if DEBUG:
 
1575
        if os.path.exists(memfile):
 
1576
          save_intermediate('meminit')
 
1577
          print >> sys.stderr, 'emcc: wrote memory initialization to %s' % memfile
 
1578
        else:
 
1579
          print >> sys.stderr, 'emcc: did not see memory initialization'
 
1580
 
 
1581
  # If we were asked to also generate HTML, do that
 
1582
  if final_suffix == 'html':
 
1583
    if DEBUG: print >> sys.stderr, 'emcc: generating HTML'
 
1584
    shell = open(shell_path).read()
 
1585
    html = open(target, 'w')
 
1586
    if not Compression.on:
 
1587
      html.write(shell.replace('{{{ SCRIPT_CODE }}}', open(final).read()))
 
1588
    else:
 
1589
      # Compress the main code
 
1590
      js_target = unsuffixed(target) + '.js'
 
1591
      shutil.move(final, js_target)
 
1592
      Compression.compress(js_target)
 
1593
 
 
1594
      # Run the decompressor in a worker, and add code to
 
1595
      #   1. download the compressed file
 
1596
      #   2. decompress to a typed array
 
1597
      #   3. convert to a string of source code
 
1598
      #   4. insert a script element with that source code (more effective than eval)
 
1599
      decoding = '''
 
1600
        var decompressWorker = new Worker('decompress.js');
 
1601
        var decompressCallbacks = [];
 
1602
        var decompressions = 0;
 
1603
        Module["decompress"] = function(data, callback) {
 
1604
          var id = decompressCallbacks.length;
 
1605
          decompressCallbacks.push(callback);
 
1606
          decompressWorker.postMessage({ data: data, id: id });
 
1607
          if (Module['setStatus']) {
 
1608
            decompressions++;
 
1609
            Module['setStatus']('Decompressing...');
 
1610
          }
 
1611
        };
 
1612
        decompressWorker.onmessage = function(event) {
 
1613
          decompressCallbacks[event.data.id](event.data.data);
 
1614
          decompressCallbacks[event.data.id] = null;
 
1615
          if (Module['setStatus']) {
 
1616
            decompressions--;
 
1617
            if (decompressions == 0) {
 
1618
              Module['setStatus']('');
 
1619
            }
 
1620
          }
 
1621
        };
 
1622
        var compiledCodeXHR = new XMLHttpRequest();
 
1623
        compiledCodeXHR.open('GET', '%s', true);
 
1624
        compiledCodeXHR.responseType = 'arraybuffer';
 
1625
        compiledCodeXHR.onload = function() {
 
1626
          var arrayBuffer = compiledCodeXHR.response;
 
1627
          if (!arrayBuffer) throw('Loading compressed code failed.');
 
1628
          var byteArray = new Uint8Array(arrayBuffer);
 
1629
          Module.decompress(byteArray, function(decompressed) {
 
1630
            var source = Array.prototype.slice.apply(decompressed).map(function(x) { return String.fromCharCode(x) }).join(''); // createObjectURL instead?
 
1631
            var scriptTag = document.createElement('script');
 
1632
            scriptTag.setAttribute('type', 'text/javascript');
 
1633
            scriptTag.innerHTML = source;
 
1634
            document.body.appendChild(scriptTag);
 
1635
          });
 
1636
        };
 
1637
        compiledCodeXHR.send(null);
 
1638
''' % Compression.compressed_name(js_target)
 
1639
      html.write(shell.replace('{{{ SCRIPT_CODE }}}', decoding))
 
1640
 
 
1641
      # Add decompressor with web worker glue code
 
1642
      decompressor = open('decompress.js', 'w')
 
1643
      decompressor.write(open(Compression.decoder).read())
 
1644
      decompressor.write('''
 
1645
        onmessage = function(event) {
 
1646
          postMessage({ data: %s(event.data.data), id: event.data.id });
 
1647
        };
 
1648
''' % Compression.js_name)
 
1649
      decompressor.close()
 
1650
 
 
1651
    html.close()
 
1652
  else:
 
1653
    if split_js_file:
 
1654
        from tools.split import split_javascript_file
 
1655
        split_javascript_file(final, unsuffixed(target), split_js_file)
 
1656
    else:
 
1657
        # copy final JS to output
 
1658
        shutil.move(final, target)
 
1659
 
 
1660
  if DEBUG: print >> sys.stderr, 'emcc: total time: %.2f seconds' % (time.time() - start_time)
 
1661
 
 
1662
finally:
 
1663
  if not TEMP_DIR:
 
1664
    try:
 
1665
      shutil.rmtree(temp_dir)
 
1666
    except:
 
1667
      pass
 
1668
  else:
 
1669
    print >> sys.stderr, 'emcc saved files are in:', temp_dir
 
1670