pax_global_header00006660000000000000000000000064125053471370014521gustar00rootroot0000000000000052 comment=83bde5e85c0fb3a7c9c1c043866a5f8151c40298 pygccjit-0.4/000077500000000000000000000000001250534713700132005ustar00rootroot00000000000000pygccjit-0.4/.gitignore000066400000000000000000000000671250534713700151730ustar00rootroot00000000000000*~ gccjit.c build dist doc/_build */__pycache__/* *.pycpygccjit-0.4/COPYING000066400000000000000000001045131250534713700142370ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . pygccjit-0.4/MANIFEST.in000066400000000000000000000001741250534713700147400ustar00rootroot00000000000000include COPYING recursive-include gccjit *.py *.pyx *.pxd recursive-include tests *.py recursive-include examples *.py *.bf pygccjit-0.4/README.rst000066400000000000000000000006211250534713700146660ustar00rootroot00000000000000Python bindings for libgccjit.so (using Cython) Tested with Python 2.7 and 3.2 GPLv3 or later. JIT-compiled functions are wrapped up as `ctypes` callables. Prebuilt HTML documentation can be seen at http://pygccjit.readthedocs.org/en/latest/index.html Caveats ^^^^^^^ * Most of the API is wrapped, but not all. * Currently the ctypes hack forces all functions to be of type: int foo(int); pygccjit-0.4/doc/000077500000000000000000000000001250534713700137455ustar00rootroot00000000000000pygccjit-0.4/doc/Makefile000066400000000000000000000126741250534713700154170ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/gccjit.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/gccjit.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/gccjit" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/gccjit" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." pygccjit-0.4/doc/conf.py000066400000000000000000000170511250534713700152500ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # gccjit documentation build configuration file, created by # sphinx-quickstart on Wed May 7 17:57:19 2014. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'gccjit' copyright = u'2014-2015, David Malcolm' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.4' # The full version, including alpha/beta/rc tags. release = '0.4' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'gccjitdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'gccjit.tex', u'gccjit Documentation', u'David Malcolm', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'gccjit', u'gccjit Documentation', [u'David Malcolm'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'gccjit', u'gccjit Documentation', u'David Malcolm', 'gccjit', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' pygccjit-0.4/doc/index.rst000066400000000000000000000024441250534713700156120ustar00rootroot00000000000000.. Copyright 2014 David Malcolm Copyright 2014 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Python bindings for libgccjit ============================= This document describes the `Python bindings `_ to `libgccjit `_. The bindings support both CPython 2 and CPython 3 (using Cython). Note that both libgccjit and the bindings are of "Alpha" quality; the APIs are not yet set in stone, and they shouldn't be used in production yet. Contents: .. toctree:: :maxdepth: 2 tutorial/index.rst topics/index.rst Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` pygccjit-0.4/doc/sum-of-squares.png000066400000000000000000000544671250534713700173620ustar00rootroot00000000000000PNG  IHDRhkq{bKGD IDATxyXTe K leb h["boe`(m&aV$  "ʦ3L0p\\̙sync)0'hSRcLIqf1% 1ƔBZ@=`JLķ)7H%K`B(""kA Ӆ)'f&f1% 1Ɣ'hSRcLIqf1% 1Ɣ'hSRYRRRv4%!!g: =~UCL0DPk Z`Æ pssÀ0zhܺu Dѭ[7cԩq-4,ZgΜ +++b޽;[hkkC$aӦM@SS?ԩS077ٳg{_k)5(׺RΝKqqqedbbBO>%MJhȐ!%"x"iiiڴi@111cV[O]/w0XUHAAPXXXg-yD___DFFbРASN*/-֭[V?yts]uV,XY1ƞB&N_8tV^?nnn'0RSSqM:O+V@AAѫWj? !?=e}B455ɓ'~òeːCA__۶mCRR`ͅRSS^^^(..ƍX~.epƍZ}cԨQpww^xxZnSA\PɉD"bƌBҠ2Kr :t t8Jȑ#9s&b 3hwƤI893@|5ٙ3g}!1R 5%!osBĘJ3hd=zݻw1gЌ18A3ƘcJ zWjݻw_B+Z?#"|>}:pB4?Ɣ_$TAfk)gΜݻf fO믿lc߾}q###}Q1!,L^h|ЭdaaAn4tZˣё(11iƍ۰auA!Ƀ8XHR̝;nnnԩSڪQg}EϞ=eC&BEEFUm#G{mV,)N*D"ȑ#puuŰa]/++ wiU9R}qj쟚X1c`Ϟ=>.\077NH |8cmЧahGVVV%ꫯ-UrrrjYf*++Tڤ:5]~]Vo߾SXXHhРADD`߿ $`*,_˗/oV?000FD"k׮w֬Yz\}Ο?}}}YUUrN{hZqˠZO;;;ӧOڵ.:>ۡ:/U KKzjg HMME.]dT:thXk?A'''!==]qWN ӦMòep)KuN> ̞=[11&$P1 ]g _ %g6le5S VSXYYU{ ),,ƍ=,)ڼy"""p=|7.//k׮ݻ[(2Z'hd_d*Gaaa-[TX[ 5˿/lذ۶mSh8pd㥗^vcmfǚgϞXbBЀBd3hSRcLIqf1% \7| \KBLB%IZT!OCLqC֞qV1pqq<<< ]vA$V͛-+,,ocȐ!8z(v튁Ν; + 66X!c$)%___ٲ˗SQQyyyk$)>>]ܻw/͙3VZEӦMݻw!"rww'u^l_$dJNkU}5 d }>f1% 1Ɣ'h$"c4SI%%%=?cBꕒ"tMKݻJBXpfuJHHhikkD0k2͎RYdՍ!""226a=!776l>}`͚5022300EsNxv)**Ž;DDD`ԩXbbqرc Ehh(nܸ{ᰳ_|֯_lD5LMMu7맰vkJHHlCrmØ3h#H˗/㫯oOOO̴ R=ϕg@}ٮxV+ȉ矛nMg'Nk}XX1u֑5ݻ?N/^;wƤ ёuVmw$533#mmmjv5#F֭[i4f*((]KKKPT׮] ҕ+WHMM?" '=== +cf$ӖcL|b,\o`gg.]СCС"""0{lbٲeXb.ݸq#?dffk׮aڴiç~ёm۶!)) Cjj* }S`ggz vvvp{H$HMMERR>V4kI[̔% TT>}K,AfffK&4qMB&HBvZdgg˖bcȐ!ٳ)!P!.\'###rJ8p@dm A֭[:Dqbfm 'hbjj𢪌1c))NЌ18A3ƘcJ/\Z\vMXO*ݻ⭬~ݻw=X]8A3|"1`J'h*EBSRcLIqf1% 1Ɣ'hSRcLIqf1% 1Ɣ'hSRcLIqf1% 1Ɣ'hSRcLIqf1% 1Ɣ'hSRcLIqf1% 1Ɣ'hSRcLIqf1%.tbZDRvzzzPWW&tttZ2DFpfDǏ#99x Ґtdeeӧx)rss2oddс&444ЩS't ;wFN`bbRU6NЬݓJHHH@ll,bccq$$$ %%>puuuѵkW=z􀡡! d500v~Vo@ii)@Dx)(++CVV233cDGG###YYY(,,֞X,FNЭ[7XXX @aii 333<ҩ8Av111z*^k׮!66D-zQF޽;tRgUŲ䝑LdeeÇxG~hhhJබޫMDD$t3GQXDXX_:u+O>ܡCOS;v 666Xp!\]]abba29ݻW+i  ^{ B8A3A᧟~@ݻSLm0b8;;wށ&ggj8z( ua̘1D_ii)/>}O˗QZZ GFǎUipf \z{{cؾ};<==ѣGlذ'N܆ҥKGXX_0`ƏI&o߾G),NLeee066F^^sDر#rss///[@8y$BBBCXZZbĉ4iF.8#DL1cl!D\=III!kmFFFx7c$''ի7o.\t/FDDy%A3:u Fj6X|9>3>n'߿Ν;ѣΝ RZ 'h&T 3337j;HH8ݻcڵk8t:L8;;c…4i\%<#1{F}ա?s;/oÇ/@SSo6,--~zddd4ԕ+Wꫯʵ:v숓'O_lX[]vaܹsd ZpfFBBBhhhW^8y$uJ/޽YfO?mܜ9sاŋY"&&v1o<^qf={6X,ƴi..b̜9o޽{q9888믿XSFЧO: \z5>^xAX[#66/^z%\rE )wySb"9֭[ǏsfС||| ccc899a:EBRRR`ii "9)SSAR/_BU'NLi ++ aaa1b0S?JЋ/F\\Pv,''"Bډ2ܸq%%%x뭷paCVD4h,,,1ZMyy9ÑXz(nc7oq9 1dqZXX`„ HMM8g8A3;q1~x 'hԹsg>>GNLL?,;S ]JJ Y~*ϜO8u$cҥKvZdgg\G5<Ј1T222"4bںu+^ƌCTXXHԭ[jЋ/&'''x%]$"ڵ+Rr 1TTTDᤧG(>>IGGf0ڗƌAWΦ;W E1h333\v ӦMC\\>S:t耈̞=XlVXcccC]]۶mCRR`ͅll///Nz-… ׯ{=$&&B"^lmk)FFFOe˖K^1ڽ#G`̙VVVfO2Xu-QRR9A3X3|FPPc`bbI&aϞ= o4c5ܹsq$''+]NЌ1LQ˖ IDATo> 1ƚICCcǎEppB?y}kSUS} $S޽ZdaaAK.ѪUVTT9::R~~B{СC^[VCџ}kSi֬Y NJJ5s]R)Ν 777tԩJR`ذa:t(&={l!b„ h 1$ [[[oƐՓ|2=_~Νᅬ/wezzz"22 TPP???ܿn݂!|}}k}U?+2l޼kR{ݻw| 쐒lٲ}fhhXg '8<K.FBB\Odee*hGVVVԵ.f"TVV&W5_Mݺu#Ǐ?_T*W=Ī_NhӦMGbX6\m6@K,PƜ"ɻ]}'O[['33IKKٳt!%uuu#" PO*ܹse9;; ֹDDԱcGT'O'O^Mؐ5=+)g``@֑;{N/^}6m'O{88=J"***ƠRi%nUP׮]/lWCѣGƍWo{cƌ!H$@ ""Nc}wTmO.dՋ}]"z>V @:s|}}I"Ptt4^MܹvMD ([[[zuT~YYYe?꣨}q@yyynHc37$--?i7==A~j>!Vehh(>C ɪzukjvMmK*˚ijj֙4i֭[ϫ гj &Իݎ;%K`(,,~SÌ3b(--mR yޓϳCU)q:t4 *jjjH$M7bbb`eeq_F```Lk֬={xzzbӦMXv-iTT}GyjN]vPKא$$$yCǴip 5 ׮]СCo߾&]k9h{Txܣ_'h33fU#ptt#Gb…ݻ7o߮b*Ϧ]G" &&/_W_}~ PSSFiFQm9U>|1988_|E山. ! k֬ir{A$aܸqOꊡIS)q(F14r ://PndJKK FC]yƍԔ:wL~~~ zUEEE񩷽u֑5ݻ?N/^;wڒNikkSTTTKaa! KKKے?[[[PΎh͚5diiIXZZ*g\`}*b\={ZK,ˊ?$ZaD엏9;;ҥKÃ֯_O%%%vȨZAJyo(;;[YsNȠ ڴi=}T;bpU4yd222"SSSzweɷ@VVVn:hɔGDߓۗΝ;G۷o'###rqq}+ޓŋ UU[:ꢨf͚Zw4G=Icǎ>Ul &{8p|}}eH$B?#uԩClu_牍_~"j-})*A;4~fSI)tZZKr%ݻs<@ٵ~Ol!'77ON׮]k=~~D]V>hŊn gWl,YDS)ʣGヰ0׻ޅ DH\R%g(RmeKVOTmy5_vvv-C[8233^{Mq R||<}]2ڴi\ciiizAFFF4tPz7iΝ.8u!;ruu/ VϯhLgAAA$)##CAQ߫#3f(c)#G`̙rݺX777 K)8c-1qD 1ƚ)$$9sBcʹcTh,cm\TTNx ) 555HR`rJxxxѱ5Pz쉂bcJM*VK6;4455 1eg!""/_n pfJDKKK6cرc?_|1h4PZZrCaH̞=~!̙*}rfJCOOD[PƄ 0|pl޼͔D"޽+t(cȑ֭~'Y ) 555իB &&NNNիΝ;==V4S*8{a05 }AHHtuu[=NLիt !66cǎ-#HR133رcBکP <}[}X*NLhhh_ѣG3R8q",YǏ v\TaJgFRR+T0V"رcػw/,X tH ))SsػwСv >>:4͔&>clٲYYYBT?2DDDE萪͔҇~---_^P z1Ǝw}˖-իWagg'tXpfJIGG7nĶmp a*$<<*n޼P|gPWWqZ` 777 k233ggg7oĘ1cADؿ?RRR k$ [ gΜc C{.NLYZZb8p|||1wѣl2̛7QQQ-R}pfJoĉزe ֬Y۷ k0o<888@,#66[lС5r3V_>@nn.V\)tHL a֭񁖖v77V"T8A6cʕ000ŋ={CBŔD"ooo>5[q6?Ξ=ӧOϟ:$&ɍb񈋋G}3 ANNN=F OOOke8p &MkkkDGGc׮]ҥС) 'h&u ك~{  "W_}'NDqMO:<ڴyΝ;pssúu`iiu!;;[Иo &M[[[ѣӧNЬ300ၝ;w{={6~w"kt[={ k׮Tʹ34SOiiix7ѥK_~Affa29DEEa…\]]}:V#"":`ƌ#G(͔ x1rH9 PJmYii)~gl߾ѣ/^ wwwAN 4S-JMMř3gdХKOիЩSU;wb߾}¸qcرh]Ǐq ܼyQQQy&!H<2B=`nnΝ;]t :w A__>&|>|wƵk`iiM$!k`ffqɖ 11+::HOO /:HL,WA]]YkkkCKKr:Ӄ!D"```POfFFFb@~~>F~ SNUKϠ """0|p7Ν;ARdW^^LdddEQQSٺyyyWTT ??}yWJaa!j-GEErss!J"cU077 ajjݻ={ui||<O?!&&666?>͛ssFpfHMMRib<|fffYSV{=~!99O<x1`޽{p9rׯ_GΝ1uT̛7NNNDBr fԨQ8{l̷&555Ye&"$$$^qqqDtt4`ll>}@KK ѵkWL6 ӧOǐ!C1h&s̙30w իCpttcoƷ~>}bR&&&3f ƍɹ &//u&222ʑDGG#44!!!|20yd̘1F­[p ϟZNLPSNEHH***-WWWĉ믿 T\\3g 88ХK?'O ^x:޽{?"++ o/^QĘ=J"T{D"_݊?HMM444hGot{%%%ta۷/D"z뭷-j3h&tܹ4Ȩ_xŸtQQQՅ3Əq)"¯uXp!6W+pfsuuÇeDkhh`ؿ0DW"<<tJJJ`oo?ÇoGR)9KB,-W[ ĉ;vle...Ez|YK.5jF gggt֭U~ÇcŊذa?2_'h&8D$:u“'O %%%p.\/"""ر,!=Ziصk/^c" :::B8A3=.m&tHmJii)\st󡧧!C^ðaꫯ*gΜo>}ĉ:$qfJҥKprrHȒspסCbذaxЯ_?n޼#GbРAT-4S DnݺA$ÇeSeeexW`llng4)kVZ]bʕBj455k.:u B#NЌ) 띔HU 4&MС}Xf 4SL:Ax{{_~?1dܾ}nBBB>#b͘vN<Ǐ J*//ݻw[nCzz:jjjH$0a'hƘ0߿\%ppp@ii)աjT+ˤ f1hƔԣG?㣏>:Vս{wtb())nΝ;P['hGPX38p9sС*uuuܹ_|VH8UH\\1k,8p@pX3:t3glE FѣG;&Q>N*7o: 111iwgUmٲ޳hT'h϶TQPPt!C` Z?Q.NЌ)p3-ذaC [9 ͅ<==tR`ҥɑk"BDD-[+++$''c044q9Y;N9Ξ=+ĮbDDD4j;Uebb//Z:v쨲3U*YFockkKDDyyydccCk׮ɓ'dccC=z箓IEhtY:t꒺:QPPikkӱcǚ,00?ЃZ9*T\\Lfff$Ç V䚛WZE(55:? !"!TZZ*[חл+[V^^ިxۣ-[sέr;x,AkhhЇ~(tH8TŋzzzՖ6 RbåjMI&nݺ%[5WLL #tJe׿555Q1hWT-755ȵN}v vrgM..5H$7|D NL5TV[pvvkdee.[`'11BtF7x-vOr< +VѣGwa޼y033l۶ NNNPVVuH$aaaҥK!!!5k~gٗO" --M4Gbb"OD< D CQ(---̚5! ZV1pqq<<< ]vA$͛-+,,ocȐ!8z(v튁Ν; + 66VaqgeeΝ; ^"ȑ#puuMڐǏѣ "hhhѣ ĨQ ѣ`gԩSrJ̙3Ç͛7>>deePicFFF$… g266&teJNNR X̌)**W.X# >\Vn1b0g :3grrr#xyyxg`XXN8!ZBVVn*3qkރ8A16&QTP28%Y MRGT)ADnNb:HjixT1ВH\.|fe<˞}[;TQQp@^^nݪ T#`ʕZ[P[7o ,_*BCC!ɰ~z ,, m۶ Zk׮P6%%8v8p !???ܿެFjj*},Z~~~h٭[VЮ]PTT"7@=h3FeZۃ~!sεA3SFkO"$$QQQZ}իW:)njb7|c퐕zƍCZZǕ24 7[RxvprrIs^-&)forfLǏ] AI>?66... 1;v,x/ 1d.v)L$ܠcr~q6@kwbڨxҿaϞ=;w.&Nخuѣ.vL$ܠ >rذa|}}ZkΝ;cڵ=o4y{G䄼<]JI" 5z˗QYY7|SGOpBddd4TZی.\~Mx !!!xwqʕfd/"'''@FFz-QM{ڏ[ɫ?///,^VVVKWXXo#Gdﴅ$}7hi.:1O'ӧ?? [[[Ĵ"f&N#4 'K$OAY'2sͥݻڸq#=x˵ӅT-\hmIuh2YRUUʜOTLRy{{ӭ[3=ۑ97hӴA˧~Z:::6H&SSS᱖^_^^3f4ښ+4;wtX4 T'_PV LUlʈٞHqurf̘(D1/om)((PzNU_---XZZ T.rϞ=-r$0sLhvcKXjQQQLΦWb;VttƝ;w$V\\333OߍuCtT!L-i/شYr&UfϞ#GbٲeHIIIoooKkރf-FV`޽QZZպT)jzO>֭DYM120;j&*ܠ b.rf_m\x13jU|x~` 7G) UU6z\.fˬ_GlllC,FFFUy6UWWhly 4aaa+Wb'C ޽{DYY̙3J(!l̓Nz@T u6hp8 :ܹsΜ9bTZZJck֬J!LF֭k:uDYYYcgϞ%ooo@&&&eCMNъ+4Z&' iƍחӅ?A2飏>‰H{MSLnݺ3eddФIhM֭SHeP)44VXAj=#djjJIIIti266j,**m۶ |WTXXHDێT}ιAK& ZʦON|3sLx z֬Y4oni.F1ݑL=ܠA';$@ гgO`z' Jm*B vիWc˖-JoHjkk _ut4S2гgԭ[PSSQFiܜ9stTӶc͚QdkPֲ7nK.´3g7!"DDD -- i4 6m1jjjpM 6 dBƜ.];w@˩RYY;v͛@jj*<==N:8%?$$$ ##K,AJJ ݻwcg9 CII0{ӻu#)) &Mإ0}k LdI[nN:QQQm߾ЪUӧ4h y1 4 @ކ?.Tmm-M:,X@rO[RRVV\.7x-Z$DCeee 3)?%)K=TŤiڠMFFFFT]]MDM0>3@=j޽{ mؠ]-[}XMM ٳJJJ@7nh4"rTFJM^|qqq!!! #3.]P?;ZCnnn˗/+˝={зo_1,^2Lq[˨_l}/_FVV a=xÆ XXX(ݻ*Tvv6ݺuSkď?u։]  A\7oʕ+op1 =SBnn.4fa &54vXYq G~Ih@6n܈u }Kr04!pڵ2:>Ih@.^@UU;駟"..N$A?۷(xڀaƍؿ?"##1tPؿ?'rm@/ƚ5k0c a ڀX[[k=GYY,XÇcӦMb$4c"'t4c"z9ϣb$4c"Zp!N8SNi\`deegoQ~233?s琙 SSSf͂_ c: \d(..% +++d2XZZ (++Cii)ʐХKkpss;^ut]X3ܠY$qu͛(--~`jj C a_4cIߨc 1$4cITg0ZIENDB`pygccjit-0.4/doc/topics/000077500000000000000000000000001250534713700152465ustar00rootroot00000000000000pygccjit-0.4/doc/topics/compilation.rst000066400000000000000000000105471250534713700203250ustar00rootroot00000000000000.. Copyright 2014-2015 David Malcolm Copyright 2014-2015 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Compiling a context =================== Once populated, a :py:class:`gccjit.Context` can be compiled to machine code, either in-memory via :py:meth:`gccjit.Context.compile` or to disk via :py:meth:`gccjit.Context.compile_to_file`. You can compile a context multiple times (using either form of compilation), although any errors that occur on the context will prevent any future compilation of that context. In-memory compilation ********************* .. py:method:: gccjit.Context.compile(self) :rtype: :py:class:`gccjit.Result` This calls into GCC and builds the code, returning a :py:class:`gccjit.Result`. .. py:class:: gccjit.Result A :py:class:`gccjit.Result` encapsulates the result of compiling a :py:class:`gccjit.Context` in-memory, and the lifetimes of any machine code functions or globals that are within the result. .. py:method:: get_code(funcname) Locate the given function within the built machine code. Functions are looked up by name. For this to succeed, a function with a name matching `funcname` must have been created on `result`'s context (or a parent context) via a call to :py:meth:`gccjit.Context.new_function` with `kind` :py:data:`gccjit.FunctionKind.EXPORTED`. .. error-handling? The returned value is an `int`, actually a pointer to the machine code within the address space of the process. This will need to be wrapped up with `ctypes` to be callable:: import ctypes # "[int] -> int" functype: int_int_func_type = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) code = int_int_func_type(jit_result.get_code(b"square")) assert code(5) == 25 The code has the same lifetime as the :py:class:`gccjit.Result` instance; the pointer becomes invalid when the result instance is cleaned up. .. TODO: gcc_jit_result_get_global Ahead-of-time compilation ************************* Although libgccjit is primarily aimed at just-in-time compilation, it can also be used for implementing more traditional ahead-of-time compilers, via the :py:meth:`gccjit.Context.compile_to_file` API entrypoint. .. py:method:: gccjit.Context.compile_to_file(self, kind, path) Compile the context to a file of the given kind:: ctxt.compile_to_file(gccjit.OutputKind.EXECUTABLE, 'a.out') :py:meth:`gccjit.Context.compile_to_file` ignores the suffix of ``path``, and insteads uses `kind` to decide what to do. .. note:: This is different from the ``gcc`` program, which does make use of the suffix of the output file when determining what to do. The available kinds of output are: ============================================ ============== Output kind Typical suffix ============================================ ============== :py:data:`gccjit.OutputKind.ASSEMBLER` .s :py:data:`gccjit.OutputKind.OBJECT_FILE` .o :py:data:`gccjit.OutputKind.DYNAMIC_LIBRARY` .so or .dll :py:data:`gccjit.OutputKind.EXECUTABLE` None, or .exe ============================================ ============== .. py:class:: gccjit.OutputKind .. py:data:: ASSEMBLER Compile the context to an assembler file. .. py:data:: OBJECT_FILE Compile the context to an object file. .. py:data:: DYNAMIC_LIBRARY Compile the context to a dynamic library. There is currently no support for specifying other libraries to link against. .. py:data:: EXECUTABLE Compile the context to an executable. There is currently no support for specifying libraries to link against. pygccjit-0.4/doc/topics/contexts.rst000066400000000000000000000420741250534713700176560ustar00rootroot00000000000000.. Copyright 2014-2015 David Malcolm Copyright 2014-2015 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Compilation contexts ==================== .. py:class:: gccjit.Context The top-level of the API is the `gccjit.Context` class. A `gccjit.Context` instance encapsulates the state of a compilation. You can set up options on it, and add types, functions and code. Invoking :py:meth:`gccjit.Context.compile` on it gives you a :py:class:`gccjit.Result`. .. py:method:: dump_to_file(path, update_locations) .. py:method:: get_first_error() .. py:method:: new_location(filename, line, column) Make a :py:class:`gccjit.Location` representing a source location, for use by the debugger:: loc = ctxt.new_location('web.js', 5, 0) .. note:: You need to enable :py:data:`gccjit.BoolOption.DEBUGINFO` on the context for these locations to actually be usable by the debugger:: ctxt.set_bool_option(gccjit.BoolOption.DEBUGINFO, True) :rtype: :py:class:`gccjit.Location` .. py:method:: new_global(Type type_, name, Location loc=None) :rtype: :py:class:`gccjit.LValue` .. py:method:: new_array_type(Type element_type, int num_elements, \ Location loc=None) :rtype: :py:class:`gccjit.Type` .. py:method:: new_field(Type type_, name, Location loc=None) :rtype: :py:class:`gccjit.Field` .. py:method:: new_struct(name, fields=None, Location loc=None) :rtype: :py:class:`gccjit.Struct` .. py:method:: new_union(name, fields=None, Location loc=None) Construct a new "union" type. :rtype: :py:class:`gccjit.Type` :param field: The fields that make up the union :type fields: A sequence of :py:class:`gccjit.Field` :param loc: The source location, if any, or None :type loc: :py:class:`gccjit.Location` For example, to create the equivalent of: .. code-block:: c union u { int as_int; float as_float; }; you can use:: ctxt = gccjit.Context() int_type = ctxt.get_type(gccjit.TypeKind.INT) float_type = ctxt.get_type(gccjit.TypeKind.FLOAT) as_int = ctxt.new_field(int_type, b'as_int') as_float = ctxt.new_field(float_type, b'as_float') u = ctxt.new_union(b'u', [as_int, as_float]) .. py:method:: new_function_ptr_type(return_type, param_types, loc=None, is_variadic=False) :param return_type: The return type of the function :type return_type: :py:class:`gccjit.Type` :param param_types: The types of the parameters :type param_types: A sequence of :py:class:`gccjit.Type` :param loc: The source location, if any, or None :type loc: :py:class:`gccjit.Location` :param is_variadic: Is the function variadic (i.e. accepts a variable number of arguments) :type is_variadic: :py:class:`bool` :rtype: :py:class:`gccjit.Type` For example, to create the equivalent of: .. code-block:: c typedef void (*fn_ptr_type) (int, int int); you can use:: >>> ctxt = gccjit.Context() >>> void_type = ctxt.get_type(gccjit.TypeKind.VOID) >>> int_type = ctxt.get_type(gccjit.TypeKind.INT) >>> fn_ptr_type = ctxt.new_function_ptr_type (void_type, [int_type, int_type, int_type]) >>> print(fn_ptr_type) void (*) (int, int, int) .. py:method:: new_param(Type type_, name, Location loc=None) :rtype: :py:class:`gccjit.Param` .. py:method:: new_function(kind, Type return_type, name, params, \ Location loc=None, \ is_variadic=False) :rtype: :py:class:`gccjit.Function` .. py:method:: get_builtin_function(name) :rtype: :py:class:`gccjit.Function` .. py:method:: zero(type_) Given a :py:class:`gccjit.Type`, which must be a numeric type, get the constant 0 as a :py:class:`gccjit.RValue` of that type. :rtype: :py:class:`gccjit.RValue` .. py:method:: one(type_) Given a :py:class:`gccjit.Type`, which must be a numeric type, get the constant 1 as a :py:class:`gccjit.RValue` of that type. :rtype: :py:class:`gccjit.RValue` .. py:method:: new_rvalue_from_double(numeric_type, value) Given a :py:class:`gccjit.Type`, which must be a numeric type, get a floating-point constant as a :py:class:`gccjit.RValue` of that type. :rtype: :py:class:`gccjit.RValue` .. py:method:: new_rvalue_from_int(type_, value) Given a :py:class:`gccjit.Type`, which must be a numeric type, get an integer constant as a :py:class:`gccjit.RValue` of that type. :rtype: :py:class:`gccjit.RValue` .. py:method:: new_rvalue_from_ptr(pointer_type, value) Given a :py:class:`gccjit.Type`, which must be a pointer type, and an address, get a :py:class:`gccjit.RValue` representing that address as a pointer of that type:: ptr = ctxt.new_rvalue_from_ptr(int_star, 0xDEADBEEF) :rtype: :py:class:`gccjit.RValue` .. py:method:: null(pointer_type) Given a :py:class:`gccjit.Type`, which must be a pointer type, get a :py:class:`gccjit.RValue` representing the `NULL` pointer of that type:: ptr = ctxt.null(int_star) :rtype: :py:class:`gccjit.RValue` .. py:method:: new_string_literal(value) Make a :py:class:`gccjit.RValue` for the given string literal value (actually bytes):: msg = ctxt.new_string_literal(b'hello world\n') :param bytes value: the bytes of the string literal :rtype: :py:class:`gccjit.RValue` .. py:method:: new_unary_op(op, result_type, rvalue, loc=None) Make a :py:class:`gccjit.RValue` for the given unary operation. :param op: Which unary operation :type op: :py:class:`gccjit.UnaryOp` :param result_type: The type of the result :type result_type: :py:class:`gccjit.Type` :param rvalue: The input expression :type rvalue: :py:class:`gccjit.RValue` :param loc: The source location, if any, or None :type loc: :py:class:`gccjit.Location` :rtype: :py:class:`gccjit.RValue` .. py:method:: new_binary_op(op, result_type, a, b, loc=None) Make a :py:class:`gccjit.RValue` for the given binary operation. :param op: Which binary operation :type op: :py:class:`gccjit.BinaryOp` :param result_type: The type of the result :type result_type: :py:class:`gccjit.Type` :param a: The first input expression :type a: :py:class:`gccjit.RValue` :param b: The second input expression :type b: :py:class:`gccjit.RValue` :param loc: The source location, if any, or None :type loc: :py:class:`gccjit.Location` :rtype: :py:class:`gccjit.RValue` .. py:method:: new_comparison(op, a, b, loc=None) Make a :py:class:`gccjit.RValue` of boolean type for the given comparison. :param op: Which comparison :type op: :py:class:`gccjit.Comparison` :param a: The first input expression :type a: :py:class:`gccjit.RValue` :param b: The second input expression :type b: :py:class:`gccjit.RValue` :param loc: The source location, if any, or None :type loc: :py:class:`gccjit.Location` :rtype: :py:class:`gccjit.RValue` .. py:method:: new_child_context(self) :rtype: :py:class:`gccjit.Context` .. py:method:: new_cast(RValue rvalue, Type type_, Location loc=None) :rtype: :py:class:`gccjit.RValue` .. py:method:: new_array_access(ptr, index, loc=None) :param ptr: The pointer or array :type ptr: :py:class:`gccjit.RValue` :param index: The index within the array :type index: :py:class:`gccjit.RValue` :param loc: The source location, if any, or None :type loc: :py:class:`gccjit.Location` :rtype: :py:class:`gccjit.LValue` .. py:method:: new_call(Function func, args, Location loc=None) :rtype: :py:class:`gccjit.RValue` .. py:method:: new_call_through_ptr(fn_ptr, args, loc=None) :param fn_ptr: A function pointer :type fn_ptr: :py:class:`gccjit.RValue` :param args: The arguments to the function call :type args: A sequence of :py:class:`gccjit.RValue` :param loc: The source location, if any, or None :type loc: :py:class:`gccjit.Location` :rtype: :py:class:`gccjit.RValue` For example, to create the equivalent of: .. code-block:: c typedef void (*fn_ptr_type) (int, int, int); fn_ptr_type fn_ptr; fn_ptr (a, b, c); you can use:: block.add_eval (ctxt.new_call_through_ptr(fn_ptr, [a, b, c])) Debugging --------- .. py:method:: gccjit.Context.dump_reproducer_to_file(self, path) Write C source code into `path` that can be compiled into a self-contained executable (i.e. with libgccjit as the only dependency). The generated code will attempt to replay the API calls that have been made into the given context, at the C level, eliminating any dependency on Python or on client code or data. This may be useful when debugging the library or client code, for reducing a complicated recipe for reproducing a bug into a simpler form. Typically you need to supply :option:`-Wno-unused-variable` when compiling the generated file (since the result of each API call is assigned to a unique variable within the generated C source, and not all are necessarily then used). .. py:method:: gccjit.Context.set_logfile(self, f) To help with debugging; enable ongoing logging of the context's activity to the given file object. For example, the following will enable logging to stderr:: ctxt.set_logfile(sys.stderr) Examples of information logged include: * API calls * the various steps involved within compilation * activity on any :py:class:`gccjit.Result` instances created by the context * activity within any child contexts The precise format and kinds of information logged is subject to change. Unfortunately, doing so creates a leak of an underlying :c:type:`FILE *` object. There may a performance cost for logging. Options ------- String options ************** .. py:method:: gccjit.Context.set_str_option(self, opt, val) Set a string option of the context; see :py:class:`gccjit.StrOption` for notes on the options and their meanings. :param opt: Which option to set :type opt: :py:class:`gccjit.StrOption` :param str val: The new value .. py:class:: gccjit.StrOption .. py:data:: PROGNAME The name of the program, for use as a prefix when printing error messages to stderr. If `None`, or default, "libgccjit.so" is used. Boolean options *************** .. py:method:: gccjit.Context.set_bool_option(self, opt, val) Set a boolean option of the context; see :py:class:`gccjit.BoolOption` for notes on the options and their meanings. :param opt: Which option to set :type opt: :py:class:`gccjit.BoolOption` :param str val: The new value .. py:class:: gccjit.BoolOption .. py:data:: DEBUGINFO If true, :py:meth:`gccjit.Context.compile` will attempt to do the right thing so that if you attach a debugger to the process, it will be able to inspect variables and step through your code. Note that you can't step through code unless you set up source location information for the code (by creating and passing in `gccjit.Location` instances). .. py:data:: DUMP_INITIAL_TREE If true, :py:meth:`gccjit.Context.compile` will dump its initial "tree" representation of your code to stderr (before any optimizations). Here's some sample output (from the `square` example):: > side-effects head 0x7f4875a761e0 tail 0x7f4875a761f8 stmts 0x7f4875a62d20 0x7f4875a62d00 stmt side-effects arg 0 VOID file (null) line 0 col 0 align 1 context >> stmt unit size align 32 symtab 0 alias set -1 canonical type 0x7f4875a645e8 precision 32 min max pointer_to_this > side-effects arg 0 side-effects arg 0 arg 1 arg 0 arg 1 >>>> .. py:data:: DUMP_INITIAL_GIMPLE If true, :py:meth:`gccjit.Context.compile` will dump the "gimple" representation of your code to stderr, before any optimizations are performed. The dump resembles C code:: square (signed int i) { signed int D.56; entry: D.56 = i * i; return D.56; } .. py:data:: DUMP_GENERATED_CODE If true, :py:meth:`gccjit.Context.compile` will dump the final generated code to stderr, in the form of assembly language:: .file "fake.c" .text .globl square .type square, @function square: .LFB0: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl %edi, -4(%rbp) .L2: movl -4(%rbp), %eax imull -4(%rbp), %eax popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE0: .size square, .-square .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.1-%{gcc_release})" .section .note.GNU-stack,"",@progbits .. py:data:: DUMP_SUMMARY If true, :py:meth:`gccjit.Context.compile` will print information to stderr on the actions it is performing, followed by a profile showing the time taken and memory usage of each phase. .. py:data:: DUMP_EVERYTHING If true, :py:meth:`gccjit.Context.compile` will dump copious amount of information on what it's doing to various files within a temporary directory. Use :py:data:`gccjit.BoolOption.KEEP_INTERMEDIATES` (see below) to see the results. The files are intended to be human-readable, but the exact files and their formats are subject to change. .. py:data:: SELFCHECK_GC If true, libgccjit will aggressively run its garbage collector, to shake out bugs (greatly slowing down the compile). This is likely to only be of interest to developers *of* the library. It is used when running the selftest suite. .. py:data:: KEEP_INTERMEDIATES If true, the gccjit.Context will not clean up intermediate files written to the filesystem, and will display their location on stderr. Integer options *************** .. py:method:: gccjit.Context.set_int_option(seld, opt, val) Set an integer option of the context; see :py:class:`gccjit.IntOption` for notes on the options and their meanings. :param opt: Which option to set :type opt: :py:class:`gccjit.IntOption` :param str val: The new value .. py:class:: gccjit.IntOption .. py:data:: OPTIMIZATION_LEVEL How much to optimize the code. Valid values are 0-3, corresponding to GCC's command-line options -O0 through -O3. The default value is 0 (unoptimized). pygccjit-0.4/doc/topics/expressions.rst000066400000000000000000000142001250534713700203570ustar00rootroot00000000000000.. Copyright 2014 David Malcolm Copyright 2014 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Expressions =========== .. py:class:: gccjit.RValue .. py:method:: dereference_field(Field field, Location loc=None) .. """dereference_field(field:Field, loc:Location=None) -> LValue""" return LValue_from_c(c_api.gcc_jit_rvalue_dereference_field (self._get_c_rvalue(), get_c_location(loc), field._get_c_field())) .. py:method:: dereference(loc=None) .. """dereference(loc:Location=None) -> LValue""" return LValue_from_c(c_api.gcc_jit_rvalue_dereference (self._get_c_rvalue(), get_c_location(loc))) .. py:method:: get_type() .. return Type_from_c(c_api.gcc_jit_rvalue_get_type (self._get_c_rvalue())) .. py:class:: gccjit.LValue .. py:method:: get_address(loc=None) Get the address of this lvalue, as a :py:class:`gccjit.RValue` of type `T*`. Unary Operations **************** Unary operations are :py:class:`gccjit.RValue` instances built using :py:meth:`gccjit.Context.new_unary_op` with an operation from one of the following: ========================================= ============ Unary Operation C equivalent ========================================= ============ :py:data:`gccjit.UnaryOp.MINUS` `-(EXPR)` :py:data:`gccjit.UnaryOp.BITWISE_NEGATE` `~(EXPR)` :py:data:`gccjit.UnaryOp.LOGICAL_NEGATE` `!(EXPR)` ========================================= ============ .. py:class:: gccjit.UnaryOp .. py:data:: MINUS Negate an arithmetic value; analogous to: .. code-block:: c -(EXPR) in C. .. py:data:: BITWISE_NEGATE Bitwise negation of an integer value (one's complement); analogous to: .. code-block:: c ~(EXPR) in C. .. py:data:: LOGICAL_NEGATE Logical negation of an arithmetic or pointer value; analogous to: .. code-block:: c !(EXPR) in C. Binary Operations ***************** Unary operations are :py:class:`gccjit.RValue` instances built using :py:meth:`gccjit.Context.new_binary_op` with an operation from one of the following: ======================================= ============ Binary Operation C equivalent ======================================= ============ :py:data:`gccjit.BinaryOp.PLUS` `x + y` :py:data:`gccjit.BinaryOp.MINUS` `x - y` :py:data:`gccjit.BinaryOp.MULT` `x * y` :py:data:`gccjit.BinaryOp.DIVIDE` `x / y` :py:data:`gccjit.BinaryOp.MODULO` `x % y` :py:data:`gccjit.BinaryOp.BITWISE_AND` `x & y` :py:data:`gccjit.BinaryOp.BITWISE_XOR` `x ^ y` :py:data:`gccjit.BinaryOp.BITWISE_OR` `x | y` :py:data:`gccjit.BinaryOp.LOGICAL_AND` `x && y` :py:data:`gccjit.BinaryOp.LOGICAL_OR` `x || y` ======================================= ============ .. py:class:: gccjit.BinaryOp .. py:data:: PLUS Addition of arithmetic values; analogous to: .. code-block:: c (EXPR_A) + (EXPR_B) in C. For pointer addition, use :py:meth:`gccjit.Context.new_array_access`. .. py:data:: MINUS Subtraction of arithmetic values; analogous to: .. code-block:: c (EXPR_A) - (EXPR_B) in C. .. py:data:: MULT Multiplication of a pair of arithmetic values; analogous to: .. code-block:: c (EXPR_A) * (EXPR_B) in C. .. py:data:: DIVIDE Quotient of division of arithmetic values; analogous to: .. code-block:: c (EXPR_A) / (EXPR_B) in C. The result type affects the kind of division: if the result type is integer-based, then the result is truncated towards zero, whereas a floating-point result type indicates floating-point division. .. py:data:: MODULO Remainder of division of arithmetic values; analogous to: .. code-block:: c (EXPR_A) % (EXPR_B) in C. .. py:data:: BITWISE_AND Bitwise AND; analogous to: .. code-block:: c (EXPR_A) & (EXPR_B) in C. .. py:data:: BITWISE_XOR Bitwise exclusive OR; analogous to: .. code-block:: c (EXPR_A) ^ (EXPR_B) in C. .. py:data:: BITWISE_OR Bitwise inclusive OR; analogous to: .. code-block:: c (EXPR_A) | (EXPR_B) in C. .. py:data:: LOGICAL_AND Logical AND; analogous to: .. code-block:: c (EXPR_A) && (EXPR_B) in C. .. py:data:: LOGICAL_OR Logical OR; analogous to: .. code-block:: c (EXPR_A) || (EXPR_B) in C. Comparisons *********** Comparisons are :py:class:`gccjit.RValue` instances of boolean type built using :py:meth:`gccjit.Context.new_comparison` with an operation from one of the following: ======================================= ============ Comparison C equivalent ======================================= ============ :py:data:`gccjit.Comparison.EQ` `x == y` :py:data:`gccjit.Comparison.NE` `x != y` :py:data:`gccjit.Comparison.LT` `x < y` :py:data:`gccjit.Comparison.LE` `x <= y` :py:data:`gccjit.Comparison.GT` `x > y` :py:data:`gccjit.Comparison.GE` `x >= y` ======================================= ============ .. py:class:: gccjit.Comparison .. py:data:: EQ .. py:data:: NE .. py:data:: LT .. py:data:: LE .. py:data:: GT .. py:data:: GE pygccjit-0.4/doc/topics/functions.rst000066400000000000000000000125171250534713700200160ustar00rootroot00000000000000.. Copyright 2014 David Malcolm Copyright 2014 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Functions ========= .. py:class:: gccjit.Param .. py:class:: gccjit.Function .. py:method:: new_local(type_, name, loc=None) Add a new local variable to the function:: i = fn.new_local(int_type, b'i') :rtype: :py:class:`gccjit.LValue` .. py:method:: new_block(name) Create a :py:class:`gccjit.Block`. The name can be None, or you can give it a meaningful name, which may show up in dumps of the internal representation, and in error messages:: entry = fn.new_block('entry') on_true = fn.new_block('on_true') .. py:method:: get_param(index) .. """get_param(index:int) -> Param""" .. py:method:: dump_to_dot(path) Write a dump in GraphViz format to the given path. .. py:class:: gccjit.Block A `gccjit.Block` is a basic block within a function, i.e. a sequence of statements with a single entry point and a single exit point. The first basic block that you create within a function will be the entrypoint. Each basic block that you create within a function must be terminated, either with a conditional, a jump, or a return. It's legal to have multiple basic blocks that return within one function. .. py:method:: add_eval(rvalue, loc=None) Add evaluation of an rvalue, discarding the result (e.g. a function call that "returns" void), for example:: call = ctxt.new_call(some_fn, args) block.add_eval(call) This is equivalent to this C code: .. code-block:: c (void)expression; .. py:method:: add_assignment(lvalue, rvalue, loc=None) Add evaluation of an rvalue, assigning the result to the given lvalue, for example:: # i = 0 entry_block.add_assignment(local_i, ctxt.zero(the_type)) This is roughly equivalent to this C code: .. code-block:: c lvalue = rvalue; .. py:method:: add_assignment_op(lvalue, op, rvalue, loc=None) Add evaluation of an rvalue, using the result to modify an lvalue via the given :py:data:`gccjit.BinaryOp`. For example:: # i++ loop_block.add_assignment_op(local_i, gccjit.BinaryOp.PLUS, ctxt.one(the_type)) This is analogous to "+=" and friends: .. code-block:: c lvalue += rvalue; lvalue *= rvalue; lvalue /= rvalue; /* etc */ .. py:method:: add_comment(text, Location loc=None) Add a no-op textual comment to the internal representation of the code. It will be optimized away, but will be visible in the dumps seen via :py:data:`gccjit.BoolOption.DUMP_INITIAL_TREE` and :py:data:`gccjit.BoolOption.DUMP_INITIAL_GIMPLE` and thus may be of use when debugging how your project's internal representation gets converted to the libgccjit IR. .. py:method:: end_with_conditional(boolval, \ on_true, \ on_false=None, \ loc=None) Terminate a block by adding evaluation of an rvalue, branching on the result to the appropriate successor block. This is roughly equivalent to this C code: .. code-block:: c if (boolval) goto on_true; else goto on_false; Example:: # while (i < n) cond_block.end_with_conditional( ctxt.new_comparison(gccjit.Comparison.LT, local_i, param_n), loop_block, after_loop_block) .. py:method:: end_with_jump(target, loc=None) Terminate a block by adding a jump to the given target block. This is roughly equivalent to this C code: .. code-block:: c goto target; Example:: loop_block.end_with_jump(cond_block) .. py:method:: end_with_return(RValue rvalue, loc=None) Terminate a block by adding evaluation of an rvalue, returning the value. This is roughly equivalent to this C code: .. code-block:: c return expression; Example:: # return sum after_loop_block.end_with_return(local_sum) .. py:method:: end_with_void_return(loc=None) Terminate a block by adding a valueless return, for use within a function with "void" return type. This is equivalent to this C code: .. code-block:: c return; .. py:method:: get_function() Get the :py:class:`gccjit.Function` that this block is within. .. py:class:: gccjit.FunctionKind .. py:data:: EXPORTED .. py:data:: INTERNAL .. py:data:: IMPORTED .. py:data:: ALWAYS_INLINE pygccjit-0.4/doc/topics/index.rst000066400000000000000000000015711250534713700171130ustar00rootroot00000000000000.. Copyright 2015 David Malcolm Copyright 2015 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Topic Reference =============== .. toctree:: :maxdepth: 2 contexts.rst types.rst expressions.rst functions.rst locations.rst compilation.rst pygccjit-0.4/doc/topics/locations.rst000066400000000000000000000037101250534713700177740ustar00rootroot00000000000000.. Copyright 2014 David Malcolm Copyright 2014 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Source Locations ================ .. py:class:: gccjit.Location A `gccjit.Location` encapsulates a source code location, so that you can (optionally) associate locations in your language with statements in the JIT-compiled code, allowing the debugger to single-step through your language. You can construct them using :py:meth:`gccjit.Context.new_location()`. You need to enable :py:data:`gccjit.BoolOption.DEBUGINFO` on the :py:class:`gccjit.Context` for these locations to actually be usable by the debugger:: ctxt.set_bool_option(gccjit.BoolOption.DEBUGINFO, True) `gccjit.Location` instances are optional; most API entrypoints accepting one default to `None`. Faking it --------- If you don't have source code for your internal representation, but need to debug, you can generate a C-like representation of the functions in your context using :py:meth:`gccjit.Context.dump_to_file()`:: ctxt.dump_to_file(b'/tmp/something.c', True) This will dump C-like code to the given path. If the `update_locations` argument is `True`, this will also set up `gccjit.Location` information throughout the context, pointing at the dump file as if it were a source file, giving you *something* you can step through in the debugger. pygccjit-0.4/doc/topics/types.rst000066400000000000000000000111551250534713700171470ustar00rootroot00000000000000.. Copyright 2014-2015 David Malcolm Copyright 2014-2015 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Types ===== Types can be created in several ways: * fundamental types can be accessed using :py:meth:`gccjit.Context.get_type`:: int_type = ctxt.get_type(gccjit.TypeKind.INT) See :py:class:`gccjit.TypeKind` for the available types. You can get `int` types of specific sizes (in bytes) using :py:meth:`gccjit.Context.get_int_type`:: int_type = ctxt.get_int_type(4, is_signed=True) * derived types can be accessed by calling methods on an existing type:: const_int_star = int_type.get_const().get_pointer() int_const_star = int_type.get_pointer().get_const() * by creating structures (see below). .. py:class:: gccjit.Type .. py:method:: get_pointer() Given type `T` get type `T*`. :rtype: :py:class:`gccjit.Type` .. py:method:: get_const() Given type `T` get type `const T`. :rtype: :py:class:`gccjit.Type` .. py:method:: get_volatile() Given type `T` get type `volatile T`. :rtype: :py:class:`gccjit.Type` Standard types -------------- .. py:method:: gccjit.Context.get_type(self, type_enum) Look up one of the standard types (see :py:class:`gccjit.TypeKind`):: int_type = ctxt.get_type(gccjit.TypeKind.INT) :param type_enum: Which type to lookup :type type_enum: :py:class:`gccjit.TypeKind` .. py:class:: gccjit.TypeKind .. py:data:: VOID C's "void" type. .. py:data:: VOID_PTR C's "void \*". .. py:data:: BOOL C++'s bool type; also C99's "_Bool" type, aka "bool" if using stdbool.h. .. py:data:: CHAR .. py:data:: SIGNED_CHAR .. py:data:: UNSIGNED_CHAR C's "char" (of some signedness) and the variants where the signedness is specified. .. py:data:: SHORT .. py:data:: UNSIGNED_SHORT C's "short" (signed) and "unsigned short". .. py:data:: INT .. py:data:: UNSIGNED_INT C's "int" (signed) and "unsigned int":: int_type = ctxt.get_type(gccjit.TypeKind.INT) .. py:data:: LONG .. py:data:: UNSIGNED_LONG C's "long" (signed) and "unsigned long". .. py:data:: LONG_LONG .. py:data:: UNSIGNED_LONG_LONG C99's "long long" (signed) and "unsigned long long". .. py:data:: FLOAT .. py:data:: DOUBLE .. py:data:: LONG_DOUBLE Floating-point types .. py:data:: CONST_CHAR_PTR C type: (const char \*):: const_char_p = ctxt.get_type(gccjit.TypeKind.CONST_CHAR_PTR) .. py:data:: SIZE_T The C "size_t" type. .. py:data:: FILE_PTR C type: (FILE \*) .. py:method:: gccjit.Context.get_int_type(self, num_bytes, is_signed) Look up an integet type of the given size:: int_type = ctxt.get_int_type(4, is_signed=True) Structures ---------- You can model C `struct` types by creating :py:class:`gccjit.Struct` and :py:class:`gccjit.Field` instances, in either order: * by creating the fields, then the structure. For example, to model: .. code-block:: c struct coord {double x; double y; }; you could call:: field_x = ctxt.new_field(double_type, b'x') field_y = ctxt.new_field(double_type, b'y') coord = ctxt.new_struct(b'coord', [field_x, field_y]) (see :py:meth:`gccjit.Context.new_field()` and :py:meth:`gccjit.Context.new_struct()`), or * by creating the structure, then populating it with fields, typically to allow modelling self-referential structs such as: .. code-block:: c struct node { int m_hash; struct node *m_next; }; like this:: node = ctxt.new_struct(b'node') node_ptr = node.get_pointer() field_hash = ctxt.new_field(int_type, b'm_hash') field_next = ctxt.new_field(node_ptr, b'm_next') node.set_fields([field_hash, field_next]) (see :py:meth:`gccjit.Struct.set_fields`) .. py:class:: gccjit.Field .. TODO .. py:class:: gccjit.Struct .. py:method:: set_fields(fields, loc=None) Populate the fields of a formerly-opaque struct type. This can only be called once on a given struct type. pygccjit-0.4/doc/tutorial/000077500000000000000000000000001250534713700156105ustar00rootroot00000000000000pygccjit-0.4/doc/tutorial/bf.rst000066400000000000000000000177631250534713700167470ustar00rootroot00000000000000.. Copyright 2015 David Malcolm Copyright 2015 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Implementing a "brainf" compiler -------------------------------- In this example we use libgccjit to construct a compiler for an esoteric programming language that we shall refer to as "brainf". The compiler can run the generated code in-process (JIT compilation), or write the generated code as a machine code executable (classic ahead-of-time compilation). The "brainf" language ********************* brainf scripts operate on an array of bytes, with a notional data pointer within the array. brainf is hard for humans to read, but it's trivial to write a parser for it, as there is no lexing; just a stream of bytes. The operations are: ====================== ============================= Character Meaning ====================== ============================= ``>`` ``idx += 1`` ``<`` ``idx -= 1`` ``+`` ``data[idx] += 1`` ``-`` ``data[idx] -= 1`` ``.`` ``output (data[idx])`` ``,`` ``data[idx] = input ()`` ``[`` loop until ``data[idx] == 0`` ``]`` end of loop Anything else ignored ====================== ============================= Unlike the previous example, we'll implement an ahead-of-time compiler, which reads ``.bf`` scripts and outputs executables (though it would be trivial to have it run them JIT-compiled in-process). Here's what a simple ``.bf`` script looks like: .. literalinclude:: ../../examples/emit-alphabet.bf :lines: 1- .. note:: This example makes use of whitespace and comments for legibility, but could have been written as:: ++++++++++++++++++++++++++ >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++< [>.+<-] It's not a particularly useful language, except for providing compiler-writers with a test case that's easy to parse. Converting a brainf script to libgccjit IR ****************************************** We write simple code to populate a :py:class:`gccjit.Context`. .. literalinclude:: ../../examples/bf.py :start-after: import gccjit :end-before: def compile_to_file(self, output_path): :language: python Compiling a context to a file ***************************** In previous examples, we compiled and ran the generated machine code in-process. We can do that: .. literalinclude:: ../../examples/bf.py :start-after: # Running the generated code in-process :end-before: # Entrypoint :language: python but this time we'll also provide a way to compile the context directly to an executable, using :py:meth:`gccjit.Context.compile_to_file`. To do so, we need to export a ``main`` function. A helper function for doing so is provided by the JIT API: .. literalinclude:: ../../gccjit/__init__.py :start-after: # Make it easy to make a "main" function: :language: python which we can use (as ``gccjit.make_main``) to compile the function to an executable: .. literalinclude:: ../../examples/bf.py :start-after: # Compiling to an executable :end-before: # Running the generated code in-process :language: python Finally, here's the top-level of the program: .. literalinclude:: ../../examples/bf.py :start-after: # Entrypoint :language: python The overall script `examples/bf.py` is thus a bf-to-machine-code compiler, which we can use to compile .bf files, either to run in-process, .. code-block:: console $ PYTHONPATH=. python examples/bf.py \ emit-alphabet.bf ABCDEFGHIJKLMNOPQRSTUVWXYZ or to compile into machine code executables: .. code-block:: console $ PYTHONPATH=. python examples/bf.py \ emit-alphabet.bf \ -o a.out which we can run independently: .. code-block:: console $ ./a.out ABCDEFGHIJKLMNOPQRSTUVWXYZ Success! We can also inspect the generated executable using standard tools: .. code-block:: console $ objdump -d a.out |less which shows that libgccjit has managed to optimize the function somewhat (for example, the runs of 26 and 65 increment operations have become integer constants 0x1a and 0x41): .. code-block:: console 0000000000400620
: 400620: 80 3d 39 0a 20 00 00 cmpb $0x0,0x200a39(%rip) # 601060 40062b: 0f 1f 44 00 00 nopl 0x0(%rax,%rax,1) 400630: 48 83 ec 08 sub $0x8,%rsp 400634: 0f b6 05 26 0a 20 00 movzbl 0x200a26(%rip),%eax # 601061 40063b: c6 05 1e 0a 20 00 1a movb $0x1a,0x200a1e(%rip) # 601060 400642: 8d 78 41 lea 0x41(%rax),%edi 400645: 40 88 3d 15 0a 20 00 mov %dil,0x200a15(%rip) # 601061 40064c: 0f 1f 40 00 nopl 0x0(%rax) 400650: 40 0f b6 ff movzbl %dil,%edi 400654: e8 87 fe ff ff callq 4004e0 400659: 0f b6 05 01 0a 20 00 movzbl 0x200a01(%rip),%eax # 601061 400660: 80 2d f9 09 20 00 01 subb $0x1,0x2009f9(%rip) # 601060 400667: 8d 78 01 lea 0x1(%rax),%edi 40066a: 40 88 3d f0 09 20 00 mov %dil,0x2009f0(%rip) # 601061 400671: 75 dd jne 400650 400673: 31 c0 xor %eax,%eax 400675: 48 83 c4 08 add $0x8,%rsp 400679: c3 retq 40067a: 66 0f 1f 44 00 00 nopw 0x0(%rax,%rax,1) We also set up debugging information (via :py:meth:`gccjit.Context.new_location` and :py:data:`gccjit.BoolOption.DEBUGINFO`), so it's possible to use ``gdb`` to singlestep through the generated binary and inspect the internal state ``idx`` and ``data_cells``: .. code-block:: console (gdb) break main Breakpoint 1 at 0x400790 (gdb) run Starting program: a.out Breakpoint 1, 0x0000000000400790 in main (argc=1, argv=0x7fffffffe448) (gdb) stepi 0x0000000000400797 in main (argc=1, argv=0x7fffffffe448) (gdb) stepi 0x00000000004007a0 in main (argc=1, argv=0x7fffffffe448) (gdb) stepi 9 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++< (gdb) list 4 5 cell 0 = 26 6 ++++++++++++++++++++++++++ 7 8 cell 1 = 65 9 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++< 10 11 while cell#0 != 0 12 [ 13 > (gdb) n 6 ++++++++++++++++++++++++++ (gdb) n 9 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++< (gdb) p idx $1 = 1 (gdb) p data_cells $2 = "\032", '\000' (gdb) p data_cells[0] $3 = 26 '\032' (gdb) p data_cells[1] $4 = 0 '\000' (gdb) list 4 5 cell 0 = 26 6 ++++++++++++++++++++++++++ 7 8 cell 1 = 65 9 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++< 10 11 while cell#0 != 0 12 [ 13 > Other forms of ahead-of-time-compilation **************************************** The above demonstrates compiling a :py:class:`gccjit.Context` directly to an executable. It's also possible to compile it to an object file, and to a dynamic library. See the documentation of :py:meth:`gccjit.Context.compile_to_file` for more information. pygccjit-0.4/doc/tutorial/index.rst000066400000000000000000000014641250534713700174560ustar00rootroot00000000000000.. Copyright 2015 David Malcolm Copyright 2015 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Tutorial ======== .. toctree:: :maxdepth: 2 trivial-example.rst loops.rst bf.rst pygccjit-0.4/doc/tutorial/loops.rst000066400000000000000000000207421250534713700175030ustar00rootroot00000000000000.. Copyright 2014 David Malcolm Copyright 2014 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Loops and variables ------------------- Consider this C function: .. code-block:: c int loop_test (int n) { int sum = 0; for (int i = 0; i < n; i++) sum += i * i; return sum; } This example demonstrates some more features of libgccjit, with local variables and a loop. Let's construct this from Python. To break this down into libgccjit terms, it's usually easier to reword the `for` loop as a `while` loop, giving: .. code-block:: c int loop_test (int n) { int sum = 0; int i = 0; while (i < n) { sum += i * i; i++; } return sum; } Here's what the final control flow graph will look like: .. figure:: ../sum-of-squares.png :alt: image of a control flow graph As before, we import the libgccjit Python bindings and make a :py:class:`gccjit.Context`: >>> import gccjit >>> ctxt = gccjit.Context() The function works with the C `int` type: >>> the_type = ctxt.get_type(gccjit.TypeKind.INT) though we could equally well make it work on, say, `double`: >>> the_type = ctxt.get_type(gccjit.TypeKind.DOUBLE) Let's build the function: >>> return_type = the_type >>> param_n = ctxt.new_param(the_type, b"n") >>> fn = ctxt.new_function(gccjit.FunctionKind.EXPORTED, ... return_type, ... b"loop_test", ... [param_n]) >>> print(fn) loop_test The base class of expression is the :py:class:`gccjit.RValue`, representing an expression that can be on the *right*-hand side of an assignment: a value that can be computed somehow, and assigned *to* a storage area (such as a variable). It has a specific :py:class:`gccjit.Type`. Anothe important class is :py:class:`gccjit.LValue`. A :py:class:`gccjit.LValue` is something that can of the *left*-hand side of an assignment: a storage area (such as a variable). In other words, every assignment can be thought of as: .. code-block:: c LVALUE = RVALUE; Note that :py:class:`gccjit.LValue` is a subclass of :py:class:`gccjit.RValue`, where in an assignment of the form: .. code-block:: c LVALUE_A = LVALUE_B; the `LVALUE_B` implies reading the current value of that storage area, assigning it into the `LVALUE_A`. So far the only expressions we've seen are `i * i`:: ctxt.new_binary_op(gccjit.BinaryOp.MULT, int_type, param_i, param_i) which is a :py:class:`gccjit.RValue`, and the various function parameters: `param_i` and `param_n`, instances of :py:class:`gccjit.Param`, which is a subclass of :py:class:`gccjit.LValue` (and, in turn, of :py:class:`gccjit.RValue`): we can both read from and write to function parameters within the body of a function. Our new example has a couple of local variables. We create them by calling :py:meth:`gccjit.Function.new_local`, supplying a type and a name: >>> local_i = fn.new_local(the_type, b"i") >>> print(local_i) i >>> local_sum = fn.new_local(the_type, b"sum") >>> print(local_sum) sum These are instances of :py:class:`gccjit.LValue` - they can be read from and written to. Note that there is no precanned way to create *and* initialize a variable like in C: .. code-block:: c int i = 0; Instead, having added the local to the function, we have to separately add an assignment of `0` to `local_i` at the beginning of the function. This function has a loop, so we need to build some basic blocks to handle the control flow. In this case, we need 4 blocks: 1. before the loop (initializing the locals) 2. the conditional at the top of the loop (comparing `i < n`) 3. the body of the loop 4. after the loop terminates (`return sum`) so we create these as :py:class:`gccjit.Block` instances within the :py:class:`gccjit.Function`: >>> entry_block = fn.new_block(b'entry') >>> cond_block = fn.new_block(b"cond") >>> loop_block = fn.new_block(b"loop") >>> after_loop_block = fn.new_block(b"after_loop") We now populate each block with statements. The entry block consists of initializations followed by a jump to the conditional. We assign `0` to `i` and to `sum`, using :py:meth:`gccjit.Block.add_assignment` to add an assignment statement, and using :py:meth:`gccjit.Context.zero` to get the constant value `0` for the relevant type for the right-hand side of the assignment: >>> entry_block.add_assignment(local_i, ctxt.zero(the_type)) >>> entry_block.add_assignment(local_sum, ctxt.zero(the_type)) We can then terminate the entry block by jumping to the conditional: >>> entry_block.end_with_jump(cond_block) The conditional block is equivalent to the line `while (i < n)` from our C example. It contains a single statement: a conditional, which jumps to one of two destination blocks depending on a boolean :py:class:`gccjit.RValue`, in this case the comparison of `i` and `n`. We build the comparison using :py:meth:`gccjit.Context.new_comparison`: >>> guard = ctxt.new_comparison(gccjit.Comparison.LT, local_i, param_n) >>> print(guard) i < n and can then use this to add `cond_block`'s sole statement, via :py:meth:`gccjit.Block.end_with_conditional`: >>> cond_block.end_with_conditional(guard, ... loop_block, # on true ... after_loop_block) # on false Next, we populate the body of the loop. The C statement `sum += i * i;` is an assignment operation, where an lvalue is modified "in-place". We use :py:meth:`gccjit.Block.add_assignment_op` to handle these operations: >>> loop_block.add_assignment_op(local_sum, ... gccjit.BinaryOp.PLUS, ... ctxt.new_binary_op(gccjit.BinaryOp.MULT, ... the_type, ... local_i, local_i)) The `i++` can be thought of as `i += 1`, and can thus be handled in a similar way. We use :py:meth:`gccjit.Context.one` to get the constant value `1` (for the relevant type) for the right-hand side of the assignment: >>> loop_block.add_assignment_op(local_i, ... gccjit.BinaryOp.PLUS, ... ctxt.one(the_type)) The loop body completes by jumping back to the conditional: >>> loop_block.end_with_jump(cond_block) Finally, we populate the `after_loop` block, reached when the loop conditional is false. At the C level this is simply: .. code-block:: c return sum; so the block is just one statement: >>> after_loop_block.end_with_return(local_sum) .. note:: You can intermingle block creation with statement creation, but given that the terminator statements generally include references to other blocks, I find it's clearer to create all the blocks, *then* all the statements. We've finished populating the function. As before, we can now compile it to machine code: >>> jit_result = ctxt.compile() >>> void_ptr = jit_result.get_code(b'loop_test') and use `ctypes` to turn it into a Python callable: >>> import ctypes >>> int_int_func_type = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) >>> callable = int_int_func_type(void_ptr) Now we can call it: >>> callable(10) 285 Visualizing the control flow graph ********************************** You can see the control flow graph of a function using :py:meth:`gccjit.Function.dump_to_dot`: >>> fn.dump_to_dot('/tmp/sum-of-squares.dot') giving a .dot file in GraphViz format. You can convert this to an image using `dot`: .. code-block:: bash $ dot -Tpng /tmp/sum-of-squares.dot -o /tmp/sum-of-squares.png or use a viewer (my preferred one is xdot.py; see https://github.com/jrfonseca/xdot.py; on Fedora you can install it with `yum install python-xdot`): .. figure:: ../sum-of-squares.png :alt: image of a control flow graph Full example ************ Here's what the above looks like as a complete program: .. literalinclude:: ../../examples/sum_of_squares.py :lines: 34- :language: python pygccjit-0.4/doc/tutorial/trivial-example.rst000066400000000000000000000137051250534713700214530ustar00rootroot00000000000000.. Copyright 2014 David Malcolm Copyright 2014 Red Hat, Inc. This is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Creating a trivial machine code function ---------------------------------------- Consider this C function: .. code-block:: c int square(int i) { return i * i; } How can we construct this from within Python using libgccjit? First we need to import the Python bindings to libgccjit: >>> import gccjit All state associated with compilation is associated with a :py:class:`gccjit.Context`: >>> ctxt = gccjit.Context() The JIT library has a system of types. It is statically-typed: every expression is of a specific type, fixed at compile-time. In our example, all of the expressions are of the C `int` type, so let's obtain this from the context, as a :py:class:`gccjit.Type`: >>> int_type = ctxt.get_type(gccjit.TypeKind.INT) The various objects in the API have reasonable `__str__` methods: >>> print(int_type) int Let's create the function. To do so, we first need to construct its single parameter, specifying its type and giving it a name: >>> param_i = ctxt.new_param(int_type, b'i') >>> print(param_i) i Now we can create the function: >>> fn = ctxt.new_function(gccjit.FunctionKind.EXPORTED, ... int_type, # return type ... b"square", # name ... [param_i]) # params >>> print(fn) square To define the code within the function, we must create basic blocks containing statements. Every basic block contains a list of statements, eventually terminated by a statement that either returns, or jumps to another basic block. Our function has no control-flow, so we just need one basic block: >>> block = fn.new_block(b'entry') >>> print(block) entry Our basic block is relatively simple: it immediately terminates by returning the value of an expression. We can build the expression: >>> expr = ctxt.new_binary_op(gccjit.BinaryOp.MULT, ... int_type, ... param_i, param_i) >>> print(expr) i * i This in itself doesn't do anything; we have to add this expression to a statement within the block. In this case, we use it to build a return statement, which terminates the basic block: >>> block.end_with_return(expr) OK, we've populated the context. We can now compile it: >>> jit_result = ctxt.compile() and get a :py:class:`gccjit.Result`. We can now look up a specific machine code routine within the result, in this case, the function we created above: >>> void_ptr = jit_result.get_code(b"square") We can now use ctypes.CFUNCTYPE to turn it into something we can call from Python: >>> import ctypes >>> int_int_func_type = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) >>> callable = int_int_func_type(void_ptr) It should now be possible to run the code: >>> callable(5) 25 Options ******* To get more information on what's going on, you can set debugging flags on the context using :py:meth:`gccjit.Context.set_bool_option`. .. (I'm deliberately not mentioning :py:data:`gccjit.BoolOption.DUMP_INITIAL_TREE` here since I think it's probably more of use to implementors than to users) Setting :py:data:`gccjit.BoolOption.DUMP_INITIAL_GIMPLE` will dump a C-like representation to stderr when you compile (GCC's "GIMPLE" representation):: >>> ctxt.set_bool_option(gccjit.BoolOption.DUMP_INITIAL_GIMPLE, True) >>> jit_result = ctxt.compile() square (signed int i) { signed int D.260; entry: D.260 = i * i; return D.260; } We can see the generated machine code in assembler form (on stderr) by setting :py:data:`gccjit.BoolOption.DUMP_GENERATED_CODE` on the context before compiling: >>> ctxt.set_bool_option(gccjit.BoolOption.DUMP_GENERATED_CODE, True) >>> jit_result = ctxt.compile() .file "fake.c" .text .globl square .type square, @function square: .LFB6: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6, -16 movq %rsp, %rbp .cfi_def_cfa_register 6 movl %edi, -4(%rbp) .L14: movl -4(%rbp), %eax imull -4(%rbp), %eax popq %rbp .cfi_def_cfa 7, 8 ret .cfi_endproc .LFE6: .size square, .-square .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)" .section .note.GNU-stack,"",@progbits By default, no optimizations are performed, the equivalent of GCC's `-O0` option. We can turn things up to e.g. `-O3` by calling :py:meth:`gccjit.Context.set_int_option` with :py:data:`gccjit.IntOption.OPTIMIZATION_LEVEL`: >>> ctxt.set_int_option(gccjit.IntOption.OPTIMIZATION_LEVEL, 3) >>> jit_result = ctxt.compile() .file "fake.c" .text .p2align 4,,15 .globl square .type square, @function square: .LFB7: .cfi_startproc .L16: movl %edi, %eax imull %edi, %eax ret .cfi_endproc .LFE7: .size square, .-square .ident "GCC: (GNU) 4.9.0 20131023 (Red Hat 0.2-0.5.1920c315ff984892399893b380305ab36e07b455.fc20)" .section .note.GNU-stack,"",@progbits Naturally this has only a small effect on such a trivial function. Full example ************ Here's what the above looks like as a complete program: .. literalinclude:: ../../examples/square.py :lines: 27- :language: python pygccjit-0.4/examples/000077500000000000000000000000001250534713700150165ustar00rootroot00000000000000pygccjit-0.4/examples/__init__.py000066400000000000000000000000001250534713700171150ustar00rootroot00000000000000pygccjit-0.4/examples/bf.py000066400000000000000000000237611250534713700157700ustar00rootroot00000000000000# Copyright 2015 David Malcolm # Copyright 2015 Red Hat, Inc. # # This is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see # . # A compiler for the "bf" language import sys import gccjit class Paren: def __init__(self, b_test, b_body, b_after): self.b_test = b_test self.b_body = b_body self.b_after = b_after class CompileError(Exception): def __init__(self, compiler, msg): self.filename = compiler.filename self.line = compiler.line self.column = compiler.column self.msg = msg def __str__(self): return ("%s:%i:%i: %s" % (self.filename, self.line, self.column, self.msg)) class Compiler: def __init__(self): #, filename): self.ctxt = gccjit.Context() if 1: self.ctxt.set_int_option(gccjit.IntOption.OPTIMIZATION_LEVEL, 3); self.ctxt.set_bool_option(gccjit.BoolOption.DUMP_INITIAL_GIMPLE, 0); self.ctxt.set_bool_option(gccjit.BoolOption.DUMP_GENERATED_CODE, 0); self.ctxt.set_bool_option(gccjit.BoolOption.DEBUGINFO, 1); self.ctxt.set_bool_option(gccjit.BoolOption.DUMP_EVERYTHING, 0); self.ctxt.set_bool_option(gccjit.BoolOption.KEEP_INTERMEDIATES, 0); self.void_type = self.ctxt.get_type(gccjit.TypeKind.VOID) self.int_type = self.ctxt.get_type(gccjit.TypeKind.INT) self.byte_type = self.ctxt.get_type(gccjit.TypeKind.UNSIGNED_CHAR) self.array_type = self.ctxt.new_array_type(self.byte_type, 30000) self.func_getchar = ( self.ctxt.new_function(gccjit.FunctionKind.IMPORTED, self.int_type, b"getchar", [])) self.func_putchar = ( self.ctxt.new_function(gccjit.FunctionKind.IMPORTED, self.void_type, b"putchar", [self.ctxt.new_param(self.int_type, b"c")])) self.func = self.ctxt.new_function(gccjit.FunctionKind.EXPORTED, self.void_type, b'func', []) self.curblock = self.func.new_block(b"initial") self.int_zero = self.ctxt.zero(self.int_type) self.int_one = self.ctxt.one(self.int_type) self.byte_zero = self.ctxt.zero(self.byte_type) self.byte_one = self.ctxt.one(self.byte_type) self.data_cells = self.ctxt.new_global(gccjit.GlobalKind.INTERNAL, self.array_type, b"data_cells") self.idx = self.func.new_local(self.int_type, b"idx") self.open_parens = [] self.curblock.add_comment(b"idx = 0;") self.curblock.add_assignment(self.idx, self.int_zero) def get_current_data(self, loc): """Get 'data_cells[idx]' as an lvalue. """ return self.ctxt.new_array_access(self.data_cells, self.idx, loc) def current_data_is_zero(self, loc): """Get 'data_cells[idx] == 0' as a boolean rvalue.""" return self.ctxt.new_comparison(gccjit.Comparison.EQ, self.get_current_data(loc), self.byte_zero, loc) def compile_char(self, ch): """Compile one bf character.""" loc = self.ctxt.new_location(self.filename, self.line, self.column) # Turn this on to trace execution, by injecting putchar() # of each source char. if 0: arg = self.ctxt.new_rvalue_from_int (self.int_type, ch) call = self.ctxt.new_call (self.func_putchar, [arg], loc) self.curblock.add_eval (call, loc) if ch == '>': self.curblock.add_comment(b"'>': idx += 1;", loc) self.curblock.add_assignment_op(self.idx, gccjit.BinaryOp.PLUS, self.int_one, loc) elif ch == '<': self.curblock.add_comment(b"'<': idx -= 1;", loc) self.curblock.add_assignment_op(self.idx, gccjit.BinaryOp.MINUS, self.int_one, loc) elif ch == '+': self.curblock.add_comment(b"'+': data[idx] += 1;", loc) self.curblock.add_assignment_op(self.get_current_data (loc), gccjit.BinaryOp.PLUS, self.byte_one, loc) elif ch == '-': self.curblock.add_comment(b"'-': data[idx] -= 1;", loc) self.curblock.add_assignment_op(self.get_current_data(loc), gccjit.BinaryOp.MINUS, self.byte_one, loc) elif ch == '.': arg = self.ctxt.new_cast(self.get_current_data(loc), self.int_type, loc) call = self.ctxt.new_call(self.func_putchar, [arg], loc) self.curblock.add_comment(b"'.': putchar ((int)data[idx]);", loc) self.curblock.add_eval(call, loc) elif ch == ',': call = self.ctxt.new_call(self.func_getchar, [], loc) self.curblock.add_comment(b"',': data[idx] = (unsigned char)getchar ();", loc) self.curblock.add_assignment(self.get_current_data(loc), self.ctxt.new_cast(call, self.byte_type, loc), loc) elif ch == '[': loop_test = self.func.new_block() on_zero = self.func.new_block() on_non_zero = self.func.new_block() self.curblock.end_with_jump(loop_test, loc) loop_test.add_comment(b"'['", loc) loop_test.end_with_conditional(self.current_data_is_zero(loc), on_zero, on_non_zero, loc) self.open_parens.append(Paren(loop_test, on_non_zero, on_zero)) self.curblock = on_non_zero; elif ch == ']': self.curblock.add_comment(b"']'", loc) if not self.open_parens: raise CompileError(self, "mismatching parens") paren = self.open_parens.pop() self.curblock.end_with_jump(paren.b_test) self.curblock = paren.b_after elif ch == '\n': self.line +=1; self.column = 0; if ch != '\n': self.column += 1 def parse_into_ctxt(self, filename): """ Parse the given .bf file into the gccjit.Context, containing a single "main" function suitable for compiling into an executable. """ self.filename = filename; self.line = 1 self.column = 0 with open(filename) as f_in: for ch in f_in.read(): self.compile_char(ch) self.curblock.end_with_void_return() # Compiling to an executable def compile_to_file(self, output_path): # Wrap "func" up in a "main" function mainfunc, argv, argv = gccjit.make_main(self.ctxt) block = mainfunc.new_block() block.add_eval(self.ctxt.new_call(self.func, [])) block.end_with_return(self.int_zero) self.ctxt.compile_to_file(gccjit.OutputKind.EXECUTABLE, output_path) # Running the generated code in-process def run(self): import ctypes result = self.ctxt.compile() py_func_type = ctypes.CFUNCTYPE(None) py_func = py_func_type(result.get_code(b'func')) py_func() # Entrypoint def main(argv): from optparse import OptionParser parser = OptionParser() parser.add_option("-o", "--output", dest="outputfile", help="compile to FILE", metavar="FILE") (options, args) = parser.parse_args() if len(args) != 1: raise ValueError('No input file') inputfile = args[0] c = Compiler() c.parse_into_ctxt(inputfile) if options.outputfile: c.compile_to_file(options.outputfile) else: c.run() if __name__ == '__main__': try: main(sys.argv) except Exception as exc: print(exc) sys.exit(1) pygccjit-0.4/examples/emit-alphabet.bf000077500000000000000000000003731250534713700200510ustar00rootroot00000000000000[ Emit the uppercase alphabet ] cell 0 = 26 ++++++++++++++++++++++++++ cell 1 = 65 >+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++< while cell#0 != 0 [ > . emit cell#1 + increment cell@1 <- decrement cell@0 ] pygccjit-0.4/examples/square.py000066400000000000000000000053071250534713700166750ustar00rootroot00000000000000# Copyright 2014 David Malcolm # Copyright 2014 Red Hat, Inc. # # This is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see # . """ This examples creates and runs the equivalent of this C function: int square(int i) { return i * i; } """ import ctypes import gccjit def create_fn(): # Create a compilation context: ctxt = gccjit.Context() # Turn these on to get various kinds of debugging: if 0: ctxt.set_bool_option(gccjit.BoolOption.DUMP_INITIAL_TREE, True) ctxt.set_bool_option(gccjit.BoolOption.DUMP_INITIAL_GIMPLE, True) ctxt.set_bool_option(gccjit.BoolOption.DUMP_GENERATED_CODE, True) # Adjust this to control optimization level of the generated code: if 0: ctxt.set_int_option(gccjit.IntOption.OPTIMIZATION_LEVEL, 3) int_type = ctxt.get_type(gccjit.TypeKind.INT) # Create parameter "i": param_i = ctxt.new_param(int_type, b'i') # Create the function: fn = ctxt.new_function(gccjit.FunctionKind.EXPORTED, int_type, b"square", [param_i]) # Create a basic block within the function: block = fn.new_block(b'entry') # This basic block is relatively simple: block.end_with_return( ctxt.new_binary_op(gccjit.BinaryOp.MULT, int_type, param_i, param_i)) # Having populated the context, compile it. jit_result = ctxt.compile() # This is what you get back from ctxt.compile(): assert isinstance(jit_result, gccjit.Result) return jit_result def test_calling_fn(i): jit_result = create_fn() # Look up a specific machine code routine within the gccjit.Result, # in this case, the function we created above: void_ptr = jit_result.get_code(b"square") # Now use ctypes.CFUNCTYPE to turn it into something we can call # from Python: int_int_func_type = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) code = int_int_func_type(void_ptr) # Now try running the code: return code(i) if __name__ == '__main__': print(test_calling_fn(5)) pygccjit-0.4/examples/sum_of_squares.py000066400000000000000000000073121250534713700204260ustar00rootroot00000000000000# Copyright 2013 David Malcolm # Copyright 2013 Red Hat, Inc. # # This is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see # . """ This examples creates and runs the equivalent of this C function: int loop_test (int n) { int i = 0; int sum = 0; while (i < n) { sum += i * i; i++; } return sum; } """ import ctypes import gccjit def populate_ctxt(ctxt): the_type = ctxt.get_type(gccjit.TypeKind.INT) return_type = the_type param_n = ctxt.new_param(the_type, b"n") fn = ctxt.new_function(gccjit.FunctionKind.EXPORTED, return_type, b"loop_test", [param_n]) # Build locals local_i = fn.new_local(the_type, b"i") local_sum = fn.new_local(the_type, b"sum") assert str(local_i) == 'i' # Build blocks entry_block = fn.new_block(b'entry') cond_block = fn.new_block(b"cond") loop_block = fn.new_block(b"loop") after_loop_block = fn.new_block(b"after_loop") # entry_block: ######################################### # sum = 0 entry_block.add_assignment(local_sum, ctxt.zero(the_type)) # i = 0 entry_block.add_assignment(local_i, ctxt.zero(the_type)) entry_block.end_with_jump(cond_block) ### cond_block: ######################################## # while (i < n) cond_block.end_with_conditional(ctxt.new_comparison(gccjit.Comparison.LT, local_i, param_n), loop_block, after_loop_block) ### loop_block: ######################################## # sum += i * i loop_block.add_assignment_op(local_sum, gccjit.BinaryOp.PLUS, ctxt.new_binary_op(gccjit.BinaryOp.MULT, the_type, local_i, local_i)) # i++ loop_block.add_assignment_op(local_i, gccjit.BinaryOp.PLUS, ctxt.one(the_type)) # goto cond_block loop_block.end_with_jump(cond_block) ### after_loop_block: ################################## # return sum after_loop_block.end_with_return(local_sum) def create_fn(): # Create a compilation context: ctxt = gccjit.Context() if 0: ctxt.set_bool_option(gccjit.BoolOption.DUMP_INITIAL_TREE, True) ctxt.set_bool_option(gccjit.BoolOption.DUMP_INITIAL_GIMPLE, True) ctxt.set_bool_option(gccjit.BoolOption.DUMP_EVERYTHING, True) ctxt.set_bool_option(gccjit.BoolOption.KEEP_INTERMEDIATES, True) if 0: ctxt.set_int_option(gccjit.IntOption.OPTIMIZATION_LEVEL, 3) populate_ctxt(ctxt) jit_result = ctxt.compile() return jit_result def test_calling_fn(i): jit_result = create_fn() int_int_func_type = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) code = int_int_func_type(jit_result.get_code(b"loop_test")) return code(i) if __name__ == '__main__': print(test_calling_fn(10)) pygccjit-0.4/gccjit/000077500000000000000000000000001250534713700144435ustar00rootroot00000000000000pygccjit-0.4/gccjit/__init__.py000066400000000000000000000043731250534713700165630ustar00rootroot00000000000000# Copyright 2014 Simon Feltman # Copyright 2015 David Malcolm # Copyright 2015 Red Hat, Inc. # # This is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see # . from __future__ import absolute_import from ._gccjit import (Context, Object, Result, RValue, LValue, Type, Location, Field, Struct, Param, Function, Block, FunctionKind, UnaryOp, BinaryOp, Comparison, StrOption, IntOption, BoolOption, OutputKind, TypeKind, GlobalKind, Error, ) # Make it easy to make a "main" function: def make_main(ctxt): """ Make "main" function: int main (int argc, char **argv) { ... } Return (func, param_argc, param_argv) """ int_type = ctxt.get_type(TypeKind.INT) param_argc = ctxt.new_param(int_type, b"argc") char_ptr_ptr_type = ( ctxt.get_type(TypeKind.CHAR).get_pointer().get_pointer()) param_argv = ctxt.new_param(char_ptr_ptr_type, b"argv") func_main = ctxt.new_function(FunctionKind.EXPORTED, int_type, b"main", [param_argc, param_argv]) return (func_main, param_argc, param_argv) pygccjit-0.4/gccjit/gccjit.pxd000066400000000000000000000431021250534713700164230ustar00rootroot00000000000000# Copyright 2013-2015 David Malcolm # Copyright 2013-2015 Red Hat, Inc. # Copyright 2014 Simon Feltman # # This is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see # . from libc.stdio cimport * cdef extern from "libgccjit.h": # # Data structures. # ctypedef struct gcc_jit_object: pass ctypedef struct gcc_jit_context: pass ctypedef struct gcc_jit_result: pass ctypedef struct gcc_jit_location: pass ctypedef struct gcc_jit_type: pass ctypedef struct gcc_jit_function: pass ctypedef struct gcc_jit_block: pass ctypedef struct gcc_jit_rvalue: pass ctypedef struct gcc_jit_lvalue: pass ctypedef struct gcc_jit_param: pass ctypedef struct gcc_jit_field: pass ctypedef struct gcc_jit_struct: pass cdef enum gcc_jit_types: GCC_JIT_TYPE_VOID, GCC_JIT_TYPE_VOID_PTR, GCC_JIT_TYPE_BOOL, GCC_JIT_TYPE_CHAR, GCC_JIT_TYPE_SIGNED_CHAR, GCC_JIT_TYPE_UNSIGNED_CHAR, GCC_JIT_TYPE_SHORT, GCC_JIT_TYPE_UNSIGNED_SHORT, GCC_JIT_TYPE_INT, GCC_JIT_TYPE_UNSIGNED_INT, GCC_JIT_TYPE_LONG, GCC_JIT_TYPE_UNSIGNED_LONG, GCC_JIT_TYPE_LONG_LONG, GCC_JIT_TYPE_UNSIGNED_LONG_LONG, GCC_JIT_TYPE_FLOAT, GCC_JIT_TYPE_DOUBLE, GCC_JIT_TYPE_LONG_DOUBLE, GCC_JIT_TYPE_CONST_CHAR_PTR, GCC_JIT_TYPE_SIZE_T, GCC_JIT_TYPE_FILE_PTR # # Option-management # cdef enum gcc_jit_str_option: GCC_JIT_STR_OPTION_PROGNAME GCC_JIT_NUM_STR_OPTIONS cdef enum gcc_jit_int_option: GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL GCC_JIT_NUM_INT_OPTIONS cdef enum gcc_jit_bool_option: GCC_JIT_BOOL_OPTION_DEBUGINFO GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE GCC_JIT_BOOL_OPTION_DUMP_SUMMARY GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING GCC_JIT_BOOL_OPTION_SELFCHECK_GC GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES GCC_JIT_NUM_BOOL_OPTIONS void gcc_jit_context_set_str_option (gcc_jit_context *ctxt, gcc_jit_str_option opt, char *value) void gcc_jit_context_set_int_option (gcc_jit_context *ctxt, gcc_jit_int_option opt, int value) void gcc_jit_context_set_bool_option (gcc_jit_context *ctxt, gcc_jit_bool_option opt, int value) # # Context management # gcc_jit_context *gcc_jit_context_acquire () void gcc_jit_context_release (gcc_jit_context *ctxt) gcc_jit_result *gcc_jit_context_compile (gcc_jit_context *ctxt) cdef enum gcc_jit_output_kind: GCC_JIT_OUTPUT_KIND_ASSEMBLER GCC_JIT_OUTPUT_KIND_OBJECT_FILE GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY GCC_JIT_OUTPUT_KIND_EXECUTABLE void gcc_jit_context_compile_to_file (gcc_jit_context *ctxt, gcc_jit_output_kind output_kind, char *output_path) void gcc_jit_context_dump_to_file (gcc_jit_context *ctxt, char *path, int update_locations) char *gcc_jit_context_get_first_error (gcc_jit_context *ctxt) char *gcc_jit_context_get_last_error (gcc_jit_context *ctxt) void *gcc_jit_result_get_code (gcc_jit_result *result, char *funcname) void gcc_jit_result_release (gcc_jit_result *result) gcc_jit_context *gcc_jit_object_get_context (gcc_jit_object *obj) char *gcc_jit_object_get_debug_string (gcc_jit_object *obj) gcc_jit_location *gcc_jit_context_new_location (gcc_jit_context *ctxt, char *filename, int line, int column) gcc_jit_object *gcc_jit_location_as_object (gcc_jit_location *loc) # # Types # gcc_jit_object *gcc_jit_type_as_object (gcc_jit_type *type) gcc_jit_type *gcc_jit_context_get_type (gcc_jit_context *ctxt, gcc_jit_types type_enum) gcc_jit_type *gcc_jit_context_get_int_type (gcc_jit_context *ctxt, int num_bytes, int is_signed) gcc_jit_type *gcc_jit_type_get_pointer (gcc_jit_type *type) gcc_jit_type *gcc_jit_type_get_const (gcc_jit_type *type) gcc_jit_type *gcc_jit_type_get_volatile (gcc_jit_type *type) gcc_jit_type *gcc_jit_context_new_array_type (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_type *element_type, int num_elements) gcc_jit_field *gcc_jit_context_new_field (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_type *type, char *name) gcc_jit_object *gcc_jit_field_as_object (gcc_jit_field *field) gcc_jit_struct *gcc_jit_context_new_struct_type (gcc_jit_context *ctxt, gcc_jit_location *loc, const char *name, int num_fields, gcc_jit_field **fields) gcc_jit_struct *gcc_jit_context_new_opaque_struct (gcc_jit_context *ctxt, gcc_jit_location *loc, const char *name) gcc_jit_type *gcc_jit_struct_as_type (gcc_jit_struct *struct_type) void gcc_jit_struct_set_fields (gcc_jit_struct *struct_type, gcc_jit_location *loc, int num_fields, gcc_jit_field **fields) gcc_jit_type *gcc_jit_context_new_union_type (gcc_jit_context *ctxt, gcc_jit_location *loc, const char *name, int num_fields, gcc_jit_field **fields) gcc_jit_type *gcc_jit_context_new_function_ptr_type (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_type *return_type, int num_params, gcc_jit_type **param_types, int is_variadic) # # Constructing functions. # gcc_jit_param *gcc_jit_context_new_param (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_type *type, char *name) gcc_jit_object *gcc_jit_param_as_object (gcc_jit_param *param) gcc_jit_lvalue *gcc_jit_param_as_lvalue (gcc_jit_param *param) gcc_jit_rvalue *gcc_jit_param_as_rvalue (gcc_jit_param *param) cdef enum gcc_jit_function_kind: GCC_JIT_FUNCTION_EXPORTED, GCC_JIT_FUNCTION_INTERNAL, GCC_JIT_FUNCTION_IMPORTED, GCC_JIT_FUNCTION_ALWAYS_INLINE gcc_jit_function *gcc_jit_context_new_function (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_function_kind kind, gcc_jit_type *return_type, char *name, int num_params, gcc_jit_param **params, int is_variadic) gcc_jit_function *gcc_jit_context_get_builtin_function (gcc_jit_context *ctxt, char *name) gcc_jit_object *gcc_jit_function_as_object (gcc_jit_function *func) gcc_jit_param *gcc_jit_function_get_param (gcc_jit_function *func, int index) void gcc_jit_function_dump_to_dot (gcc_jit_function *func, char *path) gcc_jit_block *gcc_jit_function_new_block (gcc_jit_function *func, char *name) gcc_jit_object *gcc_jit_block_as_object (gcc_jit_block *block) gcc_jit_function *gcc_jit_block_get_function (gcc_jit_block *block) # # lvalues, rvalues and expressions. # cdef enum gcc_jit_global_kind: GCC_JIT_GLOBAL_EXPORTED, GCC_JIT_GLOBAL_INTERNAL, GCC_JIT_GLOBAL_IMPORTED gcc_jit_lvalue *gcc_jit_context_new_global (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_global_kind kind, gcc_jit_type *type, char *name) gcc_jit_object *gcc_jit_lvalue_as_object (gcc_jit_lvalue *lvalue) gcc_jit_rvalue *gcc_jit_lvalue_as_rvalue (gcc_jit_lvalue *lvalue) gcc_jit_object *gcc_jit_rvalue_as_object (gcc_jit_rvalue *rvalue) gcc_jit_type *gcc_jit_rvalue_get_type (gcc_jit_rvalue *rvalue) gcc_jit_rvalue *gcc_jit_context_new_rvalue_from_int (gcc_jit_context *ctxt, gcc_jit_type *type, int value) gcc_jit_rvalue *gcc_jit_context_zero (gcc_jit_context *ctxt, gcc_jit_type *type) gcc_jit_rvalue *gcc_jit_context_one (gcc_jit_context *ctxt, gcc_jit_type *type) gcc_jit_rvalue *gcc_jit_context_new_rvalue_from_double (gcc_jit_context *ctxt, gcc_jit_type *numeric_type, double value) gcc_jit_rvalue *gcc_jit_context_new_rvalue_from_ptr (gcc_jit_context *ctxt, gcc_jit_type *pointer_type, void *value) gcc_jit_rvalue *gcc_jit_context_null (gcc_jit_context *ctxt, gcc_jit_type *pointer_type) gcc_jit_rvalue *gcc_jit_context_new_string_literal (gcc_jit_context *ctxt, char *value) cdef enum gcc_jit_unary_op: GCC_JIT_UNARY_OP_MINUS, GCC_JIT_UNARY_OP_BITWISE_NEGATE, GCC_JIT_UNARY_OP_LOGICAL_NEGATE, GCC_JIT_UNARY_OP_ABS gcc_jit_rvalue *gcc_jit_context_new_unary_op (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_unary_op op, gcc_jit_type *result_type, gcc_jit_rvalue *rvalue) cdef enum gcc_jit_binary_op: GCC_JIT_BINARY_OP_PLUS, GCC_JIT_BINARY_OP_MINUS, GCC_JIT_BINARY_OP_MULT GCC_JIT_BINARY_OP_DIVIDE, GCC_JIT_BINARY_OP_MODULO, GCC_JIT_BINARY_OP_BITWISE_AND, GCC_JIT_BINARY_OP_BITWISE_XOR, GCC_JIT_BINARY_OP_BITWISE_OR, GCC_JIT_BINARY_OP_LOGICAL_AND, GCC_JIT_BINARY_OP_LOGICAL_OR gcc_jit_rvalue *gcc_jit_context_new_binary_op (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_binary_op op, gcc_jit_type *result_type, gcc_jit_rvalue *a, gcc_jit_rvalue *b) cdef enum gcc_jit_comparison: GCC_JIT_COMPARISON_EQ, GCC_JIT_COMPARISON_NE, GCC_JIT_COMPARISON_LT, GCC_JIT_COMPARISON_LE, GCC_JIT_COMPARISON_GT, GCC_JIT_COMPARISON_GE gcc_jit_rvalue *gcc_jit_context_new_comparison (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_comparison op, gcc_jit_rvalue *a, gcc_jit_rvalue *b) gcc_jit_rvalue *gcc_jit_context_new_call (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_function *func, int numargs , gcc_jit_rvalue **args) gcc_jit_rvalue *gcc_jit_context_new_call_through_ptr (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_rvalue *fn_ptr, int numargs, gcc_jit_rvalue **args) gcc_jit_rvalue *gcc_jit_context_new_cast (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_rvalue *rvalue, gcc_jit_type *type) gcc_jit_lvalue *gcc_jit_context_new_array_access (gcc_jit_context *ctxt, gcc_jit_location *loc, gcc_jit_rvalue *ptr, gcc_jit_rvalue *index) gcc_jit_lvalue *gcc_jit_lvalue_access_field (gcc_jit_lvalue *struct_, gcc_jit_location *loc, gcc_jit_field *field) gcc_jit_rvalue *gcc_jit_rvalue_access_field (gcc_jit_rvalue *struct_, gcc_jit_location *loc, gcc_jit_field *field) gcc_jit_lvalue *gcc_jit_rvalue_dereference_field (gcc_jit_rvalue *ptr, gcc_jit_location *loc, gcc_jit_field *field) gcc_jit_lvalue *gcc_jit_rvalue_dereference (gcc_jit_rvalue *rvalue, gcc_jit_location *loc) gcc_jit_rvalue *gcc_jit_lvalue_get_address (gcc_jit_lvalue *lvalue, gcc_jit_location *loc) gcc_jit_lvalue *gcc_jit_function_new_local (gcc_jit_function *func, gcc_jit_location *loc, gcc_jit_type *type, char *name) # # Statement-creation. # void gcc_jit_block_add_eval (gcc_jit_block *block, gcc_jit_location *loc, gcc_jit_rvalue *rvalue) void gcc_jit_block_add_assignment (gcc_jit_block *block, gcc_jit_location *loc, gcc_jit_lvalue *lvalue, gcc_jit_rvalue *rvalue) void gcc_jit_block_add_assignment_op (gcc_jit_block *block, gcc_jit_location *loc, gcc_jit_lvalue *lvalue, gcc_jit_binary_op op, gcc_jit_rvalue *rvalue) void gcc_jit_block_add_comment (gcc_jit_block *block, gcc_jit_location *loc, char *text) void gcc_jit_block_end_with_conditional (gcc_jit_block *block, gcc_jit_location *loc, gcc_jit_rvalue *boolval, gcc_jit_block *on_true, gcc_jit_block *on_false) void gcc_jit_block_end_with_jump (gcc_jit_block *block, gcc_jit_location *loc, gcc_jit_block *target) void gcc_jit_block_end_with_return (gcc_jit_block *block, gcc_jit_location *loc, gcc_jit_rvalue *rvalue) void gcc_jit_block_end_with_void_return (gcc_jit_block *block, gcc_jit_location *loc) # # Nested contexts. # gcc_jit_context *gcc_jit_context_new_child_context (gcc_jit_context *parent_ctxt) void gcc_jit_context_dump_reproducer_to_file (gcc_jit_context *ctxt, const char *path) void gcc_jit_context_set_logfile (gcc_jit_context *ctxt, FILE *logfile, int flags, int verbosity) pygccjit-0.4/gccjit/gccjit.pyx000066400000000000000000001041261250534713700164540ustar00rootroot00000000000000# Copyright 2013-2015 David Malcolm # Copyright 2013-2015 Red Hat, Inc. # Copyright 2014 Simon Feltman # # This is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see # . from libc.stdlib cimport malloc, free cimport gccjit as c_api class Error(Exception): def __init__(self, msg): self.msg = msg cdef class Context: cdef c_api.gcc_jit_context* _c_ctxt def __cinit__(self, acquire=True): if acquire: self._c_ctxt = c_api.gcc_jit_context_acquire() else: self._c_ctxt = NULL def __dealloc__(self): c_api.gcc_jit_context_release(self._c_ctxt) def set_str_option(self, opt, val): """set_int_option(self, opt:StrOption, val:str)""" c_api.gcc_jit_context_set_str_option(self._c_ctxt, opt, val) def set_bool_option(self, opt, val): """set_int_option(self, opt:BoolOption, val:bool)""" c_api.gcc_jit_context_set_bool_option(self._c_ctxt, opt, val) def set_int_option(self, opt, val): """set_int_option(self, opt:IntOption, val:int)""" c_api.gcc_jit_context_set_int_option(self._c_ctxt, opt, val) def get_type(self, type_enum): """get_type(self, type_enum:TypeKind) -> Type""" return Type_from_c(self._c_ctxt, c_api.gcc_jit_context_get_type(self._c_ctxt, type_enum)) def get_int_type(self, num_bytes, is_signed): """get_int_type(self, num_bytes:int, is_signed:bool) -> Type""" return Type_from_c(self._c_ctxt, c_api.gcc_jit_context_get_int_type(self._c_ctxt, num_bytes, is_signed)) def compile(self): """compile(self) -> Result""" cdef c_api.gcc_jit_result *c_result c_result = c_api.gcc_jit_context_compile(self._c_ctxt) if c_result == NULL: raise Error(self.get_first_error()) r = Result() r._set_c_ptr(c_result) return r def compile_to_file(self, kind, path): """compile_to_file(self, OutputKind:kind, path) -> None""" c_api.gcc_jit_context_compile_to_file(self._c_ctxt, kind, path) def dump_to_file(self, path, update_locations): c_api.gcc_jit_context_dump_to_file(self._c_ctxt, path, update_locations) def get_first_error(self): cdef char *err = c_api.gcc_jit_context_get_first_error(self._c_ctxt) if err: return err return None def get_last_error(self): cdef char *err = c_api.gcc_jit_context_get_last_error(self._c_ctxt) if err: return err return None def dump_reproducer_to_file(self, path): c_api.gcc_jit_context_dump_reproducer_to_file(self._c_ctxt, path) def set_logfile(self, f): cdef c_api.FILE *c_fileptr = c_api.fdopen(f.fileno(), "w") c_api.gcc_jit_context_set_logfile(self._c_ctxt, c_fileptr, 0, 0) # FIXME: no good way to clean this up, beyond a flag # for the context to take ownership of the FILE *. def new_location(self, filename, line, column): """new_location(self, filename:str, line:int, column:int) -> Location""" cdef c_api.gcc_jit_location *c_loc c_loc = c_api.gcc_jit_context_new_location(self._c_ctxt, filename, line, column) loc = Location() loc._set_c_location(c_loc) return loc def new_global(self, kind, Type type_, name, Location loc=None): """new_global(self, kind:GlobalKind, type_:Type, name:str, loc:Location=None) -> LValue""" c_lvalue = c_api.gcc_jit_context_new_global(self._c_ctxt, get_c_location(loc), kind, type_._get_c_type(), name) return LValue_from_c(self._c_ctxt, c_lvalue) def new_array_type(self, Type element_type, int num_elements, Location loc=None): """new_array_type(self, element_type:Type, num_elements:int, loc:Location=None) -> Type""" c_type = c_api.gcc_jit_context_new_array_type(self._c_ctxt, get_c_location(loc), element_type._get_c_type(), num_elements) return Type_from_c(self._c_ctxt, c_type) def new_field(self, Type type_, name, Location loc=None): """new_field(self, type_:Type, name:str, loc:Location=None) -> Field""" c_field = c_api.gcc_jit_context_new_field(self._c_ctxt, get_c_location(loc), type_._get_c_type(), name) field = Field() field._set_c_field(c_field) return field def new_struct(self, name, fields=None, Location loc=None): """new_struct(self, name:str, fields:list, loc:Location=None) -> Struct""" cdef int num_fields cdef c_api.gcc_jit_field **c_fields = NULL cdef Field field cdef c_api.gcc_jit_struct *c_struct if fields is None: c_struct = c_api.gcc_jit_context_new_opaque_struct(self._c_ctxt, get_c_location(loc), name) else: fields = list(fields) num_fields = len(fields) c_fields = \ malloc(num_fields * sizeof(c_api.gcc_jit_field *)) if c_fields is NULL: raise MemoryError() for i in range(num_fields): field = fields[i] c_fields[i] = field._get_c_field() c_struct = c_api.gcc_jit_context_new_struct_type(self._c_ctxt, get_c_location(loc), name, num_fields, c_fields) py_struct = Struct() py_struct._set_c_struct(c_struct) free(c_fields) return py_struct def new_union(self, name, fields=None, Location loc=None): """new_union(self, name:str, fields:list, loc:Location=None) -> Type""" cdef int num_fields cdef c_api.gcc_jit_field **c_fields = NULL cdef Field field cdef c_api.gcc_jit_type *c_type fields = list(fields) num_fields = len(fields) c_fields = \ malloc(num_fields * sizeof(c_api.gcc_jit_field *)) if c_fields is NULL: raise MemoryError() for i in range(num_fields): field = fields[i] c_fields[i] = field._get_c_field() c_type = c_api.gcc_jit_context_new_union_type(self._c_ctxt, get_c_location(loc), name, num_fields, c_fields) py_type = Type() py_type._set_c_type(c_type) free(c_fields) return py_type def new_function_ptr_type(self, Type return_type, param_types, Location loc=None, is_variadic=False): """new_function_ptr_type(self, return_type:Type, param_types:list, loc:Location=None, is_variadic=False) -> Type""" cdef int num_params cdef c_api.gcc_jit_type **c_param_types = NULL cdef Type type_ cdef c_api.gcc_jit_type *c_fn_ptr_type param_types = list(param_types) num_params = len(param_types) c_param_types = \ malloc(num_params * sizeof(c_api.gcc_jit_type *)) if c_param_types is NULL: raise MemoryError() for i in range(num_params): type_ = param_types[i] c_param_types[i] = type_._get_c_type() c_fn_ptr_type = c_api.gcc_jit_context_new_function_ptr_type (self._c_ctxt, get_c_location(loc), return_type._get_c_type(), num_params, c_param_types, is_variadic) py_type = Type() py_type._set_c_type(c_fn_ptr_type) free(c_param_types) return py_type def new_param(self, Type type_, name, Location loc=None): """new_param(self, type_:Type, name:str, loc:Location=None) -> Param""" c_result = c_api.gcc_jit_context_new_param(self._c_ctxt, get_c_location(loc), type_._get_c_type(), name) return Param_from_c(self._c_ctxt, c_result) def new_function(self, kind, Type return_type, name, params, Location loc=None, is_variadic=False): """new_function(self, kind:FunctionKind, return_type:Type, name:str, params:list, loc:Location=None, is_variadic=False) -> Function""" cdef Param param params = list(params) cdef int num_params = len(params) cdef c_api.gcc_jit_param **c_params = \ malloc(num_params * sizeof(c_api.gcc_jit_param *)) if c_params is NULL: raise MemoryError() for i in range(num_params): param = params[i] c_params[i] = param._get_c_param() c_function = c_api.gcc_jit_context_new_function(self._c_ctxt, get_c_location(loc), kind, return_type._get_c_type(), name, len(params), c_params, is_variadic) free(c_params) return Function_from_c(self._c_ctxt, c_function) def get_builtin_function(self, name): """get_builtin_function(self, name:str) -> Function""" c_function = c_api.gcc_jit_context_get_builtin_function (self._c_ctxt, name) return Function_from_c(self._c_ctxt, c_function) def zero(self, Type type_): """zero(self, type_:Type) -> RValue""" c_rvalue = c_api.gcc_jit_context_zero(self._c_ctxt, type_._get_c_type()) return RValue_from_c(self._c_ctxt, c_rvalue) def one(self, Type type_): """one(self, type_:Type) -> RValue""" c_rvalue = c_api.gcc_jit_context_one(self._c_ctxt, type_._get_c_type()) return RValue_from_c(self._c_ctxt, c_rvalue) def new_rvalue_from_double(self, Type numeric_type, double value): """new_rvalue_from_double(self, numeric_type:Type, value:float) -> RValue""" c_rvalue = c_api.gcc_jit_context_new_rvalue_from_double(self._c_ctxt, numeric_type._get_c_type(), value) return RValue_from_c(self._c_ctxt, c_rvalue) def new_rvalue_from_int(self, Type type_, int value): """new_rvalue_from_int(self, type_:Type, value:int) -> RValue""" c_rvalue = c_api.gcc_jit_context_new_rvalue_from_int(self._c_ctxt, type_._get_c_type(), value) return RValue_from_c(self._c_ctxt, c_rvalue) def new_rvalue_from_ptr(self, Type pointer_type, long value): c_rvalue = c_api.gcc_jit_context_new_rvalue_from_ptr(self._c_ctxt, pointer_type._get_c_type(), value) return RValue_from_c(self._c_ctxt, c_rvalue) def null(self, Type pointer_type): """null(self, pointer_type:Type) -> RValue""" c_rvalue = c_api.gcc_jit_context_null(self._c_ctxt, pointer_type._get_c_type()) return RValue_from_c(self._c_ctxt, c_rvalue) def new_string_literal(self, char *value): """new_string_literal(self, value:str) -> RValue""" c_rvalue = c_api.gcc_jit_context_new_string_literal(self._c_ctxt, value) return RValue_from_c(self._c_ctxt, c_rvalue) def new_unary_op(self, op, Type result_type, RValue rvalue, Location loc=None): """new_unary_op(self, op:UnaryOp, result_type:Type, rvalue:RValue, loc:Location=None) -> RValue""" c_rvalue = c_api.gcc_jit_context_new_unary_op (self._c_ctxt, get_c_location(loc), op, result_type._get_c_type(), rvalue._get_c_rvalue()) return RValue_from_c(self._c_ctxt, c_rvalue) def new_binary_op(self, op, Type result_type, RValue a, RValue b, Location loc=None): """new_binary_op(self, op:BinaryOp, result_type:Type, a:RValue, b:RValue, loc:Location=None) -> RValue""" c_rvalue = c_api.gcc_jit_context_new_binary_op(self._c_ctxt, get_c_location(loc), op, result_type._get_c_type(), a._get_c_rvalue(), b._get_c_rvalue()) return RValue_from_c(self._c_ctxt, c_rvalue) def new_comparison(self, op, RValue a, RValue b, Location loc=None): """new_comparison(self, op:Comparison, a:RValue, b:RValue, loc:Location=None) -> RValue""" c_rvalue = c_api.gcc_jit_context_new_comparison(self._c_ctxt, get_c_location(loc), op, a._get_c_rvalue(), b._get_c_rvalue()) return RValue_from_c(self._c_ctxt, c_rvalue) def new_child_context(self): """new_child_context(self) -> Context""" c_child_ctxt = c_api.gcc_jit_context_new_child_context(self._c_ctxt) if c_child_ctxt == NULL: raise Exception("Unknown error creating child context.") py_child_ctxt = Context(acquire=False) py_child_ctxt._c_ctxt = c_child_ctxt return py_child_ctxt def new_cast(self, RValue rvalue, Type type_, Location loc=None): """new_cast(self, rvalue:RValue, type_:Type, loc:Location=None) -> RValue""" c_rvalue = c_api.gcc_jit_context_new_cast(self._c_ctxt, get_c_location(loc), rvalue._get_c_rvalue(), type_._get_c_type()) return RValue_from_c(self._c_ctxt, c_rvalue) def new_array_access(self, RValue ptr, RValue index, Location loc=None): """new_array_access(self, ptr:RValue, index:RValue, loc:Location=None) -> LValue""" c_lvalue = c_api.gcc_jit_context_new_array_access(self._c_ctxt, get_c_location(loc), ptr._get_c_rvalue(), index._get_c_rvalue()) return LValue_from_c(self._c_ctxt, c_lvalue) def new_call(self, Function func, args, Location loc=None): """new_call(self, func:Function, args:list of RValue, loc:Location=None) -> RValue""" args = list(args) cdef int num_args = len(args) cdef c_api.gcc_jit_rvalue **c_args = \ malloc(num_args * sizeof(c_api.gcc_jit_rvalue *)) if c_args is NULL: raise MemoryError() cdef RValue rvalue for i in range(num_args): rvalue = args[i] c_args[i] = rvalue._get_c_rvalue() c_rvalue = c_api.gcc_jit_context_new_call(self._c_ctxt, get_c_location(loc), func._get_c_function(), num_args, c_args) free(c_args) return RValue_from_c(self._c_ctxt, c_rvalue) def new_call_through_ptr(self, RValue fn_ptr, args, Location loc=None): """new_call(self, fn_ptr:RValue, args:list of RValue, loc:Location=None) -> RValue""" args = list(args) cdef int num_args = len(args) cdef c_api.gcc_jit_rvalue **c_args = \ malloc(num_args * sizeof(c_api.gcc_jit_rvalue *)) if c_args is NULL: raise MemoryError() cdef RValue rvalue for i in range(num_args): rvalue = args[i] c_args[i] = rvalue._get_c_rvalue() c_rvalue = c_api.gcc_jit_context_new_call_through_ptr(self._c_ctxt, get_c_location(loc), fn_ptr._get_c_rvalue(), num_args, c_args) free(c_args) return RValue_from_c(self._c_ctxt, c_rvalue) cdef class Result: cdef c_api.gcc_jit_result* _c_result def __cinit__(self): self._c_result = NULL def __dealloc__(self): c_api.gcc_jit_result_release(self._c_result) cdef _set_c_ptr(self, c_api.gcc_jit_result* c_result): self._c_result = c_result def get_code(self, funcname): cdef void *ptr = c_api.gcc_jit_result_get_code(self._c_result, funcname) return ptr cdef class Object: cdef c_api.gcc_jit_object *_c_object def __cinit__(self): self._c_object = NULL def __str__(self): if self._c_object: # Require UTF-8 encoding for now return c_api.gcc_jit_object_get_debug_string(self._c_object).decode('utf-8') else: return 'NULL' def __richcmp__(Object self, Object other, int op): if op == 2: # == return self._c_object == other._c_object elif op == 3: # != return self._c_object != other._c_object cdef c_api.gcc_jit_context* _get_c_context(self): return c_api.gcc_jit_object_get_context(self._c_object) cdef class Type(Object): cdef c_api.gcc_jit_type* _get_c_type(self): return self._c_object cdef _set_c_type(self, c_api.gcc_jit_type* c_type): self._c_object = c_type def get_pointer(self): """get_pointer(self) -> Type""" return Type_from_c(self._get_c_context(), c_api.gcc_jit_type_get_pointer(self._get_c_type())) def get_const(self): """get_const(self) -> Type""" return Type_from_c(self._get_c_context(), c_api.gcc_jit_type_get_const(self._get_c_type())) def get_volatile(self): """get_volatile(self) -> Type""" return Type_from_c(self._get_c_context(), c_api.gcc_jit_type_get_volatile(self._get_c_type())) cdef Type_from_c(c_api.gcc_jit_context *c_ctxt, c_api.gcc_jit_type *c_type): if c_type == NULL: raise Error(c_api.gcc_jit_context_get_last_error(c_ctxt)) t = Type() t._set_c_type(c_type) return t cdef class Location(Object): cdef c_api.gcc_jit_location* _get_c_location(self): return self._c_object cdef _set_c_location(self, c_api.gcc_jit_location* c_location): self._c_object = c_location cdef c_api.gcc_jit_location* get_c_location(Location py_location): """Get a C location pointer given a Python object, handling None.""" if py_location is None: return NULL else: return py_location._get_c_location() cdef class Field(Object): cdef c_api.gcc_jit_field* _get_c_field(self): return self._c_object cdef _set_c_field(self, c_api.gcc_jit_field* c_field): self._c_object = c_field cdef class Struct(Type): cdef c_api.gcc_jit_struct* _get_c_struct(self): return self._c_object cdef _set_c_struct(self, c_api.gcc_jit_struct* c_struct): self._c_object = c_struct def set_fields(self, fields, Location loc=None): """set_fields(self, fields, loc:Location=None) -> None""" fields = list(fields) num_fields = len(fields) c_fields = \ malloc(num_fields * sizeof(c_api.gcc_jit_field *)) cdef Field field if c_fields is NULL: raise MemoryError() for i in range(num_fields): field = fields[i] c_fields[i] = field._get_c_field() c_api.gcc_jit_struct_set_fields(self._get_c_struct(), get_c_location(loc), num_fields, c_fields) free(c_fields) cdef class RValue(Object): cdef c_api.gcc_jit_rvalue* _get_c_rvalue(self): return self._c_object cdef _set_c_rvalue(self, c_api.gcc_jit_rvalue* c_rvalue): self._c_object = c_rvalue def dereference_field(self, Field field, Location loc=None): """dereference_field(self, field:Field, loc:Location=None) -> LValue""" return LValue_from_c(self._get_c_context(), c_api.gcc_jit_rvalue_dereference_field (self._get_c_rvalue(), get_c_location(loc), field._get_c_field())) def dereference(self, loc=None): """dereference(self, loc:Location=None) -> LValue""" return LValue_from_c(self._get_c_context(), c_api.gcc_jit_rvalue_dereference (self._get_c_rvalue(), get_c_location(loc))) def get_type(self): return Type_from_c(self._get_c_context(), c_api.gcc_jit_rvalue_get_type (self._get_c_rvalue())) cdef RValue RValue_from_c(c_api.gcc_jit_context *c_ctxt, c_api.gcc_jit_rvalue *c_rvalue): if c_rvalue == NULL: raise Error(c_api.gcc_jit_context_get_last_error(c_ctxt)) py_rvalue = RValue() py_rvalue._set_c_rvalue(c_rvalue) return py_rvalue cdef class LValue(RValue): cdef c_api.gcc_jit_lvalue* _get_c_lvalue(self): return self._c_object cdef _set_c_lvalue(self, c_api.gcc_jit_lvalue* c_lvalue): self._c_object = c_lvalue def get_address(self, Location loc=None): """get_address(self, loc:Location=None) -> RValue""" return RValue_from_c(self._get_c_context(), c_api.gcc_jit_lvalue_get_address(self._get_c_lvalue(), get_c_location(loc))) cdef LValue LValue_from_c(c_api.gcc_jit_context *c_ctxt, c_api.gcc_jit_lvalue *c_lvalue): if c_lvalue == NULL: raise Error(c_api.gcc_jit_context_get_last_error(c_ctxt)) py_lvalue = LValue() py_lvalue._set_c_lvalue(c_lvalue) return py_lvalue cdef class Param(LValue): cdef c_api.gcc_jit_param* _get_c_param(self): return self._c_object cdef _set_c_param(self, c_api.gcc_jit_param* c_param): self._c_object = c_param cdef Param Param_from_c(c_api.gcc_jit_context *c_ctxt, c_api.gcc_jit_param *c_param): if c_param == NULL: raise Error(c_api.gcc_jit_context_get_last_error(c_ctxt)) p = Param() p._set_c_param(c_param) return p cdef class Function(Object): cdef c_api.gcc_jit_function* _get_c_function(self): return self._c_object cdef _set_c_function(self, c_api.gcc_jit_function* c_function): self._c_object = c_function def new_local(self, Type type_, name, Location loc=None): """new_local(self, type_:Type, name:str, loc:Location=None) -> LValue""" c_lvalue = c_api.gcc_jit_function_new_local(self._get_c_function(), get_c_location(loc), type_._get_c_type(), name) return LValue_from_c(self._get_c_context(), c_lvalue) def new_block(self, name=None): """new_block(self, name:str) -> Block""" cdef char *c_name if name is None: c_name = NULL else: c_name = name c_block = c_api.gcc_jit_function_new_block(self._get_c_function(), c_name) if c_block == NULL: raise Error(c_api.gcc_jit_context_get_last_error(self._get_c_context())) block = Block() block._set_c_block(c_block) return block def get_param(self, index): """get_param(self, index:int) -> Param""" c_param = c_api.gcc_jit_function_get_param (self._get_c_function(), index) return Param_from_c(self._get_c_context(), c_param) def dump_to_dot(self, char *path): """dump_to_dot(self, path:str)""" c_api.gcc_jit_function_dump_to_dot (self._get_c_function(), path) cdef Function Function_from_c(c_api.gcc_jit_context *c_ctxt, c_api.gcc_jit_function *c_function): if c_function == NULL: raise Error(c_api.gcc_jit_context_get_last_error(c_ctxt)) f = Function() f._set_c_function(c_function) return f cdef class Block(Object): cdef c_api.gcc_jit_block* _get_c_block(self): return self._c_object cdef _set_c_block(self, c_api.gcc_jit_block* c_block): self._c_object = c_block def add_eval(self, RValue rvalue, Location loc=None): """add_eval(self, rvalue:RValue, loc:Location=None)""" c_api.gcc_jit_block_add_eval(self._get_c_block(), get_c_location(loc), rvalue._get_c_rvalue()) def add_assignment(self, LValue lvalue, RValue rvalue, Location loc=None): """add_assignment(self, lvalue:LValue, rvalue:RValue, loc:Location=None)""" c_api.gcc_jit_block_add_assignment(self._get_c_block(), get_c_location(loc), lvalue._get_c_lvalue(), rvalue._get_c_rvalue()) def add_assignment_op(self, LValue lvalue, op, RValue rvalue, Location loc=None): """add_assignment(self, lvalue:LValue, op:BinaryOp, rvalue:RValue, loc:Location=None)""" c_api.gcc_jit_block_add_assignment_op(self._get_c_block(), get_c_location(loc), lvalue._get_c_lvalue(), op, rvalue._get_c_rvalue()) def add_comment(self, text, Location loc=None): """add_comment(self, text:str, loc:Location=None)""" c_api.gcc_jit_block_add_comment (self._get_c_block(), get_c_location(loc), text) def end_with_conditional(self, RValue boolval, Block on_true, Block on_false=None, Location loc=None): """end_with_conditional(self, on_true:Block, on_false:Block=None, loc:Location=None)""" c_api.gcc_jit_block_end_with_conditional(self._get_c_block(), get_c_location(loc), boolval._get_c_rvalue(), on_true._get_c_block(), on_false._get_c_block() if on_false else NULL) def end_with_jump(self, Block target, Location loc=None): """end_with_jump(self, target:Block, loc:Location=None)""" c_api.gcc_jit_block_end_with_jump(self._get_c_block(), get_c_location(loc), target._get_c_block()) def end_with_return(self, RValue rvalue, loc=None): """end_with_return(self, rvalue:RValue, loc:Location=None)""" c_api.gcc_jit_block_end_with_return(self._get_c_block(), get_c_location(loc), rvalue._get_c_rvalue()) def end_with_void_return(self, loc=None): """end_with_void_return(self, loc:Location=None)""" c_api.gcc_jit_block_end_with_void_return(self._get_c_block(), get_c_location(loc)) def get_function(self): """get_function(self) -> Function""" c_function = c_api.gcc_jit_block_get_function (self._get_c_block()) return Function_from_c(self._get_c_context(), c_function) cdef class FunctionKind: EXPORTED = c_api.GCC_JIT_FUNCTION_EXPORTED INTERNAL = c_api.GCC_JIT_FUNCTION_INTERNAL IMPORTED = c_api.GCC_JIT_FUNCTION_IMPORTED ALWAYS_INLINE = c_api.GCC_JIT_FUNCTION_ALWAYS_INLINE cdef class UnaryOp: MINUS = c_api.GCC_JIT_UNARY_OP_MINUS BITWISE_NEGATE = c_api.GCC_JIT_UNARY_OP_BITWISE_NEGATE LOGICAL_NEGATE = c_api.GCC_JIT_UNARY_OP_LOGICAL_NEGATE ABS = c_api.GCC_JIT_UNARY_OP_ABS cdef class BinaryOp: PLUS = c_api.GCC_JIT_BINARY_OP_PLUS MINUS = c_api.GCC_JIT_BINARY_OP_MINUS MULT = c_api.GCC_JIT_BINARY_OP_MULT DIVIDE = c_api.GCC_JIT_BINARY_OP_DIVIDE MODULO = c_api.GCC_JIT_BINARY_OP_MODULO BITWISE_AND = c_api.GCC_JIT_BINARY_OP_BITWISE_AND BITWISE_XOR = c_api.GCC_JIT_BINARY_OP_BITWISE_XOR BITWISE_OR = c_api.GCC_JIT_BINARY_OP_BITWISE_OR LOGICAL_AND = c_api.GCC_JIT_BINARY_OP_LOGICAL_AND LOGICAL_OR = c_api.GCC_JIT_BINARY_OP_LOGICAL_OR cdef class Comparison: EQ = c_api.GCC_JIT_COMPARISON_EQ NE = c_api.GCC_JIT_COMPARISON_NE LT = c_api.GCC_JIT_COMPARISON_LT LE = c_api.GCC_JIT_COMPARISON_LE GT = c_api.GCC_JIT_COMPARISON_GT GE = c_api.GCC_JIT_COMPARISON_GE cdef class StrOption: PROGNAME = c_api.GCC_JIT_STR_OPTION_PROGNAME cdef class IntOption: OPTIMIZATION_LEVEL = c_api.GCC_JIT_INT_OPTION_OPTIMIZATION_LEVEL cdef class BoolOption: DEBUGINFO = c_api.GCC_JIT_BOOL_OPTION_DEBUGINFO DUMP_INITIAL_TREE = c_api.GCC_JIT_BOOL_OPTION_DUMP_INITIAL_TREE DUMP_INITIAL_GIMPLE = c_api.GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE DUMP_GENERATED_CODE = c_api.GCC_JIT_BOOL_OPTION_DUMP_GENERATED_CODE DUMP_SUMMARY = c_api.GCC_JIT_BOOL_OPTION_DUMP_SUMMARY DUMP_EVERYTHING = c_api.GCC_JIT_BOOL_OPTION_DUMP_EVERYTHING SELFCHECK_GC = c_api.GCC_JIT_BOOL_OPTION_SELFCHECK_GC KEEP_INTERMEDIATES = c_api.GCC_JIT_BOOL_OPTION_KEEP_INTERMEDIATES cdef class OutputKind: ASSEMBLER = c_api.GCC_JIT_OUTPUT_KIND_ASSEMBLER OBJECT_FILE = c_api.GCC_JIT_OUTPUT_KIND_OBJECT_FILE DYNAMIC_LIBRARY = c_api.GCC_JIT_OUTPUT_KIND_DYNAMIC_LIBRARY EXECUTABLE = c_api.GCC_JIT_OUTPUT_KIND_EXECUTABLE cdef class TypeKind: VOID = c_api.GCC_JIT_TYPE_VOID VOID_PTR = c_api.GCC_JIT_TYPE_VOID_PTR BOOL = c_api.GCC_JIT_TYPE_BOOL CHAR = c_api.GCC_JIT_TYPE_CHAR SIGNED_CHAR = c_api.GCC_JIT_TYPE_SIGNED_CHAR UNSIGNED_CHAR = c_api.GCC_JIT_TYPE_UNSIGNED_CHAR SHORT = c_api.GCC_JIT_TYPE_SHORT UNSIGNED_SHORT = c_api.GCC_JIT_TYPE_UNSIGNED_SHORT INT = c_api.GCC_JIT_TYPE_INT UNSIGNED_INT = c_api.GCC_JIT_TYPE_UNSIGNED_INT LONG = c_api.GCC_JIT_TYPE_LONG UNSIGNED_LONG = c_api.GCC_JIT_TYPE_UNSIGNED_LONG LONG_LONG = c_api.GCC_JIT_TYPE_LONG_LONG UNSIGNED_LONG_LONG = c_api.GCC_JIT_TYPE_UNSIGNED_LONG_LONG FLOAT = c_api.GCC_JIT_TYPE_FLOAT DOUBLE = c_api.GCC_JIT_TYPE_DOUBLE LONG_DOUBLE = c_api.GCC_JIT_TYPE_LONG_DOUBLE CONST_CHAR_PTR = c_api.GCC_JIT_TYPE_CONST_CHAR_PTR SIZE_T = c_api.GCC_JIT_TYPE_SIZE_T FILE_PTR = c_api.GCC_JIT_TYPE_FILE_PTR cdef class GlobalKind: EXPORTED = c_api.GCC_JIT_GLOBAL_EXPORTED INTERNAL = c_api.GCC_JIT_GLOBAL_INTERNAL IMPORTED = c_api.GCC_JIT_GLOBAL_IMPORTED pygccjit-0.4/setup.py000066400000000000000000000030141250534713700147100ustar00rootroot00000000000000"""Python bindings for libgccjit""" # Attempt using setuptools which supports the "tests" target. try: from setuptools import setup from distutils.extension import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext doclines = __doc__.split("\n") classifiers = """\ Development Status :: 3 - Alpha Intended Audience :: Developers License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+) Programming Language :: Python Topic :: Software Development :: Libraries :: Python Modules Operating System :: Unix Programming Language :: Python :: 2 Programming Language :: Python :: 3 """ setup( name='gccjit', version='0.4', author="David Malcolm", author_email="jit@gcc.gnu.org", url="https://github.com/davidmalcolm/pygccjit", packages=['gccjit',], license='GPL v3', description = doclines[0], classifiers = filter(None, classifiers.split("\n")), cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("gccjit._gccjit", ["gccjit/gccjit.pyx"], libraries=["gccjit"], # Hacks for ease of hacking on this: #include_dirs = ['/home/david/coding/gcc-python/gcc-git-jit-clean/src/gcc/jit'], #library_dirs=["/home/david/coding/gcc-python/gcc-git-jit-clean/build/gcc/"], )], test_suite='tests', test_loader='tests:TestLoader', ) pygccjit-0.4/tests/000077500000000000000000000000001250534713700143425ustar00rootroot00000000000000pygccjit-0.4/tests/__init__.py000066400000000000000000000003431250534713700164530ustar00rootroot00000000000000 import unittest class TestLoader(unittest.TestLoader): def loadTestsFromName(self, name, module=None): if '.' in name: return super().loadTestsFromName(name, module) return self.discover(name) pygccjit-0.4/tests/test.py000066400000000000000000000211551250534713700156770ustar00rootroot00000000000000# Copyright 2013-2015 David Malcolm # Copyright 2013-2015 Red Hat, Inc. # # This is free software: you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see # . import ctypes import os import tempfile import unittest import gccjit int_int_func_type = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) class JitTests(unittest.TestCase): def test_square(self): from examples.square import test_calling_fn for i in range(5): self.assertEqual(test_calling_fn(i), i * i) def test_sum_of_squares(self): from examples.sum_of_squares import test_calling_fn for i in range(5): self.assertEqual(test_calling_fn(i), sum([j * j for j in range(i)])) def test_imported_function(self): """ void some_fn (const char *name) { static char buffer[1024]; snprintf(buffer, sizeof(buffer), "hello %s\n", name); } """ ctxt = gccjit.Context() void_type = ctxt.get_type(gccjit.TypeKind.VOID) const_char_p = ctxt.get_type(gccjit.TypeKind.CONST_CHAR_PTR) char_type = ctxt.get_type(gccjit.TypeKind.CHAR) char_p = char_type.get_pointer() int_type = ctxt.get_type(gccjit.TypeKind.INT) size_type = ctxt.get_type(gccjit.TypeKind.SIZE_T) buf_type = ctxt.new_array_type(char_type, 1024) # extern int snprintf(char *str, size_t size, const char *format, ...); snprintf = ctxt.new_function(gccjit.FunctionKind.IMPORTED, int_type, b'snprintf', [ctxt.new_param(char_p, b's'), ctxt.new_param(size_type, b'n'), ctxt.new_param(const_char_p, b'format')], is_variadic=True) # void some_fn (const char *name) { param_name = ctxt.new_param(const_char_p, b'name') func = ctxt.new_function(gccjit.FunctionKind.EXPORTED, void_type, b'some_fn', [param_name]) # static char buffer[1024]; buffer = func.new_local(buf_type, b'buffer') # snprintf(buffer, sizeof(buffer), "hello %s\n", name); args = [ctxt.new_cast(buffer.get_address(), char_p), ctxt.new_rvalue_from_int(size_type, 1024), ctxt.new_string_literal(b'hello %s\n'), param_name] block = func.new_block(b'entry') call = ctxt.new_call(snprintf, args) self.assertEqual(call.get_type(), int_type) block.add_eval(call) block.end_with_void_return() result = ctxt.compile() py_func_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p) py_func = py_func_type(result.get_code(b'some_fn')) py_func(b'blah') def test_opaque_struct(self): ctxt = gccjit.Context() foo = ctxt.new_struct(b'foo') foo_ptr = foo.get_pointer() self.assertEqual(str(foo_ptr), 'struct foo *') foo.set_fields([ctxt.new_field(foo_ptr, b'prev'), ctxt.new_field(foo_ptr, b'next')]) def test_rvalue_from_ptr(self): ctxt = gccjit.Context() type_ = ctxt.get_type(gccjit.TypeKind.CONST_CHAR_PTR) null_ptr = ctxt.new_rvalue_from_ptr(type_, 0) self.assertEqual(str(null_ptr), '(const char *)NULL') type_ = ctxt.get_type(gccjit.TypeKind.VOID_PTR) nonnull_ptr = ctxt.new_rvalue_from_ptr(type_, id(self)) self.assertEqual(str(nonnull_ptr), '(void *)0x%x' % id(self)) def test_dereference(self): ctxt = gccjit.Context() type_ = ctxt.get_type(gccjit.TypeKind.CONST_CHAR_PTR) nonnull_ptr = ctxt.new_rvalue_from_ptr(type_, id(self)) self.assertEqual(str(nonnull_ptr.dereference()), '*(const char *)0x%x' % id(self)) def test_call_through_function_ptr(self): ctxt = gccjit.Context() void_type = ctxt.get_type(gccjit.TypeKind.VOID) int_type = ctxt.get_type(gccjit.TypeKind.INT) fn_ptr_type = ctxt.new_function_ptr_type (void_type, [int_type, int_type, int_type]) self.assertEqual(str(fn_ptr_type), 'void (*) (int, int, int)') fn_ptr = ctxt.new_param(fn_ptr_type, b"fn") a = ctxt.new_param(int_type, b"a") b = ctxt.new_param(int_type, b"b") c = ctxt.new_param(int_type, b"c") call = ctxt.new_call_through_ptr(fn_ptr, [a, b, c]) self.assertEqual(str(call), 'fn (a, b, c)') def test_union(self): ctxt = gccjit.Context() int_type = ctxt.get_type(gccjit.TypeKind.INT) float_type = ctxt.get_type(gccjit.TypeKind.FLOAT) as_int = ctxt.new_field(int_type, b'as_int') as_float = ctxt.new_field(float_type, b'as_float') u = ctxt.new_union(b'u', [as_int, as_float]) self.assertEqual(str(u), 'union u') def test_bf_aot(self): from examples import bf from subprocess import Popen, PIPE c = bf.Compiler() c.parse_into_ctxt(b'examples/emit-alphabet.bf') c.compile_to_file(b'emit-alphabet.exe') p = Popen(b'./emit-alphabet.exe', stdout=PIPE) out, err = p.communicate() self.assertEqual(out, b'ABCDEFGHIJKLMNOPQRSTUVWXYZ') def test_bf_jit(self): from examples import bf c = bf.Compiler() c.parse_into_ctxt(b'examples/emit-alphabet.bf') c.run() def test_dump_reproducer(self): from examples.sum_of_squares import populate_ctxt ctxt = gccjit.Context() populate_ctxt(ctxt) with tempfile.NamedTemporaryFile(delete=False, suffix=".c") as f: ctxt.dump_reproducer_to_file(f.name.encode('utf-8')) try: with open(f.name) as f: gensrc = f.read() self.assertIn('#include ', gensrc) finally: os.unlink(f.name) def test_set_logfile(self): from examples.sum_of_squares import populate_ctxt ctxt = gccjit.Context() with tempfile.NamedTemporaryFile(suffix=".txt") as f: ctxt.set_logfile(f) populate_ctxt(ctxt) ctxt.compile() with open(f.name) as f: logtxt = f.read() self.assertIn('JIT: ', logtxt) self.assertIn('entering: gcc_jit_context_get_type', logtxt) class ErrorTests(unittest.TestCase): def test_get_type_error(self): ctxt = gccjit.Context() with self.assertRaises(gccjit.Error) as cm: ctxt.get_type(-1) self.assertEqual(cm.exception.msg, (b'gcc_jit_context_get_type:' b' unrecognized value for enum gcc_jit_types: -1')) def test_new_function_error(self): ctxt = gccjit.Context() int_type = ctxt.get_type(gccjit.TypeKind.INT) with self.assertRaises(gccjit.Error) as cm: ctxt.new_function(gccjit.FunctionKind.IMPORTED, int_type, b"contains a space", []) self.assertEqual(cm.exception.msg, (b'gcc_jit_context_new_function:' b' name "contains a space" contains invalid character:' b" ' '")) def test_new_block_error(self): ctxt = gccjit.Context() int_type = ctxt.get_type(gccjit.TypeKind.INT) func = ctxt.new_function(gccjit.FunctionKind.IMPORTED, int_type, b"foo", []) with self.assertRaises(gccjit.Error) as cm: func.new_block() self.assertEqual(cm.exception.msg, (b'gcc_jit_function_new_block:' b' cannot add block to an imported function')) if __name__ == '__main__': unittest.main()