From a0482fa4e7fa27b01184f938097f0666b78016dd Mon Sep 17 00:00:00 2001 From: Dimitry Andric Date: Thu, 16 Sep 2010 21:14:28 +0000 Subject: [PATCH] Make vendor/clang/dist exactly the same as upstream's r108428. Some files and directories were already added/removed in the upstream repository, but were not added/removed here, when the previous snapshot was imported. Note: I did not import the file test/Lexer/conflict-marker.c, because it contains merge conflict markers on purpose, which upsets our pre-commit hooks. Approved by: rpaulo (mentor) --- VER | 1 - docs/BlockImplementation.txt | 647 ----- include/clang/AST/DeclNodes.def | 165 -- include/clang/AST/StmtNodes.def | 165 -- lib/Headers/arm_neon.h | 537 ---- lib/Headers/arm_neon.td | 341 --- tools/CIndex/CIndex.cpp | 2589 -------------------- tools/CIndex/CIndex.darwin.exports | 81 - tools/CIndex/CIndex.exports | 81 - tools/CIndex/CIndexCodeCompletion.cpp | 512 ---- tools/CIndex/CIndexDiagnostic.cpp | 285 --- tools/CIndex/CIndexDiagnostic.h | 53 - tools/CIndex/CIndexInclusionStack.cpp | 67 - tools/CIndex/CIndexUSRs.cpp | 469 ---- tools/CIndex/CIndexer.cpp | 154 -- tools/CIndex/CIndexer.h | 78 - tools/CIndex/CMakeLists.txt | 56 - tools/CIndex/CXCursor.cpp | 369 --- tools/CIndex/CXCursor.h | 112 - tools/CIndex/CXSourceLocation.h | 75 - tools/CIndex/Makefile | 55 - tools/index-test/CMakeLists.txt | 23 - tools/index-test/Makefile | 25 - tools/index-test/index-test.cpp | 334 --- utils/pch-test.pl | 61 - win32/clangAST/clangAST.vcproj | 347 --- win32/clangAnalysis/clangAnalysis.vcproj | 351 --- win32/clangBasic/clangBasic.vcproj | 236 -- win32/clangCodeGen/clangCodeGen.vcproj | 271 -- win32/clangDriver/clangDriver.vcproj | 270 -- win32/clangLex/clangLex.vcproj | 283 --- win32/clangLibDriver/clangLibDriver.vcproj | 205 -- win32/clangParse/clangParse.vcproj | 248 -- win32/clangRewrite/clangRewrite.vcproj | 191 -- win32/clangSema/clangSema.vcproj | 263 -- www/analyzer/menu.js | 17 - 36 files changed, 10017 deletions(-) delete mode 100644 VER delete mode 100644 docs/BlockImplementation.txt delete mode 100644 include/clang/AST/DeclNodes.def delete mode 100644 include/clang/AST/StmtNodes.def delete mode 100644 lib/Headers/arm_neon.h delete mode 100644 lib/Headers/arm_neon.td delete mode 100644 tools/CIndex/CIndex.cpp delete mode 100644 tools/CIndex/CIndex.darwin.exports delete mode 100644 tools/CIndex/CIndex.exports delete mode 100644 tools/CIndex/CIndexCodeCompletion.cpp delete mode 100644 tools/CIndex/CIndexDiagnostic.cpp delete mode 100644 tools/CIndex/CIndexDiagnostic.h delete mode 100644 tools/CIndex/CIndexInclusionStack.cpp delete mode 100644 tools/CIndex/CIndexUSRs.cpp delete mode 100644 tools/CIndex/CIndexer.cpp delete mode 100644 tools/CIndex/CIndexer.h delete mode 100644 tools/CIndex/CMakeLists.txt delete mode 100644 tools/CIndex/CXCursor.cpp delete mode 100644 tools/CIndex/CXCursor.h delete mode 100644 tools/CIndex/CXSourceLocation.h delete mode 100644 tools/CIndex/Makefile delete mode 100644 tools/index-test/CMakeLists.txt delete mode 100644 tools/index-test/Makefile delete mode 100644 tools/index-test/index-test.cpp delete mode 100755 utils/pch-test.pl delete mode 100644 win32/clangAST/clangAST.vcproj delete mode 100644 win32/clangAnalysis/clangAnalysis.vcproj delete mode 100644 win32/clangBasic/clangBasic.vcproj delete mode 100644 win32/clangCodeGen/clangCodeGen.vcproj delete mode 100644 win32/clangDriver/clangDriver.vcproj delete mode 100644 win32/clangLex/clangLex.vcproj delete mode 100644 win32/clangLibDriver/clangLibDriver.vcproj delete mode 100644 win32/clangParse/clangParse.vcproj delete mode 100644 win32/clangRewrite/clangRewrite.vcproj delete mode 100644 win32/clangSema/clangSema.vcproj delete mode 100644 www/analyzer/menu.js diff --git a/VER b/VER deleted file mode 100644 index cd5ac039d67e..000000000000 --- a/VER +++ /dev/null @@ -1 +0,0 @@ -2.0 diff --git a/docs/BlockImplementation.txt b/docs/BlockImplementation.txt deleted file mode 100644 index c420455979cf..000000000000 --- a/docs/BlockImplementation.txt +++ /dev/null @@ -1,647 +0,0 @@ -Block Implementation Specification - -Copyright 2008-2009 Apple, Inc. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -0. History - -2008/7/14 - created -2008/8/21 - revised, C++ -2008/9/24 - add NULL isa field to __block storage -2008/10/1 - revise block layout to use a static descriptor structure -2008/10/6 - revise block layout to use an unsigned long int flags -2008/10/28 - specify use of _Block_object_assign/dispose for all "Object" types in helper functions -2008/10/30 - revise new layout to have invoke function in same place -2008/10/30 - add __weak support - -This document describes the Apple ABI implementation specification of Blocks. - -1. High Level - -A Block consists of a structure of the following form: - -struct Block_literal_1 { - void *isa; // initialized to &_NSConcreteStackBlock or &_NSConcreteGlobalBlock - int flags; - int reserved; - void (*invoke)(void *, ...); - struct Block_descriptor_1 { - unsigned long int reserved; // NULL - unsigned long int size; // sizeof(struct Block_literal_1) - // optional helper functions - void (*copy_helper)(void *dst, void *src); - void (*dispose_helper)(void *src); - } *descriptor; - // imported variables -}; - -The following flags bits are used by the compiler: - -enum { - BLOCK_HAS_COPY_DISPOSE = (1 << 25), - BLOCK_HAS_CTOR = (1 << 26), // helpers have C++ code - BLOCK_IS_GLOBAL = (1 << 28), - BLOCK_HAS_DESCRIPTOR = (1 << 29), // interim until complete world build is accomplished -}; - -Block literals may occur within functions where the structure is created in stack local memory. They may also appear as initialization expressions for Block variables of global or static local variables. - -When a Block literal expression is evaluated the stack based structure is initialized as follows: - -1) static descriptor structure is declared and initialized as follows: -1a) the invoke function pointer is set to a function that takes the Block structure as its first argument and the rest of the arguments (if any) to the Block and executes the Block compound statement. -1b) the size field is set to the size of the following Block literal structure. -1c) the copy_helper and dispose_helper function pointers are set to respective helper functions if they are required by the Block literal -2) a stack (or global) Block literal data structure is created and initialized as follows: -2a) the isa field is set to the address of the external _NSConcreteStackBlock, which is a block of uninitialized memory supplied in libSystem, or _NSConcreteGlobalBlock if this is a static or file level block literal. -2) The flags field is set to zero unless there are variables imported into the block that need helper functions for program level Block_copy() and Block_release() operations, in which case the (1<<25) flags bit is set. - -As an example, the Block literal expression - ^ { printf("hello world\n"); } -would cause to be created on a 32-bit system: - -struct __block_literal_1 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_1 *); - struct __block_descriptor_1 *descriptor; -}; - -void __block_invoke_1(struct __block_literal_1 *_block) { - printf("hello world\n"); -} - -static struct __block_descriptor_1 { - unsigned long int reserved; - unsigned long int Block_size; -} __block_descriptor_1 = { 0, sizeof(struct __block_literal_1), __block_invoke_1 }; - -and where the block literal appeared - - struct __block_literal_1 _block_literal = { - &_NSConcreteStackBlock, - (1<<29), , - __block_invoke_1, - &__block_descriptor_1 - }; - -Blocks import other Block references, const copies of other variables, and variables marked __block. In Objective-C variables may additionally be objects. - -When a Block literal expression used as the initial value of a global or static local variable it is initialized as follows: - struct __block_literal_1 __block_literal_1 = { - &_NSConcreteGlobalBlock, - (1<<28)|(1<<29), , - __block_invoke_1, - &__block_descriptor_1 - }; -that is, a different address is provided as the first value and a particular (1<<28) bit is set in the flags field, and otherwise it is the same as for stack based Block literals. This is an optimization that can be used for any Block literal that imports no const or __block storage variables. - - -2. Imported Variables - -Variables of "auto" storage class are imported as const copies. Variables of "__block" storage class are imported as a pointer to an enclosing data structure. Global variables are simply referenced and not considered as imported. - -2.1 Imported const copy variables - -Automatic storage variables not marked with __block are imported as const copies. - -The simplest example is that of importing a variable of type int. - - int x = 10; - void (^vv)(void) = ^{ printf("x is %d\n", x); } - x = 11; - vv(); - -would be compiled - -struct __block_literal_2 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_2 *); - struct __block_descriptor_2 *descriptor; - const int x; -}; - -void __block_invoke_2(struct __block_literal_2 *_block) { - printf("x is %d\n", _block->x); -} - -static struct __block_descriptor_2 { - unsigned long int reserved; - unsigned long int Block_size; -} __block_descriptor_2 = { 0, sizeof(struct __block_literal_2) }; - -and - - struct __block_literal_2 __block_literal_2 = { - &_NSConcreteStackBlock, - (1<<29), , - __block_invoke_2, - &__block_descriptor_2, - x - }; - -In summary, scalars, structures, unions, and function pointers are generally imported as const copies with no need for helper functions. - -2.2 Imported const copy of Block reference - -The first case where copy and dispose helper functions are required is for the case of when a block itself is imported. In this case both a copy_helper function and a dispose_helper function are needed. The copy_helper function is passed both the existing stack based pointer and the pointer to the new heap version and should call back into the runtime to actually do the copy operation on the imported fields within the block. The runtime functions are all described in Section 5.0 Runtime Helper Functions. - -An example: - - void (^existingBlock)(void) = ...; - void (^vv)(void) = ^{ existingBlock(); } - vv(); - -struct __block_literal_3 { - ...; // existing block -}; - -struct __block_literal_4 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_4 *); - struct __block_literal_3 *const existingBlock; -}; - -void __block_invoke_4(struct __block_literal_2 *_block) { - __block->existingBlock->invoke(__block->existingBlock); -} - -void __block_copy_4(struct __block_literal_4 *dst, struct __block_literal_4 *src) { - //_Block_copy_assign(&dst->existingBlock, src->existingBlock, 0); - _Block_object_assign(&dst->existingBlock, src->existingBlock, BLOCK_FIELD_IS_BLOCK); -} - -void __block_dispose_4(struct __block_literal_4 *src) { - // was _Block_destroy - _Block_object_dispose(src->existingBlock, BLOCK_FIELD_IS_BLOCK); -} - -static struct __block_descriptor_4 { - unsigned long int reserved; - unsigned long int Block_size; - void (*copy_helper)(struct __block_literal_4 *dst, struct __block_literal_4 *src); - void (*dispose_helper)(struct __block_literal_4 *); -} __block_descriptor_4 = { - 0, - sizeof(struct __block_literal_4), - __block_copy_4, - __block_dispose_4, -}; - -and where it is used - - struct __block_literal_4 _block_literal = { - &_NSConcreteStackBlock, - (1<<25)|(1<<29), - __block_invoke_4, - & __block_descriptor_4 - existingBlock, - }; - -2.2.1 Importing __attribute__((NSObject)) variables. - -GCC introduces __attribute__((NSObject)) on structure pointers to mean "this is an object". This is useful because many low level data structures are declared as opaque structure pointers, e.g. CFStringRef, CFArrayRef, etc. When used from C, however, these are still really objects and are the second case where that requires copy and dispose helper functions to be generated. The copy helper functions generated by the compiler should use the _Block_object_assign runtime helper function and in the dispose helper the _Block_object_dispose runtime helper function should be called. - -For example, block xyzzy in the following - - struct Opaque *__attribute__((NSObject)) objectPointer = ...; - ... - void (^xyzzy)(void) = ^{ CFPrint(objectPointer); }; - -would have helper functions - -void __block_copy_xyzzy(struct __block_literal_5 *dst, struct __block_literal_5 *src) { - _Block_object_assign(&dst->objectPointer, src-> objectPointer, BLOCK_FIELD_IS_OBJECT); -} - -void __block_dispose_xyzzy(struct __block_literal_5 *src) { - _Block_object_dispose(src->objectPointer, BLOCK_FIELD_IS_OBJECT); -} - -generated. - - -2.3 Imported __block marked variables. - -2.3.1 Layout of __block marked variables - -The compiler must embed variables that are marked __block in a specialized structure of the form: - -struct _block_byref_xxxx { - void *isa; - struct Block_byref *forwarding; - int flags; //refcount; - int size; - typeof(marked_variable) marked_variable; -}; - -Variables of certain types require helper functions for when Block_copy() and Block_release() are performed upon a referencing Block. At the "C" level only variables that are of type Block or ones that have __attribute__((NSObject)) marked require helper functions. In Objective-C objects require helper functions and in C++ stack based objects require helper functions. Variables that require helper functions use the form: - -struct _block_byref_xxxx { - void *isa; - struct _block_byref_xxxx *forwarding; - int flags; //refcount; - int size; - // helper functions called via Block_copy() and Block_release() - void (*byref_keep)(void *dst, void *src); - void (*byref_dispose)(void *); - typeof(marked_variable) marked_variable; -}; - -The structure is initialized such that - a) the forwarding pointer is set to the beginning of its enclosing structure, - b) the size field is initialized to the total size of the enclosing structure, - c) the flags field is set to either 0 if no helper functions are needed or (1<<25) if they are, - d) the helper functions are initialized (if present) - e) the variable itself is set to its initial value. - f) the isa field is set to NULL - -2.3.2 Access to __block variables from within its lexical scope. - -In order to "move" the variable to the heap upon a copy_helper operation the compiler must rewrite access to such a variable to be indirect through the structures forwarding pointer. For example: - - int __block i = 10; - i = 11; - -would be rewritten to be: - - struct _block_byref_i { - void *isa; - struct _block_byref_i *forwarding; - int flags; //refcount; - int size; - int captured_i; - } i = { NULL, &i, 0, sizeof(struct _block_byref_i), 11 }; - - i.forwarding->captured_i = 11; - -In the case of a Block reference variable being marked __block the helper code generated must use the _Block_object_assign and _Block_object_dispose routines supplied by the runtime to make the copies. For example: - - __block void (voidBlock)(void) = blockA; - voidBlock = blockB; - -would translate into - -struct _block_byref_voidBlock { - void *isa; - struct _block_byref_voidBlock *forwarding; - int flags; //refcount; - int size; - void (*byref_keep)(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src); - void (*byref_dispose)(struct _block_byref_voidBlock *); - void (^captured_voidBlock)(void); -}; - -void _block_byref_keep_helper(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src) { - //_Block_copy_assign(&dst->captured_voidBlock, src->captured_voidBlock, 0); - _Block_object_assign(&dst->captured_voidBlock, src->captured_voidBlock, BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER); -} - -void _block_byref_dispose_helper(struct _block_byref_voidBlock *param) { - //_Block_destroy(param->captured_voidBlock, 0); - _Block_object_dispose(param->captured_voidBlock, BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER)} - -and - struct _block_byref_voidBlock voidBlock = {( .forwarding=&voidBlock, .flags=(1<<25), .size=sizeof(struct _block_byref_voidBlock *), - .byref_keep=_block_byref_keep_helper, .byref_dispose=_block_byref_dispose_helper, - .captured_voidBlock=blockA }; - - voidBlock.forwarding->captured_voidBlock = blockB; - - -2.3.3 Importing __block variables into Blocks - -A Block that uses a __block variable in its compound statement body must import the variable and emit copy_helper and dispose_helper helper functions that, in turn, call back into the runtime to actually copy or release the byref data block using the functions _Block_object_assign and _Block_object_dispose. - -For example: - - int __block i = 2; - functioncall(^{ i = 10; }); - -would translate to - -struct _block_byref_i { - void *isa; // set to NULL - struct _block_byref_voidBlock *forwarding; - int flags; //refcount; - int size; - void (*byref_keep)(struct _block_byref_i *dst, struct _block_byref_i *src); - void (*byref_dispose)(struct _block_byref_i *); - int captured_i; -}; - - -struct __block_literal_5 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_5 *); - struct __block_descriptor_5 *descriptor; - struct _block_byref_i *i_holder; -}; - -void __block_invoke_5(struct __block_literal_5 *_block) { - _block->forwarding->captured_i = 10; -} - -void __block_copy_5(struct __block_literal_5 *dst, struct __block_literal_5 *src) { - //_Block_byref_assign_copy(&dst->captured_i, src->captured_i); - _Block_object_assign(&dst->captured_i, src->captured_i, BLOCK_FIELD_IS_BYREF | BLOCK_BYREF_CALLER); -} - -void __block_dispose_5(struct __block_literal_5 *src) { - //_Block_byref_release(src->captured_i); - _Block_object_dispose(src->captured_i, BLOCK_FIELD_IS_BYREF | BLOCK_BYREF_CALLER); -} - -static struct __block_descriptor_5 { - unsigned long int reserved; - unsigned long int Block_size; - void (*copy_helper)(struct __block_literal_5 *dst, struct __block_literal_5 *src); - void (*dispose_helper)(struct __block_literal_5 *); -} __block_descriptor_5 = { 0, sizeof(struct __block_literal_5) __block_copy_5, __block_dispose_5 }; - -and - - struct _block_byref_i i = {( .forwarding=&i, .flags=0, .size=sizeof(struct _block_byref_i) )}; - struct __block_literal_5 _block_literal = { - &_NSConcreteStackBlock, - (1<<25)|(1<<29), , - __block_invoke_5, - &__block_descriptor_5, - 2, - }; - -2.3.4 Importing __attribute__((NSObject)) __block variables - -A __block variable that is also marked __attribute__((NSObject)) should have byref_keep and byref_dispose helper functions that use _Block_object_assign and _Block_object_dispose. - -2.3.5 __block escapes - -Because Blocks referencing __block variables may have Block_copy() performed upon them the underlying storage for the variables may move to the heap. In Objective-C Garbage Collection Only compilation environments the heap used is the garbage collected one and no further action is required. Otherwise the compiler must issue a call to potentially release any heap storage for __block variables at all escapes or terminations of their scope. - - -2.3.6 Nesting - -Blocks may contain Block literal expressions. Any variables used within inner blocks are imported into all enclosing Block scopes even if the variables are not used. This includes const imports as well as __block variables. - -3. Objective C Extensions to Blocks - -3.1 Importing Objects - -Objects should be treated as __attribute__((NSObject)) variables; all copy_helper, dispose_helper, byref_keep, and byref_dispose helper functions should use _Block_object_assign and _Block_object_dispose. There should be no code generated that uses -retain or -release methods. - - -3.2 Blocks as Objects - -The compiler will treat Blocks as objects when synthesizing property setters and getters, will characterize them as objects when generating garbage collection strong and weak layout information in the same manner as objects, and will issue strong and weak write-barrier assignments in the same manner as objects. - -3.3 __weak __block Support - -Objective-C (and Objective-C++) support the __weak attribute on __block variables. Under normal circumstances the compiler uses the Objective-C runtime helper support functions objc_assign_weak and objc_read_weak. Both should continue to be used for all reads and writes of __weak __block variables: - objc_read_weak(&block->byref_i->forwarding->i) - -The __weak variable is stored in a _block_byref_xxxx structure and the Block has copy and dispose helpers for this structure that call: - _Block_object_assign(&dest->_block_byref_i, src-> _block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BYREF); -and - _Block_object_dispose(src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BYREF); - - -In turn, the block_byref copy support helpers distinguish between whether the __block variable is a Block or not and should either call: - _Block_object_assign(&dest->_block_byref_i, src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_OBJECT | BLOCK_BYREF_CALLER); -for something declared as an object or - _Block_object_assign(&dest->_block_byref_i, src->_block_byref_i, BLOCK_FIELD_IS_WEAK | BLOCK_FIELD_IS_BLOCK | BLOCK_BYREF_CALLER); -for something declared as a Block. - -A full example follows: - - - __block __weak id obj = ; - functioncall(^{ [obj somemessage]; }); - -would translate to - -struct _block_byref_obj { - void *isa; // uninitialized - struct _block_byref_obj *forwarding; - int flags; //refcount; - int size; - void (*byref_keep)(struct _block_byref_i *dst, struct _block_byref_i *src); - void (*byref_dispose)(struct _block_byref_i *); - int captured_obj; -}; - -void _block_byref_obj_keep(struct _block_byref_voidBlock *dst, struct _block_byref_voidBlock *src) { - //_Block_copy_assign(&dst->captured_obj, src->captured_obj, 0); - _Block_object_assign(&dst->captured_obj, src->captured_obj, BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK | BLOCK_BYREF_CALLER); -} - -void _block_byref_obj_dispose(struct _block_byref_voidBlock *param) { - //_Block_destroy(param->captured_obj, 0); - _Block_object_dispose(param->captured_obj, BLOCK_FIELD_IS_OBJECT | BLOCK_FIELD_IS_WEAK | BLOCK_BYREF_CALLER); -}; - -for the block byref part and - -struct __block_literal_5 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_5 *); - struct __block_descriptor_5 *descriptor; - struct _block_byref_obj *byref_obj; -}; - -void __block_invoke_5(struct __block_literal_5 *_block) { - [objc_read_weak(&_block->byref_obj->forwarding->captured_obj) somemessage]; -} - -void __block_copy_5(struct __block_literal_5 *dst, struct __block_literal_5 *src) { - //_Block_byref_assign_copy(&dst->byref_obj, src->byref_obj); - _Block_object_assign(&dst->byref_obj, src->byref_obj, BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK); -} - -void __block_dispose_5(struct __block_literal_5 *src) { - //_Block_byref_release(src->byref_obj); - _Block_object_dispose(src->byref_obj, BLOCK_FIELD_IS_BYREF | BLOCK_FIELD_IS_WEAK); -} - -static struct __block_descriptor_5 { - unsigned long int reserved; - unsigned long int Block_size; - void (*copy_helper)(struct __block_literal_5 *dst, struct __block_literal_5 *src); - void (*dispose_helper)(struct __block_literal_5 *); -} __block_descriptor_5 = { 0, sizeof(struct __block_literal_5), __block_copy_5, __block_dispose_5 }; - -and within the compound statement: - - struct _block_byref_obj obj = {( .forwarding=&obj, .flags=(1<<25), .size=sizeof(struct _block_byref_obj), - .byref_keep=_block_byref_obj_keep, .byref_dispose=_block_byref_obj_dispose, - .captured_obj = )}; - - struct __block_literal_5 _block_literal = { - &_NSConcreteStackBlock, - (1<<25)|(1<<29), , - __block_invoke_5, - &__block_descriptor_5, - &obj, // a reference to the on-stack structure containing "captured_obj" - }; - - - functioncall(_block_literal->invoke(&_block_literal)); - - -4.0 C++ Support - -Within a block stack based C++ objects are copied as const copies using the const copy constructor. It is an error if a stack based C++ object is used within a block if it does not have a const copy constructor. In addition both copy and destroy helper routines must be synthesized for the block to support the Block_copy() operation, and the flags work marked with the (1<<26) bit in addition to the (1<<25) bit. The copy helper should call the constructor using appropriate offsets of the variable within the supplied stack based block source and heap based destination for all const constructed copies, and similarly should call the destructor in the destroy routine. - -As an example, suppose a C++ class FOO existed with a const copy constructor. Within a code block a stack version of a FOO object is declared and used within a Block literal expression: - -{ - FOO foo; - void (^block)(void) = ^{ printf("%d\n", foo.value()); }; -} - -The compiler would synthesize - -struct __block_literal_10 { - void *isa; - int flags; - int reserved; - void (*invoke)(struct __block_literal_10 *); - struct __block_descriptor_10 *descriptor; - const FOO foo; -}; - -void __block_invoke_10(struct __block_literal_10 *_block) { - printf("%d\n", _block->foo.value()); -} - -void __block_literal_10(struct __block_literal_10 *dst, struct __block_literal_10 *src) { - comp_ctor(&dst->foo, &src->foo); -} - -void __block_dispose_10(struct __block_literal_10 *src) { - comp_dtor(&src->foo); -} - -static struct __block_descriptor_10 { - unsigned long int reserved; - unsigned long int Block_size; - void (*copy_helper)(struct __block_literal_10 *dst, struct __block_literal_10 *src); - void (*dispose_helper)(struct __block_literal_10 *); -} __block_descriptor_10 = { 0, sizeof(struct __block_literal_10), __block_copy_10, __block_dispose_10 }; - -and the code would be: -{ - FOO foo; - comp_ctor(&foo); // default constructor - struct __block_literal_10 _block_literal = { - &_NSConcreteStackBlock, - (1<<25)|(1<<26)|(1<<29), , - __block_invoke_10, - &__block_descriptor_10, - }; - comp_ctor(&_block_literal->foo, &foo); // const copy into stack version - struct __block_literal_10 &block = &_block_literal; // assign literal to block variable - block->invoke(block); // invoke block - comp_dtor(&_block_literal->foo); // destroy stack version of const block copy - comp_dtor(&foo); // destroy original version -} - - -C++ objects stored in __block storage start out on the stack in a block_byref data structure as do other variables. Such objects (if not const objects) must support a regular copy constructor. The block_byref data structure will have copy and destroy helper routines synthesized by the compiler. The copy helper will have code created to perform the copy constructor based on the initial stack block_byref data structure, and will also set the (1<<26) bit in addition to the (1<<25) bit. The destroy helper will have code to do the destructor on the object stored within the supplied block_byref heap data structure. - -To support member variable and function access the compiler will synthesize a const pointer to a block version of the this pointer. - -5.0 Runtime Helper Functions - -The runtime helper functions are described in /usr/local/include/Block_private.h. To summarize their use, a block requires copy/dispose helpers if it imports any block variables, __block storage variables, __attribute__((NSObject)) variables, or C++ const copied objects with constructor/destructors. The (1<<26) bit is set and functions are generated. - -The block copy helper function should, for each of the variables of the type mentioned above, call - _Block_object_assign(&dst->target, src->target, BLOCK_FIELD_); -in the copy helper and - _Block_object_dispose(->target, BLOCK_FIELD_); -in the dispose helper where - is - -enum { - BLOCK_FIELD_IS_OBJECT = 3, // id, NSObject, __attribute__((NSObject)), block, ... - BLOCK_FIELD_IS_BLOCK = 7, // a block variable - BLOCK_FIELD_IS_BYREF = 8, // the on stack structure holding the __block variable - - BLOCK_FIELD_IS_WEAK = 16, // declared __weak - - BLOCK_BYREF_CALLER = 128, // called from byref copy/dispose helpers -}; - -and of course the CTORs/DTORs for const copied C++ objects. - -The block_byref data structure similarly requires copy/dispose helpers for block variables, __attribute__((NSObject)) variables, or C++ const copied objects with constructor/destructors, and again the (1<<26) bit is set and functions are generated in the same manner. - -Under ObjC we allow __weak as an attribute on __block variables, and this causes the addition of BLOCK_FIELD_IS_WEAK orred onto the BLOCK_FIELD_IS_BYREF flag when copying the block_byref structure in the block copy helper, and onto the BLOCK_FIELD_ field within the block_byref copy/dispose helper calls. - -The prototypes, and summary, of the helper functions are - -/* Certain field types require runtime assistance when being copied to the heap. The following function is used - to copy fields of types: blocks, pointers to byref structures, and objects (including __attribute__((NSObject)) pointers. - BLOCK_FIELD_IS_WEAK is orthogonal to the other choices which are mutually exclusive. - Only in a Block copy helper will one see BLOCK_FIELD_IS_BYREF. - */ -void _Block_object_assign(void *destAddr, const void *object, const int flags); - -/* Similarly a compiler generated dispose helper needs to call back for each field of the byref data structure. - (Currently the implementation only packs one field into the byref structure but in principle there could be more). - The same flags used in the copy helper should be used for each call generated to this function: - */ -void _Block_object_dispose(const void *object, const int flags); - -The following functions have been used and will continue to be supported until new compiler support is complete. - -// Obsolete functions. -// Copy helper callback for copying a block imported into a Block -// Called by copy_helper helper functions synthesized by the compiler. -// The address in the destination block of an imported Block is provided as the first argument -// and the value of the existing imported Block is the second. -// Use: _Block_object_assign(dest, src, BLOCK_FIELD_IS_BLOCK {| BLOCK_FIELD_IS_WEAK}); -void _Block_copy_assign(struct Block_basic **dest, const struct Block_basic *src, const int flags); - -// Destroy helper callback for releasing Blocks imported into a Block -// Called by dispose_helper helper functions synthesized by the compiler. -// The value of the imported Block variable is passed back. -// Use: _Block_object_dispose(src, BLOCK_FIELD_IS_BLOCK {| BLOCK_FIELD_IS_WEAK}); -void _Block_destroy(const struct Block_basic *src, const int flags); - -// Byref data block copy helper callback -// Called by block copy helpers when copying __block structures -// Use: _Block_object_assign(dest, src, BLOCK_FIELD_IS_BYREF {| BLOCK_FIELD_IS_WEAK}); -void _Block_byref_assign_copy(struct Block_byref **destp, struct Block_byref *src); - -// Byref data block release helper callback -// Called by block release helpers when releasing a Block -// Called at escape points in scope where __block variables live (under non-GC-only conditions) -// Use: _Block_object_dispose(src, BLOCK_FIELD_IS_BYREF {| BLOCK_FIELD_IS_WEAK}); -void §(struct Block_byref *shared_struct); - - diff --git a/include/clang/AST/DeclNodes.def b/include/clang/AST/DeclNodes.def deleted file mode 100644 index 5b03ff8d9119..000000000000 --- a/include/clang/AST/DeclNodes.def +++ /dev/null @@ -1,165 +0,0 @@ -//===-- DeclNodes.def - Metadata about Decl AST nodes -----------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the declaration nodes within the AST. The -// description of the declaration nodes uses six macros: -// -// DECL(Derived, Base) describes a normal declaration type Derived -// and specifies its base class. Note that Derived should not have -// the Decl suffix on it, while Base should. -// -// LAST_DECL(Derived, Base) is like DECL, but is used for the last -// declaration in the list. -// -// ABSTRACT_DECL(Derived, Base) describes an abstract class that is -// used to specify a classification of declarations. For example, -// TagDecl is an abstract class used to describe the various kinds of -// "tag" declarations (unions, structs, classes, enums). -// -// DECL_CONTEXT(Decl) specifies that Decl is a kind of declaration -// that is also a DeclContext. -// -// LAST_DECL_CONTEXT(Decl) is like DECL_CONTEXT, but is used for the -// last declaration context. -// -// DECL_RANGE(CommonBase, Start, End) specifies a range of -// declaration values that have a common (potentially indirect) base -// class. -// -// LAST_DECL_RANGE(CommonBase, Start, End) is like DECL_RANGE, but is -// used for the last declaration range. -// -// Note that, due to the use of ranges, the order of the these -// declarations is significant. A declaration should be listed under -// its base class. -// ===----------------------------------------------------------------------===// - -#ifndef DECL -# define DECL(Derived, Base) -#endif - -#ifndef LAST_DECL -# define LAST_DECL(Derived, Base) DECL(Derived, Base) -#endif - -#ifndef ABSTRACT_DECL -# define ABSTRACT_DECL(Derived, Base) -#endif - -#ifndef DECL_CONTEXT -# define DECL_CONTEXT(Decl) -#endif - -#ifndef DECL_CONTEXT_BASE -# define DECL_CONTEXT_BASE(Decl) DECL_CONTEXT(Decl) -#endif - -#ifndef LAST_DECL_CONTEXT -# define LAST_DECL_CONTEXT(Decl) DECL_CONTEXT(Decl) -#endif - -#ifndef DECL_RANGE -# define DECL_RANGE(CommonBase, Start, End) -#endif - -#ifndef LAST_DECL_RANGE -# define LAST_DECL_RANGE(CommonBase, Start, End) \ - DECL_RANGE(CommonBase, Start, End) -#endif - -DECL(TranslationUnit, Decl) -ABSTRACT_DECL(Named, Decl) - DECL(Namespace, NamedDecl) - DECL(UsingDirective, NamedDecl) - DECL(NamespaceAlias, NamedDecl) - ABSTRACT_DECL(Type, NamedDecl) - DECL(Typedef, TypeDecl) - DECL(UnresolvedUsingTypename, TypeDecl) - ABSTRACT_DECL(Tag, TypeDecl) - DECL(Enum, TagDecl) - DECL(Record, TagDecl) - DECL(CXXRecord, RecordDecl) - DECL(ClassTemplateSpecialization, CXXRecordDecl) - DECL(ClassTemplatePartialSpecialization, - ClassTemplateSpecializationDecl) - DECL(TemplateTypeParm, TypeDecl) - ABSTRACT_DECL(Value, NamedDecl) - DECL(EnumConstant, ValueDecl) - DECL(UnresolvedUsingValue, ValueDecl) - ABSTRACT_DECL(Declarator, ValueDecl) - DECL(Function, DeclaratorDecl) - DECL(CXXMethod, FunctionDecl) - DECL(CXXConstructor, CXXMethodDecl) - DECL(CXXDestructor, CXXMethodDecl) - DECL(CXXConversion, CXXMethodDecl) - DECL(Field, DeclaratorDecl) - DECL(ObjCIvar, FieldDecl) - DECL(ObjCAtDefsField, FieldDecl) - DECL(Var, DeclaratorDecl) - DECL(ImplicitParam, VarDecl) - DECL(ParmVar, VarDecl) - DECL(NonTypeTemplateParm, VarDecl) - ABSTRACT_DECL(Template, NamedDecl) - DECL(FunctionTemplate, TemplateDecl) - DECL(ClassTemplate, TemplateDecl) - DECL(TemplateTemplateParm, TemplateDecl) - DECL(Using, NamedDecl) - DECL(UsingShadow, NamedDecl) - DECL(ObjCMethod, NamedDecl) - ABSTRACT_DECL(ObjCContainer, NamedDecl) - DECL(ObjCCategory, ObjCContainerDecl) - DECL(ObjCProtocol, ObjCContainerDecl) - DECL(ObjCInterface, ObjCContainerDecl) - ABSTRACT_DECL(ObjCImpl, ObjCContainerDecl) - DECL(ObjCCategoryImpl, ObjCImplDecl) - DECL(ObjCImplementation, ObjCImplDecl) - DECL(ObjCProperty, NamedDecl) - DECL(ObjCCompatibleAlias, NamedDecl) -DECL(LinkageSpec, Decl) -DECL(ObjCPropertyImpl, Decl) -DECL(ObjCForwardProtocol, Decl) -DECL(ObjCClass, Decl) -DECL(FileScopeAsm, Decl) -DECL(Friend, Decl) -DECL(FriendTemplate, Decl) -DECL(StaticAssert, Decl) -LAST_DECL(Block, Decl) - -// Declaration contexts. DECL_CONTEXT_BASE indicates that it has subclasses. -DECL_CONTEXT(TranslationUnit) -DECL_CONTEXT(Namespace) -DECL_CONTEXT(LinkageSpec) -DECL_CONTEXT(ObjCMethod) -DECL_CONTEXT_BASE(Tag) -DECL_CONTEXT_BASE(Function) -DECL_CONTEXT_BASE(ObjCContainer) -LAST_DECL_CONTEXT(Block) - -// Declaration ranges -DECL_RANGE(Named, Namespace, ObjCCompatibleAlias) -DECL_RANGE(ObjCContainer, ObjCCategory, ObjCImplementation) -DECL_RANGE(Field, Field, ObjCAtDefsField) -DECL_RANGE(Type, Typedef, TemplateTypeParm) -DECL_RANGE(Tag, Enum, ClassTemplatePartialSpecialization) -DECL_RANGE(Record, Record, ClassTemplatePartialSpecialization) -DECL_RANGE(Value, EnumConstant, NonTypeTemplateParm) -DECL_RANGE(Declarator, Function, NonTypeTemplateParm) -DECL_RANGE(Function, Function, CXXConversion) -DECL_RANGE(Template, FunctionTemplate, TemplateTemplateParm) -DECL_RANGE(ObjCImpl, ObjCCategoryImpl, ObjCImplementation) -LAST_DECL_RANGE(Var, Var, NonTypeTemplateParm) - -#undef LAST_DECL_RANGE -#undef DECL_RANGE -#undef LAST_DECL_CONTEXT -#undef DECL_CONTEXT_BASE -#undef DECL_CONTEXT -#undef ABSTRACT_DECL -#undef LAST_DECL -#undef DECL diff --git a/include/clang/AST/StmtNodes.def b/include/clang/AST/StmtNodes.def deleted file mode 100644 index 3a23e49148d5..000000000000 --- a/include/clang/AST/StmtNodes.def +++ /dev/null @@ -1,165 +0,0 @@ -//===-- StmtNodes.def - Metadata about Stmt AST nodes -----------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the AST Node info database. -// -//===---------------------------------------------------------------------===// - -#ifndef FIRST_STMT -#define FIRST_STMT(CLASS) -#define LAST_STMT(CLASS) -#endif - -#ifndef FIRST_EXPR -#define FIRST_EXPR(CLASS) -#define LAST_EXPR(CLASS) -#endif - -#ifndef EXPR -# define EXPR(Type, Base) STMT(Type, Base) -#endif - -#ifndef ABSTRACT_EXPR -# define ABSTRACT_EXPR(Type, Base) EXPR(Type, Base) -#endif - -// Normal Statements. -STMT(NullStmt , Stmt) -FIRST_STMT(NullStmt) -STMT(CompoundStmt , Stmt) -STMT(CaseStmt , SwitchCase) -STMT(DefaultStmt , SwitchCase) -STMT(LabelStmt , Stmt) -STMT(IfStmt , Stmt) -STMT(SwitchStmt , Stmt) -STMT(WhileStmt , Stmt) -STMT(DoStmt , Stmt) -STMT(ForStmt , Stmt) -STMT(GotoStmt , Stmt) -STMT(IndirectGotoStmt, Stmt) -STMT(ContinueStmt , Stmt) -STMT(BreakStmt , Stmt) -STMT(ReturnStmt , Stmt) -STMT(DeclStmt , Stmt) -STMT(SwitchCase , Stmt) - -// GNU Stmt Extensions -STMT(AsmStmt , Stmt) - -// Obj-C statements -STMT(ObjCAtTryStmt , Stmt) -STMT(ObjCAtCatchStmt , Stmt) -STMT(ObjCAtFinallyStmt , Stmt) -STMT(ObjCAtThrowStmt , Stmt) -STMT(ObjCAtSynchronizedStmt , Stmt) -// Obj-C2 statements -STMT(ObjCForCollectionStmt, Stmt) - -// C++ statements -STMT(CXXCatchStmt, Stmt) -STMT(CXXTryStmt , Stmt) - -LAST_STMT(CXXTryStmt) - -// Expressions. -ABSTRACT_EXPR(Expr , Stmt) -EXPR(PredefinedExpr , Expr) -EXPR(DeclRefExpr , Expr) -EXPR(IntegerLiteral , Expr) -EXPR(FloatingLiteral , Expr) -EXPR(ImaginaryLiteral , Expr) -EXPR(StringLiteral , Expr) -EXPR(CharacterLiteral , Expr) -EXPR(ParenExpr , Expr) -EXPR(UnaryOperator , Expr) -EXPR(OffsetOfExpr , Expr) -EXPR(SizeOfAlignOfExpr , Expr) -EXPR(ArraySubscriptExpr , Expr) -EXPR(CallExpr , Expr) -EXPR(MemberExpr , Expr) -ABSTRACT_EXPR(CastExpr , Expr) -EXPR(BinaryOperator , Expr) -EXPR(CompoundAssignOperator, BinaryOperator) -EXPR(ConditionalOperator , Expr) -EXPR(ImplicitCastExpr , CastExpr) -ABSTRACT_EXPR(ExplicitCastExpr, CastExpr) -EXPR(CStyleCastExpr , ExplicitCastExpr) -EXPR(CompoundLiteralExpr , Expr) -EXPR(ExtVectorElementExpr , Expr) -EXPR(InitListExpr , Expr) -EXPR(DesignatedInitExpr , Expr) -EXPR(ImplicitValueInitExpr , Expr) -EXPR(ParenListExpr , Expr) -EXPR(VAArgExpr , Expr) - -// GNU Extensions. -EXPR(AddrLabelExpr , Expr) -EXPR(StmtExpr , Expr) -EXPR(TypesCompatibleExpr , Expr) -EXPR(ChooseExpr , Expr) -EXPR(GNUNullExpr , Expr) - -// C++ Expressions. -EXPR(CXXOperatorCallExpr , CallExpr) -EXPR(CXXMemberCallExpr , CallExpr) -ABSTRACT_EXPR(CXXNamedCastExpr , ExplicitCastExpr) -EXPR(CXXStaticCastExpr , CXXNamedCastExpr) -EXPR(CXXDynamicCastExpr , CXXNamedCastExpr) -EXPR(CXXReinterpretCastExpr , CXXNamedCastExpr) -EXPR(CXXConstCastExpr , CXXNamedCastExpr) -EXPR(CXXFunctionalCastExpr , ExplicitCastExpr) -EXPR(CXXTypeidExpr , Expr) -EXPR(CXXBoolLiteralExpr , Expr) -EXPR(CXXNullPtrLiteralExpr , Expr) -EXPR(CXXThisExpr , Expr) -EXPR(CXXThrowExpr , Expr) -EXPR(CXXDefaultArgExpr , Expr) -EXPR(CXXZeroInitValueExpr , Expr) -EXPR(CXXNewExpr , Expr) -EXPR(CXXDeleteExpr , Expr) -EXPR(CXXPseudoDestructorExpr, Expr) -EXPR(UnresolvedLookupExpr , Expr) -EXPR(UnaryTypeTraitExpr , Expr) -EXPR(DependentScopeDeclRefExpr , Expr) -EXPR(CXXConstructExpr , Expr) -EXPR(CXXBindTemporaryExpr , Expr) -EXPR(CXXBindReferenceExpr , Expr) -EXPR(CXXExprWithTemporaries , Expr) -EXPR(CXXTemporaryObjectExpr , CXXConstructExpr) -EXPR(CXXUnresolvedConstructExpr, Expr) -EXPR(CXXDependentScopeMemberExpr, Expr) -EXPR(UnresolvedMemberExpr , Expr) - -// Obj-C Expressions. -EXPR(ObjCStringLiteral , Expr) -EXPR(ObjCEncodeExpr , Expr) -EXPR(ObjCMessageExpr , Expr) -EXPR(ObjCSelectorExpr , Expr) -EXPR(ObjCProtocolExpr , Expr) -EXPR(ObjCIvarRefExpr , Expr) -EXPR(ObjCPropertyRefExpr , Expr) -EXPR(ObjCImplicitSetterGetterRefExpr , Expr) -EXPR(ObjCSuperExpr , Expr) -EXPR(ObjCIsaExpr , Expr) - -// Clang Extensions. -EXPR(ShuffleVectorExpr , Expr) -EXPR(BlockExpr , Expr) -EXPR(BlockDeclRefExpr , Expr) - -FIRST_EXPR(PredefinedExpr) -LAST_EXPR(BlockDeclRefExpr) - -#undef ABSTRACT_EXPR -#undef EXPR -#undef STMT -#undef FIRST_STMT -#undef LAST_STMT -#undef FIRST_EXPR -#undef LAST_EXPR diff --git a/lib/Headers/arm_neon.h b/lib/Headers/arm_neon.h deleted file mode 100644 index 4508a27f36a4..000000000000 --- a/lib/Headers/arm_neon.h +++ /dev/null @@ -1,537 +0,0 @@ -/*===---- arm_neon.h - NEON intrinsics --------------------------------------=== - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - *===-----------------------------------------------------------------------=== - */ - -#ifndef __ARM_NEON_H -#define __ARM_NEON_H - -#ifndef __ARM_NEON__ -#error "NEON support not enabled" -#endif - -// NEON document appears to be specified in terms of stdint types. -#include - -// Define some NEON-specific scalar types for floats and polynomials. -typedef float float32_t; -typedef uint8_t poly8_t; - -// FIXME: probably need a 'poly' attribute or something for correct codegen to -// disambiguate from uint16_t. -typedef uint16_t poly16_t; - -typedef __attribute__(( __vector_size__(8) )) int8_t __neon_int8x8_t; -typedef __attribute__(( __vector_size__(16) )) int8_t __neon_int8x16_t; -typedef __attribute__(( __vector_size__(8) )) int16_t __neon_int16x4_t; -typedef __attribute__(( __vector_size__(16) )) int16_t __neon_int16x8_t; -typedef __attribute__(( __vector_size__(8) )) int32_t __neon_int32x2_t; -typedef __attribute__(( __vector_size__(16) )) int32_t __neon_int32x4_t; -typedef __attribute__(( __vector_size__(8) )) int64_t __neon_int64x1_t; -typedef __attribute__(( __vector_size__(16) )) int64_t __neon_int64x2_t; -typedef __attribute__(( __vector_size__(8) )) uint8_t __neon_uint8x8_t; -typedef __attribute__(( __vector_size__(16) )) uint8_t __neon_uint8x16_t; -typedef __attribute__(( __vector_size__(8) )) uint16_t __neon_uint16x4_t; -typedef __attribute__(( __vector_size__(16) )) uint16_t __neon_uint16x8_t; -typedef __attribute__(( __vector_size__(8) )) uint32_t __neon_uint32x2_t; -typedef __attribute__(( __vector_size__(16) )) uint32_t __neon_uint32x4_t; -typedef __attribute__(( __vector_size__(8) )) uint64_t __neon_uint64x1_t; -typedef __attribute__(( __vector_size__(16) )) uint64_t __neon_uint64x2_t; -typedef __attribute__(( __vector_size__(8) )) uint16_t __neon_float16x4_t; -typedef __attribute__(( __vector_size__(16) )) uint16_t __neon_float16x8_t; -typedef __attribute__(( __vector_size__(8) )) float32_t __neon_float32x2_t; -typedef __attribute__(( __vector_size__(16) )) float32_t __neon_float32x4_t; -typedef __attribute__(( __vector_size__(8) )) poly8_t __neon_poly8x8_t; -typedef __attribute__(( __vector_size__(16) )) poly8_t __neon_poly8x16_t; -typedef __attribute__(( __vector_size__(8) )) poly16_t __neon_poly16x4_t; -typedef __attribute__(( __vector_size__(16) )) poly16_t __neon_poly16x8_t; - -typedef struct __int8x8_t { - __neon_int8x8_t val; -} int8x8_t; - -typedef struct __int8x16_t { - __neon_int8x16_t val; -} int8x16_t; - -typedef struct __int16x4_t { - __neon_int16x4_t val; -} int16x4_t; - -typedef struct __int16x8_t { - __neon_int16x8_t val; -} int16x8_t; - -typedef struct __int32x2_t { - __neon_int32x2_t val; -} int32x2_t; - -typedef struct __int32x4_t { - __neon_int32x4_t val; -} int32x4_t; - -typedef struct __int64x1_t { - __neon_int64x1_t val; -} int64x1_t; - -typedef struct __int64x2_t { - __neon_int64x2_t val; -} int64x2_t; - -typedef struct __uint8x8_t { - __neon_uint8x8_t val; -} uint8x8_t; - -typedef struct __uint8x16_t { - __neon_uint8x16_t val; -} uint8x16_t; - -typedef struct __uint16x4_t { - __neon_uint16x4_t val; -} uint16x4_t; - -typedef struct __uint16x8_t { - __neon_uint16x8_t val; -} uint16x8_t; - -typedef struct __uint32x2_t { - __neon_uint32x2_t val; -} uint32x2_t; - -typedef struct __uint32x4_t { - __neon_uint32x4_t val; -} uint32x4_t; - -typedef struct __uint64x1_t { - __neon_uint64x1_t val; -} uint64x1_t; - -typedef struct __uint64x2_t { - __neon_uint64x2_t val; -} uint64x2_t; - -typedef struct __float16x4_t { - __neon_float16x4_t val; -} float16x4_t; - -typedef struct __float16x8_t { - __neon_float16x8_t val; -} float16x8_t; - -typedef struct __float32x2_t { - __neon_float32x2_t val; -} float32x2_t; - -typedef struct __float32x4_t { - __neon_float32x4_t val; -} float32x4_t; - -typedef struct __poly8x8_t { - __neon_poly8x8_t val; -} poly8x8_t; - -typedef struct __poly8x16_t { - __neon_poly8x16_t val; -} poly8x16_t; - -typedef struct __poly16x4_t { - __neon_poly16x4_t val; -} poly16x4_t; - -typedef struct __poly16x8_t { - __neon_poly16x8_t val; -} poly16x8_t; - -// FIXME: write tool to stamp out the structure-of-array types, possibly gen this whole file. - -// Intrinsics, per ARM document DUI0348B -#define __ai static __attribute__((__always_inline__)) - -#define INTTYPES_WIDE(op, builtin) \ - __ai int16x8_t op##_s8(int16x8_t a, int8x8_t b) { return (int16x8_t){ builtin(a.val, b.val) }; } \ - __ai int32x4_t op##_s16(int32x4_t a, int16x4_t b) { return (int32x4_t){ builtin(a.val, b.val) }; } \ - __ai int64x2_t op##_s32(int64x2_t a, int32x2_t b) { return (int64x2_t){ builtin(a.val, b.val) }; } \ - __ai uint16x8_t op##_u8(uint16x8_t a, uint8x8_t b) { return (uint16x8_t){ builtin(a.val, b.val) }; } \ - __ai uint32x4_t op##_u16(uint32x4_t a, uint16x4_t b) { return (uint32x4_t){ builtin(a.val, b.val) }; } \ - __ai uint64x2_t op##_u32(uint64x2_t a, uint32x2_t b) { return (uint64x2_t){ builtin(a.val, b.val) }; } - -#define INTTYPES_WIDENING(op, builtin) \ - __ai int16x8_t op##_s8(int8x8_t a, int8x8_t b) { return (int16x8_t){ builtin(a.val, b.val) }; } \ - __ai int32x4_t op##_s16(int16x4_t a, int16x4_t b) { return (int32x4_t){ builtin(a.val, b.val) }; } \ - __ai int64x2_t op##_s32(int32x2_t a, int32x2_t b) { return (int64x2_t){ builtin(a.val, b.val) }; } \ - __ai uint16x8_t op##_u8(uint8x8_t a, uint8x8_t b) { return (uint16x8_t){ builtin(a.val, b.val) }; } \ - __ai uint32x4_t op##_u16(uint16x4_t a, uint16x4_t b) { return (uint32x4_t){ builtin(a.val, b.val) }; } \ - __ai uint64x2_t op##_u32(uint32x2_t a, uint32x2_t b) { return (uint64x2_t){ builtin(a.val, b.val) }; } - -#define INTTYPES_WIDENING_MUL(op, builtin) \ - __ai int16x8_t op##_s8(int16x8_t a, int8x8_t b, int8x8_t c) { return (int16x8_t){ builtin(a.val, b.val, c.val) }; } \ - __ai int32x4_t op##_s16(int32x4_t a, int16x4_t b, int16x4_t c) { return (int32x4_t){ builtin(a.val, b.val, c.val) }; } \ - __ai int64x2_t op##_s32(int64x2_t a, int32x2_t b, int32x2_t c) { return (int64x2_t){ builtin(a.val, b.val, c.val) }; } \ - __ai uint16x8_t op##_u8(uint16x8_t a, uint8x8_t b, uint8x8_t c) { return (uint16x8_t){ builtin(a.val, b.val, c.val) }; } \ - __ai uint32x4_t op##_u16(uint32x4_t a, uint16x4_t b, uint16x4_t c) { return (uint32x4_t){ builtin(a.val, b.val, c.val) }; } \ - __ai uint64x2_t op##_u32(uint64x2_t a, uint32x2_t b, uint32x2_t c) { return (uint64x2_t){ builtin(a.val, b.val, c.val) }; } - -#define INTTYPES_NARROWING(op, builtin) \ - __ai int8x8_t op##_s16(int16x8_t a, int16x8_t b) { return (int8x8_t){ builtin(a.val, b.val) }; } \ - __ai int16x4_t op##_s32(int32x4_t a, int32x4_t b) { return (int16x4_t){ builtin(a.val, b.val) }; } \ - __ai int32x2_t op##_s64(int64x2_t a, int64x2_t b) { return (int32x2_t){ builtin(a.val, b.val) }; } \ - __ai uint8x8_t op##_u16(uint16x8_t a, uint16x8_t b) { return (uint8x8_t){ builtin(a.val, b.val) }; } \ - __ai uint16x4_t op##_u32(uint32x4_t a, uint32x4_t b) { return (uint16x4_t){ builtin(a.val, b.val) }; } \ - __ai uint32x2_t op##_u64(uint64x2_t a, uint64x2_t b) { return (uint32x2_t){ builtin(a.val, b.val) }; } - -#define INTTYPES_ADD_32(op, builtin) \ - __ai int8x8_t op##_s8(int8x8_t a, int8x8_t b) { return (int8x8_t){ builtin(a.val, b.val) }; } \ - __ai int16x4_t op##_s16(int16x4_t a, int16x4_t b) { return (int16x4_t){ builtin(a.val, b.val) }; } \ - __ai int32x2_t op##_s32(int32x2_t a, int32x2_t b) { return (int32x2_t){ builtin(a.val, b.val) }; } \ - __ai uint8x8_t op##_u8(uint8x8_t a, uint8x8_t b) { return (uint8x8_t){ builtin(a.val, b.val) }; } \ - __ai uint16x4_t op##_u16(uint16x4_t a, uint16x4_t b) { return (uint16x4_t){ builtin(a.val, b.val) }; } \ - __ai uint32x2_t op##_u32(uint32x2_t a, uint32x2_t b) { return (uint32x2_t){ builtin(a.val, b.val) }; } \ - __ai int8x16_t op##q_s8(int8x16_t a, int8x16_t b) { return (int8x16_t){ builtin(a.val, b.val) }; } \ - __ai int16x8_t op##q_s16(int16x8_t a, int16x8_t b) { return (int16x8_t){ builtin(a.val, b.val) }; } \ - __ai int32x4_t op##q_s32(int32x4_t a, int32x4_t b) { return (int32x4_t){ builtin(a.val, b.val) }; } \ - __ai uint8x16_t op##q_u8(uint8x16_t a, uint8x16_t b) { return (uint8x16_t){ builtin(a.val, b.val) }; } \ - __ai uint16x8_t op##q_u16(uint16x8_t a, uint16x8_t b) { return (uint16x8_t){ builtin(a.val, b.val) }; } \ - __ai uint32x4_t op##q_u32(uint32x4_t a, uint32x4_t b) { return (uint32x4_t){ builtin(a.val, b.val) }; } - -#define INTTYPES_ADD_64(op, builtin) \ - __ai int64x1_t op##_s64(int64x1_t a, int64x1_t b) { return (int64x1_t){ builtin(a.val, b.val) }; } \ - __ai uint64x1_t op##_u64(uint64x1_t a, uint64x1_t b) { return (uint64x1_t){ builtin(a.val, b.val) }; } \ - __ai int64x2_t op##q_s64(int64x2_t a, int64x2_t b) { return (int64x2_t){ builtin(a.val, b.val) }; } \ - __ai uint64x2_t op##q_u64(uint64x2_t a, uint64x2_t b) { return (uint64x2_t){ builtin(a.val, b.val) }; } - -#define FLOATTYPES_CMP(op, builtin) \ - __ai uint32x2_t op##_f32(float32x2_t a, float32x2_t b) { return (uint32x2_t){ builtin(a.val, b.val) }; } \ - __ai uint32x4_t op##q_f32(float32x4_t a, float32x4_t b) { return (uint32x4_t){ builtin(a.val, b.val) }; } - -#define INT_FLOAT_CMP_OP(op, cc) \ - __ai uint8x8_t op##_s8(int8x8_t a, int8x8_t b) { return (uint8x8_t){(__neon_uint8x8_t)(a.val cc b.val)}; } \ - __ai uint16x4_t op##_s16(int16x4_t a, int16x4_t b) { return (uint16x4_t){(__neon_uint16x4_t)(a.val cc b.val)}; } \ - __ai uint32x2_t op##_s32(int32x2_t a, int32x2_t b) { return (uint32x2_t){(__neon_uint32x2_t)(a.val cc b.val)}; } \ - __ai uint32x2_t op##_f32(float32x2_t a, float32x2_t b) { return (uint32x2_t){(__neon_uint32x2_t)(a.val cc b.val)}; } \ - __ai uint8x8_t op##_u8(uint8x8_t a, uint8x8_t b) { return (uint8x8_t){a.val cc b.val}; } \ - __ai uint16x4_t op##_u16(uint16x4_t a, uint16x4_t b) { return (uint16x4_t){a.val cc b.val}; } \ - __ai uint32x2_t op##_u32(uint32x2_t a, uint32x2_t b) { return (uint32x2_t){a.val cc b.val}; } \ - __ai uint8x16_t op##q_s8(int8x16_t a, int8x16_t b) { return (uint8x16_t){(__neon_uint8x16_t)(a.val cc b.val)}; } \ - __ai uint16x8_t op##q_s16(int16x8_t a, int16x8_t b) { return (uint16x8_t){(__neon_uint16x8_t)(a.val cc b.val)}; } \ - __ai uint32x4_t op##q_s32(int32x4_t a, int32x4_t b) { return (uint32x4_t){(__neon_uint32x4_t)(a.val cc b.val)}; } \ - __ai uint32x4_t op##q_f32(float32x4_t a, float32x4_t b) { return (uint32x4_t){(__neon_uint32x4_t)(a.val cc b.val)}; } \ - __ai uint8x16_t op##q_u8(uint8x16_t a, uint8x16_t b) { return (uint8x16_t){a.val cc b.val}; } \ - __ai uint16x8_t op##q_u16(uint16x8_t a, uint16x8_t b) { return (uint16x8_t){a.val cc b.val}; } \ - __ai uint32x4_t op##q_u32(uint32x4_t a, uint32x4_t b) { return (uint32x4_t){a.val cc b.val}; } - -#define INT_UNARY(op, builtin) \ - __ai int8x8_t op##_s8(int8x8_t a) { return (int8x8_t){ builtin(a.val) }; } \ - __ai int16x4_t op##_s16(int16x4_t a) { return (int16x4_t){ builtin(a.val) }; } \ - __ai int32x2_t op##_s32(int32x2_t a) { return (int32x2_t){ builtin(a.val) }; } \ - __ai int8x16_t op##q_s8(int8x16_t a) { return (int8x16_t){ builtin(a.val) }; } \ - __ai int16x8_t op##q_s16(int16x8_t a) { return (int16x8_t){ builtin(a.val) }; } \ - __ai int32x4_t op##q_s32(int32x4_t a) { return (int32x4_t){ builtin(a.val) }; } - -#define FP_UNARY(op, builtin) \ - __ai float32x2_t op##_f32(float32x2_t a) { return (float32x2_t){ builtin(a.val) }; } \ - __ai float32x4_t op##q_f32(float32x4_t a) { return (float32x4_t){ builtin(a.val) }; } - -#define FP_BINARY(op, builtin) \ - __ai float32x2_t op##_f32(float32x2_t a, float32x2_t b) { return (float32x2_t){ builtin(a.val, b.val) }; } \ - __ai float32x4_t op##q_f32(float32x4_t a, float32x4_t b) { return (float32x4_t){ builtin(a.val, b.val) }; } - -#define INT_FP_PAIRWISE_ADD(op, builtin) \ - __ai int8x8_t op##_s8(int8x8_t a, int8x8_t b) { return (int8x8_t){ builtin(a.val, b.val) }; } \ - __ai int16x4_t op##_s16(int16x4_t a, int16x4_t b) { return (int16x4_t){ builtin(a.val, b.val) }; } \ - __ai int32x2_t op##_s32(int32x2_t a, int32x2_t b) { return (int32x2_t){ builtin(a.val, b.val) }; } \ - __ai uint8x8_t op##_u8(uint8x8_t a, uint8x8_t b) { return (uint8x8_t){ builtin(a.val, b.val) }; } \ - __ai uint16x4_t op##_u16(uint16x4_t a, uint16x4_t b) { return (uint16x4_t){ builtin(a.val, b.val) }; } \ - __ai uint32x2_t op##_u32(uint32x2_t a, uint32x2_t b) { return (uint32x2_t){ builtin(a.val, b.val) }; } \ - __ai float32x2_t op##_f32(float32x2_t a, float32x2_t b) { return (float32x2_t){ builtin(a.val, b.val) }; } - -#define INT_LOGICAL_OP(op, lop) \ - __ai int8x8_t op##_s8(int8x8_t a, int8x8_t b) { return (int8x8_t){ a.val lop b.val }; } \ - __ai int16x4_t op##_s16(int16x4_t a, int16x4_t b) { return (int16x4_t){ a.val lop b.val }; } \ - __ai int32x2_t op##_s32(int32x2_t a, int32x2_t b) { return (int32x2_t){ a.val lop b.val }; } \ - __ai int64x1_t op##_s64(int64x1_t a, int64x1_t b) { return (int64x1_t){ a.val lop b.val }; } \ - __ai uint8x8_t op##_u8(uint8x8_t a, uint8x8_t b) { return (uint8x8_t){ a.val lop b.val }; } \ - __ai uint16x4_t op##_u16(uint16x4_t a, uint16x4_t b) { return (uint16x4_t){ a.val lop b.val }; } \ - __ai uint32x2_t op##_u32(uint32x2_t a, uint32x2_t b) { return (uint32x2_t){ a.val lop b.val }; } \ - __ai uint64x1_t op##_u64(uint64x1_t a, uint64x1_t b) { return (uint64x1_t){ a.val lop b.val }; } \ - __ai int8x16_t op##q_s8(int8x16_t a, int8x16_t b) { return (int8x16_t){ a.val lop b.val }; } \ - __ai int16x8_t op##q_s16(int16x8_t a, int16x8_t b) { return (int16x8_t){ a.val lop b.val }; } \ - __ai int32x4_t op##q_s32(int32x4_t a, int32x4_t b) { return (int32x4_t){ a.val lop b.val }; } \ - __ai int64x2_t op##q_s64(int64x2_t a, int64x2_t b) { return (int64x2_t){ a.val lop b.val }; } \ - __ai uint8x16_t op##q_u8(uint8x16_t a, uint8x16_t b) { return (uint8x16_t){ a.val lop b.val }; } \ - __ai uint16x8_t op##q_u16(uint16x8_t a, uint16x8_t b) { return (uint16x8_t){ a.val lop b.val }; } \ - __ai uint32x4_t op##q_u32(uint32x4_t a, uint32x4_t b) { return (uint32x4_t){ a.val lop b.val }; } \ - __ai uint64x2_t op##q_u64(uint64x2_t a, uint64x2_t b) { return (uint64x2_t){ a.val lop b.val }; } - -// vector add -__ai int8x8_t vadd_s8(int8x8_t a, int8x8_t b) { return (int8x8_t){a.val + b.val}; } -__ai int16x4_t vadd_s16(int16x4_t a, int16x4_t b) { return (int16x4_t){a.val + b.val}; } -__ai int32x2_t vadd_s32(int32x2_t a, int32x2_t b) { return (int32x2_t){a.val + b.val}; } -__ai int64x1_t vadd_s64(int64x1_t a, int64x1_t b) { return (int64x1_t){a.val + b.val}; } -__ai float32x2_t vadd_f32(float32x2_t a, float32x2_t b) { return (float32x2_t){a.val + b.val}; } -__ai uint8x8_t vadd_u8(uint8x8_t a, uint8x8_t b) { return (uint8x8_t){a.val + b.val}; } -__ai uint16x4_t vadd_u16(uint16x4_t a, uint16x4_t b) { return (uint16x4_t){a.val + b.val}; } -__ai uint32x2_t vadd_u32(uint32x2_t a, uint32x2_t b) { return (uint32x2_t){a.val + b.val}; } -__ai uint64x1_t vadd_u64(uint64x1_t a, uint64x1_t b) { return (uint64x1_t){a.val + b.val}; } -__ai int8x16_t vaddq_s8(int8x16_t a, int8x16_t b) { return (int8x16_t){a.val + b.val}; } -__ai int16x8_t vaddq_s16(int16x8_t a, int16x8_t b) { return (int16x8_t){a.val + b.val}; } -__ai int32x4_t vaddq_s32(int32x4_t a, int32x4_t b) { return (int32x4_t){a.val + b.val}; } -__ai int64x2_t vaddq_s64(int64x2_t a, int64x2_t b) { return (int64x2_t){a.val + b.val}; } -__ai float32x4_t vaddq_f32(float32x4_t a, float32x4_t b) { return (float32x4_t){a.val + b.val}; } -__ai uint8x16_t vaddq_u8(uint8x16_t a, uint8x16_t b) { return (uint8x16_t){a.val + b.val}; } -__ai uint16x8_t vaddq_u16(uint16x8_t a, uint16x8_t b) { return (uint16x8_t){a.val + b.val}; } -__ai uint32x4_t vaddq_u32(uint32x4_t a, uint32x4_t b) { return (uint32x4_t){a.val + b.val}; } -__ai uint64x2_t vaddq_u64(uint64x2_t a, uint64x2_t b) { return (uint64x2_t){a.val + b.val}; } - -// vector long add -INTTYPES_WIDENING(vaddl, __builtin_neon_vaddl) - -// vector wide add -INTTYPES_WIDE(vaddw, __builtin_neon_vaddw) - -// halving add -// rounding halving add -INTTYPES_ADD_32(vhadd, __builtin_neon_vhadd) -INTTYPES_ADD_32(vrhadd, __builtin_neon_vrhadd) - -// saturating add -INTTYPES_ADD_32(vqadd, __builtin_neon_vqadd) -INTTYPES_ADD_64(vqadd, __builtin_neon_vqadd) - -// add high half -// rounding add high half -INTTYPES_NARROWING(vaddhn, __builtin_neon_vaddhn) -INTTYPES_NARROWING(vraddhn, __builtin_neon_vraddhn) - -// multiply -// mul-poly - -// multiple accumulate -// multiple subtract - -// multiple accumulate long -// multiple subtract long -INTTYPES_WIDENING_MUL(vmlal, __builtin_neon_vmlal) -INTTYPES_WIDENING_MUL(vmlsl, __builtin_neon_vmlsl) - -// saturating doubling multiply high -// saturating rounding doubling multiply high - -// saturating doubling multiply accumulate long -// saturating doubling multiply subtract long - -// long multiply -// long multiply-poly -INTTYPES_WIDENING(vmull, __builtin_neon_vmull) -__ai poly16x8_t vmull_p8(poly8x8_t a, poly8x8_t b) { return (poly16x8_t){ __builtin_neon_vmull(a.val, b.val) }; } - -// saturating doubling long multiply - -// subtract - -// long subtract -INTTYPES_WIDENING(vsubl, __builtin_neon_vsubl) - -// wide subtract -INTTYPES_WIDE(vsubw, __builtin_neon_vsubw) - -// saturating subtract -INTTYPES_ADD_32(vqsub, __builtin_neon_vqsub) -INTTYPES_ADD_64(vqsub, __builtin_neon_vqsub) - -// halving subtract -INTTYPES_ADD_32(vhsub, __builtin_neon_vhsub) - -// subtract high half -// rounding subtract high half -INTTYPES_NARROWING(vsubhn, __builtin_neon_vsubhn) -INTTYPES_NARROWING(vrsubhn, __builtin_neon_vrsubhn) - -// compare eq -// compare ge -// compare le -// compare gt -// compare lt -INT_FLOAT_CMP_OP(vceq, ==) -INT_FLOAT_CMP_OP(vcge, >=) -INT_FLOAT_CMP_OP(vcle, <=) -INT_FLOAT_CMP_OP(vcgt, >) -INT_FLOAT_CMP_OP(vclt, <) - -// compare eq-poly - -// compare abs ge -// compare abs le -// compare abs gt -// compare abs lt -FLOATTYPES_CMP(vcage, __builtin_neon_vcage) -FLOATTYPES_CMP(vcale, __builtin_neon_vcale) -FLOATTYPES_CMP(vcagt, __builtin_neon_vcagt) -FLOATTYPES_CMP(vcalt, __builtin_neon_vcalt) - -// test bits - -// abs diff -INTTYPES_ADD_32(vabd, __builtin_neon_vabd) -FP_BINARY(vabd, __builtin_neon_vabd) - -// abs diff long -INTTYPES_WIDENING(vabdl, __builtin_neon_vabdl) - -// abs diff accumulate -// abs diff accumulate long - -// max -// min -INTTYPES_ADD_32(vmax, __builtin_neon_vmax) -FP_BINARY(vmax, __builtin_neon_vmax) -INTTYPES_ADD_32(vmin, __builtin_neon_vmin) -FP_BINARY(vmin, __builtin_neon_vmin) - -// pairwise add -// pairwise max -// pairwise min -INT_FP_PAIRWISE_ADD(vpadd, __builtin_neon_vpadd) -INT_FP_PAIRWISE_ADD(vpmax, __builtin_neon_vpmax) -INT_FP_PAIRWISE_ADD(vpmin, __builtin_neon_vpmin) - -// long pairwise add -// long pairwise add accumulate - -// recip -// recip sqrt -FP_BINARY(vrecps, __builtin_neon_vrecps) -FP_BINARY(vrsqrts, __builtin_neon_vrsqrts) - -// shl by vec -// saturating shl by vec -// rounding shl by vec -// saturating rounding shl by vec - -// shr by constant -// shl by constant -// rounding shr by constant -// shr by constant and accumulate -// rounding shr by constant and accumulate -// saturating shl by constant -// s->u saturating shl by constant -// narrowing saturating shr by constant -// s->u narrowing saturating shr by constant -// s->u rounding narrowing saturating shr by constant -// narrowing saturating shr by constant -// rounding narrowing shr by constant -// rounding narrowing saturating shr by constant -// widening shl by constant - -// shr and insert -// shl and insert - -// loads and stores, single vector -// loads and stores, lane -// loads, dupe - -// loads and stores, arrays - -// vget,vgetq lane -// vset, vsetq lane - -// vcreate -// vdup, vdupq -// vmov, vmovq -// vdup_lane, vdupq_lane -// vcombine -// vget_high, vget_low - -// vcvt {u,s} <-> f, f <-> f16 -// narrow -// long move (unpack) -// saturating narrow -// saturating narrow s->u - -// table lookup -// extended table lookup - -// mla with scalar -// widening mla with scalar -// widening saturating doubling mla with scalar -// mls with scalar -// widening mls with scalar -// widening saturating doubling mls with scalar -// mul by scalar -// long mul with scalar -// long mul by scalar -// saturating doubling long mul with scalar -// saturating doubling long mul by scalar -// saturating doubling mul high with scalar -// saturating doubling mul high by scalar -// saturating rounding doubling mul high with scalar -// saturating rounding doubling mul high by scalar -// mla with scalar -// widening mla with sclar -// widening saturating doubling mla with scalar -// mls with scalar -// widening mls with scalar -// widening saturating doubling mls with scalar - -// extract - -// endian swap (vrev) - -// negate - -// abs -// saturating abs -// saturating negate -// count leading signs -INT_UNARY(vabs, __builtin_neon_vabs) -FP_UNARY(vabs, __builtin_neon_vabs) -INT_UNARY(vqabs, __builtin_neon_vqabs) -INT_UNARY(vqneg, __builtin_neon_vqneg) -INT_UNARY(vcls, __builtin_neon_vcls) - -// count leading zeroes -// popcount - -// recip_est -// recip_sqrt_est - -// not-poly -// not - -// and -// or -// xor -// andn -// orn -INT_LOGICAL_OP(vand, &) -INT_LOGICAL_OP(vorr, |) -INT_LOGICAL_OP(veor, ^) -INT_LOGICAL_OP(vbic, &~) -INT_LOGICAL_OP(vorn, |~) - -// bitselect - -// transpose elts -// interleave elts -// deinterleave elts - -// vreinterpret - -#endif /* __ARM_NEON_H */ diff --git a/lib/Headers/arm_neon.td b/lib/Headers/arm_neon.td deleted file mode 100644 index 7ffbfb4a46ac..000000000000 --- a/lib/Headers/arm_neon.td +++ /dev/null @@ -1,341 +0,0 @@ -//===--- arm_neon.td - ARM NEON compiler interface ------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines the TableGen definitions from which the ARM NEON header -// file will be generated. See ARM document DUI0348B. -// -//===----------------------------------------------------------------------===// - -class Op; - -def OP_NONE : Op; -def OP_ADD : Op; -def OP_SUB : Op; -def OP_MUL : Op; -def OP_MLA : Op; -def OP_MLS : Op; -def OP_MUL_N : Op; -def OP_MLA_N : Op; -def OP_MLS_N : Op; -def OP_EQ : Op; -def OP_GE : Op; -def OP_LE : Op; -def OP_GT : Op; -def OP_LT : Op; -def OP_NEG : Op; -def OP_NOT : Op; -def OP_AND : Op; -def OP_OR : Op; -def OP_XOR : Op; -def OP_ANDN : Op; -def OP_ORN : Op; -def OP_CAST : Op; -def OP_HI : Op; -def OP_LO : Op; -def OP_CONC : Op; -def OP_DUP : Op; -def OP_SEL : Op; -def OP_REV64 : Op; -def OP_REV32 : Op; -def OP_REV16 : Op; - -class Inst { - string Prototype = p; - string Types = t; - Op Operand = o; - bit isShift = 0; -} - -// Used to generate Builtins.def -class SInst : Inst {} -class IInst : Inst {} -class WInst : Inst {} - -// prototype: return (arg, arg, ...) -// v: void -// t: best-fit integer (int/poly args) -// x: signed integer (int/float args) -// u: unsigned integer (int/float args) -// f: float (int args) -// d: default -// w: double width elements, same num elts -// n: double width elements, half num elts -// h: half width elements, double num elts -// e: half width elements, double num elts, unsigned -// i: constant int -// l: constant uint64 -// s: scalar of element type -// a: scalar of element type (splat to vector type) -// k: default elt width, double num elts -// #: array of default vectors -// p: pointer type -// c: const pointer type - -// sizes: -// c: char -// s: short -// i: int -// l: long -// f: float -// h: half-float - -// size modifiers: -// U: unsigned -// Q: 128b -// P: polynomial - -//////////////////////////////////////////////////////////////////////////////// -// E.3.1 Addition -def VADD : Inst<"ddd", "csilfUcUsUiUlQcQsQiQlQfQUcQUsQUiQUl", OP_ADD>; -def VADDL : SInst<"wdd", "csiUcUsUi">; -def VADDW : SInst<"wwd", "csiUcUsUi">; -def VHADD : SInst<"ddd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VRHADD : SInst<"ddd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VQADD : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VADDHN : IInst<"dww", "csiUcUsUi">; -def VRADDHN : IInst<"dww", "csiUcUsUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.2 Multiplication -def VMUL : Inst<"ddd", "csifUcUsUiPcQcQsQiQfQUcQUsQUiQPc", OP_MUL>; -def VMLA : Inst<"dddd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_MLA>; -def VMLAL : SInst<"wwdd", "csiUcUsUi">; -def VMLS : Inst<"dddd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_MLS>; -def VMLSL : SInst<"wwdd", "csiUcUsUi">; -def VQDMULH : SInst<"ddd", "siQsQi">; -def VQRDMULH : SInst<"ddd", "siQsQi">; -def VQDMLAL : SInst<"wwdd", "si">; -def VQDMLSL : SInst<"wwdd", "si">; -def VMULL : SInst<"wdd", "csiUcUsUiPc">; -def VQDMULL : SInst<"wdd", "si">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.3 Subtraction -def VSUB : Inst<"ddd", "csilfUcUsUiUlQcQsQiQlQfQUcQUsQUiQUl", OP_SUB>; -def VSUBL : SInst<"wdd", "csiUcUsUi">; -def VSUBW : SInst<"wwd", "csiUcUsUi">; -def VQSUB : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VHSUB : SInst<"ddd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VSUBHN : IInst<"dww", "csiUcUsUi">; -def VRSUBHN : IInst<"dww", "csiUcUsUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.4 Comparison -def VCEQ : Inst<"udd", "csifUcUsUiPcQcQsQiQfQUcQUsQUiQPc", OP_EQ>; -def VCGE : Inst<"udd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_GE>; -def VCLE : Inst<"udd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_LE>; -def VCGT : Inst<"udd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_GT>; -def VCLT : Inst<"udd", "csifUcUsUiQcQsQiQfQUcQUsQUi", OP_LT>; -def VCAGE : IInst<"udd", "fQf">; -def VCALE : IInst<"udd", "fQf">; -def VCAGT : IInst<"udd", "fQf">; -def VCALT : IInst<"udd", "fQf">; -def VTST : WInst<"udd", "csiUcUsUiPcQcQsQiQUcQUsQUiQPc">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.5 Absolute Difference -def VABD : SInst<"ddd", "csiUcUsUifQcQsQiQUcQUsQUiQf">; -def VABDL : SInst<"wdd", "csiUcUsUi">; -def VABA : SInst<"dddd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VABAL : SInst<"wwdd", "csiUcUsUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.6 Max/Min -def VMAX : SInst<"ddd", "csiUcUsUifQcQsQiQUcQUsQUiQf">; -def VMIN : SInst<"ddd", "csiUcUsUifQcQsQiQUcQUsQUiQf">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.7 Pairdise Addition -def VPADD : IInst<"ddd", "csiUcUsUif">; -def VPADDL : SInst<"nd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VPADAL : SInst<"nnd", "csiUcUsUiQcQsQiQUcQUsQUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.8-9 Folding Max/Min -def VPMAX : SInst<"ddd", "csiUcUsUif">; -def VPMIN : SInst<"ddd", "csiUcUsUif">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.10 Reciprocal/Sqrt -def VRECPS : IInst<"ddd", "fQf">; -def VRSQRTS : IInst<"ddd", "fQf">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.11 Shifts by signed variable -def VSHL : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VQSHL : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VRSHL : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VQRSHL : SInst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.12 Shifts by constant -let isShift = 1 in { -def VSHR_N : SInst<"ddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VSHL_N : IInst<"ddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VRSHR_N : SInst<"ddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VSRA_N : SInst<"dddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VRSRA_N : SInst<"dddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VQSHL_N : SInst<"ddi", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl">; -def VQSHLU_N : SInst<"udi", "csilQcQsQiQl">; -def VSHRN_N : IInst<"hki", "silUsUiUl">; -def VQSHRUN_N : SInst<"eki", "sil">; -def VQRSHRUN_N : SInst<"eki", "sil">; -def VQSHRN_N : SInst<"hki", "silUsUiUl">; -def VRSHRN_N : IInst<"hki", "silUsUiUl">; -def VQRSHRN_N : SInst<"hki", "silUsUiUl">; -def VSHLL_N : SInst<"wdi", "csiUcUsUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.13 Shifts with insert -def VSRI_N : WInst<"dddi", "csilUcUsUiUlPcPsQcQsQiQlQUcQUsQUiQUlQPcQPs">; -def VSLI_N : WInst<"dddi", "csilUcUsUiUlPcPsQcQsQiQlQUcQUsQUiQUlQPcQPs">; -} - -//////////////////////////////////////////////////////////////////////////////// -// E.3.14 Loads and stores of a single vector -def VLD1 : WInst<"dc", "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VLD1_LANE : WInst<"dci", "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VLD1_DUP : WInst<"dc", "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VST1 : WInst<"vpd", "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VST1_LANE : WInst<"vpdi", "QUcQUsQUiQUlQcQsQiQlQhQfQPcQPsUcUsUiUlcsilhfPcPs">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.15 Loads and stores of an N-element structure -def VLD2 : WInst<"2c", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VLD3 : WInst<"3c", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VLD4 : WInst<"4c", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VLD2_DUP : WInst<"2c", "UcUsUiUlcsilhfPcPs">; -def VLD3_DUP : WInst<"3c", "UcUsUiUlcsilhfPcPs">; -def VLD4_DUP : WInst<"4c", "UcUsUiUlcsilhfPcPs">; -def VLD2_LANE : WInst<"2ci", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; -def VLD3_LANE : WInst<"3ci", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; -def VLD4_LANE : WInst<"4ci", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; -def VST2 : WInst<"vp2", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VST3 : WInst<"vp3", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VST4 : WInst<"vp4", "QUcQUsQUiQcQsQiQhQfQPcQPsUcUsUiUlcsilhfPcPs">; -def VST2_LANE : WInst<"vp2i", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; -def VST3_LANE : WInst<"vp3i", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; -def VST4_LANE : WInst<"vp4i", "QUsQUiQsQiQhQfQPsUcUsUicsihfPcPs">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.16 Extract lanes from a vector -def VGET_LANE : IInst<"sdi", "UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUl">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.17 Set lanes within a vector -def VSET_LANE : IInst<"dsdi", "UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUl">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.18 Initialize a vector from bit pattern -def VCREATE: Inst<"dl", "csihfUcUsUiUlPcPsl", OP_CAST>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.19 Set all lanes to same value -def VDUP_N : Inst<"ds", "UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUl", OP_DUP>; -def VMOV_N : Inst<"ds", "UcUsUicsiPcPsfQUcQUsQUiQcQsQiQPcQPsQflUlQlQUl", OP_DUP>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.20 Combining vectors -def VCOMBINE : Inst<"kdd", "csilhfUcUsUiUlPcPs", OP_CONC>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.21 Splitting vectors -def VGET_HIGH : Inst<"dk", "csilhfUcUsUiUlPcPs", OP_HI>; -def VGET_LOW : Inst<"dk", "csilhfUcUsUiUlPcPs", OP_LO>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.22 Converting vectors -def VCVT_S32 : SInst<"xd", "fQf">; -def VCVT_U32 : SInst<"ud", "fQf">; -def VCVT_F16 : SInst<"hk", "f">; -def VCVT_N_S32 : SInst<"xdi", "fQf">; -def VCVT_N_U32 : SInst<"udi", "fQf">; -def VCVT_F32 : SInst<"fd", "iUiQiQUi">; -def VCVT_F32_F16 : SInst<"kh", "f">; -def VCVT_N_F32 : SInst<"fdi", "iUiQiQUi">; -def VMOVN : IInst<"hk", "silUsUiUl">; -def VMOVL : SInst<"wd", "csiUcUsUi">; -def VQMOVN : SInst<"hk", "silUsUiUl">; -def VQMOVUN : SInst<"ek", "sil">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.23-24 Table lookup, Extended table lookup -def VTBL1 : WInst<"ddt", "UccPc">; -def VTBL2 : WInst<"d2t", "UccPc">; -def VTBL3 : WInst<"d3t", "UccPc">; -def VTBL4 : WInst<"d4t", "UccPc">; -def VTBX1 : WInst<"dddt", "UccPc">; -def VTBX2 : WInst<"dd2t", "UccPc">; -def VTBX3 : WInst<"dd3t", "UccPc">; -def VTBX4 : WInst<"dd4t", "UccPc">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.25 Operations with a scalar value -def VMLA_LANE : IInst<"ddddi", "siUsUifQsQiQUsQUiQf">; -def VMLAL_LANE : SInst<"wwddi", "siUsUi">; -def VQDMLAL_LANE : SInst<"wwddi", "si">; -def VMLS_LANE : IInst<"ddddi", "siUsUifQsQiQUsQUiQf">; -def VMLSL_LANE : SInst<"wwddi", "siUsUi">; -def VQDMLSL_LANE : SInst<"wwddi", "si">; -def VMUL_N : Inst<"dds", "sifUsUiQsQiQfQUsQUi", OP_MUL_N>; -def VMULL_N : SInst<"wda", "siUsUi">; -def VMULL_LANE : SInst<"wddi", "siUsUi">; -def VQDMULL_N : SInst<"wda", "si">; -def VQDMULL_LANE : SInst<"wddi", "si">; -def VQDMULH_N : SInst<"dda", "siQsQi">; -def VQDMULH_LANE : SInst<"dddi", "siQsQi">; -def VQRDMULH_N : SInst<"dda", "siQsQi">; -def VQRDMULH_LANE : SInst<"dddi", "siQsQi">; -def VMLA_N : Inst<"ddda", "siUsUifQsQiQUsQUiQf", OP_MLA_N>; -def VMLAL_N : SInst<"wwda", "siUsUi">; -def VQDMLAL_N : SInst<"wwda", "si">; -def VMLS_N : Inst<"ddds", "siUsUifQsQiQUsQUiQf", OP_MLS_N>; -def VMLSL_N : SInst<"wwda", "siUsUi">; -def VQDMLSL_N : SInst<"wwda", "si">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.26 Vector Extract -def VEXT : WInst<"dddi", "cUcPcsUsPsiUilUlQcQUcQPcQsQUsQPsQiQUiQlQUl">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.27 Reverse vector elements (sdap endianness) -def VREV64 : Inst<"dd", "csiUcUsUiPcPsfQcQsQiQUcQUsQUiQPcQPsQf", OP_REV64>; -def VREV32 : Inst<"dd", "csUcUsPcQcQsQUcQUsQPc", OP_REV32>; -def VREV16 : Inst<"dd", "cUcPcQcQUcQPc", OP_REV16>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.28 Other single operand arithmetic -def VABS : SInst<"dd", "csifQcQsQiQf">; -def VQABS : SInst<"dd", "csiQcQsQi">; -def VNEG : Inst<"dd", "csifQcQsQiQf", OP_NEG>; -def VQNEG : SInst<"dd", "csiQcQsQi">; -def VCLS : SInst<"dd", "csiQcQsQi">; -def VCLZ : IInst<"dd", "csiUcUsUiQcQsQiQUcQUsQUi">; -def VCNT : WInst<"dd", "UccPcQUcQcQPc">; -def VRECPE : SInst<"dd", "fUiQfQUi">; -def VRSQRTE : SInst<"dd", "fUiQfQUi">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.29 Logical operations -def VMVN : Inst<"dd", "csiUcUsUiPcQcQsQiQUcQUsQUiQPc", OP_NOT>; -def VAND : Inst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl", OP_AND>; -def VORR : Inst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl", OP_OR>; -def VEOR : Inst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl", OP_XOR>; -def VBIC : Inst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl", OP_ANDN>; -def VORN : Inst<"ddd", "csilUcUsUiUlQcQsQiQlQUcQUsQUiQUl", OP_ORN>; -def VBSL : Inst<"dudd", "csilUcUsUiUlfPcPsQcQsQiQlQUcQUsQUiQUlQfQPcQPs", OP_SEL>; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.30 Transposition operations -def VTRN: WInst<"2dd", "csiUcUsUifPcPsQcQsQiQUcQUsQUiQfQPcQPs">; -def VZIP: WInst<"2dd", "csUcUsfPcPsQcQsQiQUcQUsQUiQfQPcQPs">; -def VUZP: WInst<"2dd", "csiUcUsUifPcPsQcQsQiQUcQUsQUiQfQPcQPs">; - -//////////////////////////////////////////////////////////////////////////////// -// E.3.31 Vector reinterpret cast operations diff --git a/tools/CIndex/CIndex.cpp b/tools/CIndex/CIndex.cpp deleted file mode 100644 index 9cdb9659fe95..000000000000 --- a/tools/CIndex/CIndex.cpp +++ /dev/null @@ -1,2589 +0,0 @@ -//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements the main API hooks in the Clang-C Source Indexing -// library. -// -//===----------------------------------------------------------------------===// - -#include "CIndexer.h" -#include "CXCursor.h" -#include "CXSourceLocation.h" -#include "CIndexDiagnostic.h" - -#include "clang/Basic/Version.h" - -#include "clang/AST/DeclVisitor.h" -#include "clang/AST/StmtVisitor.h" -#include "clang/AST/TypeLocVisitor.h" -#include "clang/Basic/Diagnostic.h" -#include "clang/Frontend/ASTUnit.h" -#include "clang/Frontend/CompilerInstance.h" -#include "clang/Frontend/FrontendDiagnostic.h" -#include "clang/Lex/Lexer.h" -#include "clang/Lex/PreprocessingRecord.h" -#include "clang/Lex/Preprocessor.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/System/Program.h" -#include "llvm/System/Signals.h" - -// Needed to define L_TMPNAM on some systems. -#include - -using namespace clang; -using namespace clang::cxcursor; -using namespace clang::cxstring; - -//===----------------------------------------------------------------------===// -// Crash Reporting. -//===----------------------------------------------------------------------===// - -#ifdef __APPLE__ -#define USE_CRASHTRACER -#include "clang/Analysis/Support/SaveAndRestore.h" -// Integrate with crash reporter. -extern "C" const char *__crashreporter_info__; -#define NUM_CRASH_STRINGS 32 -static unsigned crashtracer_counter = 0; -static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 }; -static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 }; -static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 }; - -static unsigned SetCrashTracerInfo(const char *str, - llvm::SmallString<1024> &AggStr) { - - unsigned slot = 0; - while (crashtracer_strings[slot]) { - if (++slot == NUM_CRASH_STRINGS) - slot = 0; - } - crashtracer_strings[slot] = str; - crashtracer_counter_id[slot] = ++crashtracer_counter; - - // We need to create an aggregate string because multiple threads - // may be in this method at one time. The crash reporter string - // will attempt to overapproximate the set of in-flight invocations - // of this function. Race conditions can still cause this goal - // to not be achieved. - { - llvm::raw_svector_ostream Out(AggStr); - for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i) - if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n'; - } - __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str(); - return slot; -} - -static void ResetCrashTracerInfo(unsigned slot) { - unsigned max_slot = 0; - unsigned max_value = 0; - - crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0; - - for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i) - if (agg_crashtracer_strings[i] && - crashtracer_counter_id[i] > max_value) { - max_slot = i; - max_value = crashtracer_counter_id[i]; - } - - __crashreporter_info__ = agg_crashtracer_strings[max_slot]; -} - -namespace { -class ArgsCrashTracerInfo { - llvm::SmallString<1024> CrashString; - llvm::SmallString<1024> AggregateString; - unsigned crashtracerSlot; -public: - ArgsCrashTracerInfo(llvm::SmallVectorImpl &Args) - : crashtracerSlot(0) - { - { - llvm::raw_svector_ostream Out(CrashString); - Out << "ClangCIndex [" << getClangFullVersion() << "]" - << "[createTranslationUnitFromSourceFile]: clang"; - for (llvm::SmallVectorImpl::iterator I=Args.begin(), - E=Args.end(); I!=E; ++I) - Out << ' ' << *I; - } - crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(), - AggregateString); - } - - ~ArgsCrashTracerInfo() { - ResetCrashTracerInfo(crashtracerSlot); - } -}; -} -#endif - -/// \brief The result of comparing two source ranges. -enum RangeComparisonResult { - /// \brief Either the ranges overlap or one of the ranges is invalid. - RangeOverlap, - - /// \brief The first range ends before the second range starts. - RangeBefore, - - /// \brief The first range starts after the second range ends. - RangeAfter -}; - -/// \brief Compare two source ranges to determine their relative position in -/// the translation unit. -static RangeComparisonResult RangeCompare(SourceManager &SM, - SourceRange R1, - SourceRange R2) { - assert(R1.isValid() && "First range is invalid?"); - assert(R2.isValid() && "Second range is invalid?"); - if (R1.getEnd() == R2.getBegin() || - SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin())) - return RangeBefore; - if (R2.getEnd() == R1.getBegin() || - SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin())) - return RangeAfter; - return RangeOverlap; -} - -/// \brief Translate a Clang source range into a CIndex source range. -/// -/// Clang internally represents ranges where the end location points to the -/// start of the token at the end. However, for external clients it is more -/// useful to have a CXSourceRange be a proper half-open interval. This routine -/// does the appropriate translation. -CXSourceRange cxloc::translateSourceRange(const SourceManager &SM, - const LangOptions &LangOpts, - SourceRange R) { - // We want the last character in this location, so we will adjust the - // location accordingly. - // FIXME: How do do this with a macro instantiation location? - SourceLocation EndLoc = R.getEnd(); - if (!EndLoc.isInvalid() && EndLoc.isFileID()) { - unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts); - EndLoc = EndLoc.getFileLocWithOffset(Length); - } - - CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts }, - R.getBegin().getRawEncoding(), - EndLoc.getRawEncoding() }; - return Result; -} - -//===----------------------------------------------------------------------===// -// Cursor visitor. -//===----------------------------------------------------------------------===// - -namespace { - -// Cursor visitor. -class CursorVisitor : public DeclVisitor, - public TypeLocVisitor, - public StmtVisitor -{ - /// \brief The translation unit we are traversing. - ASTUnit *TU; - - /// \brief The parent cursor whose children we are traversing. - CXCursor Parent; - - /// \brief The declaration that serves at the parent of any statement or - /// expression nodes. - Decl *StmtParent; - - /// \brief The visitor function. - CXCursorVisitor Visitor; - - /// \brief The opaque client data, to be passed along to the visitor. - CXClientData ClientData; - - // MaxPCHLevel - the maximum PCH level of declarations that we will pass on - // to the visitor. Declarations with a PCH level greater than this value will - // be suppressed. - unsigned MaxPCHLevel; - - /// \brief When valid, a source range to which the cursor should restrict - /// its search. - SourceRange RegionOfInterest; - - using DeclVisitor::Visit; - using TypeLocVisitor::Visit; - using StmtVisitor::Visit; - - /// \brief Determine whether this particular source range comes before, comes - /// after, or overlaps the region of interest. - /// - /// \param R a half-open source range retrieved from the abstract syntax tree. - RangeComparisonResult CompareRegionOfInterest(SourceRange R); - -public: - CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData, - unsigned MaxPCHLevel, - SourceRange RegionOfInterest = SourceRange()) - : TU(TU), Visitor(Visitor), ClientData(ClientData), - MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest) - { - Parent.kind = CXCursor_NoDeclFound; - Parent.data[0] = 0; - Parent.data[1] = 0; - Parent.data[2] = 0; - StmtParent = 0; - } - - bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false); - - std::pair - getPreprocessedEntities(); - - bool VisitChildren(CXCursor Parent); - - // Declaration visitors - bool VisitAttributes(Decl *D); - bool VisitBlockDecl(BlockDecl *B); - bool VisitDeclContext(DeclContext *DC); - bool VisitTranslationUnitDecl(TranslationUnitDecl *D); - bool VisitTypedefDecl(TypedefDecl *D); - bool VisitTagDecl(TagDecl *D); - bool VisitEnumConstantDecl(EnumConstantDecl *D); - bool VisitDeclaratorDecl(DeclaratorDecl *DD); - bool VisitFunctionDecl(FunctionDecl *ND); - bool VisitFieldDecl(FieldDecl *D); - bool VisitVarDecl(VarDecl *); - bool VisitObjCMethodDecl(ObjCMethodDecl *ND); - bool VisitObjCContainerDecl(ObjCContainerDecl *D); - bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND); - bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID); - bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); - bool VisitObjCImplDecl(ObjCImplDecl *D); - bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); - bool VisitObjCImplementationDecl(ObjCImplementationDecl *D); - // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations, - // etc. - // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations. - bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D); - bool VisitObjCClassDecl(ObjCClassDecl *D); - - // Type visitors - // FIXME: QualifiedTypeLoc doesn't provide any location information - bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL); - bool VisitTypedefTypeLoc(TypedefTypeLoc TL); - bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL); - bool VisitTagTypeLoc(TagTypeLoc TL); - // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information - bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL); - bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL); - bool VisitPointerTypeLoc(PointerTypeLoc TL); - bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL); - bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL); - bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL); - bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL); - bool VisitFunctionTypeLoc(FunctionTypeLoc TL); - bool VisitArrayTypeLoc(ArrayTypeLoc TL); - // FIXME: Implement for TemplateSpecializationTypeLoc - // FIXME: Implement visitors here when the unimplemented TypeLocs get - // implemented - bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL); - bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL); - - // Statement visitors - bool VisitStmt(Stmt *S); - bool VisitDeclStmt(DeclStmt *S); - // FIXME: LabelStmt label? - bool VisitIfStmt(IfStmt *S); - bool VisitSwitchStmt(SwitchStmt *S); - bool VisitWhileStmt(WhileStmt *S); - bool VisitForStmt(ForStmt *S); - - // Expression visitors - bool VisitBlockExpr(BlockExpr *B); - bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E); - bool VisitExplicitCastExpr(ExplicitCastExpr *E); - bool VisitObjCMessageExpr(ObjCMessageExpr *E); - bool VisitObjCEncodeExpr(ObjCEncodeExpr *E); - bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E); -}; - -} // end anonymous namespace - -RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) { - return RangeCompare(TU->getSourceManager(), R, RegionOfInterest); -} - -/// \brief Visit the given cursor and, if requested by the visitor, -/// its children. -/// -/// \param Cursor the cursor to visit. -/// -/// \param CheckRegionOfInterest if true, then the caller already checked that -/// this cursor is within the region of interest. -/// -/// \returns true if the visitation should be aborted, false if it -/// should continue. -bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) { - if (clang_isInvalid(Cursor.kind)) - return false; - - if (clang_isDeclaration(Cursor.kind)) { - Decl *D = getCursorDecl(Cursor); - assert(D && "Invalid declaration cursor"); - if (D->getPCHLevel() > MaxPCHLevel) - return false; - - if (D->isImplicit()) - return false; - } - - // If we have a range of interest, and this cursor doesn't intersect with it, - // we're done. - if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) { - SourceRange Range = - cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor)); - if (Range.isInvalid() || CompareRegionOfInterest(Range)) - return false; - } - - switch (Visitor(Cursor, Parent, ClientData)) { - case CXChildVisit_Break: - return true; - - case CXChildVisit_Continue: - return false; - - case CXChildVisit_Recurse: - return VisitChildren(Cursor); - } - - return false; -} - -std::pair -CursorVisitor::getPreprocessedEntities() { - PreprocessingRecord &PPRec - = *TU->getPreprocessor().getPreprocessingRecord(); - - bool OnlyLocalDecls - = !TU->isMainFileAST() && TU->getOnlyLocalDecls(); - - // There is no region of interest; we have to walk everything. - if (RegionOfInterest.isInvalid()) - return std::make_pair(PPRec.begin(OnlyLocalDecls), - PPRec.end(OnlyLocalDecls)); - - // Find the file in which the region of interest lands. - SourceManager &SM = TU->getSourceManager(); - std::pair Begin - = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin()); - std::pair End - = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd()); - - // The region of interest spans files; we have to walk everything. - if (Begin.first != End.first) - return std::make_pair(PPRec.begin(OnlyLocalDecls), - PPRec.end(OnlyLocalDecls)); - - ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap - = TU->getPreprocessedEntitiesByFile(); - if (ByFileMap.empty()) { - // Build the mapping from files to sets of preprocessed entities. - for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls), - EEnd = PPRec.end(OnlyLocalDecls); - E != EEnd; ++E) { - std::pair P - = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin()); - ByFileMap[P.first].push_back(*E); - } - } - - return std::make_pair(ByFileMap[Begin.first].begin(), - ByFileMap[Begin.first].end()); -} - -/// \brief Visit the children of the given cursor. -/// -/// \returns true if the visitation should be aborted, false if it -/// should continue. -bool CursorVisitor::VisitChildren(CXCursor Cursor) { - if (clang_isReference(Cursor.kind)) { - // By definition, references have no children. - return false; - } - - // Set the Parent field to Cursor, then back to its old value once we're - // done. - class SetParentRAII { - CXCursor &Parent; - Decl *&StmtParent; - CXCursor OldParent; - - public: - SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent) - : Parent(Parent), StmtParent(StmtParent), OldParent(Parent) - { - Parent = NewParent; - if (clang_isDeclaration(Parent.kind)) - StmtParent = getCursorDecl(Parent); - } - - ~SetParentRAII() { - Parent = OldParent; - if (clang_isDeclaration(Parent.kind)) - StmtParent = getCursorDecl(Parent); - } - } SetParent(Parent, StmtParent, Cursor); - - if (clang_isDeclaration(Cursor.kind)) { - Decl *D = getCursorDecl(Cursor); - assert(D && "Invalid declaration cursor"); - return VisitAttributes(D) || Visit(D); - } - - if (clang_isStatement(Cursor.kind)) - return Visit(getCursorStmt(Cursor)); - if (clang_isExpression(Cursor.kind)) - return Visit(getCursorExpr(Cursor)); - - if (clang_isTranslationUnit(Cursor.kind)) { - ASTUnit *CXXUnit = getCursorASTUnit(Cursor); - if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() && - RegionOfInterest.isInvalid()) { - const std::vector &TLDs = CXXUnit->getTopLevelDecls(); - for (std::vector::const_iterator it = TLDs.begin(), - ie = TLDs.end(); it != ie; ++it) { - if (Visit(MakeCXCursor(*it, CXXUnit), true)) - return true; - } - } else if (VisitDeclContext( - CXXUnit->getASTContext().getTranslationUnitDecl())) - return true; - - // Walk the preprocessing record. - if (CXXUnit->getPreprocessor().getPreprocessingRecord()) { - // FIXME: Once we have the ability to deserialize a preprocessing record, - // do so. - PreprocessingRecord::iterator E, EEnd; - for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) { - if (MacroInstantiation *MI = dyn_cast(*E)) { - if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit))) - return true; - - continue; - } - - if (MacroDefinition *MD = dyn_cast(*E)) { - if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit))) - return true; - - continue; - } - } - } - return false; - } - - // Nothing to visit at the moment. - return false; -} - -bool CursorVisitor::VisitBlockDecl(BlockDecl *B) { - for (BlockDecl::param_iterator I=B->param_begin(), E=B->param_end(); I!=E;++I) - if (Decl *D = *I) - if (Visit(D)) - return true; - - return Visit(MakeCXCursor(B->getBody(), StmtParent, TU)); -} - -bool CursorVisitor::VisitDeclContext(DeclContext *DC) { - for (DeclContext::decl_iterator - I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) { - - CXCursor Cursor = MakeCXCursor(*I, TU); - - if (RegionOfInterest.isValid()) { - SourceRange Range = - cxloc::translateCXSourceRange(clang_getCursorExtent(Cursor)); - if (Range.isInvalid()) - continue; - - switch (CompareRegionOfInterest(Range)) { - case RangeBefore: - // This declaration comes before the region of interest; skip it. - continue; - - case RangeAfter: - // This declaration comes after the region of interest; we're done. - return false; - - case RangeOverlap: - // This declaration overlaps the region of interest; visit it. - break; - } - } - - if (Visit(Cursor, true)) - return true; - } - - return false; -} - -bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) { - llvm_unreachable("Translation units are visited directly by Visit()"); - return false; -} - -bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) { - if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo()) - return Visit(TSInfo->getTypeLoc()); - - return false; -} - -bool CursorVisitor::VisitTagDecl(TagDecl *D) { - return VisitDeclContext(D); -} - -bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) { - if (Expr *Init = D->getInitExpr()) - return Visit(MakeCXCursor(Init, StmtParent, TU)); - return false; -} - -bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) { - if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo()) - if (Visit(TSInfo->getTypeLoc())) - return true; - - return false; -} - -bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) { - if (VisitDeclaratorDecl(ND)) - return true; - - if (ND->isThisDeclarationADefinition() && - Visit(MakeCXCursor(ND->getBody(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitFieldDecl(FieldDecl *D) { - if (VisitDeclaratorDecl(D)) - return true; - - if (Expr *BitWidth = D->getBitWidth()) - return Visit(MakeCXCursor(BitWidth, StmtParent, TU)); - - return false; -} - -bool CursorVisitor::VisitVarDecl(VarDecl *D) { - if (VisitDeclaratorDecl(D)) - return true; - - if (Expr *Init = D->getInit()) - return Visit(MakeCXCursor(Init, StmtParent, TU)); - - return false; -} - -bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) { - if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo()) - if (Visit(TSInfo->getTypeLoc())) - return true; - - for (ObjCMethodDecl::param_iterator P = ND->param_begin(), - PEnd = ND->param_end(); - P != PEnd; ++P) { - if (Visit(MakeCXCursor(*P, TU))) - return true; - } - - if (ND->isThisDeclarationADefinition() && - Visit(MakeCXCursor(ND->getBody(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) { - return VisitDeclContext(D); -} - -bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) { - if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(), - TU))) - return true; - - ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin(); - for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(), - E = ND->protocol_end(); I != E; ++I, ++PL) - if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) - return true; - - return VisitObjCContainerDecl(ND); -} - -bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) { - ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin(); - for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(), - E = PID->protocol_end(); I != E; ++I, ++PL) - if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) - return true; - - return VisitObjCContainerDecl(PID); -} - -bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { - // Issue callbacks for super class. - if (D->getSuperClass() && - Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), - D->getSuperClassLoc(), - TU))) - return true; - - ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); - for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(), - E = D->protocol_end(); I != E; ++I, ++PL) - if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) - return true; - - return VisitObjCContainerDecl(D); -} - -bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) { - return VisitObjCContainerDecl(D); -} - -bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { - // 'ID' could be null when dealing with invalid code. - if (ObjCInterfaceDecl *ID = D->getClassInterface()) - if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU))) - return true; - - return VisitObjCImplDecl(D); -} - -bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { -#if 0 - // Issue callbacks for super class. - // FIXME: No source location information! - if (D->getSuperClass() && - Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(), - D->getSuperClassLoc(), - TU))) - return true; -#endif - - return VisitObjCImplDecl(D); -} - -bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) { - ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin(); - for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(), - E = D->protocol_end(); - I != E; ++I, ++PL) - if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) { - for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C) - if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { - ASTContext &Context = TU->getASTContext(); - - // Some builtin types (such as Objective-C's "id", "sel", and - // "Class") have associated declarations. Create cursors for those. - QualType VisitType; - switch (TL.getType()->getAs()->getKind()) { - case BuiltinType::Void: - case BuiltinType::Bool: - case BuiltinType::Char_U: - case BuiltinType::UChar: - case BuiltinType::Char16: - case BuiltinType::Char32: - case BuiltinType::UShort: - case BuiltinType::UInt: - case BuiltinType::ULong: - case BuiltinType::ULongLong: - case BuiltinType::UInt128: - case BuiltinType::Char_S: - case BuiltinType::SChar: - case BuiltinType::WChar: - case BuiltinType::Short: - case BuiltinType::Int: - case BuiltinType::Long: - case BuiltinType::LongLong: - case BuiltinType::Int128: - case BuiltinType::Float: - case BuiltinType::Double: - case BuiltinType::LongDouble: - case BuiltinType::NullPtr: - case BuiltinType::Overload: - case BuiltinType::Dependent: - break; - - case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor? - break; - - case BuiltinType::ObjCId: - VisitType = Context.getObjCIdType(); - break; - - case BuiltinType::ObjCClass: - VisitType = Context.getObjCClassType(); - break; - - case BuiltinType::ObjCSel: - VisitType = Context.getObjCSelType(); - break; - } - - if (!VisitType.isNull()) { - if (const TypedefType *Typedef = VisitType->getAs()) - return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(), - TU)); - } - - return false; -} - -bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) { - return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU)); -} - -bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) { - return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); -} - -bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) { - return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU)); -} - -bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { - if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU))) - return true; - - for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { - if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I), - TU))) - return true; - } - - return false; -} - -bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { - if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseTypeLoc())) - return true; - - if (TL.hasProtocolsAsWritten()) { - for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) { - if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), - TL.getProtocolLoc(I), - TU))) - return true; - } - } - - return false; -} - -bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) { - return Visit(TL.getPointeeLoc()); -} - -bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { - return Visit(TL.getPointeeLoc()); -} - -bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { - return Visit(TL.getPointeeLoc()); -} - -bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { - return Visit(TL.getPointeeLoc()); -} - -bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { - return Visit(TL.getPointeeLoc()); -} - -bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) { - if (Visit(TL.getResultLoc())) - return true; - - for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I) - if (Decl *D = TL.getArg(I)) - if (Visit(MakeCXCursor(D, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) { - if (Visit(TL.getElementLoc())) - return true; - - if (Expr *Size = TL.getSizeExpr()) - return Visit(MakeCXCursor(Size, StmtParent, TU)); - - return false; -} - -bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { - return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU)); -} - -bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { - if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo()) - return Visit(TSInfo->getTypeLoc()); - - return false; -} - -bool CursorVisitor::VisitStmt(Stmt *S) { - for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end(); - Child != ChildEnd; ++Child) { - if (*Child && Visit(MakeCXCursor(*Child, StmtParent, TU))) - return true; - } - - return false; -} - -bool CursorVisitor::VisitDeclStmt(DeclStmt *S) { - for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end(); - D != DEnd; ++D) { - if (*D && Visit(MakeCXCursor(*D, TU))) - return true; - } - - return false; -} - -bool CursorVisitor::VisitIfStmt(IfStmt *S) { - if (VarDecl *Var = S->getConditionVariable()) { - if (Visit(MakeCXCursor(Var, TU))) - return true; - } - - if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) - return true; - if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU))) - return true; - if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) { - if (VarDecl *Var = S->getConditionVariable()) { - if (Visit(MakeCXCursor(Var, TU))) - return true; - } - - if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) - return true; - if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitWhileStmt(WhileStmt *S) { - if (VarDecl *Var = S->getConditionVariable()) { - if (Visit(MakeCXCursor(Var, TU))) - return true; - } - - if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) - return true; - if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitForStmt(ForStmt *S) { - if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU))) - return true; - if (VarDecl *Var = S->getConditionVariable()) { - if (Visit(MakeCXCursor(Var, TU))) - return true; - } - - if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU))) - return true; - if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU))) - return true; - if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU))) - return true; - - return false; -} - -bool CursorVisitor::VisitBlockExpr(BlockExpr *B) { - return Visit(B->getBlockDecl()); -} - -bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { - if (E->isArgumentType()) { - if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo()) - return Visit(TSInfo->getTypeLoc()); - - return false; - } - - return VisitExpr(E); -} - -bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) { - if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten()) - if (Visit(TSInfo->getTypeLoc())) - return true; - - return VisitCastExpr(E); -} - -bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { - if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo()) - if (Visit(TSInfo->getTypeLoc())) - return true; - - return VisitExpr(E); -} - -bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) { - if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo()) - if (Visit(TSInfo->getTypeLoc())) - return true; - - return VisitExpr(E); -} - -bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) { - return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc()); -} - - -bool CursorVisitor::VisitAttributes(Decl *D) { - for (const Attr *A = D->getAttrs(); A; A = A->getNext()) - if (Visit(MakeCXCursor(A, D, TU))) - return true; - - return false; -} - -extern "C" { -CXIndex clang_createIndex(int excludeDeclarationsFromPCH, - int displayDiagnostics) { - CIndexer *CIdxr = new CIndexer(); - if (excludeDeclarationsFromPCH) - CIdxr->setOnlyLocalDecls(); - if (displayDiagnostics) - CIdxr->setDisplayDiagnostics(); - return CIdxr; -} - -void clang_disposeIndex(CXIndex CIdx) { - if (CIdx) - delete static_cast(CIdx); -} - -void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) { - if (CIdx) { - CIndexer *CXXIdx = static_cast(CIdx); - CXXIdx->setUseExternalASTGeneration(value); - } -} - -CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx, - const char *ast_filename) { - if (!CIdx) - return 0; - - CIndexer *CXXIdx = static_cast(CIdx); - - llvm::IntrusiveRefCntPtr Diags; - return ASTUnit::LoadFromPCHFile(ast_filename, Diags, - CXXIdx->getOnlyLocalDecls(), - 0, 0, true); -} - -CXTranslationUnit -clang_createTranslationUnitFromSourceFile(CXIndex CIdx, - const char *source_filename, - int num_command_line_args, - const char **command_line_args, - unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files) { - if (!CIdx) - return 0; - - CIndexer *CXXIdx = static_cast(CIdx); - - // Configure the diagnostics. - DiagnosticOptions DiagOpts; - llvm::IntrusiveRefCntPtr Diags; - Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); - - llvm::SmallVector RemappedFiles; - for (unsigned I = 0; I != num_unsaved_files; ++I) { - llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); - const llvm::MemoryBuffer *Buffer - = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); - RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, - Buffer)); - } - - if (!CXXIdx->getUseExternalASTGeneration()) { - llvm::SmallVector Args; - - // The 'source_filename' argument is optional. If the caller does not - // specify it then it is assumed that the source file is specified - // in the actual argument list. - if (source_filename) - Args.push_back(source_filename); - Args.insert(Args.end(), command_line_args, - command_line_args + num_command_line_args); - Args.push_back("-Xclang"); - Args.push_back("-detailed-preprocessing-record"); - unsigned NumErrors = Diags->getNumErrors(); - -#ifdef USE_CRASHTRACER - ArgsCrashTracerInfo ACTI(Args); -#endif - - llvm::OwningPtr Unit( - ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(), - Diags, - CXXIdx->getClangResourcesPath(), - CXXIdx->getOnlyLocalDecls(), - RemappedFiles.data(), - RemappedFiles.size(), - /*CaptureDiagnostics=*/true)); - - // FIXME: Until we have broader testing, just drop the entire AST if we - // encountered an error. - if (NumErrors != Diags->getNumErrors()) { - // Make sure to check that 'Unit' is non-NULL. - if (CXXIdx->getDisplayDiagnostics() && Unit.get()) { - for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(), - DEnd = Unit->stored_diag_end(); - D != DEnd; ++D) { - CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions()); - CXString Msg = clang_formatDiagnostic(&Diag, - clang_defaultDiagnosticDisplayOptions()); - fprintf(stderr, "%s\n", clang_getCString(Msg)); - clang_disposeString(Msg); - } -#ifdef LLVM_ON_WIN32 - // On Windows, force a flush, since there may be multiple copies of - // stderr and stdout in the file system, all with different buffers - // but writing to the same device. - fflush(stderr); -#endif - } - } - - return Unit.take(); - } - - // Build up the arguments for invoking 'clang'. - std::vector argv; - - // First add the complete path to the 'clang' executable. - llvm::sys::Path ClangPath = static_cast(CIdx)->getClangPath(); - argv.push_back(ClangPath.c_str()); - - // Add the '-emit-ast' option as our execution mode for 'clang'. - argv.push_back("-emit-ast"); - - // The 'source_filename' argument is optional. If the caller does not - // specify it then it is assumed that the source file is specified - // in the actual argument list. - if (source_filename) - argv.push_back(source_filename); - - // Generate a temporary name for the AST file. - argv.push_back("-o"); - char astTmpFile[L_tmpnam]; - argv.push_back(tmpnam(astTmpFile)); - - // Remap any unsaved files to temporary files. - std::vector TemporaryFiles; - std::vector RemapArgs; - if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles)) - return 0; - - // The pointers into the elements of RemapArgs are stable because we - // won't be adding anything to RemapArgs after this point. - for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i) - argv.push_back(RemapArgs[i].c_str()); - - // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'. - for (int i = 0; i < num_command_line_args; ++i) - if (const char *arg = command_line_args[i]) { - if (strcmp(arg, "-o") == 0) { - ++i; // Also skip the matching argument. - continue; - } - if (strcmp(arg, "-emit-ast") == 0 || - strcmp(arg, "-c") == 0 || - strcmp(arg, "-fsyntax-only") == 0) { - continue; - } - - // Keep the argument. - argv.push_back(arg); - } - - // Generate a temporary name for the diagnostics file. - char tmpFileResults[L_tmpnam]; - char *tmpResultsFileName = tmpnam(tmpFileResults); - llvm::sys::Path DiagnosticsFile(tmpResultsFileName); - TemporaryFiles.push_back(DiagnosticsFile); - argv.push_back("-fdiagnostics-binary"); - - argv.push_back("-Xclang"); - argv.push_back("-detailed-preprocessing-record"); - - // Add the null terminator. - argv.push_back(NULL); - - // Invoke 'clang'. - llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null - // on Unix or NUL (Windows). - std::string ErrMsg; - const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile, - NULL }; - llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL, - /* redirects */ &Redirects[0], - /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg); - - if (!ErrMsg.empty()) { - std::string AllArgs; - for (std::vector::iterator I = argv.begin(), E = argv.end(); - I != E; ++I) { - AllArgs += ' '; - if (*I) - AllArgs += *I; - } - - Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg; - } - - ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags, - CXXIdx->getOnlyLocalDecls(), - RemappedFiles.data(), - RemappedFiles.size(), - /*CaptureDiagnostics=*/true); - if (ATU) { - LoadSerializedDiagnostics(DiagnosticsFile, - num_unsaved_files, unsaved_files, - ATU->getFileManager(), - ATU->getSourceManager(), - ATU->getStoredDiagnostics()); - } else if (CXXIdx->getDisplayDiagnostics()) { - // We failed to load the ASTUnit, but we can still deserialize the - // diagnostics and emit them. - FileManager FileMgr; - Diagnostic Diag; - SourceManager SourceMgr(Diag); - // FIXME: Faked LangOpts! - LangOptions LangOpts; - llvm::SmallVector Diags; - LoadSerializedDiagnostics(DiagnosticsFile, - num_unsaved_files, unsaved_files, - FileMgr, SourceMgr, Diags); - for (llvm::SmallVector::iterator D = Diags.begin(), - DEnd = Diags.end(); - D != DEnd; ++D) { - CXStoredDiagnostic Diag(*D, LangOpts); - CXString Msg = clang_formatDiagnostic(&Diag, - clang_defaultDiagnosticDisplayOptions()); - fprintf(stderr, "%s\n", clang_getCString(Msg)); - clang_disposeString(Msg); - } - -#ifdef LLVM_ON_WIN32 - // On Windows, force a flush, since there may be multiple copies of - // stderr and stdout in the file system, all with different buffers - // but writing to the same device. - fflush(stderr); -#endif - } - - if (ATU) { - // Make the translation unit responsible for destroying all temporary files. - for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i) - ATU->addTemporaryFile(TemporaryFiles[i]); - ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName())); - } else { - // Destroy all of the temporary files now; they can't be referenced any - // longer. - llvm::sys::Path(astTmpFile).eraseFromDisk(); - for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i) - TemporaryFiles[i].eraseFromDisk(); - } - - return ATU; -} - -void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) { - if (CTUnit) - delete static_cast(CTUnit); -} - -CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) { - if (!CTUnit) - return createCXString(""); - - ASTUnit *CXXUnit = static_cast(CTUnit); - return createCXString(CXXUnit->getOriginalSourceFileName(), true); -} - -CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) { - CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } }; - return Result; -} - -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// CXSourceLocation and CXSourceRange Operations. -//===----------------------------------------------------------------------===// - -extern "C" { -CXSourceLocation clang_getNullLocation() { - CXSourceLocation Result = { { 0, 0 }, 0 }; - return Result; -} - -unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) { - return (loc1.ptr_data[0] == loc2.ptr_data[0] && - loc1.ptr_data[1] == loc2.ptr_data[1] && - loc1.int_data == loc2.int_data); -} - -CXSourceLocation clang_getLocation(CXTranslationUnit tu, - CXFile file, - unsigned line, - unsigned column) { - if (!tu) - return clang_getNullLocation(); - - ASTUnit *CXXUnit = static_cast(tu); - SourceLocation SLoc - = CXXUnit->getSourceManager().getLocation( - static_cast(file), - line, column); - - return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc); -} - -CXSourceRange clang_getNullRange() { - CXSourceRange Result = { { 0, 0 }, 0, 0 }; - return Result; -} - -CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) { - if (begin.ptr_data[0] != end.ptr_data[0] || - begin.ptr_data[1] != end.ptr_data[1]) - return clang_getNullRange(); - - CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] }, - begin.int_data, end.int_data }; - return Result; -} - -void clang_getInstantiationLocation(CXSourceLocation location, - CXFile *file, - unsigned *line, - unsigned *column, - unsigned *offset) { - SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data); - - if (!location.ptr_data[0] || Loc.isInvalid()) { - if (file) - *file = 0; - if (line) - *line = 0; - if (column) - *column = 0; - if (offset) - *offset = 0; - return; - } - - const SourceManager &SM = - *static_cast(location.ptr_data[0]); - SourceLocation InstLoc = SM.getInstantiationLoc(Loc); - - if (file) - *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc)); - if (line) - *line = SM.getInstantiationLineNumber(InstLoc); - if (column) - *column = SM.getInstantiationColumnNumber(InstLoc); - if (offset) - *offset = SM.getDecomposedLoc(InstLoc).second; -} - -CXSourceLocation clang_getRangeStart(CXSourceRange range) { - CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, - range.begin_int_data }; - return Result; -} - -CXSourceLocation clang_getRangeEnd(CXSourceRange range) { - CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] }, - range.end_int_data }; - return Result; -} - -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// CXFile Operations. -//===----------------------------------------------------------------------===// - -extern "C" { -CXString clang_getFileName(CXFile SFile) { - if (!SFile) - return createCXString(NULL); - - FileEntry *FEnt = static_cast(SFile); - return createCXString(FEnt->getName()); -} - -time_t clang_getFileTime(CXFile SFile) { - if (!SFile) - return 0; - - FileEntry *FEnt = static_cast(SFile); - return FEnt->getModificationTime(); -} - -CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) { - if (!tu) - return 0; - - ASTUnit *CXXUnit = static_cast(tu); - - FileManager &FMgr = CXXUnit->getFileManager(); - const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name)); - return const_cast(File); -} - -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// CXCursor Operations. -//===----------------------------------------------------------------------===// - -static Decl *getDeclFromExpr(Stmt *E) { - if (DeclRefExpr *RefExpr = dyn_cast(E)) - return RefExpr->getDecl(); - if (MemberExpr *ME = dyn_cast(E)) - return ME->getMemberDecl(); - if (ObjCIvarRefExpr *RE = dyn_cast(E)) - return RE->getDecl(); - - if (CallExpr *CE = dyn_cast(E)) - return getDeclFromExpr(CE->getCallee()); - if (CastExpr *CE = dyn_cast(E)) - return getDeclFromExpr(CE->getSubExpr()); - if (ObjCMessageExpr *OME = dyn_cast(E)) - return OME->getMethodDecl(); - - return 0; -} - -static SourceLocation getLocationFromExpr(Expr *E) { - if (ObjCMessageExpr *Msg = dyn_cast(E)) - return /*FIXME:*/Msg->getLeftLoc(); - if (DeclRefExpr *DRE = dyn_cast(E)) - return DRE->getLocation(); - if (MemberExpr *Member = dyn_cast(E)) - return Member->getMemberLoc(); - if (ObjCIvarRefExpr *Ivar = dyn_cast(E)) - return Ivar->getLocation(); - return E->getLocStart(); -} - -extern "C" { - -unsigned clang_visitChildren(CXCursor parent, - CXCursorVisitor visitor, - CXClientData client_data) { - ASTUnit *CXXUnit = getCursorASTUnit(parent); - - unsigned PCHLevel = Decl::MaxPCHLevel; - - // Set the PCHLevel to filter out unwanted decls if requested. - if (CXXUnit->getOnlyLocalDecls()) { - PCHLevel = 0; - - // If the main input was an AST, bump the level. - if (CXXUnit->isMainFileAST()) - ++PCHLevel; - } - - CursorVisitor CursorVis(CXXUnit, visitor, client_data, PCHLevel); - return CursorVis.VisitChildren(parent); -} - -static CXString getDeclSpelling(Decl *D) { - NamedDecl *ND = dyn_cast_or_null(D); - if (!ND) - return createCXString(""); - - if (ObjCMethodDecl *OMD = dyn_cast(ND)) - return createCXString(OMD->getSelector().getAsString()); - - if (ObjCCategoryImplDecl *CIMP = dyn_cast(ND)) - // No, this isn't the same as the code below. getIdentifier() is non-virtual - // and returns different names. NamedDecl returns the class name and - // ObjCCategoryImplDecl returns the category name. - return createCXString(CIMP->getIdentifier()->getNameStart()); - - if (ND->getIdentifier()) - return createCXString(ND->getIdentifier()->getNameStart()); - - return createCXString(""); -} - -CXString clang_getCursorSpelling(CXCursor C) { - if (clang_isTranslationUnit(C.kind)) - return clang_getTranslationUnitSpelling(C.data[2]); - - if (clang_isReference(C.kind)) { - switch (C.kind) { - case CXCursor_ObjCSuperClassRef: { - ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first; - return createCXString(Super->getIdentifier()->getNameStart()); - } - case CXCursor_ObjCClassRef: { - ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first; - return createCXString(Class->getIdentifier()->getNameStart()); - } - case CXCursor_ObjCProtocolRef: { - ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first; - assert(OID && "getCursorSpelling(): Missing protocol decl"); - return createCXString(OID->getIdentifier()->getNameStart()); - } - case CXCursor_TypeRef: { - TypeDecl *Type = getCursorTypeRef(C).first; - assert(Type && "Missing type decl"); - - return createCXString(getCursorContext(C).getTypeDeclType(Type). - getAsString()); - } - - default: - return createCXString(""); - } - } - - if (clang_isExpression(C.kind)) { - Decl *D = getDeclFromExpr(getCursorExpr(C)); - if (D) - return getDeclSpelling(D); - return createCXString(""); - } - - if (C.kind == CXCursor_MacroInstantiation) - return createCXString(getCursorMacroInstantiation(C)->getName() - ->getNameStart()); - - if (C.kind == CXCursor_MacroDefinition) - return createCXString(getCursorMacroDefinition(C)->getName() - ->getNameStart()); - - if (clang_isDeclaration(C.kind)) - return getDeclSpelling(getCursorDecl(C)); - - return createCXString(""); -} - -CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) { - switch (Kind) { - case CXCursor_FunctionDecl: - return createCXString("FunctionDecl"); - case CXCursor_TypedefDecl: - return createCXString("TypedefDecl"); - case CXCursor_EnumDecl: - return createCXString("EnumDecl"); - case CXCursor_EnumConstantDecl: - return createCXString("EnumConstantDecl"); - case CXCursor_StructDecl: - return createCXString("StructDecl"); - case CXCursor_UnionDecl: - return createCXString("UnionDecl"); - case CXCursor_ClassDecl: - return createCXString("ClassDecl"); - case CXCursor_FieldDecl: - return createCXString("FieldDecl"); - case CXCursor_VarDecl: - return createCXString("VarDecl"); - case CXCursor_ParmDecl: - return createCXString("ParmDecl"); - case CXCursor_ObjCInterfaceDecl: - return createCXString("ObjCInterfaceDecl"); - case CXCursor_ObjCCategoryDecl: - return createCXString("ObjCCategoryDecl"); - case CXCursor_ObjCProtocolDecl: - return createCXString("ObjCProtocolDecl"); - case CXCursor_ObjCPropertyDecl: - return createCXString("ObjCPropertyDecl"); - case CXCursor_ObjCIvarDecl: - return createCXString("ObjCIvarDecl"); - case CXCursor_ObjCInstanceMethodDecl: - return createCXString("ObjCInstanceMethodDecl"); - case CXCursor_ObjCClassMethodDecl: - return createCXString("ObjCClassMethodDecl"); - case CXCursor_ObjCImplementationDecl: - return createCXString("ObjCImplementationDecl"); - case CXCursor_ObjCCategoryImplDecl: - return createCXString("ObjCCategoryImplDecl"); - case CXCursor_CXXMethod: - return createCXString("CXXMethod"); - case CXCursor_UnexposedDecl: - return createCXString("UnexposedDecl"); - case CXCursor_ObjCSuperClassRef: - return createCXString("ObjCSuperClassRef"); - case CXCursor_ObjCProtocolRef: - return createCXString("ObjCProtocolRef"); - case CXCursor_ObjCClassRef: - return createCXString("ObjCClassRef"); - case CXCursor_TypeRef: - return createCXString("TypeRef"); - case CXCursor_UnexposedExpr: - return createCXString("UnexposedExpr"); - case CXCursor_BlockExpr: - return createCXString("BlockExpr"); - case CXCursor_DeclRefExpr: - return createCXString("DeclRefExpr"); - case CXCursor_MemberRefExpr: - return createCXString("MemberRefExpr"); - case CXCursor_CallExpr: - return createCXString("CallExpr"); - case CXCursor_ObjCMessageExpr: - return createCXString("ObjCMessageExpr"); - case CXCursor_UnexposedStmt: - return createCXString("UnexposedStmt"); - case CXCursor_InvalidFile: - return createCXString("InvalidFile"); - case CXCursor_InvalidCode: - return createCXString("InvalidCode"); - case CXCursor_NoDeclFound: - return createCXString("NoDeclFound"); - case CXCursor_NotImplemented: - return createCXString("NotImplemented"); - case CXCursor_TranslationUnit: - return createCXString("TranslationUnit"); - case CXCursor_UnexposedAttr: - return createCXString("UnexposedAttr"); - case CXCursor_IBActionAttr: - return createCXString("attribute(ibaction)"); - case CXCursor_IBOutletAttr: - return createCXString("attribute(iboutlet)"); - case CXCursor_PreprocessingDirective: - return createCXString("preprocessing directive"); - case CXCursor_MacroDefinition: - return createCXString("macro definition"); - case CXCursor_MacroInstantiation: - return createCXString("macro instantiation"); - } - - llvm_unreachable("Unhandled CXCursorKind"); - return createCXString(NULL); -} - -enum CXChildVisitResult GetCursorVisitor(CXCursor cursor, - CXCursor parent, - CXClientData client_data) { - CXCursor *BestCursor = static_cast(client_data); - *BestCursor = cursor; - return CXChildVisit_Recurse; -} - -CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) { - if (!TU) - return clang_getNullCursor(); - - ASTUnit *CXXUnit = static_cast(TU); - - ASTUnit::ConcurrencyCheck Check(*CXXUnit); - - SourceLocation SLoc = cxloc::translateSourceLocation(Loc); - CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound); - if (SLoc.isValid()) { - SourceRange RegionOfInterest(SLoc, SLoc.getFileLocWithOffset(1)); - - // FIXME: Would be great to have a "hint" cursor, then walk from that - // hint cursor upward until we find a cursor whose source range encloses - // the region of interest, rather than starting from the translation unit. - CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit); - CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result, - Decl::MaxPCHLevel, RegionOfInterest); - CursorVis.VisitChildren(Parent); - } - return Result; -} - -CXCursor clang_getNullCursor(void) { - return MakeCXCursorInvalid(CXCursor_InvalidFile); -} - -unsigned clang_equalCursors(CXCursor X, CXCursor Y) { - return X == Y; -} - -unsigned clang_isInvalid(enum CXCursorKind K) { - return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid; -} - -unsigned clang_isDeclaration(enum CXCursorKind K) { - return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl; -} - -unsigned clang_isReference(enum CXCursorKind K) { - return K >= CXCursor_FirstRef && K <= CXCursor_LastRef; -} - -unsigned clang_isExpression(enum CXCursorKind K) { - return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr; -} - -unsigned clang_isStatement(enum CXCursorKind K) { - return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt; -} - -unsigned clang_isTranslationUnit(enum CXCursorKind K) { - return K == CXCursor_TranslationUnit; -} - -unsigned clang_isPreprocessing(enum CXCursorKind K) { - return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing; -} - -unsigned clang_isUnexposed(enum CXCursorKind K) { - switch (K) { - case CXCursor_UnexposedDecl: - case CXCursor_UnexposedExpr: - case CXCursor_UnexposedStmt: - case CXCursor_UnexposedAttr: - return true; - default: - return false; - } -} - -CXCursorKind clang_getCursorKind(CXCursor C) { - return C.kind; -} - -CXSourceLocation clang_getCursorLocation(CXCursor C) { - if (clang_isReference(C.kind)) { - switch (C.kind) { - case CXCursor_ObjCSuperClassRef: { - std::pair P - = getCursorObjCSuperClassRef(C); - return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); - } - - case CXCursor_ObjCProtocolRef: { - std::pair P - = getCursorObjCProtocolRef(C); - return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); - } - - case CXCursor_ObjCClassRef: { - std::pair P - = getCursorObjCClassRef(C); - return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); - } - - case CXCursor_TypeRef: { - std::pair P = getCursorTypeRef(C); - return cxloc::translateSourceLocation(P.first->getASTContext(), P.second); - } - - default: - // FIXME: Need a way to enumerate all non-reference cases. - llvm_unreachable("Missed a reference kind"); - } - } - - if (clang_isExpression(C.kind)) - return cxloc::translateSourceLocation(getCursorContext(C), - getLocationFromExpr(getCursorExpr(C))); - - if (C.kind == CXCursor_PreprocessingDirective) { - SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin(); - return cxloc::translateSourceLocation(getCursorContext(C), L); - } - - if (C.kind == CXCursor_MacroInstantiation) { - SourceLocation L - = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin(); - return cxloc::translateSourceLocation(getCursorContext(C), L); - } - - if (C.kind == CXCursor_MacroDefinition) { - SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation(); - return cxloc::translateSourceLocation(getCursorContext(C), L); - } - - if (!getCursorDecl(C)) - return clang_getNullLocation(); - - Decl *D = getCursorDecl(C); - SourceLocation Loc = D->getLocation(); - if (ObjCInterfaceDecl *Class = dyn_cast(D)) - Loc = Class->getClassLoc(); - return cxloc::translateSourceLocation(getCursorContext(C), Loc); -} - -CXSourceRange clang_getCursorExtent(CXCursor C) { - if (clang_isReference(C.kind)) { - switch (C.kind) { - case CXCursor_ObjCSuperClassRef: { - std::pair P - = getCursorObjCSuperClassRef(C); - return cxloc::translateSourceRange(P.first->getASTContext(), P.second); - } - - case CXCursor_ObjCProtocolRef: { - std::pair P - = getCursorObjCProtocolRef(C); - return cxloc::translateSourceRange(P.first->getASTContext(), P.second); - } - - case CXCursor_ObjCClassRef: { - std::pair P - = getCursorObjCClassRef(C); - - return cxloc::translateSourceRange(P.first->getASTContext(), P.second); - } - - case CXCursor_TypeRef: { - std::pair P = getCursorTypeRef(C); - return cxloc::translateSourceRange(P.first->getASTContext(), P.second); - } - - default: - // FIXME: Need a way to enumerate all non-reference cases. - llvm_unreachable("Missed a reference kind"); - } - } - - if (clang_isExpression(C.kind)) - return cxloc::translateSourceRange(getCursorContext(C), - getCursorExpr(C)->getSourceRange()); - - if (clang_isStatement(C.kind)) - return cxloc::translateSourceRange(getCursorContext(C), - getCursorStmt(C)->getSourceRange()); - - if (C.kind == CXCursor_PreprocessingDirective) { - SourceRange R = cxcursor::getCursorPreprocessingDirective(C); - return cxloc::translateSourceRange(getCursorContext(C), R); - } - - if (C.kind == CXCursor_MacroInstantiation) { - SourceRange R = cxcursor::getCursorMacroInstantiation(C)->getSourceRange(); - return cxloc::translateSourceRange(getCursorContext(C), R); - } - - if (C.kind == CXCursor_MacroDefinition) { - SourceRange R = cxcursor::getCursorMacroDefinition(C)->getSourceRange(); - return cxloc::translateSourceRange(getCursorContext(C), R); - } - - if (!getCursorDecl(C)) - return clang_getNullRange(); - - Decl *D = getCursorDecl(C); - return cxloc::translateSourceRange(getCursorContext(C), D->getSourceRange()); -} - -CXCursor clang_getCursorReferenced(CXCursor C) { - if (clang_isInvalid(C.kind)) - return clang_getNullCursor(); - - ASTUnit *CXXUnit = getCursorASTUnit(C); - if (clang_isDeclaration(C.kind)) - return C; - - if (clang_isExpression(C.kind)) { - Decl *D = getDeclFromExpr(getCursorExpr(C)); - if (D) - return MakeCXCursor(D, CXXUnit); - return clang_getNullCursor(); - } - - if (C.kind == CXCursor_MacroInstantiation) { - if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition()) - return MakeMacroDefinitionCursor(Def, CXXUnit); - } - - if (!clang_isReference(C.kind)) - return clang_getNullCursor(); - - switch (C.kind) { - case CXCursor_ObjCSuperClassRef: - return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit); - - case CXCursor_ObjCProtocolRef: { - return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit); - - case CXCursor_ObjCClassRef: - return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit); - - case CXCursor_TypeRef: - return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit); - - default: - // We would prefer to enumerate all non-reference cursor kinds here. - llvm_unreachable("Unhandled reference cursor kind"); - break; - } - } - - return clang_getNullCursor(); -} - -CXCursor clang_getCursorDefinition(CXCursor C) { - if (clang_isInvalid(C.kind)) - return clang_getNullCursor(); - - ASTUnit *CXXUnit = getCursorASTUnit(C); - - bool WasReference = false; - if (clang_isReference(C.kind) || clang_isExpression(C.kind)) { - C = clang_getCursorReferenced(C); - WasReference = true; - } - - if (C.kind == CXCursor_MacroInstantiation) - return clang_getCursorReferenced(C); - - if (!clang_isDeclaration(C.kind)) - return clang_getNullCursor(); - - Decl *D = getCursorDecl(C); - if (!D) - return clang_getNullCursor(); - - switch (D->getKind()) { - // Declaration kinds that don't really separate the notions of - // declaration and definition. - case Decl::Namespace: - case Decl::Typedef: - case Decl::TemplateTypeParm: - case Decl::EnumConstant: - case Decl::Field: - case Decl::ObjCIvar: - case Decl::ObjCAtDefsField: - case Decl::ImplicitParam: - case Decl::ParmVar: - case Decl::NonTypeTemplateParm: - case Decl::TemplateTemplateParm: - case Decl::ObjCCategoryImpl: - case Decl::ObjCImplementation: - case Decl::LinkageSpec: - case Decl::ObjCPropertyImpl: - case Decl::FileScopeAsm: - case Decl::StaticAssert: - case Decl::Block: - return C; - - // Declaration kinds that don't make any sense here, but are - // nonetheless harmless. - case Decl::TranslationUnit: - break; - - // Declaration kinds for which the definition is not resolvable. - case Decl::UnresolvedUsingTypename: - case Decl::UnresolvedUsingValue: - break; - - case Decl::UsingDirective: - return MakeCXCursor(cast(D)->getNominatedNamespace(), - CXXUnit); - - case Decl::NamespaceAlias: - return MakeCXCursor(cast(D)->getNamespace(), CXXUnit); - - case Decl::Enum: - case Decl::Record: - case Decl::CXXRecord: - case Decl::ClassTemplateSpecialization: - case Decl::ClassTemplatePartialSpecialization: - if (TagDecl *Def = cast(D)->getDefinition()) - return MakeCXCursor(Def, CXXUnit); - return clang_getNullCursor(); - - case Decl::Function: - case Decl::CXXMethod: - case Decl::CXXConstructor: - case Decl::CXXDestructor: - case Decl::CXXConversion: { - const FunctionDecl *Def = 0; - if (cast(D)->getBody(Def)) - return MakeCXCursor(const_cast(Def), CXXUnit); - return clang_getNullCursor(); - } - - case Decl::Var: { - // Ask the variable if it has a definition. - if (VarDecl *Def = cast(D)->getDefinition()) - return MakeCXCursor(Def, CXXUnit); - return clang_getNullCursor(); - } - - case Decl::FunctionTemplate: { - const FunctionDecl *Def = 0; - if (cast(D)->getTemplatedDecl()->getBody(Def)) - return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit); - return clang_getNullCursor(); - } - - case Decl::ClassTemplate: { - if (RecordDecl *Def = cast(D)->getTemplatedDecl() - ->getDefinition()) - return MakeCXCursor( - cast(Def)->getDescribedClassTemplate(), - CXXUnit); - return clang_getNullCursor(); - } - - case Decl::Using: { - UsingDecl *Using = cast(D); - CXCursor Def = clang_getNullCursor(); - for (UsingDecl::shadow_iterator S = Using->shadow_begin(), - SEnd = Using->shadow_end(); - S != SEnd; ++S) { - if (Def != clang_getNullCursor()) { - // FIXME: We have no way to return multiple results. - return clang_getNullCursor(); - } - - Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(), - CXXUnit)); - } - - return Def; - } - - case Decl::UsingShadow: - return clang_getCursorDefinition( - MakeCXCursor(cast(D)->getTargetDecl(), - CXXUnit)); - - case Decl::ObjCMethod: { - ObjCMethodDecl *Method = cast(D); - if (Method->isThisDeclarationADefinition()) - return C; - - // Dig out the method definition in the associated - // @implementation, if we have it. - // FIXME: The ASTs should make finding the definition easier. - if (ObjCInterfaceDecl *Class - = dyn_cast(Method->getDeclContext())) - if (ObjCImplementationDecl *ClassImpl = Class->getImplementation()) - if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(), - Method->isInstanceMethod())) - if (Def->isThisDeclarationADefinition()) - return MakeCXCursor(Def, CXXUnit); - - return clang_getNullCursor(); - } - - case Decl::ObjCCategory: - if (ObjCCategoryImplDecl *Impl - = cast(D)->getImplementation()) - return MakeCXCursor(Impl, CXXUnit); - return clang_getNullCursor(); - - case Decl::ObjCProtocol: - if (!cast(D)->isForwardDecl()) - return C; - return clang_getNullCursor(); - - case Decl::ObjCInterface: - // There are two notions of a "definition" for an Objective-C - // class: the interface and its implementation. When we resolved a - // reference to an Objective-C class, produce the @interface as - // the definition; when we were provided with the interface, - // produce the @implementation as the definition. - if (WasReference) { - if (!cast(D)->isForwardDecl()) - return C; - } else if (ObjCImplementationDecl *Impl - = cast(D)->getImplementation()) - return MakeCXCursor(Impl, CXXUnit); - return clang_getNullCursor(); - - case Decl::ObjCProperty: - // FIXME: We don't really know where to find the - // ObjCPropertyImplDecls that implement this property. - return clang_getNullCursor(); - - case Decl::ObjCCompatibleAlias: - if (ObjCInterfaceDecl *Class - = cast(D)->getClassInterface()) - if (!Class->isForwardDecl()) - return MakeCXCursor(Class, CXXUnit); - - return clang_getNullCursor(); - - case Decl::ObjCForwardProtocol: { - ObjCForwardProtocolDecl *Forward = cast(D); - if (Forward->protocol_size() == 1) - return clang_getCursorDefinition( - MakeCXCursor(*Forward->protocol_begin(), - CXXUnit)); - - // FIXME: Cannot return multiple definitions. - return clang_getNullCursor(); - } - - case Decl::ObjCClass: { - ObjCClassDecl *Class = cast(D); - if (Class->size() == 1) { - ObjCInterfaceDecl *IFace = Class->begin()->getInterface(); - if (!IFace->isForwardDecl()) - return MakeCXCursor(IFace, CXXUnit); - return clang_getNullCursor(); - } - - // FIXME: Cannot return multiple definitions. - return clang_getNullCursor(); - } - - case Decl::Friend: - if (NamedDecl *Friend = cast(D)->getFriendDecl()) - return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); - return clang_getNullCursor(); - - case Decl::FriendTemplate: - if (NamedDecl *Friend = cast(D)->getFriendDecl()) - return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit)); - return clang_getNullCursor(); - } - - return clang_getNullCursor(); -} - -unsigned clang_isCursorDefinition(CXCursor C) { - if (!clang_isDeclaration(C.kind)) - return 0; - - return clang_getCursorDefinition(C) == C; -} - -void clang_getDefinitionSpellingAndExtent(CXCursor C, - const char **startBuf, - const char **endBuf, - unsigned *startLine, - unsigned *startColumn, - unsigned *endLine, - unsigned *endColumn) { - assert(getCursorDecl(C) && "CXCursor has null decl"); - NamedDecl *ND = static_cast(getCursorDecl(C)); - FunctionDecl *FD = dyn_cast(ND); - CompoundStmt *Body = dyn_cast(FD->getBody()); - - SourceManager &SM = FD->getASTContext().getSourceManager(); - *startBuf = SM.getCharacterData(Body->getLBracLoc()); - *endBuf = SM.getCharacterData(Body->getRBracLoc()); - *startLine = SM.getSpellingLineNumber(Body->getLBracLoc()); - *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc()); - *endLine = SM.getSpellingLineNumber(Body->getRBracLoc()); - *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc()); -} - -void clang_enableStackTraces(void) { - llvm::sys::PrintStackTraceOnErrorSignal(); -} - -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// Token-based Operations. -//===----------------------------------------------------------------------===// - -/* CXToken layout: - * int_data[0]: a CXTokenKind - * int_data[1]: starting token location - * int_data[2]: token length - * int_data[3]: reserved - * ptr_data: for identifiers and keywords, an IdentifierInfo*. - * otherwise unused. - */ -extern "C" { - -CXTokenKind clang_getTokenKind(CXToken CXTok) { - return static_cast(CXTok.int_data[0]); -} - -CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) { - switch (clang_getTokenKind(CXTok)) { - case CXToken_Identifier: - case CXToken_Keyword: - // We know we have an IdentifierInfo*, so use that. - return createCXString(static_cast(CXTok.ptr_data) - ->getNameStart()); - - case CXToken_Literal: { - // We have stashed the starting pointer in the ptr_data field. Use it. - const char *Text = static_cast(CXTok.ptr_data); - return createCXString(llvm::StringRef(Text, CXTok.int_data[2])); - } - - case CXToken_Punctuation: - case CXToken_Comment: - break; - } - - // We have to find the starting buffer pointer the hard way, by - // deconstructing the source location. - ASTUnit *CXXUnit = static_cast(TU); - if (!CXXUnit) - return createCXString(""); - - SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]); - std::pair LocInfo - = CXXUnit->getSourceManager().getDecomposedLoc(Loc); - bool Invalid = false; - llvm::StringRef Buffer - = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); - if (Invalid) - return createCXString(""); - - return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2])); -} - -CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) { - ASTUnit *CXXUnit = static_cast(TU); - if (!CXXUnit) - return clang_getNullLocation(); - - return cxloc::translateSourceLocation(CXXUnit->getASTContext(), - SourceLocation::getFromRawEncoding(CXTok.int_data[1])); -} - -CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) { - ASTUnit *CXXUnit = static_cast(TU); - if (!CXXUnit) - return clang_getNullRange(); - - return cxloc::translateSourceRange(CXXUnit->getASTContext(), - SourceLocation::getFromRawEncoding(CXTok.int_data[1])); -} - -void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range, - CXToken **Tokens, unsigned *NumTokens) { - if (Tokens) - *Tokens = 0; - if (NumTokens) - *NumTokens = 0; - - ASTUnit *CXXUnit = static_cast(TU); - if (!CXXUnit || !Tokens || !NumTokens) - return; - - ASTUnit::ConcurrencyCheck Check(*CXXUnit); - - SourceRange R = cxloc::translateCXSourceRange(Range); - if (R.isInvalid()) - return; - - SourceManager &SourceMgr = CXXUnit->getSourceManager(); - std::pair BeginLocInfo - = SourceMgr.getDecomposedLoc(R.getBegin()); - std::pair EndLocInfo - = SourceMgr.getDecomposedLoc(R.getEnd()); - - // Cannot tokenize across files. - if (BeginLocInfo.first != EndLocInfo.first) - return; - - // Create a lexer - bool Invalid = false; - llvm::StringRef Buffer - = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid); - if (Invalid) - return; - - Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), - CXXUnit->getASTContext().getLangOptions(), - Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end()); - Lex.SetCommentRetentionState(true); - - // Lex tokens until we hit the end of the range. - const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second; - llvm::SmallVector CXTokens; - Token Tok; - do { - // Lex the next token - Lex.LexFromRawLexer(Tok); - if (Tok.is(tok::eof)) - break; - - // Initialize the CXToken. - CXToken CXTok; - - // - Common fields - CXTok.int_data[1] = Tok.getLocation().getRawEncoding(); - CXTok.int_data[2] = Tok.getLength(); - CXTok.int_data[3] = 0; - - // - Kind-specific fields - if (Tok.isLiteral()) { - CXTok.int_data[0] = CXToken_Literal; - CXTok.ptr_data = (void *)Tok.getLiteralData(); - } else if (Tok.is(tok::identifier)) { - // Lookup the identifier to determine whether we have a keyword. - std::pair LocInfo - = SourceMgr.getDecomposedLoc(Tok.getLocation()); - bool Invalid = false; - llvm::StringRef Buf - = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid); - if (Invalid) - return; - - const char *StartPos = Buf.data() + LocInfo.second; - IdentifierInfo *II - = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos); - CXTok.int_data[0] = II->getTokenID() == tok::identifier? - CXToken_Identifier - : CXToken_Keyword; - CXTok.ptr_data = II; - } else if (Tok.is(tok::comment)) { - CXTok.int_data[0] = CXToken_Comment; - CXTok.ptr_data = 0; - } else { - CXTok.int_data[0] = CXToken_Punctuation; - CXTok.ptr_data = 0; - } - CXTokens.push_back(CXTok); - } while (Lex.getBufferLocation() <= EffectiveBufferEnd); - - if (CXTokens.empty()) - return; - - *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size()); - memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size()); - *NumTokens = CXTokens.size(); -} - -typedef llvm::DenseMap AnnotateTokensData; - -enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor, - CXCursor parent, - CXClientData client_data) { - AnnotateTokensData *Data = static_cast(client_data); - - // We only annotate the locations of declarations, simple - // references, and expressions which directly reference something. - CXCursorKind Kind = clang_getCursorKind(cursor); - if (clang_isDeclaration(Kind) || clang_isReference(Kind)) { - // Okay: We can annotate the location of this declaration with the - // declaration or reference - } else if (clang_isExpression(cursor.kind)) { - if (Kind != CXCursor_DeclRefExpr && - Kind != CXCursor_MemberRefExpr && - Kind != CXCursor_ObjCMessageExpr) - return CXChildVisit_Recurse; - - CXCursor Referenced = clang_getCursorReferenced(cursor); - if (Referenced == cursor || Referenced == clang_getNullCursor()) - return CXChildVisit_Recurse; - - // Okay: we can annotate the location of this expression - } else if (clang_isPreprocessing(cursor.kind)) { - // We can always annotate a preprocessing directive/macro instantiation. - } else { - // Nothing to annotate - return CXChildVisit_Recurse; - } - - CXSourceLocation Loc = clang_getCursorLocation(cursor); - (*Data)[Loc.int_data] = cursor; - return CXChildVisit_Recurse; -} - -void clang_annotateTokens(CXTranslationUnit TU, - CXToken *Tokens, unsigned NumTokens, - CXCursor *Cursors) { - if (NumTokens == 0) - return; - - // Any token we don't specifically annotate will have a NULL cursor. - for (unsigned I = 0; I != NumTokens; ++I) - Cursors[I] = clang_getNullCursor(); - - ASTUnit *CXXUnit = static_cast(TU); - if (!CXXUnit || !Tokens) - return; - - ASTUnit::ConcurrencyCheck Check(*CXXUnit); - - // Determine the region of interest, which contains all of the tokens. - SourceRange RegionOfInterest; - RegionOfInterest.setBegin( - cxloc::translateSourceLocation(clang_getTokenLocation(TU, Tokens[0]))); - SourceLocation End - = cxloc::translateSourceLocation(clang_getTokenLocation(TU, - Tokens[NumTokens - 1])); - RegionOfInterest.setEnd(CXXUnit->getPreprocessor().getLocForEndOfToken(End)); - - // A mapping from the source locations found when re-lexing or traversing the - // region of interest to the corresponding cursors. - AnnotateTokensData Annotated; - - // Relex the tokens within the source range to look for preprocessing - // directives. - SourceManager &SourceMgr = CXXUnit->getSourceManager(); - std::pair BeginLocInfo - = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin()); - std::pair EndLocInfo - = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd()); - - llvm::StringRef Buffer; - bool Invalid = false; - if (BeginLocInfo.first == EndLocInfo.first && - ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) && - !Invalid) { - Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first), - CXXUnit->getASTContext().getLangOptions(), - Buffer.begin(), Buffer.data() + BeginLocInfo.second, - Buffer.end()); - Lex.SetCommentRetentionState(true); - - // Lex tokens in raw mode until we hit the end of the range, to avoid - // entering #includes or expanding macros. - while (true) { - Token Tok; - Lex.LexFromRawLexer(Tok); - - reprocess: - if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) { - // We have found a preprocessing directive. Gobble it up so that we - // don't see it while preprocessing these tokens later, but keep track of - // all of the token locations inside this preprocessing directive so that - // we can annotate them appropriately. - // - // FIXME: Some simple tests here could identify macro definitions and - // #undefs, to provide specific cursor kinds for those. - std::vector Locations; - do { - Locations.push_back(Tok.getLocation()); - Lex.LexFromRawLexer(Tok); - } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof)); - - using namespace cxcursor; - CXCursor Cursor - = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(), - Locations.back()), - CXXUnit); - for (unsigned I = 0, N = Locations.size(); I != N; ++I) { - Annotated[Locations[I].getRawEncoding()] = Cursor; - } - - if (Tok.isAtStartOfLine()) - goto reprocess; - - continue; - } - - if (Tok.is(tok::eof)) - break; - } - } - - // Annotate all of the source locations in the region of interest that map to - // a specific cursor. - CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit); - CursorVisitor AnnotateVis(CXXUnit, AnnotateTokensVisitor, &Annotated, - Decl::MaxPCHLevel, RegionOfInterest); - AnnotateVis.VisitChildren(Parent); - - for (unsigned I = 0; I != NumTokens; ++I) { - // Determine whether we saw a cursor at this token's location. - AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]); - if (Pos == Annotated.end()) - continue; - - Cursors[I] = Pos->second; - } -} - -void clang_disposeTokens(CXTranslationUnit TU, - CXToken *Tokens, unsigned NumTokens) { - free(Tokens); -} - -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// Operations for querying linkage of a cursor. -//===----------------------------------------------------------------------===// - -extern "C" { -CXLinkageKind clang_getCursorLinkage(CXCursor cursor) { - if (!clang_isDeclaration(cursor.kind)) - return CXLinkage_Invalid; - - Decl *D = cxcursor::getCursorDecl(cursor); - if (NamedDecl *ND = dyn_cast_or_null(D)) - switch (ND->getLinkage()) { - case NoLinkage: return CXLinkage_NoLinkage; - case InternalLinkage: return CXLinkage_Internal; - case UniqueExternalLinkage: return CXLinkage_UniqueExternal; - case ExternalLinkage: return CXLinkage_External; - }; - - return CXLinkage_Invalid; -} -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// Operations for querying language of a cursor. -//===----------------------------------------------------------------------===// - -static CXLanguageKind getDeclLanguage(const Decl *D) { - switch (D->getKind()) { - default: - break; - case Decl::ImplicitParam: - case Decl::ObjCAtDefsField: - case Decl::ObjCCategory: - case Decl::ObjCCategoryImpl: - case Decl::ObjCClass: - case Decl::ObjCCompatibleAlias: - case Decl::ObjCForwardProtocol: - case Decl::ObjCImplementation: - case Decl::ObjCInterface: - case Decl::ObjCIvar: - case Decl::ObjCMethod: - case Decl::ObjCProperty: - case Decl::ObjCPropertyImpl: - case Decl::ObjCProtocol: - return CXLanguage_ObjC; - case Decl::CXXConstructor: - case Decl::CXXConversion: - case Decl::CXXDestructor: - case Decl::CXXMethod: - case Decl::CXXRecord: - case Decl::ClassTemplate: - case Decl::ClassTemplatePartialSpecialization: - case Decl::ClassTemplateSpecialization: - case Decl::Friend: - case Decl::FriendTemplate: - case Decl::FunctionTemplate: - case Decl::LinkageSpec: - case Decl::Namespace: - case Decl::NamespaceAlias: - case Decl::NonTypeTemplateParm: - case Decl::StaticAssert: - case Decl::TemplateTemplateParm: - case Decl::TemplateTypeParm: - case Decl::UnresolvedUsingTypename: - case Decl::UnresolvedUsingValue: - case Decl::Using: - case Decl::UsingDirective: - case Decl::UsingShadow: - return CXLanguage_CPlusPlus; - } - - return CXLanguage_C; -} - -extern "C" { -CXLanguageKind clang_getCursorLanguage(CXCursor cursor) { - if (clang_isDeclaration(cursor.kind)) - return getDeclLanguage(cxcursor::getCursorDecl(cursor)); - - return CXLanguage_Invalid; -} -} // end: extern "C" - -//===----------------------------------------------------------------------===// -// CXString Operations. -//===----------------------------------------------------------------------===// - -extern "C" { -const char *clang_getCString(CXString string) { - return string.Spelling; -} - -void clang_disposeString(CXString string) { - if (string.MustFreeString && string.Spelling) - free((void*)string.Spelling); -} - -} // end: extern "C" - -namespace clang { namespace cxstring { -CXString createCXString(const char *String, bool DupString){ - CXString Str; - if (DupString) { - Str.Spelling = strdup(String); - Str.MustFreeString = 1; - } else { - Str.Spelling = String; - Str.MustFreeString = 0; - } - return Str; -} - -CXString createCXString(llvm::StringRef String, bool DupString) { - CXString Result; - if (DupString || (!String.empty() && String.data()[String.size()] != 0)) { - char *Spelling = (char *)malloc(String.size() + 1); - memmove(Spelling, String.data(), String.size()); - Spelling[String.size()] = 0; - Result.Spelling = Spelling; - Result.MustFreeString = 1; - } else { - Result.Spelling = String.data(); - Result.MustFreeString = 0; - } - return Result; -} -}} - -//===----------------------------------------------------------------------===// -// Misc. utility functions. -//===----------------------------------------------------------------------===// - -extern "C" { - -CXString clang_getClangVersion() { - return createCXString(getClangFullVersion()); -} - -} // end: extern "C" diff --git a/tools/CIndex/CIndex.darwin.exports b/tools/CIndex/CIndex.darwin.exports deleted file mode 100644 index b36116805311..000000000000 --- a/tools/CIndex/CIndex.darwin.exports +++ /dev/null @@ -1,81 +0,0 @@ -_clang_annotateTokens -_clang_codeComplete -_clang_codeCompleteGetDiagnostic -_clang_codeCompleteGetNumDiagnostics -_clang_constructUSR_ObjCCategory -_clang_constructUSR_ObjCClass -_clang_constructUSR_ObjCIvar -_clang_constructUSR_ObjCMethod -_clang_constructUSR_ObjCProperty -_clang_constructUSR_ObjCProtocol -_clang_createIndex -_clang_createTranslationUnit -_clang_createTranslationUnitFromSourceFile -_clang_defaultDiagnosticDisplayOptions -_clang_disposeCodeCompleteResults -_clang_disposeDiagnostic -_clang_disposeIndex -_clang_disposeString -_clang_disposeTokens -_clang_disposeTranslationUnit -_clang_enableStackTraces -_clang_equalCursors -_clang_equalLocations -_clang_formatDiagnostic -_clang_getCString -_clang_getClangVersion -_clang_getCompletionChunkCompletionString -_clang_getCompletionChunkKind -_clang_getCompletionChunkText -_clang_getCursor -_clang_getCursorDefinition -_clang_getCursorExtent -_clang_getCursorKind -_clang_getCursorKindSpelling -_clang_getCursorLanguage -_clang_getCursorLinkage -_clang_getCursorLocation -_clang_getCursorReferenced -_clang_getCursorSpelling -_clang_getCursorUSR -_clang_getDefinitionSpellingAndExtent -_clang_getDiagnostic -_clang_getDiagnosticFixIt -_clang_getDiagnosticLocation -_clang_getDiagnosticNumFixIts -_clang_getDiagnosticNumRanges -_clang_getDiagnosticRange -_clang_getDiagnosticSeverity -_clang_getDiagnosticSpelling -_clang_getFile -_clang_getFileName -_clang_getFileTime -_clang_getInclusions -_clang_getInstantiationLocation -_clang_getLocation -_clang_getNullCursor -_clang_getNullLocation -_clang_getNullRange -_clang_getNumCompletionChunks -_clang_getNumDiagnostics -_clang_getRange -_clang_getRangeEnd -_clang_getRangeStart -_clang_getTokenExtent -_clang_getTokenKind -_clang_getTokenLocation -_clang_getTokenSpelling -_clang_getTranslationUnitCursor -_clang_getTranslationUnitSpelling -_clang_isCursorDefinition -_clang_isDeclaration -_clang_isExpression -_clang_isInvalid -_clang_isPreprocessing -_clang_isReference -_clang_isStatement -_clang_isTranslationUnit -_clang_isUnexposed -_clang_setUseExternalASTGeneration -_clang_tokenize -_clang_visitChildren diff --git a/tools/CIndex/CIndex.exports b/tools/CIndex/CIndex.exports deleted file mode 100644 index 991bb067f7d0..000000000000 --- a/tools/CIndex/CIndex.exports +++ /dev/null @@ -1,81 +0,0 @@ -clang_annotateTokens -clang_codeComplete -clang_codeCompleteGetDiagnostic -clang_codeCompleteGetNumDiagnostics -clang_constructUSR_ObjCCategory -clang_constructUSR_ObjCClass -clang_constructUSR_ObjCIvar -clang_constructUSR_ObjCMethod -clang_constructUSR_ObjCProperty -clang_constructUSR_ObjCProtocol -clang_createIndex -clang_createTranslationUnit -clang_createTranslationUnitFromSourceFile -clang_defaultDiagnosticDisplayOptions -clang_disposeCodeCompleteResults -clang_disposeDiagnostic -clang_disposeIndex -clang_disposeString -clang_disposeTokens -clang_disposeTranslationUnit -clang_enableStackTraces -clang_equalCursors -clang_equalLocations -clang_formatDiagnostic -clang_getCString -clang_getClangVersion -clang_getCompletionChunkCompletionString -clang_getCompletionChunkKind -clang_getCompletionChunkText -clang_getCursor -clang_getCursorDefinition -clang_getCursorExtent -clang_getCursorKind -clang_getCursorKindSpelling -clang_getCursorLanguage -clang_getCursorLinkage -clang_getCursorLocation -clang_getCursorReferenced -clang_getCursorSpelling -clang_getCursorUSR -clang_getDefinitionSpellingAndExtent -clang_getDiagnostic -clang_getDiagnosticFixIt -clang_getDiagnosticLocation -clang_getDiagnosticNumFixIts -clang_getDiagnosticNumRanges -clang_getDiagnosticRange -clang_getDiagnosticSeverity -clang_getDiagnosticSpelling -clang_getFile -clang_getFileName -clang_getFileTime -clang_getInclusions -clang_getInstantiationLocation -clang_getLocation -clang_getNullCursor -clang_getNullLocation -clang_getNullRange -clang_getNumCompletionChunks -clang_getNumDiagnostics -clang_getRange -clang_getRangeEnd -clang_getRangeStart -clang_getTokenExtent -clang_getTokenKind -clang_getTokenLocation -clang_getTokenSpelling -clang_getTranslationUnitCursor -clang_getTranslationUnitSpelling -clang_isCursorDefinition -clang_isDeclaration -clang_isExpression -clang_isInvalid -clang_isPreprocessing -clang_isReference -clang_isStatement -clang_isTranslationUnit -clang_isUnexposed -clang_setUseExternalASTGeneration -clang_tokenize -clang_visitChildren diff --git a/tools/CIndex/CIndexCodeCompletion.cpp b/tools/CIndex/CIndexCodeCompletion.cpp deleted file mode 100644 index a21614c74735..000000000000 --- a/tools/CIndex/CIndexCodeCompletion.cpp +++ /dev/null @@ -1,512 +0,0 @@ -//===- CIndexCodeCompletion.cpp - Code Completion API hooks ---------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements the Clang-C Source Indexing library hooks for -// code completion. -// -//===----------------------------------------------------------------------===// - -#include "CIndexer.h" -#include "CIndexDiagnostic.h" -#include "clang/Basic/SourceManager.h" -#include "clang/Basic/FileManager.h" -#include "clang/Frontend/CompilerInstance.h" -#include "clang/Frontend/FrontendDiagnostic.h" -#include "clang/Sema/CodeCompleteConsumer.h" -#include "llvm/ADT/StringExtras.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/System/Program.h" - -#ifdef UDP_CODE_COMPLETION_LOGGER -#include "clang/Basic/Version.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/Support/Timer.h" -#include "llvm/Support/raw_ostream.h" -#include -#include -#include -#include -#endif - -using namespace clang; -using namespace clang::cxstring; - -extern "C" { - -enum CXCompletionChunkKind -clang_getCompletionChunkKind(CXCompletionString completion_string, - unsigned chunk_number) { - CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; - if (!CCStr || chunk_number >= CCStr->size()) - return CXCompletionChunk_Text; - - switch ((*CCStr)[chunk_number].Kind) { - case CodeCompletionString::CK_TypedText: - return CXCompletionChunk_TypedText; - case CodeCompletionString::CK_Text: - return CXCompletionChunk_Text; - case CodeCompletionString::CK_Optional: - return CXCompletionChunk_Optional; - case CodeCompletionString::CK_Placeholder: - return CXCompletionChunk_Placeholder; - case CodeCompletionString::CK_Informative: - return CXCompletionChunk_Informative; - case CodeCompletionString::CK_ResultType: - return CXCompletionChunk_ResultType; - case CodeCompletionString::CK_CurrentParameter: - return CXCompletionChunk_CurrentParameter; - case CodeCompletionString::CK_LeftParen: - return CXCompletionChunk_LeftParen; - case CodeCompletionString::CK_RightParen: - return CXCompletionChunk_RightParen; - case CodeCompletionString::CK_LeftBracket: - return CXCompletionChunk_LeftBracket; - case CodeCompletionString::CK_RightBracket: - return CXCompletionChunk_RightBracket; - case CodeCompletionString::CK_LeftBrace: - return CXCompletionChunk_LeftBrace; - case CodeCompletionString::CK_RightBrace: - return CXCompletionChunk_RightBrace; - case CodeCompletionString::CK_LeftAngle: - return CXCompletionChunk_LeftAngle; - case CodeCompletionString::CK_RightAngle: - return CXCompletionChunk_RightAngle; - case CodeCompletionString::CK_Comma: - return CXCompletionChunk_Comma; - case CodeCompletionString::CK_Colon: - return CXCompletionChunk_Colon; - case CodeCompletionString::CK_SemiColon: - return CXCompletionChunk_SemiColon; - case CodeCompletionString::CK_Equal: - return CXCompletionChunk_Equal; - case CodeCompletionString::CK_HorizontalSpace: - return CXCompletionChunk_HorizontalSpace; - case CodeCompletionString::CK_VerticalSpace: - return CXCompletionChunk_VerticalSpace; - } - - // Should be unreachable, but let's be careful. - return CXCompletionChunk_Text; -} - -CXString clang_getCompletionChunkText(CXCompletionString completion_string, - unsigned chunk_number) { - CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; - if (!CCStr || chunk_number >= CCStr->size()) - return createCXString(0); - - switch ((*CCStr)[chunk_number].Kind) { - case CodeCompletionString::CK_TypedText: - case CodeCompletionString::CK_Text: - case CodeCompletionString::CK_Placeholder: - case CodeCompletionString::CK_CurrentParameter: - case CodeCompletionString::CK_Informative: - case CodeCompletionString::CK_LeftParen: - case CodeCompletionString::CK_RightParen: - case CodeCompletionString::CK_LeftBracket: - case CodeCompletionString::CK_RightBracket: - case CodeCompletionString::CK_LeftBrace: - case CodeCompletionString::CK_RightBrace: - case CodeCompletionString::CK_LeftAngle: - case CodeCompletionString::CK_RightAngle: - case CodeCompletionString::CK_Comma: - case CodeCompletionString::CK_ResultType: - case CodeCompletionString::CK_Colon: - case CodeCompletionString::CK_SemiColon: - case CodeCompletionString::CK_Equal: - case CodeCompletionString::CK_HorizontalSpace: - case CodeCompletionString::CK_VerticalSpace: - return createCXString((*CCStr)[chunk_number].Text, false); - - case CodeCompletionString::CK_Optional: - // Note: treated as an empty text block. - return createCXString(""); - } - - // Should be unreachable, but let's be careful. - return createCXString(0); -} - - -CXCompletionString -clang_getCompletionChunkCompletionString(CXCompletionString completion_string, - unsigned chunk_number) { - CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; - if (!CCStr || chunk_number >= CCStr->size()) - return 0; - - switch ((*CCStr)[chunk_number].Kind) { - case CodeCompletionString::CK_TypedText: - case CodeCompletionString::CK_Text: - case CodeCompletionString::CK_Placeholder: - case CodeCompletionString::CK_CurrentParameter: - case CodeCompletionString::CK_Informative: - case CodeCompletionString::CK_LeftParen: - case CodeCompletionString::CK_RightParen: - case CodeCompletionString::CK_LeftBracket: - case CodeCompletionString::CK_RightBracket: - case CodeCompletionString::CK_LeftBrace: - case CodeCompletionString::CK_RightBrace: - case CodeCompletionString::CK_LeftAngle: - case CodeCompletionString::CK_RightAngle: - case CodeCompletionString::CK_Comma: - case CodeCompletionString::CK_ResultType: - case CodeCompletionString::CK_Colon: - case CodeCompletionString::CK_SemiColon: - case CodeCompletionString::CK_Equal: - case CodeCompletionString::CK_HorizontalSpace: - case CodeCompletionString::CK_VerticalSpace: - return 0; - - case CodeCompletionString::CK_Optional: - // Note: treated as an empty text block. - return (*CCStr)[chunk_number].Optional; - } - - // Should be unreachable, but let's be careful. - return 0; -} - -unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) { - CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; - return CCStr? CCStr->size() : 0; -} - -static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd, - unsigned &Value) { - if (Memory + sizeof(unsigned) > MemoryEnd) - return true; - - memmove(&Value, Memory, sizeof(unsigned)); - Memory += sizeof(unsigned); - return false; -} - -/// \brief The CXCodeCompleteResults structure we allocate internally; -/// the client only sees the initial CXCodeCompleteResults structure. -struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults { - AllocatedCXCodeCompleteResults(); - ~AllocatedCXCodeCompleteResults(); - - /// \brief The memory buffer from which we parsed the results. We - /// retain this buffer because the completion strings point into it. - llvm::MemoryBuffer *Buffer; - - /// \brief Diagnostics produced while performing code completion. - llvm::SmallVector Diagnostics; - - /// \brief Diag object - Diagnostic Diag; - - /// \brief Language options used to adjust source locations. - LangOptions LangOpts; - - /// \brief Source manager, used for diagnostics. - SourceManager SourceMgr; - - /// \brief File manager, used for diagnostics. - FileManager FileMgr; - - /// \brief Temporary files that should be removed once we have finished - /// with the code-completion results. - std::vector TemporaryFiles; -}; - -AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults() - : CXCodeCompleteResults(), Buffer(0), SourceMgr(Diag) { } - -AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() { - for (unsigned I = 0, N = NumResults; I != N; ++I) - delete (CodeCompletionString *)Results[I].CompletionString; - delete [] Results; - delete Buffer; - - for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I) - TemporaryFiles[I].eraseFromDisk(); -} - -CXCodeCompleteResults *clang_codeComplete(CXIndex CIdx, - const char *source_filename, - int num_command_line_args, - const char **command_line_args, - unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files, - const char *complete_filename, - unsigned complete_line, - unsigned complete_column) { -#ifdef UDP_CODE_COMPLETION_LOGGER -#ifdef UDP_CODE_COMPLETION_LOGGER_PORT - const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime(); -#endif -#endif - - // The indexer, which is mainly used to determine where diagnostics go. - CIndexer *CXXIdx = static_cast(CIdx); - - // Configure the diagnostics. - DiagnosticOptions DiagOpts; - llvm::IntrusiveRefCntPtr Diags; - Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0); - - // The set of temporary files that we've built. - std::vector TemporaryFiles; - - // Build up the arguments for invoking 'clang'. - std::vector argv; - - // First add the complete path to the 'clang' executable. - llvm::sys::Path ClangPath = CXXIdx->getClangPath(); - argv.push_back(ClangPath.c_str()); - - // Add the '-fsyntax-only' argument so that we only perform a basic - // syntax check of the code. - argv.push_back("-fsyntax-only"); - - // Add the appropriate '-code-completion-at=file:line:column' argument - // to perform code completion, with an "-Xclang" preceding it. - std::string code_complete_at; - code_complete_at += complete_filename; - code_complete_at += ":"; - code_complete_at += llvm::utostr(complete_line); - code_complete_at += ":"; - code_complete_at += llvm::utostr(complete_column); - argv.push_back("-Xclang"); - argv.push_back("-code-completion-at"); - argv.push_back("-Xclang"); - argv.push_back(code_complete_at.c_str()); - argv.push_back("-Xclang"); - argv.push_back("-no-code-completion-debug-printer"); - argv.push_back("-Xclang"); - argv.push_back("-code-completion-macros"); - argv.push_back("-fdiagnostics-binary"); - - // Remap any unsaved files to temporary files. - std::vector RemapArgs; - if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles)) - return 0; - - // The pointers into the elements of RemapArgs are stable because we - // won't be adding anything to RemapArgs after this point. - for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i) - argv.push_back(RemapArgs[i].c_str()); - - // Add the source file name (FIXME: later, we'll want to build temporary - // file from the buffer, or just feed the source text via standard input). - if (source_filename) - argv.push_back(source_filename); - - // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'. - for (int i = 0; i < num_command_line_args; ++i) - if (const char *arg = command_line_args[i]) { - if (strcmp(arg, "-o") == 0) { - ++i; // Also skip the matching argument. - continue; - } - if (strcmp(arg, "-emit-ast") == 0 || - strcmp(arg, "-c") == 0 || - strcmp(arg, "-fsyntax-only") == 0) { - continue; - } - - // Keep the argument. - argv.push_back(arg); - } - - // Add the null terminator. - argv.push_back(NULL); - - // Generate a temporary name for the code-completion results file. - char tmpFile[L_tmpnam]; - char *tmpFileName = tmpnam(tmpFile); - llvm::sys::Path ResultsFile(tmpFileName); - TemporaryFiles.push_back(ResultsFile); - - // Generate a temporary name for the diagnostics file. - char tmpFileResults[L_tmpnam]; - char *tmpResultsFileName = tmpnam(tmpFileResults); - llvm::sys::Path DiagnosticsFile(tmpResultsFileName); - TemporaryFiles.push_back(DiagnosticsFile); - - // Invoke 'clang'. - llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null - // on Unix or NUL (Windows). - std::string ErrMsg; - const llvm::sys::Path *Redirects[] = { &DevNull, &ResultsFile, - &DiagnosticsFile, 0 }; - llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL, - /* redirects */ &Redirects[0], - /* secondsToWait */ 0, - /* memoryLimits */ 0, &ErrMsg); - - if (!ErrMsg.empty()) { - std::string AllArgs; - for (std::vector::iterator I = argv.begin(), E = argv.end(); - I != E; ++I) { - AllArgs += ' '; - if (*I) - AllArgs += *I; - } - - Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg; - } - - // Parse the resulting source file to find code-completion results. - using llvm::MemoryBuffer; - using llvm::StringRef; - AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults; - Results->Results = 0; - Results->NumResults = 0; - Results->Buffer = 0; - // FIXME: Set Results->LangOpts! - if (MemoryBuffer *F = MemoryBuffer::getFile(ResultsFile.c_str())) { - llvm::SmallVector CompletionResults; - StringRef Buffer = F->getBuffer(); - for (const char *Str = Buffer.data(), *StrEnd = Str + Buffer.size(); - Str < StrEnd;) { - unsigned KindValue; - if (ReadUnsigned(Str, StrEnd, KindValue)) - break; - - CodeCompletionString *CCStr - = CodeCompletionString::Deserialize(Str, StrEnd); - if (!CCStr) - continue; - - if (!CCStr->empty()) { - // Vend the code-completion result to the caller. - CXCompletionResult Result; - Result.CursorKind = (CXCursorKind)KindValue; - Result.CompletionString = CCStr; - CompletionResults.push_back(Result); - } - }; - - // Allocate the results. - Results->Results = new CXCompletionResult [CompletionResults.size()]; - Results->NumResults = CompletionResults.size(); - memcpy(Results->Results, CompletionResults.data(), - CompletionResults.size() * sizeof(CXCompletionResult)); - Results->Buffer = F; - } - - LoadSerializedDiagnostics(DiagnosticsFile, num_unsaved_files, unsaved_files, - Results->FileMgr, Results->SourceMgr, - Results->Diagnostics); - - // Make sure we delete temporary files when the code-completion results are - // destroyed. - Results->TemporaryFiles.swap(TemporaryFiles); - -#ifdef UDP_CODE_COMPLETION_LOGGER -#ifdef UDP_CODE_COMPLETION_LOGGER_PORT - const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime(); - llvm::SmallString<256> LogResult; - llvm::raw_svector_ostream os(LogResult); - - // Figure out the language and whether or not it uses PCH. - const char *lang = 0; - bool usesPCH = false; - - for (std::vector::iterator I = argv.begin(), E = argv.end(); - I != E; ++I) { - if (*I == 0) - continue; - if (strcmp(*I, "-x") == 0) { - if (I + 1 != E) { - lang = *(++I); - continue; - } - } - else if (strcmp(*I, "-include") == 0) { - if (I+1 != E) { - const char *arg = *(++I); - llvm::SmallString<512> pchName; - { - llvm::raw_svector_ostream os(pchName); - os << arg << ".pth"; - } - pchName.push_back('\0'); - struct stat stat_results; - if (stat(pchName.data(), &stat_results) == 0) - usesPCH = true; - continue; - } - } - } - - os << "{ "; - os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime()); - os << ", \"numRes\": " << Results->NumResults; - os << ", \"diags\": " << Results->Diagnostics.size(); - os << ", \"pch\": " << (usesPCH ? "true" : "false"); - os << ", \"lang\": \"" << (lang ? lang : "") << '"'; - const char *name = getlogin(); - os << ", \"user\": \"" << (name ? name : "unknown") << '"'; - os << ", \"clangVer\": \"" << getClangFullVersion() << '"'; - os << " }"; - - llvm::StringRef res = os.str(); - if (res.size() > 0) { - do { - // Setup the UDP socket. - struct sockaddr_in servaddr; - bzero(&servaddr, sizeof(servaddr)); - servaddr.sin_family = AF_INET; - servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT); - if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER, - &servaddr.sin_addr) <= 0) - break; - - int sockfd = socket(AF_INET, SOCK_DGRAM, 0); - if (sockfd < 0) - break; - - sendto(sockfd, res.data(), res.size(), 0, - (struct sockaddr *)&servaddr, sizeof(servaddr)); - close(sockfd); - } - while (false); - } -#endif -#endif - return Results; -} - -void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) { - if (!ResultsIn) - return; - - AllocatedCXCodeCompleteResults *Results - = static_cast(ResultsIn); - delete Results; -} - -unsigned -clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) { - AllocatedCXCodeCompleteResults *Results - = static_cast(ResultsIn); - if (!Results) - return 0; - - return Results->Diagnostics.size(); -} - -CXDiagnostic -clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn, - unsigned Index) { - AllocatedCXCodeCompleteResults *Results - = static_cast(ResultsIn); - if (!Results || Index >= Results->Diagnostics.size()) - return 0; - - return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts); -} - - -} // end extern "C" diff --git a/tools/CIndex/CIndexDiagnostic.cpp b/tools/CIndex/CIndexDiagnostic.cpp deleted file mode 100644 index 3db37b97da14..000000000000 --- a/tools/CIndex/CIndexDiagnostic.cpp +++ /dev/null @@ -1,285 +0,0 @@ -/*===-- CIndexDiagnostics.cpp - Diagnostics C Interface ---------*- C++ -*-===*\ -|* *| -|* The LLVM Compiler Infrastructure *| -|* *| -|* This file is distributed under the University of Illinois Open Source *| -|* License. See LICENSE.TXT for details. *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* Implements the diagnostic functions of the Clang C interface. *| -|* *| -\*===----------------------------------------------------------------------===*/ -#include "CIndexDiagnostic.h" -#include "CIndexer.h" -#include "CXSourceLocation.h" - -#include "clang/Frontend/ASTUnit.h" -#include "clang/Frontend/FrontendDiagnostic.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/ADT/Twine.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/raw_ostream.h" - -using namespace clang; -using namespace clang::cxloc; -using namespace clang::cxstring; -using namespace llvm; - -//----------------------------------------------------------------------------- -// C Interface Routines -//----------------------------------------------------------------------------- -extern "C" { - -unsigned clang_getNumDiagnostics(CXTranslationUnit Unit) { - ASTUnit *CXXUnit = static_cast(Unit); - return CXXUnit? CXXUnit->stored_diag_size() : 0; -} - -CXDiagnostic clang_getDiagnostic(CXTranslationUnit Unit, unsigned Index) { - ASTUnit *CXXUnit = static_cast(Unit); - if (!CXXUnit || Index >= CXXUnit->stored_diag_size()) - return 0; - - return new CXStoredDiagnostic(CXXUnit->stored_diag_begin()[Index], - CXXUnit->getASTContext().getLangOptions()); -} - -void clang_disposeDiagnostic(CXDiagnostic Diagnostic) { - CXStoredDiagnostic *Stored = static_cast(Diagnostic); - delete Stored; -} - -CXString clang_formatDiagnostic(CXDiagnostic Diagnostic, unsigned Options) { - if (!Diagnostic) - return createCXString(""); - - CXDiagnosticSeverity Severity = clang_getDiagnosticSeverity(Diagnostic); - - // Ignore diagnostics that should be ignored. - if (Severity == CXDiagnostic_Ignored) - return createCXString(""); - - llvm::SmallString<256> Str; - llvm::raw_svector_ostream Out(Str); - - if (Options & CXDiagnostic_DisplaySourceLocation) { - // Print source location (file:line), along with optional column - // and source ranges. - CXFile File; - unsigned Line, Column; - clang_getInstantiationLocation(clang_getDiagnosticLocation(Diagnostic), - &File, &Line, &Column, 0); - if (File) { - CXString FName = clang_getFileName(File); - Out << clang_getCString(FName) << ":" << Line << ":"; - clang_disposeString(FName); - if (Options & CXDiagnostic_DisplayColumn) - Out << Column << ":"; - - if (Options & CXDiagnostic_DisplaySourceRanges) { - unsigned N = clang_getDiagnosticNumRanges(Diagnostic); - bool PrintedRange = false; - for (unsigned I = 0; I != N; ++I) { - CXFile StartFile, EndFile; - CXSourceRange Range = clang_getDiagnosticRange(Diagnostic, I); - - unsigned StartLine, StartColumn, EndLine, EndColumn; - clang_getInstantiationLocation(clang_getRangeStart(Range), - &StartFile, &StartLine, &StartColumn, - 0); - clang_getInstantiationLocation(clang_getRangeEnd(Range), - &EndFile, &EndLine, &EndColumn, 0); - - if (StartFile != EndFile || StartFile != File) - continue; - - Out << "{" << StartLine << ":" << StartColumn << "-" - << EndLine << ":" << EndColumn << "}"; - PrintedRange = true; - } - if (PrintedRange) - Out << ":"; - } - } - - Out << " "; - } - - /* Print warning/error/etc. */ - switch (Severity) { - case CXDiagnostic_Ignored: assert(0 && "impossible"); break; - case CXDiagnostic_Note: Out << "note: "; break; - case CXDiagnostic_Warning: Out << "warning: "; break; - case CXDiagnostic_Error: Out << "error: "; break; - case CXDiagnostic_Fatal: Out << "fatal error: "; break; - } - - CXString Text = clang_getDiagnosticSpelling(Diagnostic); - if (clang_getCString(Text)) - Out << clang_getCString(Text); - else - Out << ""; - clang_disposeString(Text); - return createCXString(Out.str(), true); -} - -unsigned clang_defaultDiagnosticDisplayOptions() { - return CXDiagnostic_DisplaySourceLocation | CXDiagnostic_DisplayColumn; -} - -enum CXDiagnosticSeverity clang_getDiagnosticSeverity(CXDiagnostic Diag) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag) - return CXDiagnostic_Ignored; - - switch (StoredDiag->Diag.getLevel()) { - case Diagnostic::Ignored: return CXDiagnostic_Ignored; - case Diagnostic::Note: return CXDiagnostic_Note; - case Diagnostic::Warning: return CXDiagnostic_Warning; - case Diagnostic::Error: return CXDiagnostic_Error; - case Diagnostic::Fatal: return CXDiagnostic_Fatal; - } - - llvm_unreachable("Invalid diagnostic level"); - return CXDiagnostic_Ignored; -} - -CXSourceLocation clang_getDiagnosticLocation(CXDiagnostic Diag) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag || StoredDiag->Diag.getLocation().isInvalid()) - return clang_getNullLocation(); - - return translateSourceLocation(StoredDiag->Diag.getLocation().getManager(), - StoredDiag->LangOpts, - StoredDiag->Diag.getLocation()); -} - -CXString clang_getDiagnosticSpelling(CXDiagnostic Diag) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag) - return createCXString(""); - - return createCXString(StoredDiag->Diag.getMessage(), false); -} - -unsigned clang_getDiagnosticNumRanges(CXDiagnostic Diag) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag || StoredDiag->Diag.getLocation().isInvalid()) - return 0; - - return StoredDiag->Diag.range_size(); -} - -CXSourceRange clang_getDiagnosticRange(CXDiagnostic Diag, unsigned Range) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag || Range >= StoredDiag->Diag.range_size() || - StoredDiag->Diag.getLocation().isInvalid()) - return clang_getNullRange(); - - return translateSourceRange(StoredDiag->Diag.getLocation().getManager(), - StoredDiag->LangOpts, - StoredDiag->Diag.range_begin()[Range]); -} - -unsigned clang_getDiagnosticNumFixIts(CXDiagnostic Diag) { - CXStoredDiagnostic *StoredDiag = static_cast(Diag); - if (!StoredDiag) - return 0; - - return StoredDiag->Diag.fixit_size(); -} - -CXString clang_getDiagnosticFixIt(CXDiagnostic Diagnostic, unsigned FixIt, - CXSourceRange *ReplacementRange) { - CXStoredDiagnostic *StoredDiag - = static_cast(Diagnostic); - if (!StoredDiag || FixIt >= StoredDiag->Diag.fixit_size() || - StoredDiag->Diag.getLocation().isInvalid()) { - if (ReplacementRange) - *ReplacementRange = clang_getNullRange(); - - return createCXString(""); - } - - const FixItHint &Hint = StoredDiag->Diag.fixit_begin()[FixIt]; - if (ReplacementRange) { - if (Hint.RemoveRange.isInvalid()) { - // Create an empty range that refers to a single source - // location (which is the insertion point). - CXSourceRange Range = { - { (void *)&StoredDiag->Diag.getLocation().getManager(), - (void *)&StoredDiag->LangOpts }, - Hint.InsertionLoc.getRawEncoding(), - Hint.InsertionLoc.getRawEncoding() - }; - - *ReplacementRange = Range; - } else { - // Create a range that covers the entire replacement (or - // removal) range, adjusting the end of the range to point to - // the end of the token. - *ReplacementRange - = translateSourceRange(StoredDiag->Diag.getLocation().getManager(), - StoredDiag->LangOpts, - Hint.RemoveRange); - } - } - - return createCXString(Hint.CodeToInsert); -} - -} // end extern "C" - -void clang::LoadSerializedDiagnostics(const llvm::sys::Path &DiagnosticsPath, - unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files, - FileManager &FileMgr, - SourceManager &SourceMgr, - SmallVectorImpl &Diags) { - using llvm::MemoryBuffer; - using llvm::StringRef; - MemoryBuffer *F = MemoryBuffer::getFile(DiagnosticsPath.c_str()); - if (!F) - return; - - // Enter the unsaved files into the file manager. - for (unsigned I = 0; I != num_unsaved_files; ++I) { - const FileEntry *File = FileMgr.getVirtualFile(unsaved_files[I].Filename, - unsaved_files[I].Length, - 0); - if (!File) { - // FIXME: Hard to localize when we have no diagnostics engine! - Diags.push_back(StoredDiagnostic(Diagnostic::Fatal, - (Twine("could not remap from missing file ") + - unsaved_files[I].Filename).str())); - delete F; - return; - } - - MemoryBuffer *Buffer - = MemoryBuffer::getMemBuffer(unsaved_files[I].Contents, - unsaved_files[I].Contents + unsaved_files[I].Length); - if (!Buffer) { - delete F; - return; - } - - SourceMgr.overrideFileContents(File, Buffer); - SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User); - } - - // Parse the diagnostics, emitting them one by one until we've - // exhausted the data. - StringRef Buffer = F->getBuffer(); - const char *Memory = Buffer.data(), *MemoryEnd = Memory + Buffer.size(); - while (Memory != MemoryEnd) { - StoredDiagnostic Stored = StoredDiagnostic::Deserialize(FileMgr, SourceMgr, - Memory, MemoryEnd); - if (!Stored) - break; - - Diags.push_back(Stored); - } - delete F; -} diff --git a/tools/CIndex/CIndexDiagnostic.h b/tools/CIndex/CIndexDiagnostic.h deleted file mode 100644 index 919c21cfdbe4..000000000000 --- a/tools/CIndex/CIndexDiagnostic.h +++ /dev/null @@ -1,53 +0,0 @@ -/*===-- CIndexDiagnostic.h - Diagnostics C Interface ------------*- C++ -*-===*\ -|* *| -|* The LLVM Compiler Infrastructure *| -|* *| -|* This file is distributed under the University of Illinois Open Source *| -|* License. See LICENSE.TXT for details. *| -|* *| -|*===----------------------------------------------------------------------===*| -|* *| -|* Implements the diagnostic functions of the Clang C interface. *| -|* *| -\*===----------------------------------------------------------------------===*/ -#ifndef LLVM_CLANG_CINDEX_DIAGNOSTIC_H -#define LLVM_CLANG_CINDEX_DIAGNOSTIC_H - -struct CXUnsavedFile; - -namespace llvm { -template class SmallVectorImpl; -namespace sys { class Path; } -} - -namespace clang { - -class Diagnostic; -class FileManager; -class LangOptions; -class Preprocessor; -class StoredDiagnostic; -class SourceManager; - -/// \brief The storage behind a CXDiagnostic -struct CXStoredDiagnostic { - const StoredDiagnostic &Diag; - const LangOptions &LangOpts; - - CXStoredDiagnostic(const StoredDiagnostic &Diag, - const LangOptions &LangOpts) - : Diag(Diag), LangOpts(LangOpts) { } -}; - -/// \brief Given the path to a file that contains binary, serialized -/// diagnostics produced by Clang, load those diagnostics. -void LoadSerializedDiagnostics(const llvm::sys::Path &DiagnosticsPath, - unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files, - FileManager &FileMgr, - SourceManager &SourceMgr, - llvm::SmallVectorImpl &Diags); - -} // end namespace clang - -#endif // LLVM_CLANG_CINDEX_DIAGNOSTIC_H diff --git a/tools/CIndex/CIndexInclusionStack.cpp b/tools/CIndex/CIndexInclusionStack.cpp deleted file mode 100644 index e86323956f91..000000000000 --- a/tools/CIndex/CIndexInclusionStack.cpp +++ /dev/null @@ -1,67 +0,0 @@ -//===- CIndexInclusionStack.cpp - Clang-C Source Indexing Library ---------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines a callback mechanism for clients to get the inclusion -// stack from a translation unit. -// -//===----------------------------------------------------------------------===// - -#include "CIndexer.h" -#include "CXSourceLocation.h" -#include "clang/AST/DeclVisitor.h" -#include "clang/Frontend/ASTUnit.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/Support/raw_ostream.h" -using namespace clang; - -extern "C" { -void clang_getInclusions(CXTranslationUnit TU, CXInclusionVisitor CB, - CXClientData clientData) { - - ASTUnit *CXXUnit = static_cast(TU); - SourceManager &SM = CXXUnit->getSourceManager(); - ASTContext &Ctx = CXXUnit->getASTContext(); - - llvm::SmallVector InclusionStack; - unsigned i = SM.sloc_loaded_entry_size(); - unsigned n = SM.sloc_entry_size(); - - // In the case where all the SLocEntries are in an external source, traverse - // those SLocEntries as well. This is the case where we are looking - // at the inclusion stack of an AST/PCH file. - if (i >= n) - i = 0; - - for ( ; i < n ; ++i) { - - const SrcMgr::SLocEntry &SL = SM.getSLocEntry(i); - - if (!SL.isFile()) - continue; - - const SrcMgr::FileInfo &FI = SL.getFile(); - if (!FI.getContentCache()->Entry) - continue; - - // Build the inclusion stack. - SourceLocation L = FI.getIncludeLoc(); - InclusionStack.clear(); - while (L.isValid()) { - PresumedLoc PLoc = SM.getPresumedLoc(L); - InclusionStack.push_back(cxloc::translateSourceLocation(Ctx, L)); - L = PLoc.getIncludeLoc(); - } - - // Callback to the client. - // FIXME: We should have a function to construct CXFiles. - CB((CXFile) FI.getContentCache()->Entry, - InclusionStack.data(), InclusionStack.size(), clientData); - } -} -} // end extern C diff --git a/tools/CIndex/CIndexUSRs.cpp b/tools/CIndex/CIndexUSRs.cpp deleted file mode 100644 index 58870b930b19..000000000000 --- a/tools/CIndex/CIndexUSRs.cpp +++ /dev/null @@ -1,469 +0,0 @@ -//===- CIndexUSR.cpp - Clang-C Source Indexing Library --------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements the generation and use of USRs from CXEntities. -// -//===----------------------------------------------------------------------===// - -#include "CIndexer.h" -#include "CXCursor.h" -#include "clang/AST/DeclVisitor.h" -#include "clang/Frontend/ASTUnit.h" -#include "clang/Lex/PreprocessingRecord.h" -#include "llvm/ADT/SmallString.h" -#include "llvm/Support/raw_ostream.h" - -using namespace clang; -using namespace clang::cxstring; - -//===----------------------------------------------------------------------===// -// USR generation. -//===----------------------------------------------------------------------===// - -namespace { -class USRGenerator : public DeclVisitor { - llvm::raw_ostream &Out; - bool IgnoreResults; - ASTUnit *AU; -public: - USRGenerator(ASTUnit *au, llvm::raw_ostream &out) - : Out(out), IgnoreResults(false), AU(au) {} - - bool ignoreResults() const { return IgnoreResults; } - - // Visitation methods from generating USRs from AST elements. - void VisitBlockDecl(BlockDecl *D); - void VisitDeclContext(DeclContext *D); - void VisitFieldDecl(FieldDecl *D); - void VisitFunctionDecl(FunctionDecl *D); - void VisitNamedDecl(NamedDecl *D); - void VisitNamespaceDecl(NamespaceDecl *D); - void VisitObjCClassDecl(ObjCClassDecl *CD); - void VisitObjCContainerDecl(ObjCContainerDecl *CD); - void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *P); - void VisitObjCMethodDecl(ObjCMethodDecl *MD); - void VisitObjCPropertyDecl(ObjCPropertyDecl *D); - void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); - void VisitTagDecl(TagDecl *D); - void VisitTypedefDecl(TypedefDecl *D); - void VisitVarDecl(VarDecl *D); - - /// Generate the string component containing the location of the - /// declaration. - void GenLoc(const Decl *D); - - /// String generation methods used both by the visitation methods - /// and from other clients that want to directly generate USRs. These - /// methods do not construct complete USRs (which incorporate the parents - /// of an AST element), but only the fragments concerning the AST element - /// itself. - - /// Generate a USR fragment for a named declaration. This does - /// not include the USR component for the parent. - void GenNamedDecl(llvm::StringRef name); - - /// Generate a USR for an Objective-C class. - void GenObjCClass(llvm::StringRef cls); - /// Generate a USR for an Objective-C class category. - void GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat); - /// Generate a USR fragment for an Objective-C instance variable. The - /// complete USR can be created by concatenating the USR for the - /// encompassing class with this USR fragment. - void GenObjCIvar(llvm::StringRef ivar); - /// Generate a USR fragment for an Objective-C method. - void GenObjCMethod(llvm::StringRef sel, bool isInstanceMethod); - /// Generate a USR fragment for an Objective-C property. - void GenObjCProperty(llvm::StringRef prop); - /// Generate a USR for an Objective-C protocol. - void GenObjCProtocol(llvm::StringRef prot); -}; - -class StringUSRGenerator { -private: - llvm::SmallString<1024> StrBuf; - llvm::raw_svector_ostream Out; - USRGenerator UG; -public: - StringUSRGenerator(const CXCursor *C = 0) - : Out(StrBuf), UG(C ? cxcursor::getCursorASTUnit(*C) : 0, Out) { - // Add the USR space prefix. - Out << "c:"; - } - - llvm::StringRef str() { - return Out.str(); - } - - USRGenerator* operator->() { return &UG; } - - template - llvm::raw_svector_ostream &operator<<(const T &x) { - Out << x; - return Out; - } -}; - -} // end anonymous namespace - -//===----------------------------------------------------------------------===// -// Generating USRs from ASTS. -//===----------------------------------------------------------------------===// - -void USRGenerator::VisitBlockDecl(BlockDecl *D) { - VisitDeclContext(D->getDeclContext()); - // FIXME: Better support for anonymous blocks. - Out << "@B@anon"; -} - -void USRGenerator::VisitDeclContext(DeclContext *DC) { - if (NamedDecl *D = dyn_cast(DC)) - Visit(D); -} - -void USRGenerator::VisitFieldDecl(FieldDecl *D) { - const std::string &s = D->getNameAsString(); - if (s.empty()) { - // Bit fields can be anonymous. - IgnoreResults = true; - return; - } - VisitDeclContext(D->getDeclContext()); - Out << (isa(D) ? "@" : "@FI@") << s; -} - -void USRGenerator::VisitFunctionDecl(FunctionDecl *D) { - VisitDeclContext(D->getDeclContext()); - Out << "@F@" << D; -} - -void USRGenerator::VisitNamedDecl(NamedDecl *D) { - VisitDeclContext(D->getDeclContext()); - const std::string &s = D->getNameAsString(); - // The string can be empty if the declaration has no name; e.g., it is - // the ParmDecl with no name for declaration of a function pointer type, e.g.: - // void (*f)(void *); - // In this case, don't generate a USR. - if (s.empty()) - IgnoreResults = true; - else - GenNamedDecl(s); -} - -void USRGenerator::VisitVarDecl(VarDecl *D) { - // VarDecls can be declared 'extern' within a function or method body, - // but their enclosing DeclContext is the function, not the TU. We need - // to check the storage class to correctly generate the USR. - if (!D->hasExternalStorage()) - VisitDeclContext(D->getDeclContext()); - - const std::string &s = D->getNameAsString(); - // The string can be empty if the declaration has no name; e.g., it is - // the ParmDecl with no name for declaration of a function pointer type, e.g.: - // void (*f)(void *); - // In this case, don't generate a USR. - if (s.empty()) - IgnoreResults = true; - else - GenNamedDecl(s); -} - -void USRGenerator::VisitNamespaceDecl(NamespaceDecl *D) { - VisitDeclContext(D->getDeclContext()); - Out << "@N@" << D; -} - -void USRGenerator::VisitObjCMethodDecl(ObjCMethodDecl *D) { - Visit(cast(D->getDeclContext())); - GenObjCMethod(DeclarationName(D->getSelector()).getAsString(), - D->isInstanceMethod()); -} - -void USRGenerator::VisitObjCClassDecl(ObjCClassDecl *D) { - // FIXME: @class declarations can refer to multiple classes. We need - // to be able to traverse these. - IgnoreResults = true; -} - -void USRGenerator::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) { - // FIXME: @protocol declarations can refer to multiple protocols. We need - // to be able to traverse these. - IgnoreResults = true; -} - -void USRGenerator::VisitObjCContainerDecl(ObjCContainerDecl *D) { - switch (D->getKind()) { - default: - assert(false && "Invalid ObjC container."); - case Decl::ObjCInterface: - case Decl::ObjCImplementation: - GenObjCClass(D->getName()); - break; - case Decl::ObjCCategory: { - ObjCCategoryDecl *CD = cast(D); - ObjCInterfaceDecl *ID = CD->getClassInterface(); - if (!ID) { - // Handle invalid code where the @interface might not - // have been specified. - // FIXME: We should be able to generate this USR even if the - // @interface isn't available. - IgnoreResults = true; - return; - } - GenObjCCategory(ID->getName(), CD->getName()); - break; - } - case Decl::ObjCCategoryImpl: { - ObjCCategoryImplDecl *CD = cast(D); - ObjCInterfaceDecl *ID = CD->getClassInterface(); - if (!ID) { - // Handle invalid code where the @interface might not - // have been specified. - // FIXME: We should be able to generate this USR even if the - // @interface isn't available. - IgnoreResults = true; - return; - } - GenObjCCategory(ID->getName(), CD->getName()); - break; - } - case Decl::ObjCProtocol: - GenObjCProtocol(cast(D)->getName()); - break; - } -} - -void USRGenerator::VisitObjCPropertyDecl(ObjCPropertyDecl *D) { - Visit(cast(D->getDeclContext())); - GenObjCProperty(D->getName()); -} - -void USRGenerator::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { - if (ObjCPropertyDecl *PD = D->getPropertyDecl()) { - VisitObjCPropertyDecl(PD); - return; - } - - IgnoreResults = true; -} - -void USRGenerator::VisitTagDecl(TagDecl *D) { - D = D->getCanonicalDecl(); - VisitDeclContext(D->getDeclContext()); - switch (D->getTagKind()) { - case TagDecl::TK_struct: Out << "@S"; break; - case TagDecl::TK_class: Out << "@C"; break; - case TagDecl::TK_union: Out << "@U"; break; - case TagDecl::TK_enum: Out << "@E"; break; - } - - const std::string &s = D->getNameAsString(); - const TypedefDecl *TD = 0; - if (s.empty()) { - TD = D->getTypedefForAnonDecl(); - Out << (TD ? 'A' : 'a'); - } - - // Add the location of the tag decl to handle resolution across - // translation units. - if (D->getLinkage() == NoLinkage) { - Out << '@'; - GenLoc(D); - if (IgnoreResults) - return; - } - - if (s.empty()) { - if (TD) - Out << '@' << TD; - } - else - Out << '@' << s; -} - -void USRGenerator::VisitTypedefDecl(TypedefDecl *D) { - DeclContext *DC = D->getDeclContext(); - if (NamedDecl *DCN = dyn_cast(DC)) - Visit(DCN); - Out << "@T@"; - if (D->getLinkage() == NoLinkage) { - GenLoc(D); - if (IgnoreResults) - return; - Out << '@'; - } - Out << D->getName(); -} - -void USRGenerator::GenLoc(const Decl *D) { - const SourceManager &SM = AU->getSourceManager(); - SourceLocation L = D->getLocStart(); - if (L.isInvalid()) { - IgnoreResults = true; - return; - } - L = SM.getInstantiationLoc(L); - const std::pair &Decomposed = SM.getDecomposedLoc(L); - const FileEntry *FE = SM.getFileEntryForID(Decomposed.first); - if (FE) { - llvm::sys::Path P(FE->getName()); - Out << P.getLast(); - } - else { - // This case really isn't interesting. - IgnoreResults = true; - return; - } - Out << '@' - << SM.getLineNumber(Decomposed.first, Decomposed.second) << ':' - << SM.getColumnNumber(Decomposed.first, Decomposed.second); -} - -//===----------------------------------------------------------------------===// -// General purpose USR generation methods. -//===----------------------------------------------------------------------===// - -void USRGenerator::GenNamedDecl(llvm::StringRef name) { - Out << "@" << name; -} - -void USRGenerator::GenObjCClass(llvm::StringRef cls) { - Out << "objc(cs)" << cls; -} - -void USRGenerator::GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat) { - Out << "objc(cy)" << cls << '@' << cat; -} - -void USRGenerator::GenObjCIvar(llvm::StringRef ivar) { - GenNamedDecl(ivar); -} - -void USRGenerator::GenObjCMethod(llvm::StringRef meth, bool isInstanceMethod) { - Out << (isInstanceMethod ? "(im)" : "(cm)") << meth; -} - -void USRGenerator::GenObjCProperty(llvm::StringRef prop) { - Out << "(py)" << prop; -} - -void USRGenerator::GenObjCProtocol(llvm::StringRef prot) { - Out << "objc(pl)" << prot; -} - -//===----------------------------------------------------------------------===// -// API hooks. -//===----------------------------------------------------------------------===// - -static inline llvm::StringRef extractUSRSuffix(llvm::StringRef s) { - return s.startswith("c:") ? s.substr(2) : ""; -} - -static CXString getDeclCursorUSR(const CXCursor &C) { - Decl *D = cxcursor::getCursorDecl(C); - - // Don't generate USRs for things with invalid locations. - if (!D || D->getLocStart().isInvalid()) - return createCXString(""); - - // Check if the cursor has 'NoLinkage'. - if (const NamedDecl *ND = dyn_cast(D)) - switch (ND->getLinkage()) { - case ExternalLinkage: - // Generate USRs for all entities with external linkage. - break; - case NoLinkage: - // We allow enums, typedefs, and structs that have no linkage to - // have USRs that are anchored to the file they were defined in - // (e.g., the header). This is a little gross, but in principal - // enums/anonymous structs/etc. defined in a common header file - // are referred to across multiple translation units. - if (isa(ND) || isa(ND) || - isa(ND) || isa(ND)) - break; - // Fall-through. - case InternalLinkage: - case UniqueExternalLinkage: - return createCXString(""); - } - - StringUSRGenerator SUG(&C); - SUG->Visit(D); - - if (SUG->ignoreResults()) - return createCXString(""); - - // For development testing. - // assert(SUG.str().size() > 2); - - // Return a copy of the string that must be disposed by the caller. - return createCXString(SUG.str(), true); -} - -extern "C" { - -CXString clang_getCursorUSR(CXCursor C) { - const CXCursorKind &K = clang_getCursorKind(C); - - if (clang_isDeclaration(K)) - return getDeclCursorUSR(C); - - if (K == CXCursor_MacroDefinition) { - StringUSRGenerator SUG(&C); - SUG << "macro@" - << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart(); - return createCXString(SUG.str(), true); - } - - return createCXString(""); -} - -CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) { - StringUSRGenerator SUG; - SUG << extractUSRSuffix(clang_getCString(classUSR)); - SUG->GenObjCIvar(name); - return createCXString(SUG.str(), true); -} - -CXString clang_constructUSR_ObjCMethod(const char *name, - unsigned isInstanceMethod, - CXString classUSR) { - StringUSRGenerator SUG; - SUG << extractUSRSuffix(clang_getCString(classUSR)); - SUG->GenObjCMethod(name, isInstanceMethod); - return createCXString(SUG.str(), true); -} - -CXString clang_constructUSR_ObjCClass(const char *name) { - StringUSRGenerator SUG; - SUG->GenObjCClass(name); - return createCXString(SUG.str(), true); -} - -CXString clang_constructUSR_ObjCProtocol(const char *name) { - StringUSRGenerator SUG; - SUG->GenObjCProtocol(name); - return createCXString(SUG.str(), true); -} - -CXString clang_constructUSR_ObjCCategory(const char *class_name, - const char *category_name) { - StringUSRGenerator SUG; - SUG->GenObjCCategory(class_name, category_name); - return createCXString(SUG.str(), true); -} - -CXString clang_constructUSR_ObjCProperty(const char *property, - CXString classUSR) { - StringUSRGenerator SUG; - SUG << extractUSRSuffix(clang_getCString(classUSR)); - SUG->GenObjCProperty(property); - return createCXString(SUG.str(), true); -} - -} // end extern "C" diff --git a/tools/CIndex/CIndexer.cpp b/tools/CIndex/CIndexer.cpp deleted file mode 100644 index d5131ff6d869..000000000000 --- a/tools/CIndex/CIndexer.cpp +++ /dev/null @@ -1,154 +0,0 @@ -//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file implements the Clang-C Source Indexing library. -// -//===----------------------------------------------------------------------===// - -#include "CIndexer.h" - -#include "clang/AST/Decl.h" -#include "clang/AST/DeclVisitor.h" -#include "clang/AST/StmtVisitor.h" -#include "clang/Basic/FileManager.h" -#include "clang/Basic/SourceManager.h" -#include "clang/Basic/Version.h" -#include "clang/Sema/CodeCompleteConsumer.h" -#include "llvm/ADT/StringExtras.h" -#include "llvm/Config/config.h" -#include "llvm/Support/Compiler.h" -#include "llvm/Support/MemoryBuffer.h" -#include "llvm/Support/raw_ostream.h" -#include "llvm/System/Program.h" - -#include -#include -#include - -#ifdef LLVM_ON_WIN32 -#include -#else -#include -#endif - -using namespace clang; - -const llvm::sys::Path& CIndexer::getClangPath() { - // Did we already compute the path? - if (!ClangPath.empty()) - return ClangPath; - - // Find the location where this library lives (libCIndex.dylib). -#ifdef LLVM_ON_WIN32 - MEMORY_BASIC_INFORMATION mbi; - char path[MAX_PATH]; - VirtualQuery((void *)(uintptr_t)clang_createTranslationUnit, &mbi, - sizeof(mbi)); - GetModuleFileNameA((HINSTANCE)mbi.AllocationBase, path, MAX_PATH); - - llvm::sys::Path CIndexPath(path); - - CIndexPath.eraseComponent(); - CIndexPath.appendComponent("clang"); - CIndexPath.appendSuffix("exe"); - CIndexPath.makeAbsolute(); -#else - // This silly cast below avoids a C++ warning. - Dl_info info; - if (dladdr((void *)(uintptr_t)clang_createTranslationUnit, &info) == 0) - assert(0 && "Call to dladdr() failed"); - - llvm::sys::Path CIndexPath(info.dli_fname); - - // We now have the CIndex directory, locate clang relative to it. - CIndexPath.eraseComponent(); - CIndexPath.appendComponent(".."); - CIndexPath.appendComponent("bin"); - CIndexPath.appendComponent("clang"); -#endif - - // Cache our result. - ClangPath = CIndexPath; - return ClangPath; -} - -std::string CIndexer::getClangResourcesPath() { - llvm::sys::Path P = getClangPath(); - - if (!P.empty()) { - P.eraseComponent(); // Remove /clang from foo/bin/clang - P.eraseComponent(); // Remove /bin from foo/bin - - // Get foo/lib/clang//include - P.appendComponent("lib"); - P.appendComponent("clang"); - P.appendComponent(CLANG_VERSION_STRING); - } - - return P.str(); -} - -static llvm::sys::Path GetTemporaryPath() { - // FIXME: This is lame; sys::Path should provide this function (in particular, - // it should know how to find the temporary files dir). - std::string Error; - const char *TmpDir = ::getenv("TMPDIR"); - if (!TmpDir) - TmpDir = ::getenv("TEMP"); - if (!TmpDir) - TmpDir = ::getenv("TMP"); - if (!TmpDir) - TmpDir = "/tmp"; - llvm::sys::Path P(TmpDir); - P.appendComponent("remap"); - if (P.makeUnique(false, &Error)) - return llvm::sys::Path(""); - - // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837. - P.eraseFromDisk(false, 0); - - return P; -} - -bool clang::RemapFiles(unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files, - std::vector &RemapArgs, - std::vector &TemporaryFiles) { - for (unsigned i = 0; i != num_unsaved_files; ++i) { - // Write the contents of this unsaved file into the temporary file. - llvm::sys::Path SavedFile(GetTemporaryPath()); - if (SavedFile.empty()) - return true; - - std::string ErrorInfo; - llvm::raw_fd_ostream OS(SavedFile.c_str(), ErrorInfo); - if (!ErrorInfo.empty()) - return true; - - OS.write(unsaved_files[i].Contents, unsaved_files[i].Length); - OS.close(); - if (OS.has_error()) { - SavedFile.eraseFromDisk(); - return true; - } - - // Remap the file. - std::string RemapArg = unsaved_files[i].Filename; - RemapArg += ';'; - RemapArg += SavedFile.str(); - RemapArgs.push_back("-Xclang"); - RemapArgs.push_back("-remap-file"); - RemapArgs.push_back("-Xclang"); - RemapArgs.push_back(RemapArg); - TemporaryFiles.push_back(SavedFile); - } - - return false; -} - diff --git a/tools/CIndex/CIndexer.h b/tools/CIndex/CIndexer.h deleted file mode 100644 index 31bf779ea4a5..000000000000 --- a/tools/CIndex/CIndexer.h +++ /dev/null @@ -1,78 +0,0 @@ -//===- CIndexer.h - Clang-C Source Indexing Library -----------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines CIndexer, a subclass of Indexer that provides extra -// functionality needed by the CIndex library. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_CINDEXER_H -#define LLVM_CLANG_CINDEXER_H - -#include "clang-c/Index.h" -#include "llvm/ADT/StringRef.h" -#include "llvm/System/Path.h" -#include - -namespace clang { -namespace cxstring { - CXString createCXString(const char *String, bool DupString = false); - CXString createCXString(llvm::StringRef String, bool DupString = true); -} -} - -class CIndexer { - bool UseExternalASTGeneration; - bool OnlyLocalDecls; - bool DisplayDiagnostics; - - llvm::sys::Path ClangPath; - -public: - CIndexer() - : UseExternalASTGeneration(false), OnlyLocalDecls(false), - DisplayDiagnostics(false) { } - - /// \brief Whether we only want to see "local" declarations (that did not - /// come from a previous precompiled header). If false, we want to see all - /// declarations. - bool getOnlyLocalDecls() const { return OnlyLocalDecls; } - void setOnlyLocalDecls(bool Local = true) { OnlyLocalDecls = Local; } - - bool getDisplayDiagnostics() const { return DisplayDiagnostics; } - void setDisplayDiagnostics(bool Display = true) { - DisplayDiagnostics = Display; - } - - bool getUseExternalASTGeneration() const { return UseExternalASTGeneration; } - void setUseExternalASTGeneration(bool Value) { - UseExternalASTGeneration = Value; - } - - /// \brief Get the path of the clang binary. - const llvm::sys::Path& getClangPath(); - - /// \brief Get the path of the clang resource files. - std::string getClangResourcesPath(); -}; - -namespace clang { - /** - * \brief Given a set of "unsaved" files, create temporary files and - * construct the clang -cc1 argument list needed to perform the remapping. - * - * \returns true if an error occurred. - */ - bool RemapFiles(unsigned num_unsaved_files, - struct CXUnsavedFile *unsaved_files, - std::vector &RemapArgs, - std::vector &TemporaryFiles); -} - -#endif diff --git a/tools/CIndex/CMakeLists.txt b/tools/CIndex/CMakeLists.txt deleted file mode 100644 index 609719e627fd..000000000000 --- a/tools/CIndex/CMakeLists.txt +++ /dev/null @@ -1,56 +0,0 @@ -set(SHARED_LIBRARY TRUE) - -set(LLVM_NO_RTTI 1) - -set(LLVM_USED_LIBS - clangFrontend - clangDriver - clangSema - clangAnalysis - clangAST - clangParse - clangLex - clangBasic) - -set( LLVM_LINK_COMPONENTS - bitreader - mc - core - ) - -add_clang_library(CIndex - CIndex.cpp - CIndexCodeCompletion.cpp - CIndexDiagnostic.cpp - CIndexInclusionStack.cpp - CIndexUSRs.cpp - CIndexer.cpp - CXCursor.cpp - ../../include/clang-c/Index.h -) - -if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") - # FIXME: Deal with LLVM_SUBMIT_VERSION? - - # FIXME: This uses a special darwin-specific exports file in order to - # get underscore-prefixed names. It would be better to have build rules - # which know how to produce a darwin-suitable exports file from the - # regular exports file. - set_target_properties(CIndex - PROPERTIES - LINK_FLAGS "-avoid-version -Wl,-exported_symbols_list -Wl,${CMAKE_CURRENT_SOURCE_DIR}/CIndex.darwin.exports -Wl,-dead_strip -Wl,-seg1addr -Wl,0xE0000000" - INSTALL_NAME_DIR "@executable_path/../lib" - ) -endif() - -if(MSVC) - # windows.h doesn't compile with /Za - get_target_property(NON_ANSI_COMPILE_FLAGS CIndex COMPILE_FLAGS) - string(REPLACE /Za "" NON_ANSI_COMPILE_FLAGS ${NON_ANSI_COMPILE_FLAGS}) - set_target_properties(CIndex PROPERTIES COMPILE_FLAGS ${NON_ANSI_COMPILE_FLAGS}) -endif(MSVC) - -set_target_properties(CIndex - PROPERTIES - LINKER_LANGUAGE CXX - DEFINE_SYMBOL _CINDEX_LIB_) diff --git a/tools/CIndex/CXCursor.cpp b/tools/CIndex/CXCursor.cpp deleted file mode 100644 index 3bc5d01fbada..000000000000 --- a/tools/CIndex/CXCursor.cpp +++ /dev/null @@ -1,369 +0,0 @@ -//===- CXCursor.cpp - Routines for manipulating CXCursors -----------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines routines for manipulating CXCursors. It should be the -// only file that has internal knowledge of the encoding of the data in -// CXCursor. -// -//===----------------------------------------------------------------------===// - -#include "CXCursor.h" -#include "clang/Frontend/ASTUnit.h" -#include "clang/AST/Decl.h" -#include "clang/AST/DeclObjC.h" -#include "clang/AST/Expr.h" -#include "llvm/Support/ErrorHandling.h" - -using namespace clang; - -CXCursor cxcursor::MakeCXCursorInvalid(CXCursorKind K) { - assert(K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid); - CXCursor C = { K, { 0, 0, 0 } }; - return C; -} - -static CXCursorKind GetCursorKind(Decl *D) { - assert(D && "Invalid arguments!"); - switch (D->getKind()) { - case Decl::Enum: return CXCursor_EnumDecl; - case Decl::EnumConstant: return CXCursor_EnumConstantDecl; - case Decl::Field: return CXCursor_FieldDecl; - case Decl::Function: - return CXCursor_FunctionDecl; - case Decl::ObjCCategory: return CXCursor_ObjCCategoryDecl; - case Decl::ObjCCategoryImpl: return CXCursor_ObjCCategoryImplDecl; - case Decl::ObjCClass: - // FIXME - return CXCursor_UnexposedDecl; - case Decl::ObjCForwardProtocol: - // FIXME - return CXCursor_UnexposedDecl; - case Decl::ObjCImplementation: return CXCursor_ObjCImplementationDecl; - case Decl::ObjCInterface: return CXCursor_ObjCInterfaceDecl; - case Decl::ObjCIvar: return CXCursor_ObjCIvarDecl; - case Decl::ObjCMethod: - return cast(D)->isInstanceMethod() - ? CXCursor_ObjCInstanceMethodDecl : CXCursor_ObjCClassMethodDecl; - case Decl::CXXMethod: return CXCursor_CXXMethod; - case Decl::ObjCProperty: return CXCursor_ObjCPropertyDecl; - case Decl::ObjCProtocol: return CXCursor_ObjCProtocolDecl; - case Decl::ParmVar: return CXCursor_ParmDecl; - case Decl::Typedef: return CXCursor_TypedefDecl; - case Decl::Var: return CXCursor_VarDecl; - default: - if (TagDecl *TD = dyn_cast(D)) { - switch (TD->getTagKind()) { - case TagDecl::TK_struct: return CXCursor_StructDecl; - case TagDecl::TK_class: return CXCursor_ClassDecl; - case TagDecl::TK_union: return CXCursor_UnionDecl; - case TagDecl::TK_enum: return CXCursor_EnumDecl; - } - } - - return CXCursor_UnexposedDecl; - } - - llvm_unreachable("Invalid Decl"); - return CXCursor_NotImplemented; -} - -static CXCursorKind GetCursorKind(const Attr *A) { - assert(A && "Invalid arguments!"); - switch (A->getKind()) { - default: break; - case Attr::IBActionKind: return CXCursor_IBActionAttr; - case Attr::IBOutletKind: return CXCursor_IBOutletAttr; - } - - return CXCursor_UnexposedAttr; -} - -CXCursor cxcursor::MakeCXCursor(const Attr *A, Decl *Parent, ASTUnit *TU) { - assert(A && Parent && TU && "Invalid arguments!"); - CXCursor C = { GetCursorKind(A), { Parent, (void*)A, TU } }; - return C; -} - -CXCursor cxcursor::MakeCXCursor(Decl *D, ASTUnit *TU) { - assert(D && TU && "Invalid arguments!"); - CXCursor C = { GetCursorKind(D), { D, 0, TU } }; - return C; -} - -CXCursor cxcursor::MakeCXCursor(Stmt *S, Decl *Parent, ASTUnit *TU) { - assert(S && TU && "Invalid arguments!"); - CXCursorKind K = CXCursor_NotImplemented; - - switch (S->getStmtClass()) { - case Stmt::NoStmtClass: - break; - - case Stmt::NullStmtClass: - case Stmt::CompoundStmtClass: - case Stmt::CaseStmtClass: - case Stmt::DefaultStmtClass: - case Stmt::LabelStmtClass: - case Stmt::IfStmtClass: - case Stmt::SwitchStmtClass: - case Stmt::WhileStmtClass: - case Stmt::DoStmtClass: - case Stmt::ForStmtClass: - case Stmt::GotoStmtClass: - case Stmt::IndirectGotoStmtClass: - case Stmt::ContinueStmtClass: - case Stmt::BreakStmtClass: - case Stmt::ReturnStmtClass: - case Stmt::DeclStmtClass: - case Stmt::SwitchCaseClass: - case Stmt::AsmStmtClass: - case Stmt::ObjCAtTryStmtClass: - case Stmt::ObjCAtCatchStmtClass: - case Stmt::ObjCAtFinallyStmtClass: - case Stmt::ObjCAtThrowStmtClass: - case Stmt::ObjCAtSynchronizedStmtClass: - case Stmt::ObjCForCollectionStmtClass: - case Stmt::CXXCatchStmtClass: - case Stmt::CXXTryStmtClass: - K = CXCursor_UnexposedStmt; - break; - - case Stmt::PredefinedExprClass: - case Stmt::IntegerLiteralClass: - case Stmt::FloatingLiteralClass: - case Stmt::ImaginaryLiteralClass: - case Stmt::StringLiteralClass: - case Stmt::CharacterLiteralClass: - case Stmt::ParenExprClass: - case Stmt::UnaryOperatorClass: - case Stmt::SizeOfAlignOfExprClass: - case Stmt::ArraySubscriptExprClass: - case Stmt::BinaryOperatorClass: - case Stmt::CompoundAssignOperatorClass: - case Stmt::ConditionalOperatorClass: - case Stmt::ImplicitCastExprClass: - case Stmt::CStyleCastExprClass: - case Stmt::CompoundLiteralExprClass: - case Stmt::ExtVectorElementExprClass: - case Stmt::InitListExprClass: - case Stmt::DesignatedInitExprClass: - case Stmt::ImplicitValueInitExprClass: - case Stmt::ParenListExprClass: - case Stmt::VAArgExprClass: - case Stmt::AddrLabelExprClass: - case Stmt::StmtExprClass: - case Stmt::TypesCompatibleExprClass: - case Stmt::ChooseExprClass: - case Stmt::GNUNullExprClass: - case Stmt::CXXStaticCastExprClass: - case Stmt::CXXDynamicCastExprClass: - case Stmt::CXXReinterpretCastExprClass: - case Stmt::CXXConstCastExprClass: - case Stmt::CXXFunctionalCastExprClass: - case Stmt::CXXTypeidExprClass: - case Stmt::CXXBoolLiteralExprClass: - case Stmt::CXXNullPtrLiteralExprClass: - case Stmt::CXXThisExprClass: - case Stmt::CXXThrowExprClass: - case Stmt::CXXDefaultArgExprClass: - case Stmt::CXXZeroInitValueExprClass: - case Stmt::CXXNewExprClass: - case Stmt::CXXDeleteExprClass: - case Stmt::CXXPseudoDestructorExprClass: - case Stmt::UnresolvedLookupExprClass: - case Stmt::UnaryTypeTraitExprClass: - case Stmt::DependentScopeDeclRefExprClass: - case Stmt::CXXBindTemporaryExprClass: - case Stmt::CXXBindReferenceExprClass: - case Stmt::CXXExprWithTemporariesClass: - case Stmt::CXXUnresolvedConstructExprClass: - case Stmt::CXXDependentScopeMemberExprClass: - case Stmt::UnresolvedMemberExprClass: - case Stmt::ObjCStringLiteralClass: - case Stmt::ObjCEncodeExprClass: - case Stmt::ObjCSelectorExprClass: - case Stmt::ObjCProtocolExprClass: - case Stmt::ObjCImplicitSetterGetterRefExprClass: - case Stmt::ObjCSuperExprClass: - case Stmt::ObjCIsaExprClass: - case Stmt::ShuffleVectorExprClass: - case Stmt::BlockExprClass: - K = CXCursor_UnexposedExpr; - break; - case Stmt::DeclRefExprClass: - case Stmt::BlockDeclRefExprClass: - // FIXME: UnresolvedLookupExpr? - // FIXME: DependentScopeDeclRefExpr? - K = CXCursor_DeclRefExpr; - break; - - case Stmt::MemberExprClass: - case Stmt::ObjCIvarRefExprClass: - case Stmt::ObjCPropertyRefExprClass: - // FIXME: UnresolvedMemberExpr? - // FIXME: CXXDependentScopeMemberExpr? - K = CXCursor_MemberRefExpr; - break; - - case Stmt::CallExprClass: - case Stmt::CXXOperatorCallExprClass: - case Stmt::CXXMemberCallExprClass: - case Stmt::CXXConstructExprClass: - case Stmt::CXXTemporaryObjectExprClass: - // FIXME: CXXUnresolvedConstructExpr - // FIXME: ObjCImplicitSetterGetterRefExpr? - K = CXCursor_CallExpr; - break; - - case Stmt::ObjCMessageExprClass: - K = CXCursor_ObjCMessageExpr; - break; - } - - CXCursor C = { K, { Parent, S, TU } }; - return C; -} - -CXCursor cxcursor::MakeCursorObjCSuperClassRef(ObjCInterfaceDecl *Super, - SourceLocation Loc, - ASTUnit *TU) { - assert(Super && TU && "Invalid arguments!"); - void *RawLoc = reinterpret_cast(Loc.getRawEncoding()); - CXCursor C = { CXCursor_ObjCSuperClassRef, { Super, RawLoc, TU } }; - return C; -} - -std::pair -cxcursor::getCursorObjCSuperClassRef(CXCursor C) { - assert(C.kind == CXCursor_ObjCSuperClassRef); - return std::make_pair(static_cast(C.data[0]), - SourceLocation::getFromRawEncoding( - reinterpret_cast(C.data[1]))); -} - -CXCursor cxcursor::MakeCursorObjCProtocolRef(ObjCProtocolDecl *Super, - SourceLocation Loc, - ASTUnit *TU) { - assert(Super && TU && "Invalid arguments!"); - void *RawLoc = reinterpret_cast(Loc.getRawEncoding()); - CXCursor C = { CXCursor_ObjCProtocolRef, { Super, RawLoc, TU } }; - return C; -} - -std::pair -cxcursor::getCursorObjCProtocolRef(CXCursor C) { - assert(C.kind == CXCursor_ObjCProtocolRef); - return std::make_pair(static_cast(C.data[0]), - SourceLocation::getFromRawEncoding( - reinterpret_cast(C.data[1]))); -} - -CXCursor cxcursor::MakeCursorObjCClassRef(ObjCInterfaceDecl *Class, - SourceLocation Loc, - ASTUnit *TU) { - // 'Class' can be null for invalid code. - if (!Class) - return MakeCXCursorInvalid(CXCursor_InvalidCode); - assert(TU && "Invalid arguments!"); - void *RawLoc = reinterpret_cast(Loc.getRawEncoding()); - CXCursor C = { CXCursor_ObjCClassRef, { Class, RawLoc, TU } }; - return C; -} - -std::pair -cxcursor::getCursorObjCClassRef(CXCursor C) { - assert(C.kind == CXCursor_ObjCClassRef); - return std::make_pair(static_cast(C.data[0]), - SourceLocation::getFromRawEncoding( - reinterpret_cast(C.data[1]))); -} - -CXCursor cxcursor::MakeCursorTypeRef(TypeDecl *Type, SourceLocation Loc, - ASTUnit *TU) { - assert(Type && TU && "Invalid arguments!"); - void *RawLoc = reinterpret_cast(Loc.getRawEncoding()); - CXCursor C = { CXCursor_TypeRef, { Type, RawLoc, TU } }; - return C; -} - -std::pair -cxcursor::getCursorTypeRef(CXCursor C) { - assert(C.kind == CXCursor_TypeRef); - return std::make_pair(static_cast(C.data[0]), - SourceLocation::getFromRawEncoding( - reinterpret_cast(C.data[1]))); -} - -CXCursor cxcursor::MakePreprocessingDirectiveCursor(SourceRange Range, - ASTUnit *TU) { - CXCursor C = { CXCursor_PreprocessingDirective, - { reinterpret_cast(Range.getBegin().getRawEncoding()), - reinterpret_cast(Range.getEnd().getRawEncoding()), - TU } - }; - return C; -} - -SourceRange cxcursor::getCursorPreprocessingDirective(CXCursor C) { - assert(C.kind == CXCursor_PreprocessingDirective); - return SourceRange(SourceLocation::getFromRawEncoding( - reinterpret_cast (C.data[0])), - SourceLocation::getFromRawEncoding( - reinterpret_cast (C.data[1]))); -} - -CXCursor cxcursor::MakeMacroDefinitionCursor(MacroDefinition *MI, ASTUnit *TU) { - CXCursor C = { CXCursor_MacroDefinition, { MI, 0, TU } }; - return C; -} - -MacroDefinition *cxcursor::getCursorMacroDefinition(CXCursor C) { - assert(C.kind == CXCursor_MacroDefinition); - return static_cast(C.data[0]); -} - -CXCursor cxcursor::MakeMacroInstantiationCursor(MacroInstantiation *MI, - ASTUnit *TU) { - CXCursor C = { CXCursor_MacroInstantiation, { MI, 0, TU } }; - return C; -} - -MacroInstantiation *cxcursor::getCursorMacroInstantiation(CXCursor C) { - assert(C.kind == CXCursor_MacroInstantiation); - return static_cast(C.data[0]); -} - -Decl *cxcursor::getCursorDecl(CXCursor Cursor) { - return (Decl *)Cursor.data[0]; -} - -Expr *cxcursor::getCursorExpr(CXCursor Cursor) { - return dyn_cast_or_null(getCursorStmt(Cursor)); -} - -Stmt *cxcursor::getCursorStmt(CXCursor Cursor) { - if (Cursor.kind == CXCursor_ObjCSuperClassRef || - Cursor.kind == CXCursor_ObjCProtocolRef || - Cursor.kind == CXCursor_ObjCClassRef) - return 0; - - return (Stmt *)Cursor.data[1]; -} - -ASTContext &cxcursor::getCursorContext(CXCursor Cursor) { - return getCursorASTUnit(Cursor)->getASTContext(); -} - -ASTUnit *cxcursor::getCursorASTUnit(CXCursor Cursor) { - return static_cast(Cursor.data[2]); -} - -bool cxcursor::operator==(CXCursor X, CXCursor Y) { - return X.kind == Y.kind && X.data[0] == Y.data[0] && X.data[1] == Y.data[1] && - X.data[2] == Y.data[2]; -} diff --git a/tools/CIndex/CXCursor.h b/tools/CIndex/CXCursor.h deleted file mode 100644 index 1664f5a9ced2..000000000000 --- a/tools/CIndex/CXCursor.h +++ /dev/null @@ -1,112 +0,0 @@ -//===- CXCursor.h - Routines for manipulating CXCursors -------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines routines for manipulating CXCursors. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_CXCURSOR_H -#define LLVM_CLANG_CXCURSOR_H - -#include "clang-c/Index.h" -#include "clang/Basic/SourceLocation.h" -#include - -namespace clang { - -class ASTContext; -class ASTUnit; -class Attr; -class Decl; -class Expr; -class MacroDefinition; -class MacroInstantiation; -class NamedDecl; -class ObjCInterfaceDecl; -class ObjCProtocolDecl; -class Stmt; -class TypeDecl; - -namespace cxcursor { - -CXCursor MakeCXCursor(const clang::Attr *A, clang::Decl *Parent, ASTUnit *TU); -CXCursor MakeCXCursor(clang::Decl *D, ASTUnit *TU); -CXCursor MakeCXCursor(clang::Stmt *S, clang::Decl *Parent, ASTUnit *TU); -CXCursor MakeCXCursorInvalid(CXCursorKind K); - -/// \brief Create an Objective-C superclass reference at the given location. -CXCursor MakeCursorObjCSuperClassRef(ObjCInterfaceDecl *Super, - SourceLocation Loc, - ASTUnit *TU); - -/// \brief Unpack an ObjCSuperClassRef cursor into the interface it references -/// and optionally the location where the reference occurred. -std::pair - getCursorObjCSuperClassRef(CXCursor C); - -/// \brief Create an Objective-C protocol reference at the given location. -CXCursor MakeCursorObjCProtocolRef(ObjCProtocolDecl *Proto, SourceLocation Loc, - ASTUnit *TU); - -/// \brief Unpack an ObjCProtocolRef cursor into the protocol it references -/// and optionally the location where the reference occurred. -std::pair - getCursorObjCProtocolRef(CXCursor C); - -/// \brief Create an Objective-C class reference at the given location. -CXCursor MakeCursorObjCClassRef(ObjCInterfaceDecl *Class, SourceLocation Loc, - ASTUnit *TU); - -/// \brief Unpack an ObjCClassRef cursor into the class it references -/// and optionally the location where the reference occurred. -std::pair - getCursorObjCClassRef(CXCursor C); - -/// \brief Create a type reference at the given location. -CXCursor MakeCursorTypeRef(TypeDecl *Type, SourceLocation Loc, ASTUnit *TU); - -/// \brief Unpack a TypeRef cursor into the class it references -/// and optionally the location where the reference occurred. -std::pair getCursorTypeRef(CXCursor C); - -/// \brief Create a preprocessing directive cursor. -CXCursor MakePreprocessingDirectiveCursor(SourceRange Range, ASTUnit *TU); - -/// \brief Unpack a given preprocessing directive to retrieve its source range. -SourceRange getCursorPreprocessingDirective(CXCursor C); - -/// \brief Create a macro definition cursor. -CXCursor MakeMacroDefinitionCursor(MacroDefinition *, ASTUnit *TU); - -/// \brief Unpack a given macro definition cursor to retrieve its -/// source range. -MacroDefinition *getCursorMacroDefinition(CXCursor C); - -/// \brief Create a macro instantiation cursor. -CXCursor MakeMacroInstantiationCursor(MacroInstantiation *, ASTUnit *TU); - -/// \brief Unpack a given macro instantiation cursor to retrieve its -/// source range. -MacroInstantiation *getCursorMacroInstantiation(CXCursor C); - -Decl *getCursorDecl(CXCursor Cursor); -Expr *getCursorExpr(CXCursor Cursor); -Stmt *getCursorStmt(CXCursor Cursor); -ASTContext &getCursorContext(CXCursor Cursor); -ASTUnit *getCursorASTUnit(CXCursor Cursor); - -bool operator==(CXCursor X, CXCursor Y); - -inline bool operator!=(CXCursor X, CXCursor Y) { - return !(X == Y); -} - -}} // end namespace: clang::cxcursor - -#endif diff --git a/tools/CIndex/CXSourceLocation.h b/tools/CIndex/CXSourceLocation.h deleted file mode 100644 index 66566c126891..000000000000 --- a/tools/CIndex/CXSourceLocation.h +++ /dev/null @@ -1,75 +0,0 @@ -//===- CXSourceLocation.h - CXSourceLocations Utilities ---------*- C++ -*-===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This file defines routines for manipulating CXSourceLocations. -// -//===----------------------------------------------------------------------===// - -#ifndef LLVM_CLANG_CXSOURCELOCATION_H -#define LLVM_CLANG_CXSOURCELOCATION_H - -#include "clang-c/Index.h" -#include "clang/Basic/SourceLocation.h" -#include "clang/Basic/LangOptions.h" -#include "clang/AST/ASTContext.h" - -namespace clang { - -class SourceManager; - -namespace cxloc { - -/// \brief Translate a Clang source location into a CIndex source location. -static inline CXSourceLocation -translateSourceLocation(const SourceManager &SM, const LangOptions &LangOpts, - SourceLocation Loc) { - CXSourceLocation Result = { { (void*) &SM, (void*) &LangOpts, }, - Loc.getRawEncoding() }; - return Result; -} - -/// \brief Translate a Clang source location into a CIndex source location. -static inline CXSourceLocation translateSourceLocation(ASTContext &Context, - SourceLocation Loc) { - return translateSourceLocation(Context.getSourceManager(), - Context.getLangOptions(), - Loc); -} - -/// \brief Translate a Clang source range into a CIndex source range. -/// -/// Clang internally represents ranges where the end location points to the -/// start of the token at the end. However, for external clients it is more -/// useful to have a CXSourceRange be a proper half-open interval. This routine -/// does the appropriate translation. -CXSourceRange translateSourceRange(const SourceManager &SM, - const LangOptions &LangOpts, - SourceRange R); - -/// \brief Translate a Clang source range into a CIndex source range. -static inline CXSourceRange translateSourceRange(ASTContext &Context, - SourceRange R) { - return translateSourceRange(Context.getSourceManager(), - Context.getLangOptions(), - R); -} - -static inline SourceLocation translateSourceLocation(CXSourceLocation L) { - return SourceLocation::getFromRawEncoding(L.int_data); -} - -static inline SourceRange translateCXSourceRange(CXSourceRange R) { - return SourceRange(SourceLocation::getFromRawEncoding(R.begin_int_data), - SourceLocation::getFromRawEncoding(R.end_int_data)); -} - - -}} // end namespace: clang::cxloc - -#endif diff --git a/tools/CIndex/Makefile b/tools/CIndex/Makefile deleted file mode 100644 index 391746d4d4fd..000000000000 --- a/tools/CIndex/Makefile +++ /dev/null @@ -1,55 +0,0 @@ -##===- tools/CIndex/Makefile -------------------------------*- Makefile -*-===## -# -# The LLVM Compiler Infrastructure -# -# This file is distributed under the University of Illinois Open Source -# License. See LICENSE.TXT for details. -# -##===----------------------------------------------------------------------===## - -LEVEL = ../../../.. -LIBRARYNAME = CIndex - -EXPORTED_SYMBOL_FILE = $(PROJ_SRC_DIR)/CIndex.exports - -CPP.Flags += -I$(PROJ_SRC_DIR)/../../include -I$(PROJ_OBJ_DIR)/../../include - -# Include this here so we can get the configuration of the targets -# that have been configured for construction. We have to do this -# early so we can set up LINK_COMPONENTS before including Makefile.rules -include $(LEVEL)/Makefile.config - -LINK_LIBS_IN_SHARED = 1 -SHARED_LIBRARY = 1 - -LINK_COMPONENTS := bitreader mc core -USEDLIBS = clangFrontend.a clangDriver.a clangSema.a \ - clangAnalysis.a clangAST.a clangParse.a clangLex.a clangBasic.a - -include $(LEVEL)/Makefile.common - -##===----------------------------------------------------------------------===## -# FIXME: This is copied from the 'lto' makefile. Should we share this? -##===----------------------------------------------------------------------===## - -ifeq ($(HOST_OS),Darwin) - # set dylib internal version number to llvmCore submission number - ifdef LLVM_SUBMIT_VERSION - LLVMLibsOptions := $(LLVMLibsOptions) -Wl,-current_version \ - -Wl,$(LLVM_SUBMIT_VERSION).$(LLVM_SUBMIT_SUBVERSION) \ - -Wl,-compatibility_version -Wl,1 - endif - # extra options to override libtool defaults - LLVMLibsOptions := $(LLVMLibsOptions) \ - -avoid-version \ - -Wl,-dead_strip \ - -Wl,-seg1addr -Wl,0xE0000000 - - # Mac OS X 10.4 and earlier tools do not allow a second -install_name on command line - DARWIN_VERS := $(shell echo $(TARGET_TRIPLE) | sed 's/.*darwin\([0-9]*\).*/\1/') - ifneq ($(DARWIN_VERS),8) - LLVMLibsOptions := $(LLVMLibsOptions) \ - -no-undefined -Wl,-install_name \ - -Wl,"@executable_path/../lib/lib$(LIBRARYNAME)$(SHLIBEXT)" - endif -endif diff --git a/tools/index-test/CMakeLists.txt b/tools/index-test/CMakeLists.txt deleted file mode 100644 index 9472e580fbc5..000000000000 --- a/tools/index-test/CMakeLists.txt +++ /dev/null @@ -1,23 +0,0 @@ -set(LLVM_NO_RTTI 1) - -set( LLVM_USED_LIBS - clangIndex - clangFrontend - clangDriver - clangSema - clangAnalysis - clangAST - clangParse - clangLex - clangBasic - ) - -set( LLVM_LINK_COMPONENTS - bitreader - mc - core - ) - -add_clang_executable(index-test - index-test.cpp - ) diff --git a/tools/index-test/Makefile b/tools/index-test/Makefile deleted file mode 100644 index 4ee98fc7cc99..000000000000 --- a/tools/index-test/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -##===- tools/index-test/Makefile ---------------------------*- Makefile -*-===## -# -# The LLVM Compiler Infrastructure -# -# This file is distributed under the University of Illinois Open Source -# License. See LICENSE.TXT for details. -# -##===----------------------------------------------------------------------===## -LEVEL = ../../../.. - -TOOLNAME = index-test -CPPFLAGS += -I$(PROJ_SRC_DIR)/../../include -I$(PROJ_OBJ_DIR)/../../include -CXXFLAGS = -fno-rtti -NO_INSTALL = 1 - -# No plugins, optimize startup time. -TOOL_NO_EXPORTS = 1 - -include $(LEVEL)/Makefile.config - -LINK_COMPONENTS := bitreader mc core -USEDLIBS = clangIndex.a clangFrontend.a clangDriver.a clangSema.a \ - clangAnalysis.a clangAST.a clangParse.a clangLex.a clangBasic.a - -include $(LLVM_SRC_ROOT)/Makefile.rules diff --git a/tools/index-test/index-test.cpp b/tools/index-test/index-test.cpp deleted file mode 100644 index ff9fd5431154..000000000000 --- a/tools/index-test/index-test.cpp +++ /dev/null @@ -1,334 +0,0 @@ -//===--- index-test.cpp - Indexing test bed -------------------------------===// -// -// The LLVM Compiler Infrastructure -// -// This file is distributed under the University of Illinois Open Source -// License. See LICENSE.TXT for details. -// -//===----------------------------------------------------------------------===// -// -// This utility may be invoked in the following manner: -// index-test --help - Output help info. -// index-test [options] - Read from stdin. -// index-test [options] file - Read from "file". -// index-test [options] file1 file2 - Read these files. -// -// Files must be AST files. -// -//===----------------------------------------------------------------------===// -// -// -point-at [file:line:column] -// Point at a declaration/statement/expression. If no other operation is -// specified, prints some info about it. -// -// -print-refs -// Print ASTLocations that reference the -point-at node -// -// -print-defs -// Print ASTLocations that define the -point-at node -// -// -print-decls -// Print ASTLocations that declare the -point-at node -// -//===----------------------------------------------------------------------===// - -#include "clang/Index/Program.h" -#include "clang/Index/Indexer.h" -#include "clang/Index/Entity.h" -#include "clang/Index/TranslationUnit.h" -#include "clang/Index/ASTLocation.h" -#include "clang/Index/DeclReferenceMap.h" -#include "clang/Index/SelectorMap.h" -#include "clang/Index/Handlers.h" -#include "clang/Index/Analyzer.h" -#include "clang/Index/Utils.h" -#include "clang/Frontend/ASTUnit.h" -#include "clang/Frontend/CompilerInstance.h" -#include "clang/Frontend/CompilerInvocation.h" -#include "clang/Frontend/DiagnosticOptions.h" -#include "clang/Frontend/TextDiagnosticPrinter.h" -#include "clang/Frontend/CommandLineSourceLoc.h" -#include "clang/AST/DeclObjC.h" -#include "clang/AST/ExprObjC.h" -#include "clang/Basic/FileManager.h" -#include "clang/Basic/SourceManager.h" -#include "llvm/Support/CommandLine.h" -#include "llvm/Support/ManagedStatic.h" -#include "llvm/Support/PrettyStackTrace.h" -#include "llvm/Support/raw_ostream.h" -#include "llvm/System/Signals.h" -using namespace clang; -using namespace idx; - -class TUnit : public TranslationUnit { -public: - TUnit(ASTUnit *ast, const std::string &filename) - : AST(ast), Filename(filename), - DeclRefMap(ast->getASTContext()), - SelMap(ast->getASTContext()) { } - - virtual ASTContext &getASTContext() { return AST->getASTContext(); } - virtual DeclReferenceMap &getDeclReferenceMap() { return DeclRefMap; } - virtual SelectorMap &getSelectorMap() { return SelMap; } - - llvm::OwningPtr AST; - std::string Filename; - DeclReferenceMap DeclRefMap; - SelectorMap SelMap; -}; - -static llvm::cl::list -PointAtLocation("point-at", llvm::cl::Optional, - llvm::cl::value_desc("source-location"), - llvm::cl::desc("Point at the given source location of the first AST file")); - -enum ProgActions { - PrintPoint, // Just print the point-at node - PrintRefs, // Print references of the point-at node - PrintDefs, // Print definitions of the point-at node - PrintDecls // Print declarations of the point-at node -}; - -static llvm::cl::opt -ProgAction( - llvm::cl::desc("Choose action to perform on the pointed-at AST node:"), - llvm::cl::ZeroOrMore, - llvm::cl::init(PrintPoint), - llvm::cl::values( - clEnumValN(PrintRefs, "print-refs", - "Print references"), - clEnumValN(PrintDefs, "print-defs", - "Print definitions"), - clEnumValN(PrintDecls, "print-decls", - "Print declarations"), - clEnumValEnd)); - -static llvm::cl::opt -DisableFree("disable-free", - llvm::cl::desc("Disable freeing of memory on exit"), - llvm::cl::init(false)); - -static bool HadErrors = false; - -static void ProcessObjCMessage(ObjCMessageExpr *Msg, Indexer &Idxer) { - llvm::raw_ostream &OS = llvm::outs(); - typedef Storing ResultsTy; - ResultsTy Results; - - Analyzer Analyz(Idxer.getProgram(), Idxer); - - switch (ProgAction) { - default: assert(0); - case PrintRefs: - llvm::errs() << "Error: Cannot -print-refs on a ObjC message expression\n"; - HadErrors = true; - return; - - case PrintDecls: { - Analyz.FindObjCMethods(Msg, Results); - for (ResultsTy::iterator - I = Results.begin(), E = Results.end(); I != E; ++I) - I->print(OS); - break; - } - - case PrintDefs: { - Analyz.FindObjCMethods(Msg, Results); - for (ResultsTy::iterator - I = Results.begin(), E = Results.end(); I != E; ++I) { - const ObjCMethodDecl *D = cast(I->AsDecl()); - if (D->isThisDeclarationADefinition()) - I->print(OS); - } - break; - } - - } -} - -static void ProcessASTLocation(ASTLocation ASTLoc, Indexer &Idxer) { - assert(ASTLoc.isValid()); - - if (ObjCMessageExpr *Msg = - dyn_cast_or_null(ASTLoc.dyn_AsStmt())) - return ProcessObjCMessage(Msg, Idxer); - - Decl *D = ASTLoc.getReferencedDecl(); - if (D == 0) { - llvm::errs() << "Error: Couldn't get referenced Decl for the ASTLocation\n"; - HadErrors = true; - return; - } - - llvm::raw_ostream &OS = llvm::outs(); - typedef Storing ResultsTy; - ResultsTy Results; - - Analyzer Analyz(Idxer.getProgram(), Idxer); - - switch (ProgAction) { - default: assert(0); - case PrintRefs: { - Analyz.FindReferences(D, Results); - for (ResultsTy::iterator - I = Results.begin(), E = Results.end(); I != E; ++I) - I->print(OS); - break; - } - - case PrintDecls: { - Analyz.FindDeclarations(D, Results); - for (ResultsTy::iterator - I = Results.begin(), E = Results.end(); I != E; ++I) - I->print(OS); - break; - } - - case PrintDefs: { - Analyz.FindDeclarations(D, Results); - for (ResultsTy::iterator - I = Results.begin(), E = Results.end(); I != E; ++I) { - const Decl *D = I->AsDecl(); - bool isDef = false; - if (const FunctionDecl *FD = dyn_cast(D)) - isDef = FD->isThisDeclarationADefinition(); - else if (const VarDecl *VD = dyn_cast(D)) - isDef = VD->getInit() != 0; - else if (const ObjCMethodDecl *MD = dyn_cast(D)) - isDef = MD->isThisDeclarationADefinition(); - - if (isDef) - I->print(OS); - } - break; - } - - } -} - -static llvm::cl::opt -ASTFromSource("ast-from-source", - llvm::cl::desc("Treat the inputs as source files to parse")); - -static llvm::cl::list -CompilerArgs("arg", llvm::cl::desc("Extra arguments to use during parsing")); - -static llvm::cl::list -InputFilenames(llvm::cl::Positional, llvm::cl::desc("")); - -ASTUnit *CreateFromSource(const std::string &Filename, Diagnostic &Diags, - const char *Argv0) { - llvm::SmallVector Args; - Args.push_back(Filename.c_str()); - for (unsigned i = 0, e = CompilerArgs.size(); i != e; ++i) - Args.push_back(CompilerArgs[i].c_str()); - - void *MainAddr = (void*) (intptr_t) CreateFromSource; - std::string ResourceDir = - CompilerInvocation::GetResourcesPath(Argv0, MainAddr); - return ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(), - Diags, ResourceDir); -} - -int main(int argc, char **argv) { - llvm::sys::PrintStackTraceOnErrorSignal(); - llvm::PrettyStackTraceProgram X(argc, argv); - llvm::cl::ParseCommandLineOptions(argc, argv, - "LLVM 'Clang' Indexing Test Bed: http://clang.llvm.org\n"); - - Program Prog; - Indexer Idxer(Prog); - llvm::SmallVector TUnits; - - DiagnosticOptions DiagOpts; - llvm::OwningPtr Diags( - CompilerInstance::createDiagnostics(DiagOpts, argc, argv)); - - // If no input was specified, read from stdin. - if (InputFilenames.empty()) - InputFilenames.push_back("-"); - - for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) { - const std::string &InFile = InputFilenames[i]; - llvm::OwningPtr AST; - if (ASTFromSource) - AST.reset(CreateFromSource(InFile, *Diags, argv[0])); - else - AST.reset(ASTUnit::LoadFromPCHFile(InFile, *Diags)); - if (!AST) - return 1; - - TUnit *TU = new TUnit(AST.take(), InFile); - TUnits.push_back(TU); - - Idxer.IndexAST(TU); - } - - ASTLocation ASTLoc; - const std::string &FirstFile = TUnits[0]->Filename; - ASTUnit *FirstAST = TUnits[0]->AST.get(); - - if (!PointAtLocation.empty()) { - const std::string &Filename = PointAtLocation[0].FileName; - const FileEntry *File = FirstAST->getFileManager().getFile(Filename); - if (File == 0) { - llvm::errs() << "File '" << Filename << "' does not exist\n"; - return 1; - } - - // Safety check. Using an out-of-date AST file will only lead to crashes - // or incorrect results. - // FIXME: Check all the source files that make up the AST file. - const FileEntry *ASTFile = FirstAST->getFileManager().getFile(FirstFile); - if (File->getModificationTime() > ASTFile->getModificationTime()) { - llvm::errs() << "[" << FirstFile << "] Error: " << - "Pointing at a source file which was modified after creating " - "the AST file\n"; - return 1; - } - - unsigned Line = PointAtLocation[0].Line; - unsigned Col = PointAtLocation[0].Column; - - SourceLocation Loc = - FirstAST->getSourceManager().getLocation(File, Line, Col); - if (Loc.isInvalid()) { - llvm::errs() << "[" << FirstFile << "] Error: " << - "Couldn't resolve source location (invalid location)\n"; - return 1; - } - - ASTLoc = ResolveLocationInAST(FirstAST->getASTContext(), Loc); - if (ASTLoc.isInvalid()) { - llvm::errs() << "[" << FirstFile << "] Error: " << - "Couldn't resolve source location (no declaration found)\n"; - return 1; - } - } - - if (ASTLoc.isValid()) { - if (ProgAction == PrintPoint) { - llvm::raw_ostream &OS = llvm::outs(); - ASTLoc.print(OS); - if (const char *Comment = - FirstAST->getASTContext().getCommentForDecl(ASTLoc.dyn_AsDecl())) - OS << "Comment associated with this declaration:\n" << Comment << "\n"; - } else { - ProcessASTLocation(ASTLoc, Idxer); - } - } - - if (HadErrors) - return 1; - - if (!DisableFree) { - for (int i=0, e=TUnits.size(); i != e; ++i) - delete TUnits[i]; - } - - // Managed static deconstruction. Useful for making things like - // -time-passes usable. - llvm::llvm_shutdown(); - - return 0; -} diff --git a/utils/pch-test.pl b/utils/pch-test.pl deleted file mode 100755 index 2e17117a2a29..000000000000 --- a/utils/pch-test.pl +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/perl -w - -# This tiny little script, which should be run from the clang -# directory (with clang-cc in your patch), tries to take each -# compilable Clang test and build a PCH file from that test, then read -# and dump the contents of the PCH file just created. -use POSIX; - -$exitcode = 0; -sub testfiles($$) { - my $suffix = shift; - my $language = shift; - my $passed = 0; - my $failed = 0; - my $skipped = 0; - - @files = `ls test/*/*.$suffix`; - foreach $file (@files) { - chomp($file); - my $code = system("clang-cc -fsyntax-only -x $language $file > /dev/null 2>&1"); - if ($code == 0) { - print("."); - $code = system("clang-cc -emit-pch -x $language -o $file.pch $file > /dev/null 2>&1"); - if ($code == 0) { - $code = system("clang-cc -include-pch $file.pch -x $language -ast-dump /dev/null > /dev/null 2>&1"); - if ($code == 0) { - $passed++; - } elsif (($code & 0xFF) == SIGINT) { - exit($exitcode); - } else { - print("\n---Failed to dump AST file for \"$file\"---\n"); - $exitcode = 1; - $failed++; - } - unlink "$file.pch"; - } elsif (($code & 0xFF) == SIGINT) { - exit($exitcode); - } else { - print("\n---Failed to build PCH file for \"$file\"---\n"); - $exitcode = 1; - $failed++; - } - } elsif (($code & 0xFF) == SIGINT) { - exit($exitcode); - } else { - print("x"); - $skipped++; - } - } - - print("\n\n$passed tests passed\n"); - print("$failed tests failed\n"); - print("$skipped tests skipped ('x')\n") -} - -printf("-----Testing precompiled headers for C-----\n"); -testfiles("c", "c"); -printf("\n-----Testing precompiled headers for Objective-C-----\n"); -testfiles("m", "objective-c"); -print("\n"); -exit($exitcode); diff --git a/win32/clangAST/clangAST.vcproj b/win32/clangAST/clangAST.vcproj deleted file mode 100644 index 8795412ba8cd..000000000000 --- a/win32/clangAST/clangAST.vcproj +++ /dev/null @@ -1,347 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangAnalysis/clangAnalysis.vcproj b/win32/clangAnalysis/clangAnalysis.vcproj deleted file mode 100644 index c9850e059cff..000000000000 --- a/win32/clangAnalysis/clangAnalysis.vcproj +++ /dev/null @@ -1,351 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangBasic/clangBasic.vcproj b/win32/clangBasic/clangBasic.vcproj deleted file mode 100644 index d836a6604c73..000000000000 --- a/win32/clangBasic/clangBasic.vcproj +++ /dev/null @@ -1,236 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangCodeGen/clangCodeGen.vcproj b/win32/clangCodeGen/clangCodeGen.vcproj deleted file mode 100644 index a819fd94d867..000000000000 --- a/win32/clangCodeGen/clangCodeGen.vcproj +++ /dev/null @@ -1,271 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangDriver/clangDriver.vcproj b/win32/clangDriver/clangDriver.vcproj deleted file mode 100644 index 0a744bbe4e9c..000000000000 --- a/win32/clangDriver/clangDriver.vcproj +++ /dev/null @@ -1,270 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangLex/clangLex.vcproj b/win32/clangLex/clangLex.vcproj deleted file mode 100644 index 5bec4b8b8e7f..000000000000 --- a/win32/clangLex/clangLex.vcproj +++ /dev/null @@ -1,283 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangLibDriver/clangLibDriver.vcproj b/win32/clangLibDriver/clangLibDriver.vcproj deleted file mode 100644 index de42ef72a787..000000000000 --- a/win32/clangLibDriver/clangLibDriver.vcproj +++ /dev/null @@ -1,205 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangParse/clangParse.vcproj b/win32/clangParse/clangParse.vcproj deleted file mode 100644 index 4cf552530545..000000000000 --- a/win32/clangParse/clangParse.vcproj +++ /dev/null @@ -1,248 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangRewrite/clangRewrite.vcproj b/win32/clangRewrite/clangRewrite.vcproj deleted file mode 100644 index 7b1f898f9d67..000000000000 --- a/win32/clangRewrite/clangRewrite.vcproj +++ /dev/null @@ -1,191 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/win32/clangSema/clangSema.vcproj b/win32/clangSema/clangSema.vcproj deleted file mode 100644 index 572c3effcafa..000000000000 --- a/win32/clangSema/clangSema.vcproj +++ /dev/null @@ -1,263 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/www/analyzer/menu.js b/www/analyzer/menu.js deleted file mode 100644 index 6b393c081c85..000000000000 --- a/www/analyzer/menu.js +++ /dev/null @@ -1,17 +0,0 @@ -startList = function() { - if (document.all&&document.getElementById) { - navRoot = document.getElementById("nav"); - for (i=0; i