qcor.in 13.3 KB
Newer Older
1
#!/usr/bin/env python3
2
import argparse, sys, os, subprocess, mimetypes, re
3
4

def main(argv=None):
5
    compiler = '@CLANG_EXECUTABLE@'
6
    verbose=False
7
    baseLibs = ['-rdynamic', '-Wl,-rpath,@XACC_ROOT@/lib:@CMAKE_INSTALL_PREFIX@/lib:@LLVM_INSTALL_PREFIX@/lib',
8
                            '-L', '@CMAKE_INSTALL_PREFIX@/lib','-lqcor', '-lqrt', '-lqcor-hybrid', '-lqcor-qsim', '-lqcor-jit', 
9
                             '-L', '@XACC_ROOT@/lib', '-lxacc', '-lCppMicroServices',
10
                            '-lxacc-quantum-gate',
11
                            '-lxacc-pauli', '-lpthread']
12
    baseIncludes = ['-I', '@XACC_ROOT@/include/xacc', '-I', '@CMAKE_INSTALL_PREFIX@/include/qcor', '-I', '@XACC_ROOT@/include/quantum/gate', '-I', '@XACC_ROOT@/include/eigen']
13
    defaultFlags = ['-std=c++17', '-fplugin=@CMAKE_INSTALL_PREFIX@/clang-plugins/libqcor-syntax-handler.so']
14

15
16
17
18
19
20
21
22
23
    # This flag is primarily for our testers to point to the 
    # qcor syntax handler before make install is called
    if '-internal-syntax-handler-plugin-path' in sys.argv[1:]:
        idx = sys.argv.index('-internal-syntax-handler-plugin-path')
        pth = sys.argv[idx+1]
        sys.argv.remove(pth)
        sys.argv.remove('-internal-syntax-handler-plugin-path')
        defaultFlags = ['-std=c++17', '-fplugin='+pth+'/libqcor-syntax-handler.so']

24
25
26
    # Need to know if this is compile-only
    compileOnly = '-c' in sys.argv[1:]

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    if '-h' in sys.argv[1:] or '--help' in sys.argv[1:]:
        import argparse
        parser = argparse.ArgumentParser(description="qcor: the quantum-classical C++ compiler",
                                     formatter_class=argparse.RawTextHelpFormatter,
                                     fromfile_prefix_chars='@')
        parser.add_argument('-v', metavar='',
                        help='turn on qcor verbose mode - prints actual clang calls plus extra info while compiling.')
        parser.add_argument('-qpu', metavar=('name[:backend]'), help='specify quantum backend name. this corresponds to the name of an xacc accelerator (plus optional backend name).\nExamples include qcs:Aspen-4-2Q-H, ibm:ibmq_valencia, tnqvm, etc.')
        parser.add_argument('-shots', metavar=('n_shots'), nargs=1,help='provide the number of shots to execute on shot-enabled backend.')
        parser.add_argument('-c', metavar=('file.cpp'), help='specify compile-only, no library linking.\n$ qcor -c src.cpp [outputs src.o for future linking]\n')
        parser.add_argument('-o', metavar=('object.o'), help='provide the name of the object file (if compile only) or executable (if compile and link or just link).\n$ qcor -o out.o -c src.cpp\n$ qcor -o out.exe src.cpp\n')
        parser.add_argument('file', help='you must specify the c++ source file name to compile.')
        parser.add_argument('-I',action='append',nargs=1, metavar=('header_file.hpp'),help='specify additional headers to add to the include search path.')
        parser.add_argument('-L',action='append',nargs=1,metavar=('/path/to/libs'),help='specifiy additional linker search paths.')
        parser.add_argument('-l',action='append',nargs=1,metavar=('lib_name'),help='specifiy additional libraries to link.')
Mccaskey, Alex's avatar
Mccaskey, Alex committed
42
43
44
        parser.add_argument('-set-credentials', nargs=1, help='set api key and other credential information for remote qpu.\nMust provide at least -key KEY arguments. For IBM also specify -hub HUB -group GROUP -project PROJECT.')
        parser.add_argument('-print-credentials', nargs=1, help='print remote api credentials for given qpu name.')
        parser.add_argument('-update-credentials', nargs=1, help='set a specific credential for remote qpu access. Example\nqcor -update-credentials ibm -project MYOTHERPROJECT.')
45
46
47
        args = parser.parse_args(sys.argv)


48
    if '--verbose' in sys.argv[1:]:
49
        verbose=True
50
51
52
53
        sys.argv.remove('--verbose')
    if '-v' in sys.argv[1:]:
        verbose=True
        sys.argv.remove('-v')
54

Mccaskey, Alex's avatar
Mccaskey, Alex committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
    if '-set-credentials' in sys.argv[1:]:
        idx = sys.argv.index('-set-credentials')
        accName = sys.argv[idx+1]
        if accName not in ['ibm', 'qcs', 'rigetti', 'dwave']:
            print('invalid remote qpu name: ', accName)
            exit(1)

        try:
            kidx = sys.argv.index('-key')
        except:
            print('-key not found in command line args. must provide key if -set-credentials is used.')
            exit(1)
        
        if accName == 'ibm':
            try:
                hidx = sys.argv.index('-hub')
                gidx = sys.argv.index('-group')
                pidx = sys.argv.index('-project')
            except:
                print('-hub, -project, or -group not found in command line args. must provide them if setting credentials for ibm.')
                exit(1)
            
            key = sys.argv[kidx+1]
            hub = sys.argv[hidx+1]
            group = sys.argv[gidx+1]
            project = sys.argv[pidx+1]
            s = 'key: {}\nhub: {}\ngroup: {}\nproject: {}\n'.format(key,hub,group,project)
            f = open(os.getenv('HOME')+'/.ibm_config', 'w')
            f.write(s)
            f.close()
            print('Writing to $HOME/.ibm_config \n\n')
            print(s)
            exit(0)

    if '-print-credentials' in sys.argv[1:]:
        idx = sys.argv.index('-print-credentials')
        try:
            accName = sys.argv[idx+1]
        except:
            print('must provide qpu name after -print-credentials.')
            exit(1)
        f = open(os.getenv('HOME')+'/.{}_config'.format(accName), 'r')
        print(f.read())
        f.close()
        exit(0)

    if '-update-credentials' in sys.argv[1:]:
        idx = sys.argv.index('-update-credentials')
        try:
            accName = sys.argv[idx+1]
        except:
            print('must provide qpu name after -update-credentials.')
            exit(1)

        f = open(os.getenv('HOME')+'/.{}_config'.format(accName), 'r')
        lines = f.readlines()
        f.close()

        if '-key' in sys.argv[1:]:
            kidx = sys.argv.index('-key')
            lines[0] = 'key: {}\n'.format(sys.argv[kidx+1])

        if '-hub' in sys.argv[1:]:
            kidx = sys.argv.index('-hub')
            lines[1] = 'hub: {}\n'.format(sys.argv[kidx+1])

        if '-group' in sys.argv[1:]:
            kidx = sys.argv.index('-group')
            lines[2] = 'group: {}\n'.format(sys.argv[kidx+1])

        if '-project' in sys.argv[1:]:
            kidx = sys.argv.index('-project')
            lines[3] = 'project: {}\n'.format(sys.argv[kidx+1])
        
        f = open(os.getenv('HOME')+'/.{}_config'.format(accName), 'w')
        f.writelines(lines)
        f.close()
        print('Credential after update:')
        print(''.join([l for l in lines]))
        exit(0)


137
138
    sHandlerArgs = []
    # Get the QPU Backend
139
    accName = ''
140
141
    if '-qpu' in sys.argv[1:]:
        accidx = sys.argv.index('-qpu')
142
143
        accName = sys.argv[accidx+1]
        sys.argv.remove(accName)
144
        sys.argv.remove('-qpu')
145
        sys.argv += ['-D__internal__qcor__compile__backend=\"'+accName+'\"']
146
        sHandlerArgs = ['-Xclang', '-plugin-arg-qcor-args', '-Xclang', '-qpu', '-Xclang', '-plugin-arg-qcor-args', '-Xclang', accName]
147
148
149
150
151
    else:
        accName = 'qpp'
        sys.argv += ['-D__internal__qcor__compile__backend=\"'+accName+'\"']
        sHandlerArgs = ['-Xclang', '-plugin-arg-qcor-args', '-Xclang', '-qpu', '-Xclang', '-plugin-arg-qcor-args', '-Xclang', accName]
        
152
153
154
155
156
157
158
    # Get the shots if necessary
    shots = 0
    if '-shots' in sys.argv[1:]:
        sidx = sys.argv.index('-shots')
        shots = sys.argv[sidx+1]
        sys.argv.remove(shots)
        sys.argv.remove('-shots')
159
        sys.argv += ['-D__internal__qcor__compile__shots=\"'+str(shots)+'\"']
160
        sHandlerArgs += ['-Xclang', '-plugin-arg-qcor-args', '-Xclang', '-shots', '-Xclang', '-plugin-arg-qcor-args', '-Xclang', shots]
161

162
163
    if verbose:
        sHandlerArgs += ['-Xclang', '-plugin-arg-qcor-args', '-Xclang', '-qcor-verbose']
164

165
166
167
168
    if '-print-qir' in sys.argv[1:]:
        sys.argv.remove('-print-qir')
        sHandlerArgs += ['-Xclang', '-load', '-Xclang', '@CMAKE_INSTALL_PREFIX@/qopt-plugins/libprint_llvm_qir.so']

169
170
171
172
173
174
175
176
177
    # Optimization level for flattened (runtime) kernel
    # Default: 0 (no optimization)
    qrtOptLevel = 0
    if '-opt' in sys.argv[1:]:
        sidx = sys.argv.index('-opt')
        qrtOptLevel = sys.argv[sidx+1]
        sys.argv.remove(qrtOptLevel)
        sys.argv.remove('-opt')
        sys.argv += ['-D__internal__qcor__compile__opt__level='+qrtOptLevel]
178

179
180
    # Enable runtime kernel optimization stats print-out:
    # i.e. passes that are executed and their info (walltime, gate count reduction, etc.)
181
182
    if '-print-opt-stats' in sys.argv[1:]:
        sys.argv.remove('-print-opt-stats')
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
        sys.argv += ['-D__internal__qcor__compile__opt__print__stats']

    # Specify optimization passes to run *in addition* to the default passes at an optimization level.
    # Syntax: -opt-pass pass1[,pass2] 
    # i.e. a comma-separated list of passes.
    # Rationale:
    # - This option can be used to run an independent pass by using level 0 (no optimization)
    # and then specify which pass to be executed.
    # - It can also be used to add passes to pre-defined list of passes for an optimization level.
    # e.g., those XACC passes that are contributed externally. 
    if '-opt-pass' in sys.argv[1:]:
        sidx = sys.argv.index('-opt-pass')
        qrtOptPasses = sys.argv[sidx+1]
        sys.argv.remove(qrtOptPasses)
        sys.argv.remove('-opt-pass')
        sys.argv += ['-D__internal__qcor__compile__opt__passes=\"'+qrtOptPasses+'\"']
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
    
    # Parse qubit mapping:
    if '-qubit-map' in sys.argv[1:]:
        sidx = sys.argv.index('-qubit-map')
        qubitMap = sys.argv[sidx+1]
        sys.argv.remove(qubitMap)
        sys.argv.remove('-qubit-map')
        sys.argv += ['-D__internal__qcor__compile__qubit__map=\"'+qubitMap+'\"']
    
    # Parse placement name
    if '-placement' in sys.argv[1:]:
        sidx = sys.argv.index('-placement')
        placementName = sys.argv[sidx+1]
        sys.argv.remove(placementName)
        sys.argv.remove('-placement')
        sys.argv += ['-D__internal__qcor__compile__placement__name=\"'+placementName+'\"']
    
216
217
218
219
220
221
    if '-em' in sys.argv[1:]:
        sidx = sys.argv.index('-em')
        decorator_name = sys.argv[sidx+1]
        sys.argv.remove(decorator_name)
        sys.argv.remove('-em')
        sys.argv += ['-D__internal__qcor__compile__decorator__list=\"'+decorator_name+'\"']
222
223
224
225
226
227
228
229
    
    # Define the QRT, e.g. "nisq" or "ftqc"
    if '-qrt' in sys.argv[1:]:
        sidx = sys.argv.index('-qrt')
        qrtName = sys.argv[sidx+1]
        sys.argv.remove(qrtName)
        sys.argv.remove('-qrt')
        sys.argv += ['-D__internal__qcor__compile__qrt__mode=\"'+qrtName+'\"']   
230
231
        if qrtName == 'ftqc': 
            sys.argv += ['-D_QCOR_FTQC_RUNTIME']
232
233
234
235
236
    
    # if not empty
    if '@QCOR_APPEND_PLUGIN_PATH@':
        sys.argv += ['-D__internal__qcor__compile__plugin__path=\"@QCOR_APPEND_PLUGIN_PATH@\"']
    
237
    # Get the filename we are compiling or the object file
238
239
240
    filename = ''
    fileType = ''
    for arg in sys.argv[1:]:
241
        if os.path.isfile(arg) and mimetypes.guess_type(arg)[0] is not None:
242
243
            filename = arg
            fileType = mimetypes.guess_type(filename)[0]
244
245
246
            if fileType == 'text/x-c++src':
                break
                
247
    # If it is a C++ file
248
249
250
    if fileType == 'text/x-c++src':
        fileIdx = sys.argv[1:].index(filename)
        tmpFileName = os.path.basename(filename)
251

252
        # Move tmpFileName to end of list
253
254
        sys.argv.remove(filename)
        sys.argv.append(filename)
255

256
257
258
259
        sys.argv[0] = compiler
        commands = [compiler] + defaultFlags + sHandlerArgs + baseIncludes
        if compileOnly:
            commands += sys.argv[1:]
260
        else:
261
262
            commands += baseLibs + sys.argv[1:]

263

264
        if verbose:
265
266
            print('[qcor-exec]: ', ' '.join([c for c in commands]))

267
268
269
270
271
272
        try:
            result = subprocess.run(commands, check=True)
        except subprocess.CalledProcessError as e:
            print(e.output)
            print(e.returncode)
            return e.returncode
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
    elif fileType == '' and filename == '':
        if '-x' in sys.argv[1:] and 'c++' in sys.argv[1:]:
            sys.argv[0] = compiler
            commands = [compiler] + defaultFlags + sHandlerArgs + baseIncludes 
            if compileOnly:
                commands += sys.argv[1:]
            else:
                commands += baseLibs + sys.argv[1:]


            if verbose:
                print('[qcor-exec]: ', ' '.join([c for c in commands]))

            try:
                result = subprocess.run(commands, check=True)
            except subprocess.CalledProcessError as e:
                print(e.output)
                print(e.returncode)
                return e.returncode
        else:
            print('invalid command line arguments for qcor')
            exit(1)
295
    else:
296
297
        # This is a .o file, so execute the link phase
        commands = [compiler] + baseLibs + sys.argv[1:]
298
        if verbose:
299
            print('[qcor-exec]: ', ' '.join([c for c in commands]))
300
        try:
301
            result = subprocess.run(commands, check=True)
302
303
304
305
        except subprocess.CalledProcessError as e:
            print(e.output)
            print(e.returncode)
            return e.returncode
306

307
    return 0
308
309
310

if __name__ == "__main__":
    sys.exit(main())