Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/ASTVector.h | //===- ASTVector.h - Vector that uses ASTContext for allocation --*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides ASTVector, a vector ADT whose contents are
// allocated using the allocator associated with an ASTContext..
//
//===----------------------------------------------------------------------===//
// FIXME: Most of this is copy-and-paste from BumpVector.h and SmallVector.h.
// We can refactor this core logic into something common.
#ifndef LLVM_CLANG_AST_ASTVECTOR_H
#define LLVM_CLANG_AST_ASTVECTOR_H
#include "clang/AST/AttrIterator.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/type_traits.h"
#include <algorithm>
#include <cstring>
#include <memory>
namespace clang {
class ASTContext;
template<typename T>
class ASTVector {
private:
T *Begin, *End;
llvm::PointerIntPair<T*, 1, bool> Capacity;
void setEnd(T *P) { this->End = P; }
protected:
// Make a tag bit available to users of this class.
// FIXME: This is a horrible hack.
bool getTag() const { return Capacity.getInt(); }
void setTag(bool B) { Capacity.setInt(B); }
public:
// Default ctor - Initialize to empty.
ASTVector() : Begin(nullptr), End(nullptr), Capacity(nullptr, false) {}
ASTVector(ASTVector &&O) : Begin(O.Begin), End(O.End), Capacity(O.Capacity) {
O.Begin = O.End = nullptr;
O.Capacity.setPointer(nullptr);
O.Capacity.setInt(false);
}
ASTVector(const ASTContext &C, unsigned N)
: Begin(nullptr), End(nullptr), Capacity(nullptr, false) {
reserve(C, N);
}
ASTVector &operator=(ASTVector &&RHS) {
ASTVector O(std::move(RHS));
using std::swap;
swap(Begin, O.Begin);
swap(End, O.End);
swap(Capacity, O.Capacity);
return *this;
}
~ASTVector() {
if (std::is_class<T>::value) {
// Destroy the constructed elements in the vector.
destroy_range(Begin, End);
}
}
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T value_type;
typedef T* iterator;
typedef const T* const_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef T& reference;
typedef const T& const_reference;
typedef T* pointer;
typedef const T* const_pointer;
// forward iterator creation methods.
iterator begin() { return Begin; }
const_iterator begin() const { return Begin; }
iterator end() { return End; }
const_iterator end() const { return End; }
// reverse iterator creation methods.
reverse_iterator rbegin() { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
bool empty() const { return Begin == End; }
size_type size() const { return End-Begin; }
reference operator[](unsigned idx) {
assert(Begin + idx < End);
return Begin[idx];
}
const_reference operator[](unsigned idx) const {
assert(Begin + idx < End);
return Begin[idx];
}
reference front() {
return begin()[0];
}
const_reference front() const {
return begin()[0];
}
reference back() {
return end()[-1];
}
const_reference back() const {
return end()[-1];
}
void pop_back() {
--End;
End->~T();
}
T pop_back_val() {
T Result = back();
pop_back();
return Result;
}
void clear() {
if (std::is_class<T>::value) {
destroy_range(Begin, End);
}
End = Begin;
}
/// data - Return a pointer to the vector's buffer, even if empty().
pointer data() {
return pointer(Begin);
}
/// data - Return a pointer to the vector's buffer, even if empty().
const_pointer data() const {
return const_pointer(Begin);
}
void push_back(const_reference Elt, const ASTContext &C) {
if (End < this->capacity_ptr()) {
Retry:
new (End) T(Elt);
++End;
return;
}
grow(C);
goto Retry;
}
void reserve(const ASTContext &C, unsigned N) {
if (unsigned(this->capacity_ptr()-Begin) < N)
grow(C, N);
}
/// capacity - Return the total number of elements in the currently allocated
/// buffer.
size_t capacity() const { return this->capacity_ptr() - Begin; }
/// append - Add the specified range to the end of the SmallVector.
///
template<typename in_iter>
void append(const ASTContext &C, in_iter in_start, in_iter in_end) {
size_type NumInputs = std::distance(in_start, in_end);
if (NumInputs == 0)
return;
// Grow allocated space if needed.
if (NumInputs > size_type(this->capacity_ptr()-this->end()))
this->grow(C, this->size()+NumInputs);
// Copy the new elements over.
// TODO: NEED To compile time dispatch on whether in_iter is a random access
// iterator to use the fast uninitialized_copy.
std::uninitialized_copy(in_start, in_end, this->end());
this->setEnd(this->end() + NumInputs);
}
/// append - Add the specified range to the end of the SmallVector.
///
void append(const ASTContext &C, size_type NumInputs, const T &Elt) {
// Grow allocated space if needed.
if (NumInputs > size_type(this->capacity_ptr()-this->end()))
this->grow(C, this->size()+NumInputs);
// Copy the new elements over.
std::uninitialized_fill_n(this->end(), NumInputs, Elt);
this->setEnd(this->end() + NumInputs);
}
/// uninitialized_copy - Copy the range [I, E) onto the uninitialized memory
/// starting with "Dest", constructing elements into it as needed.
template<typename It1, typename It2>
static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
std::uninitialized_copy(I, E, Dest);
}
iterator insert(const ASTContext &C, iterator I, const T &Elt) {
if (I == this->end()) { // Important special case for empty vector.
push_back(Elt, C);
return this->end()-1;
}
if (this->End < this->capacity_ptr()) {
Retry:
new (this->end()) T(this->back());
this->setEnd(this->end()+1);
// Push everything else over.
std::copy_backward(I, this->end()-1, this->end());
*I = Elt;
return I;
}
size_t EltNo = I-this->begin();
this->grow(C);
I = this->begin()+EltNo;
goto Retry;
}
iterator insert(const ASTContext &C, iterator I, size_type NumToInsert,
const T &Elt) {
// Convert iterator to elt# to avoid invalidating iterator when we reserve()
size_t InsertElt = I - this->begin();
if (I == this->end()) { // Important special case for empty vector.
append(C, NumToInsert, Elt);
return this->begin() + InsertElt;
}
// Ensure there is enough space.
reserve(C, static_cast<unsigned>(this->size() + NumToInsert));
// Uninvalidate the iterator.
I = this->begin()+InsertElt;
// If there are more elements between the insertion point and the end of the
// range than there are being inserted, we can use a simple approach to
// insertion. Since we already reserved space, we know that this won't
// reallocate the vector.
if (size_t(this->end()-I) >= NumToInsert) {
T *OldEnd = this->end();
append(C, this->end()-NumToInsert, this->end());
// Copy the existing elements that get replaced.
std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
std::fill_n(I, NumToInsert, Elt);
return I;
}
// Otherwise, we're inserting more elements than exist already, and we're
// not inserting at the end.
// Copy over the elements that we're about to overwrite.
T *OldEnd = this->end();
this->setEnd(this->end() + NumToInsert);
size_t NumOverwritten = OldEnd-I;
this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
// Replace the overwritten part.
std::fill_n(I, NumOverwritten, Elt);
// Insert the non-overwritten middle part.
std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt);
return I;
}
template<typename ItTy>
iterator insert(const ASTContext &C, iterator I, ItTy From, ItTy To) {
// Convert iterator to elt# to avoid invalidating iterator when we reserve()
size_t InsertElt = I - this->begin();
if (I == this->end()) { // Important special case for empty vector.
append(C, From, To);
return this->begin() + InsertElt;
}
size_t NumToInsert = std::distance(From, To);
// Ensure there is enough space.
reserve(C, static_cast<unsigned>(this->size() + NumToInsert));
// Uninvalidate the iterator.
I = this->begin()+InsertElt;
// If there are more elements between the insertion point and the end of the
// range than there are being inserted, we can use a simple approach to
// insertion. Since we already reserved space, we know that this won't
// reallocate the vector.
if (size_t(this->end()-I) >= NumToInsert) {
T *OldEnd = this->end();
append(C, this->end()-NumToInsert, this->end());
// Copy the existing elements that get replaced.
std::copy_backward(I, OldEnd-NumToInsert, OldEnd);
std::copy(From, To, I);
return I;
}
// Otherwise, we're inserting more elements than exist already, and we're
// not inserting at the end.
// Copy over the elements that we're about to overwrite.
T *OldEnd = this->end();
this->setEnd(this->end() + NumToInsert);
size_t NumOverwritten = OldEnd-I;
this->uninitialized_copy(I, OldEnd, this->end()-NumOverwritten);
// Replace the overwritten part.
for (; NumOverwritten > 0; --NumOverwritten) {
*I = *From;
++I; ++From;
}
// Insert the non-overwritten middle part.
this->uninitialized_copy(From, To, OldEnd);
return I;
}
void resize(const ASTContext &C, unsigned N, const T &NV) {
if (N < this->size()) {
this->destroy_range(this->begin()+N, this->end());
this->setEnd(this->begin()+N);
} else if (N > this->size()) {
if (this->capacity() < N)
this->grow(C, N);
construct_range(this->end(), this->begin()+N, NV);
this->setEnd(this->begin()+N);
}
}
private:
/// grow - double the size of the allocated memory, guaranteeing space for at
/// least one more element or MinSize if specified.
void grow(const ASTContext &C, size_type MinSize = 1);
void construct_range(T *S, T *E, const T &Elt) {
for (; S != E; ++S)
new (S) T(Elt);
}
void destroy_range(T *S, T *E) {
while (S != E) {
--E;
E->~T();
}
}
protected:
const_iterator capacity_ptr() const {
return (iterator) Capacity.getPointer();
}
iterator capacity_ptr() { return (iterator)Capacity.getPointer(); }
};
// Define this out-of-line to dissuade the C++ compiler from inlining it.
template <typename T>
void ASTVector<T>::grow(const ASTContext &C, size_t MinSize) {
size_t CurCapacity = this->capacity();
size_t CurSize = size();
size_t NewCapacity = 2*CurCapacity;
if (NewCapacity < MinSize)
NewCapacity = MinSize;
// Allocate the memory from the ASTContext.
T *NewElts = new (C, llvm::alignOf<T>()) T[NewCapacity];
// Copy the elements over.
if (Begin != End) {
if (std::is_class<T>::value) {
std::uninitialized_copy(Begin, End, NewElts);
// Destroy the original elements.
destroy_range(Begin, End);
} else {
// Use memcpy for PODs (std::uninitialized_copy optimizes to memmove).
memcpy(NewElts, Begin, CurSize * sizeof(T));
}
}
// ASTContext never frees any memory.
Begin = NewElts;
End = NewElts+CurSize;
Capacity.setPointer(Begin+NewCapacity);
}
} // end: clang namespace
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/StmtGraphTraits.h | //===--- StmtGraphTraits.h - Graph Traits for the class Stmt ----*- 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 a template specialization of llvm::GraphTraits to
// treat ASTs (Stmt*) as graphs
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_STMTGRAPHTRAITS_H
#define LLVM_CLANG_AST_STMTGRAPHTRAITS_H
#include "clang/AST/Stmt.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/GraphTraits.h"
namespace llvm {
//template <typename T> struct GraphTraits;
template <> struct GraphTraits<clang::Stmt*> {
typedef clang::Stmt NodeType;
typedef clang::Stmt::child_iterator ChildIteratorType;
typedef llvm::df_iterator<clang::Stmt*> nodes_iterator;
static NodeType* getEntryNode(clang::Stmt* S) { return S; }
static inline ChildIteratorType child_begin(NodeType* N) {
if (N) return N->child_begin();
else return ChildIteratorType();
}
static inline ChildIteratorType child_end(NodeType* N) {
if (N) return N->child_end();
else return ChildIteratorType();
}
static nodes_iterator nodes_begin(clang::Stmt* S) {
return df_begin(S);
}
static nodes_iterator nodes_end(clang::Stmt* S) {
return df_end(S);
}
};
template <> struct GraphTraits<const clang::Stmt*> {
typedef const clang::Stmt NodeType;
typedef clang::Stmt::const_child_iterator ChildIteratorType;
typedef llvm::df_iterator<const clang::Stmt*> nodes_iterator;
static NodeType* getEntryNode(const clang::Stmt* S) { return S; }
static inline ChildIteratorType child_begin(NodeType* N) {
if (N) return N->child_begin();
else return ChildIteratorType();
}
static inline ChildIteratorType child_end(NodeType* N) {
if (N) return N->child_end();
else return ChildIteratorType();
}
static nodes_iterator nodes_begin(const clang::Stmt* S) {
return df_begin(S);
}
static nodes_iterator nodes_end(const clang::Stmt* S) {
return df_end(S);
}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/ParentMap.h | //===--- ParentMap.h - Mappings from Stmts to their Parents -----*- 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 ParentMap class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_PARENTMAP_H
#define LLVM_CLANG_AST_PARENTMAP_H
namespace clang {
class Stmt;
class Expr;
class ParentMap {
void* Impl;
public:
ParentMap(Stmt* ASTRoot);
~ParentMap();
/// \brief Adds and/or updates the parent/child-relations of the complete
/// stmt tree of S. All children of S including indirect descendants are
/// visited and updated or inserted but not the parents of S.
void addStmt(Stmt* S);
/// Manually sets the parent of \p S to \p Parent.
///
/// If \p S is already in the map, this method will update the mapping.
void setParent(const Stmt *S, const Stmt *Parent);
Stmt *getParent(Stmt*) const;
Stmt *getParentIgnoreParens(Stmt *) const;
Stmt *getParentIgnoreParenCasts(Stmt *) const;
Stmt *getParentIgnoreParenImpCasts(Stmt *) const;
Stmt *getOuterParenParent(Stmt *) const;
const Stmt *getParent(const Stmt* S) const {
return getParent(const_cast<Stmt*>(S));
}
const Stmt *getParentIgnoreParens(const Stmt *S) const {
return getParentIgnoreParens(const_cast<Stmt*>(S));
}
const Stmt *getParentIgnoreParenCasts(const Stmt *S) const {
return getParentIgnoreParenCasts(const_cast<Stmt*>(S));
}
bool hasParent(Stmt* S) const {
return getParent(S) != nullptr;
}
bool isConsumedExpr(Expr *E) const;
bool isConsumedExpr(const Expr *E) const {
return isConsumedExpr(const_cast<Expr*>(E));
}
};
} // end clang namespace
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/ASTFwd.h | //===--- ASTFwd.h ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===--------------------------------------------------------------===//
///
/// \file
/// \brief Forward declaration of all AST node types.
///
//===-------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_ASTFWD_H
#define LLVM_CLANG_AST_ASTFWD_H
namespace clang {
class Decl;
#define DECL(DERIVED, BASE) class DERIVED##Decl;
#include "clang/AST/DeclNodes.inc"
class Stmt;
#define STMT(DERIVED, BASE) class DERIVED;
#include "clang/AST/StmtNodes.inc"
class Type;
#define TYPE(DERIVED, BASE) class DERIVED##Type;
#include "clang/AST/TypeNodes.def"
class CXXCtorInitializer;
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/DependentDiagnostic.h | //===-- DependentDiagnostic.h - Dependently-generated diagnostics -*- 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 interfaces for diagnostics which may or may
// fire based on how a template is instantiated.
//
// At the moment, the only consumer of this interface is access
// control.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_DEPENDENTDIAGNOSTIC_H
#define LLVM_CLANG_AST_DEPENDENTDIAGNOSTIC_H
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclContextInternals.h"
#include "clang/AST/Type.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/SourceLocation.h"
namespace clang {
class ASTContext;
class CXXRecordDecl;
class NamedDecl;
/// A dependently-generated diagnostic.
class DependentDiagnostic {
public:
enum AccessNonce { Access = 0 };
static DependentDiagnostic *Create(ASTContext &Context,
DeclContext *Parent,
AccessNonce _,
SourceLocation Loc,
bool IsMemberAccess,
AccessSpecifier AS,
NamedDecl *TargetDecl,
CXXRecordDecl *NamingClass,
QualType BaseObjectType,
const PartialDiagnostic &PDiag) {
DependentDiagnostic *DD = Create(Context, Parent, PDiag);
DD->AccessData.Loc = Loc.getRawEncoding();
DD->AccessData.IsMember = IsMemberAccess;
DD->AccessData.Access = AS;
DD->AccessData.TargetDecl = TargetDecl;
DD->AccessData.NamingClass = NamingClass;
DD->AccessData.BaseObjectType = BaseObjectType.getAsOpaquePtr();
return DD;
}
unsigned getKind() const {
return Access;
}
bool isAccessToMember() const {
assert(getKind() == Access);
return AccessData.IsMember;
}
AccessSpecifier getAccess() const {
assert(getKind() == Access);
return AccessSpecifier(AccessData.Access);
}
SourceLocation getAccessLoc() const {
assert(getKind() == Access);
return SourceLocation::getFromRawEncoding(AccessData.Loc);
}
NamedDecl *getAccessTarget() const {
assert(getKind() == Access);
return AccessData.TargetDecl;
}
NamedDecl *getAccessNamingClass() const {
assert(getKind() == Access);
return AccessData.NamingClass;
}
QualType getAccessBaseObjectType() const {
assert(getKind() == Access);
return QualType::getFromOpaquePtr(AccessData.BaseObjectType);
}
const PartialDiagnostic &getDiagnostic() const {
return Diag;
}
private:
DependentDiagnostic(const PartialDiagnostic &PDiag,
PartialDiagnostic::Storage *Storage)
: Diag(PDiag, Storage) {}
static DependentDiagnostic *Create(ASTContext &Context,
DeclContext *Parent,
const PartialDiagnostic &PDiag);
friend class DependentStoredDeclsMap;
friend class DeclContext::ddiag_iterator;
DependentDiagnostic *NextDiagnostic;
PartialDiagnostic Diag;
struct {
unsigned Loc;
unsigned Access : 2;
unsigned IsMember : 1;
NamedDecl *TargetDecl;
CXXRecordDecl *NamingClass;
void *BaseObjectType;
} AccessData;
};
///
/// An iterator over the dependent diagnostics in a dependent context.
class DeclContext::ddiag_iterator {
public:
ddiag_iterator() : Ptr(nullptr) {}
explicit ddiag_iterator(DependentDiagnostic *Ptr) : Ptr(Ptr) {}
typedef DependentDiagnostic *value_type;
typedef DependentDiagnostic *reference;
typedef DependentDiagnostic *pointer;
typedef int difference_type;
typedef std::forward_iterator_tag iterator_category;
reference operator*() const { return Ptr; }
ddiag_iterator &operator++() {
assert(Ptr && "attempt to increment past end of diag list");
Ptr = Ptr->NextDiagnostic;
return *this;
}
ddiag_iterator operator++(int) {
ddiag_iterator tmp = *this;
++*this;
return tmp;
}
bool operator==(ddiag_iterator Other) const {
return Ptr == Other.Ptr;
}
bool operator!=(ddiag_iterator Other) const {
return Ptr != Other.Ptr;
}
ddiag_iterator &operator+=(difference_type N) {
assert(N >= 0 && "cannot rewind a DeclContext::ddiag_iterator");
while (N--)
++*this;
return *this;
}
ddiag_iterator operator+(difference_type N) const {
ddiag_iterator tmp = *this;
tmp += N;
return tmp;
}
private:
DependentDiagnostic *Ptr;
};
inline DeclContext::ddiag_range DeclContext::ddiags() const {
assert(isDependentContext()
&& "cannot iterate dependent diagnostics of non-dependent context");
const DependentStoredDeclsMap *Map
= static_cast<DependentStoredDeclsMap*>(getPrimaryContext()->getLookupPtr());
if (!Map)
// Return an empty range using the always-end default constructor.
return ddiag_range(ddiag_iterator(), ddiag_iterator());
return ddiag_range(ddiag_iterator(Map->FirstDiagnostic), ddiag_iterator());
}
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/ASTLambda.h | //===--- ASTLambda.h - Lambda Helper Functions --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file provides some common utility functions for processing
/// Lambda related AST Constructs.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_ASTLAMBDA_H
#define LLVM_CLANG_AST_ASTLAMBDA_H
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
namespace clang {
inline StringRef getLambdaStaticInvokerName() {
return "__invoke";
}
// This function returns true if M is a specialization, a template,
// or a non-generic lambda call operator.
inline bool isLambdaCallOperator(const CXXMethodDecl *MD) {
const CXXRecordDecl *LambdaClass = MD->getParent();
if (!LambdaClass || !LambdaClass->isLambda()) return false;
return MD->getOverloadedOperator() == OO_Call;
}
inline bool isLambdaCallOperator(const DeclContext *DC) {
if (!DC || !isa<CXXMethodDecl>(DC)) return false;
return isLambdaCallOperator(cast<CXXMethodDecl>(DC));
}
inline bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD) {
if (!MD) return false;
const CXXRecordDecl *LambdaClass = MD->getParent();
if (LambdaClass && LambdaClass->isGenericLambda())
return isLambdaCallOperator(MD) &&
MD->isFunctionTemplateSpecialization();
return false;
}
inline bool isLambdaConversionOperator(CXXConversionDecl *C) {
return C ? C->getParent()->isLambda() : false;
}
inline bool isLambdaConversionOperator(Decl *D) {
if (!D) return false;
if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D))
return isLambdaConversionOperator(Conv);
if (FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(D))
if (CXXConversionDecl *Conv =
dyn_cast_or_null<CXXConversionDecl>(F->getTemplatedDecl()))
return isLambdaConversionOperator(Conv);
return false;
}
inline bool isGenericLambdaCallOperatorSpecialization(DeclContext *DC) {
return isGenericLambdaCallOperatorSpecialization(
dyn_cast<CXXMethodDecl>(DC));
}
// This returns the parent DeclContext ensuring that the correct
// parent DeclContext is returned for Lambdas
inline DeclContext *getLambdaAwareParentOfDeclContext(DeclContext *DC) {
if (isLambdaCallOperator(DC))
return DC->getParent()->getParent();
else
return DC->getParent();
}
} // clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/OperationKinds.h | //===- OperationKinds.h - Operation enums -----------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file enumerates the different kinds of operations that can be
// performed by various expressions.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_OPERATIONKINDS_H
#define LLVM_CLANG_AST_OPERATIONKINDS_H
#include <limits> // HLSL Change
namespace clang {
/// CastKind - The kind of operation required for a conversion.
enum CastKind {
/// CK_Dependent - A conversion which cannot yet be analyzed because
/// either the expression or target type is dependent. These are
/// created only for explicit casts; dependent ASTs aren't required
/// to even approximately type-check.
/// (T*) malloc(sizeof(T))
/// reinterpret_cast<intptr_t>(A<T>::alloc());
CK_Dependent,
/// CK_BitCast - A conversion which causes a bit pattern of one type
/// to be reinterpreted as a bit pattern of another type. Generally
/// the operands must have equivalent size and unrelated types.
///
/// The pointer conversion char* -> int* is a bitcast. A conversion
/// from any pointer type to a C pointer type is a bitcast unless
/// it's actually BaseToDerived or DerivedToBase. A conversion to a
/// block pointer or ObjC pointer type is a bitcast only if the
/// operand has the same type kind; otherwise, it's one of the
/// specialized casts below.
///
/// Vector coercions are bitcasts.
CK_BitCast,
/// CK_LValueBitCast - A conversion which reinterprets the address of
/// an l-value as an l-value of a different kind. Used for
/// reinterpret_casts of l-value expressions to reference types.
/// bool b; reinterpret_cast<char&>(b) = 'a';
CK_LValueBitCast,
/// CK_LValueToRValue - A conversion which causes the extraction of
/// an r-value from the operand gl-value. The result of an r-value
/// conversion is always unqualified.
CK_LValueToRValue,
/// CK_NoOp - A conversion which does not affect the type other than
/// (possibly) adding qualifiers.
/// int -> int
/// char** -> const char * const *
CK_NoOp,
/// CK_BaseToDerived - A conversion from a C++ class pointer/reference
/// to a derived class pointer/reference.
/// B *b = static_cast<B*>(a);
CK_BaseToDerived,
/// CK_DerivedToBase - A conversion from a C++ class pointer
/// to a base class pointer.
/// A *a = new B();
CK_DerivedToBase,
/// CK_UncheckedDerivedToBase - A conversion from a C++ class
/// pointer/reference to a base class that can assume that the
/// derived pointer is not null.
/// const A &a = B();
/// b->method_from_a();
CK_UncheckedDerivedToBase,
/// CK_Dynamic - A C++ dynamic_cast.
CK_Dynamic,
/// CK_ToUnion - The GCC cast-to-union extension.
/// int -> union { int x; float y; }
/// float -> union { int x; float y; }
CK_ToUnion,
/// CK_ArrayToPointerDecay - Array to pointer decay.
/// int[10] -> int*
/// char[5][6] -> char(*)[6]
CK_ArrayToPointerDecay,
/// CK_FunctionToPointerDecay - Function to pointer decay.
/// void(int) -> void(*)(int)
CK_FunctionToPointerDecay,
/// CK_NullToPointer - Null pointer constant to pointer, ObjC
/// pointer, or block pointer.
/// (void*) 0
/// void (^block)() = 0;
CK_NullToPointer,
/// CK_NullToMemberPointer - Null pointer constant to member pointer.
/// int A::*mptr = 0;
/// int (A::*fptr)(int) = nullptr;
CK_NullToMemberPointer,
/// CK_BaseToDerivedMemberPointer - Member pointer in base class to
/// member pointer in derived class.
/// int B::*mptr = &A::member;
CK_BaseToDerivedMemberPointer,
/// CK_DerivedToBaseMemberPointer - Member pointer in derived class to
/// member pointer in base class.
/// int A::*mptr = static_cast<int A::*>(&B::member);
CK_DerivedToBaseMemberPointer,
/// CK_MemberPointerToBoolean - Member pointer to boolean. A check
/// against the null member pointer.
CK_MemberPointerToBoolean,
/// CK_ReinterpretMemberPointer - Reinterpret a member pointer as a
/// different kind of member pointer. C++ forbids this from
/// crossing between function and object types, but otherwise does
/// not restrict it. However, the only operation that is permitted
/// on a "punned" member pointer is casting it back to the original
/// type, which is required to be a lossless operation (although
/// many ABIs do not guarantee this on all possible intermediate types).
CK_ReinterpretMemberPointer,
/// CK_UserDefinedConversion - Conversion using a user defined type
/// conversion function.
/// struct A { operator int(); }; int i = int(A());
CK_UserDefinedConversion,
/// CK_ConstructorConversion - Conversion by constructor.
/// struct A { A(int); }; A a = A(10);
CK_ConstructorConversion,
/// CK_IntegralToPointer - Integral to pointer. A special kind of
/// reinterpreting conversion. Applies to normal, ObjC, and block
/// pointers.
/// (char*) 0x1001aab0
/// reinterpret_cast<int*>(0)
CK_IntegralToPointer,
/// CK_PointerToIntegral - Pointer to integral. A special kind of
/// reinterpreting conversion. Applies to normal, ObjC, and block
/// pointers.
/// (intptr_t) "help!"
CK_PointerToIntegral,
/// CK_PointerToBoolean - Pointer to boolean conversion. A check
/// against null. Applies to normal, ObjC, and block pointers.
CK_PointerToBoolean,
/// CK_ToVoid - Cast to void, discarding the computed value.
/// (void) malloc(2048)
CK_ToVoid,
/// CK_VectorSplat - A conversion from an arithmetic type to a
/// vector of that element type. Fills all elements ("splats") with
/// the source value.
/// __attribute__((ext_vector_type(4))) int v = 5;
CK_VectorSplat,
/// CK_IntegralCast - A cast between integral types (other than to
/// boolean). Variously a bitcast, a truncation, a sign-extension,
/// or a zero-extension.
/// long l = 5;
/// (unsigned) i
CK_IntegralCast,
/// CK_IntegralToBoolean - Integral to boolean. A check against zero.
/// (bool) i
CK_IntegralToBoolean,
/// CK_IntegralToFloating - Integral to floating point.
/// float f = i;
CK_IntegralToFloating,
/// CK_FloatingToIntegral - Floating point to integral. Rounds
/// towards zero, discarding any fractional component.
/// (int) f
CK_FloatingToIntegral,
/// CK_FloatingToBoolean - Floating point to boolean.
/// (bool) f
CK_FloatingToBoolean,
/// CK_FloatingCast - Casting between floating types of different size.
/// (double) f
/// (float) ld
CK_FloatingCast,
/// CK_CPointerToObjCPointerCast - Casting a C pointer kind to an
/// Objective-C pointer.
CK_CPointerToObjCPointerCast,
/// CK_BlockPointerToObjCPointerCast - Casting a block pointer to an
/// ObjC pointer.
CK_BlockPointerToObjCPointerCast,
/// CK_AnyPointerToBlockPointerCast - Casting any non-block pointer
/// to a block pointer. Block-to-block casts are bitcasts.
CK_AnyPointerToBlockPointerCast,
/// \brief Converting between two Objective-C object types, which
/// can occur when performing reference binding to an Objective-C
/// object.
CK_ObjCObjectLValueCast,
/// \brief A conversion of a floating point real to a floating point
/// complex of the original type. Injects the value as the real
/// component with a zero imaginary component.
/// float -> _Complex float
CK_FloatingRealToComplex,
/// \brief Converts a floating point complex to floating point real
/// of the source's element type. Just discards the imaginary
/// component.
/// _Complex long double -> long double
CK_FloatingComplexToReal,
/// \brief Converts a floating point complex to bool by comparing
/// against 0+0i.
CK_FloatingComplexToBoolean,
/// \brief Converts between different floating point complex types.
/// _Complex float -> _Complex double
CK_FloatingComplexCast,
/// \brief Converts from a floating complex to an integral complex.
/// _Complex float -> _Complex int
CK_FloatingComplexToIntegralComplex,
/// \brief Converts from an integral real to an integral complex
/// whose element type matches the source. Injects the value as
/// the real component with a zero imaginary component.
/// long -> _Complex long
CK_IntegralRealToComplex,
/// \brief Converts an integral complex to an integral real of the
/// source's element type by discarding the imaginary component.
/// _Complex short -> short
CK_IntegralComplexToReal,
/// \brief Converts an integral complex to bool by comparing against
/// 0+0i.
CK_IntegralComplexToBoolean,
/// \brief Converts between different integral complex types.
/// _Complex char -> _Complex long long
/// _Complex unsigned int -> _Complex signed int
CK_IntegralComplexCast,
/// \brief Converts from an integral complex to a floating complex.
/// _Complex unsigned -> _Complex float
CK_IntegralComplexToFloatingComplex,
/// \brief [ARC] Produces a retainable object pointer so that it may
/// be consumed, e.g. by being passed to a consuming parameter.
/// Calls objc_retain.
CK_ARCProduceObject,
/// \brief [ARC] Consumes a retainable object pointer that has just
/// been produced, e.g. as the return value of a retaining call.
/// Enters a cleanup to call objc_release at some indefinite time.
CK_ARCConsumeObject,
/// \brief [ARC] Reclaim a retainable object pointer object that may
/// have been produced and autoreleased as part of a function return
/// sequence.
CK_ARCReclaimReturnedObject,
/// \brief [ARC] Causes a value of block type to be copied to the
/// heap, if it is not already there. A number of other operations
/// in ARC cause blocks to be copied; this is for cases where that
/// would not otherwise be guaranteed, such as when casting to a
/// non-block pointer type.
CK_ARCExtendBlockObject,
/// \brief Converts from _Atomic(T) to T.
CK_AtomicToNonAtomic,
/// \brief Converts from T to _Atomic(T).
CK_NonAtomicToAtomic,
/// \brief Causes a block literal to by copied to the heap and then
/// autoreleased.
///
/// This particular cast kind is used for the conversion from a C++11
/// lambda expression to a block pointer.
CK_CopyAndAutoreleaseBlockObject,
// Convert a builtin function to a function pointer; only allowed in the
// callee of a call expression.
CK_BuiltinFnToFnPtr,
// Convert a zero value for OpenCL event_t initialization.
CK_ZeroToOCLEvent,
// Convert a pointer to a different address space.
CK_AddressSpaceConversion
// HLSL Change Starts
,
CK_FlatConversion,
CK_HLSLVectorSplat,
CK_HLSLMatrixSplat,
CK_HLSLVectorToScalarCast,
CK_HLSLMatrixToScalarCast,
CK_HLSLVectorTruncationCast,
CK_HLSLMatrixTruncationCast,
CK_HLSLVectorToMatrixCast,
CK_HLSLMatrixToVectorCast,
CK_HLSLDerivedToBase,
// HLSL ComponentConversion (HLSLCC) Casts:
CK_HLSLCC_IntegralCast,
CK_HLSLCC_IntegralToBoolean,
CK_HLSLCC_IntegralToFloating,
CK_HLSLCC_FloatingToIntegral,
CK_HLSLCC_FloatingToBoolean,
CK_HLSLCC_FloatingCast,
// HLSL Change - Made CK_Invalid an enum case because otherwise it is UB to
// assign it to a value of CastKind.
CK_Invalid = std::numeric_limits<unsigned int>::max()
};
static_assert(
sizeof(CastKind) == sizeof(unsigned int),
"Cast Kind larger than expected. Must increase value of CK_Invalid.");
// HLSL Change Ends
enum BinaryOperatorKind {
// Operators listed in order of precedence.
// Note that additions to this should also update the StmtVisitor class.
BO_PtrMemD, BO_PtrMemI, // [C++ 5.5] Pointer-to-member operators.
BO_Mul, BO_Div, BO_Rem, // [C99 6.5.5] Multiplicative operators.
BO_Add, BO_Sub, // [C99 6.5.6] Additive operators.
BO_Shl, BO_Shr, // [C99 6.5.7] Bitwise shift operators.
BO_LT, BO_GT, BO_LE, BO_GE, // [C99 6.5.8] Relational operators.
BO_EQ, BO_NE, // [C99 6.5.9] Equality operators.
BO_And, // [C99 6.5.10] Bitwise AND operator.
BO_Xor, // [C99 6.5.11] Bitwise XOR operator.
BO_Or, // [C99 6.5.12] Bitwise OR operator.
BO_LAnd, // [C99 6.5.13] Logical AND operator.
BO_LOr, // [C99 6.5.14] Logical OR operator.
BO_Assign, BO_MulAssign, // [C99 6.5.16] Assignment operators.
BO_DivAssign, BO_RemAssign,
BO_AddAssign, BO_SubAssign,
BO_ShlAssign, BO_ShrAssign,
BO_AndAssign, BO_XorAssign,
BO_OrAssign,
BO_Comma // [C99 6.5.17] Comma operator.
};
enum UnaryOperatorKind {
// Note that additions to this should also update the StmtVisitor class.
UO_PostInc, UO_PostDec, // [C99 6.5.2.4] Postfix increment and decrement
UO_PreInc, UO_PreDec, // [C99 6.5.3.1] Prefix increment and decrement
UO_AddrOf, UO_Deref, // [C99 6.5.3.2] Address and indirection
UO_Plus, UO_Minus, // [C99 6.5.3.3] Unary arithmetic
UO_Not, UO_LNot, // [C99 6.5.3.3] Unary arithmetic
UO_Real, UO_Imag, // "__real expr"/"__imag expr" Extension.
UO_Extension // __extension__ marker.
};
/// \brief The kind of bridging performed by the Objective-C bridge cast.
enum ObjCBridgeCastKind {
/// \brief Bridging via __bridge, which does nothing but reinterpret
/// the bits.
OBC_Bridge,
/// \brief Bridging via __bridge_transfer, which transfers ownership of an
/// Objective-C pointer into ARC.
OBC_BridgeTransfer,
/// \brief Bridging via __bridge_retain, which makes an ARC object available
/// as a +1 C pointer.
OBC_BridgeRetained
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/Attr.h | //===--- Attr.h - Classes for representing attributes ----------*- 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 Attr interface and subclasses.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_ATTR_H
#define LLVM_CLANG_AST_ATTR_H
#include "clang/AST/AttrIterator.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "clang/Basic/AttrKinds.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/Sanitizers.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/VersionTuple.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
namespace clang {
class ASTContext;
class IdentifierInfo;
class ObjCInterfaceDecl;
class Expr;
class QualType;
class FunctionDecl;
class TypeSourceInfo;
/// Attr - This represents one attribute.
class Attr {
private:
SourceRange Range;
unsigned AttrKind : 16;
protected:
/// An index into the spelling list of an
/// attribute defined in Attr.td file.
unsigned SpellingListIndex : 4;
bool Inherited : 1;
bool IsPackExpansion : 1;
bool Implicit : 1;
bool IsLateParsed : 1;
bool DuplicatesAllowed : 1;
void* operator new(size_t bytes) throw() {
llvm_unreachable("Attrs cannot be allocated with regular 'new'.");
}
void operator delete(void* data) throw() {
llvm_unreachable("Attrs cannot be released with regular 'delete'.");
}
public:
// Forward so that the regular new and delete do not hide global ones.
void* operator new(size_t Bytes, ASTContext &C,
size_t Alignment = 8) throw() {
return ::operator new(Bytes, C, Alignment);
}
void operator delete(void *Ptr, ASTContext &C,
size_t Alignment) throw() {
return ::operator delete(Ptr, C, Alignment);
}
protected:
Attr(attr::Kind AK, SourceRange R, unsigned SpellingListIndex,
bool IsLateParsed, bool DuplicatesAllowed)
: Range(R), AttrKind(AK), SpellingListIndex(SpellingListIndex),
Inherited(false), IsPackExpansion(false), Implicit(false),
IsLateParsed(IsLateParsed), DuplicatesAllowed(DuplicatesAllowed) {}
public:
attr::Kind getKind() const {
return static_cast<attr::Kind>(AttrKind);
}
unsigned getSpellingListIndex() const { return SpellingListIndex; }
const char *getSpelling() const;
SourceLocation getLocation() const { return Range.getBegin(); }
SourceRange getRange() const { return Range; }
void setRange(SourceRange R) { Range = R; }
bool isInherited() const { return Inherited; }
/// \brief Returns true if the attribute has been implicitly created instead
/// of explicitly written by the user.
bool isImplicit() const { return Implicit; }
void setImplicit(bool I) { Implicit = I; }
void setPackExpansion(bool PE) { IsPackExpansion = PE; }
bool isPackExpansion() const { return IsPackExpansion; }
// Clone this attribute.
Attr *clone(ASTContext &C) const;
bool isLateParsed() const { return IsLateParsed; }
// Pretty print this attribute.
void printPretty(raw_ostream &OS, const PrintingPolicy &Policy) const;
/// \brief By default, attributes cannot be duplicated when being merged;
/// however, an attribute can override this. Returns true if the attribute
/// can be duplicated when merging.
bool duplicatesAllowed() const { return DuplicatesAllowed; }
};
class InheritableAttr : public Attr {
protected:
InheritableAttr(attr::Kind AK, SourceRange R, unsigned SpellingListIndex,
bool IsLateParsed, bool DuplicatesAllowed)
: Attr(AK, R, SpellingListIndex, IsLateParsed, DuplicatesAllowed) {}
public:
void setInherited(bool I) { Inherited = I; }
// Implement isa/cast/dyncast/etc.
static bool classof(const Attr *A) {
return A->getKind() <= attr::LAST_INHERITABLE;
}
};
class InheritableParamAttr : public InheritableAttr {
protected:
InheritableParamAttr(attr::Kind AK, SourceRange R, unsigned SpellingListIndex,
bool IsLateParsed, bool DuplicatesAllowed)
: InheritableAttr(AK, R, SpellingListIndex, IsLateParsed,
DuplicatesAllowed) {}
public:
// Implement isa/cast/dyncast/etc.
static bool classof(const Attr *A) {
// Relies on relative order of enum emission with respect to MS inheritance
// attrs.
return A->getKind() <= attr::LAST_INHERITABLE_PARAM;
}
};
#include "clang/AST/Attrs.inc"
inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
const Attr *At) {
DB.AddTaggedVal(reinterpret_cast<intptr_t>(At),
DiagnosticsEngine::ak_attr);
return DB;
}
inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
const Attr *At) {
PD.AddTaggedVal(reinterpret_cast<intptr_t>(At),
DiagnosticsEngine::ak_attr);
return PD;
}
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/ASTContext.h | //===--- ASTContext.h - Context to hold long-lived AST nodes ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Defines the clang::ASTContext interface.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
#define LLVM_CLANG_AST_ASTCONTEXT_H
#include "clang/AST/ASTTypeTraits.h"
#include "clang/AST/CanonicalType.h"
#include "clang/AST/CommentCommandTraits.h"
#include "clang/AST/Decl.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/RawCommentList.h"
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "clang/Basic/AddressSpaces.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Basic/SanitizerBlacklist.h"
#include "clang/Basic/VersionTuple.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Support/Allocator.h"
#include <memory>
#include <vector>
namespace llvm {
struct fltSemantics;
}
namespace clang {
class FileManager;
class AtomicExpr;
class ASTRecordLayout;
class BlockExpr;
class CharUnits;
class DiagnosticsEngine;
class Expr;
class ASTMutationListener;
class IdentifierTable;
class MaterializeTemporaryExpr;
class SelectorTable;
class TargetInfo;
class CXXABI;
class MangleNumberingContext;
// Decls
class MangleContext;
class ObjCIvarDecl;
class ObjCPropertyDecl;
class UnresolvedSetIterator;
class UsingDecl;
class UsingShadowDecl;
class VTableContextBase;
namespace Builtin { class Context; }
namespace comments {
class FullComment;
}
struct TypeInfo {
uint64_t Width;
unsigned Align;
bool AlignIsRequired : 1;
TypeInfo() : Width(0), Align(0), AlignIsRequired(false) {}
TypeInfo(uint64_t Width, unsigned Align, bool AlignIsRequired)
: Width(Width), Align(Align), AlignIsRequired(AlignIsRequired) {}
};
/// \brief Holds long-lived AST nodes (such as types and decls) that can be
/// referred to throughout the semantic analysis of a file.
class ASTContext : public RefCountedBase<ASTContext> {
ASTContext &this_() { return *this; }
mutable SmallVector<Type *, 0> Types;
mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
mutable llvm::FoldingSet<ComplexType> ComplexTypes;
mutable llvm::FoldingSet<PointerType> PointerTypes;
mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
mutable llvm::FoldingSet<ConstantArrayType> ConstantArrayTypes;
mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
mutable std::vector<VariableArrayType*> VariableArrayTypes;
mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
mutable llvm::FoldingSet<DependentSizedExtVectorType>
DependentSizedExtVectorTypes;
mutable llvm::FoldingSet<VectorType> VectorTypes;
mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
FunctionProtoTypes;
mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
mutable llvm::FoldingSet<SubstTemplateTypeParmType>
SubstTemplateTypeParmTypes;
mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
SubstTemplateTypeParmPackTypes;
mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
TemplateSpecializationTypes;
mutable llvm::FoldingSet<ParenType> ParenTypes;
mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
ASTContext&>
DependentTemplateSpecializationTypes;
llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
mutable llvm::FoldingSet<AutoType> AutoTypes;
mutable llvm::FoldingSet<AtomicType> AtomicTypes;
llvm::FoldingSet<AttributedType> AttributedTypes;
mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
SubstTemplateTemplateParms;
mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
ASTContext&>
SubstTemplateTemplateParmPacks;
/// \brief The set of nested name specifiers.
///
/// This set is managed by the NestedNameSpecifier class.
mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
mutable NestedNameSpecifier *GlobalNestedNameSpecifier;
friend class NestedNameSpecifier;
/// \brief A cache mapping from RecordDecls to ASTRecordLayouts.
///
/// This is lazily created. This is intentionally not serialized.
mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
ASTRecordLayouts;
mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
ObjCLayouts;
/// \brief A cache from types to size and alignment information.
typedef llvm::DenseMap<const Type *, struct TypeInfo> TypeInfoMap;
mutable TypeInfoMap MemoizedTypeInfo;
/// \brief A cache mapping from CXXRecordDecls to key functions.
llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
/// \brief Mapping from ObjCContainers to their ObjCImplementations.
llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
/// \brief Mapping from ObjCMethod to its duplicate declaration in the same
/// interface.
llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
/// \brief Mapping from __block VarDecls to their copy initialization expr.
llvm::DenseMap<const VarDecl*, Expr*> BlockVarCopyInits;
/// \brief Mapping from class scope functions specialization to their
/// template patterns.
llvm::DenseMap<const FunctionDecl*, FunctionDecl*>
ClassScopeSpecializationPattern;
/// \brief Mapping from materialized temporaries with static storage duration
/// that appear in constant initializers to their evaluated values.
llvm::DenseMap<const MaterializeTemporaryExpr*, APValue>
MaterializedTemporaryValues;
/// \brief Representation of a "canonical" template template parameter that
/// is used in canonical template names.
class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
TemplateTemplateParmDecl *Parm;
public:
CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
: Parm(Parm) { }
TemplateTemplateParmDecl *getParam() const { return Parm; }
void Profile(llvm::FoldingSetNodeID &ID) { Profile(ID, Parm); }
static void Profile(llvm::FoldingSetNodeID &ID,
TemplateTemplateParmDecl *Parm);
};
mutable llvm::FoldingSet<CanonicalTemplateTemplateParm>
CanonTemplateTemplateParms;
TemplateTemplateParmDecl *
getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
/// \brief The typedef for the __int128_t type.
mutable TypedefDecl *Int128Decl;
/// \brief The typedef for the __uint128_t type.
mutable TypedefDecl *UInt128Decl;
/// \brief The typedef for the __float128 stub type.
mutable TypeDecl *Float128StubDecl;
/// \brief The typedef for the target specific predefined
/// __builtin_va_list type.
mutable TypedefDecl *BuiltinVaListDecl;
/// \brief The typedef for the predefined \c id type.
mutable TypedefDecl *ObjCIdDecl;
/// \brief The typedef for the predefined \c SEL type.
mutable TypedefDecl *ObjCSelDecl;
/// \brief The typedef for the predefined \c Class type.
mutable TypedefDecl *ObjCClassDecl;
/// \brief The typedef for the predefined \c Protocol class in Objective-C.
mutable ObjCInterfaceDecl *ObjCProtocolClassDecl;
/// \brief The typedef for the predefined 'BOOL' type.
mutable TypedefDecl *BOOLDecl;
// Typedefs which may be provided defining the structure of Objective-C
// pseudo-builtins
QualType ObjCIdRedefinitionType;
QualType ObjCClassRedefinitionType;
QualType ObjCSelRedefinitionType;
/// The identifier 'NSObject'.
IdentifierInfo *NSObjectName = nullptr;
/// The identifier 'NSCopying'.
IdentifierInfo *NSCopyingName = nullptr;
QualType ObjCConstantStringType;
mutable RecordDecl *CFConstantStringTypeDecl;
mutable QualType ObjCSuperType;
QualType ObjCNSStringType;
/// \brief The typedef declaration for the Objective-C "instancetype" type.
TypedefDecl *ObjCInstanceTypeDecl;
/// \brief The type for the C FILE type.
TypeDecl *FILEDecl;
/// \brief The type for the C jmp_buf type.
TypeDecl *jmp_bufDecl;
/// \brief The type for the C sigjmp_buf type.
TypeDecl *sigjmp_bufDecl;
/// \brief The type for the C ucontext_t type.
TypeDecl *ucontext_tDecl;
/// \brief Type for the Block descriptor for Blocks CodeGen.
///
/// Since this is only used for generation of debug info, it is not
/// serialized.
mutable RecordDecl *BlockDescriptorType;
/// \brief Type for the Block descriptor for Blocks CodeGen.
///
/// Since this is only used for generation of debug info, it is not
/// serialized.
mutable RecordDecl *BlockDescriptorExtendedType;
/// \brief Declaration for the CUDA cudaConfigureCall function.
FunctionDecl *cudaConfigureCallDecl;
/// \brief Keeps track of all declaration attributes.
///
/// Since so few decls have attrs, we keep them in a hash map instead of
/// wasting space in the Decl class.
llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
/// \brief A mapping from non-redeclarable declarations in modules that were
/// merged with other declarations to the canonical declaration that they were
/// merged into.
llvm::DenseMap<Decl*, Decl*> MergedDecls;
/// \brief A mapping from a defining declaration to a list of modules (other
/// than the owning module of the declaration) that contain merged
/// definitions of that entity.
llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
public:
/// \brief A type synonym for the TemplateOrInstantiation mapping.
typedef llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>
TemplateOrSpecializationInfo;
private:
/// \brief A mapping to contain the template or declaration that
/// a variable declaration describes or was instantiated from,
/// respectively.
///
/// For non-templates, this value will be NULL. For variable
/// declarations that describe a variable template, this will be a
/// pointer to a VarTemplateDecl. For static data members
/// of class template specializations, this will be the
/// MemberSpecializationInfo referring to the member variable that was
/// instantiated or specialized. Thus, the mapping will keep track of
/// the static data member templates from which static data members of
/// class template specializations were instantiated.
///
/// Given the following example:
///
/// \code
/// template<typename T>
/// struct X {
/// static T value;
/// };
///
/// template<typename T>
/// T X<T>::value = T(17);
///
/// int *x = &X<int>::value;
/// \endcode
///
/// This mapping will contain an entry that maps from the VarDecl for
/// X<int>::value to the corresponding VarDecl for X<T>::value (within the
/// class template X) and will be marked TSK_ImplicitInstantiation.
llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
TemplateOrInstantiation;
/// \brief Keeps track of the declaration from which a UsingDecl was
/// created during instantiation.
///
/// The source declaration is always a UsingDecl, an UnresolvedUsingValueDecl,
/// or an UnresolvedUsingTypenameDecl.
///
/// For example:
/// \code
/// template<typename T>
/// struct A {
/// void f();
/// };
///
/// template<typename T>
/// struct B : A<T> {
/// using A<T>::f;
/// };
///
/// template struct B<int>;
/// \endcode
///
/// This mapping will contain an entry that maps from the UsingDecl in
/// B<int> to the UnresolvedUsingDecl in B<T>.
llvm::DenseMap<UsingDecl *, NamedDecl *> InstantiatedFromUsingDecl;
llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
InstantiatedFromUsingShadowDecl;
llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
/// \brief Mapping that stores the methods overridden by a given C++
/// member function.
///
/// Since most C++ member functions aren't virtual and therefore
/// don't override anything, we store the overridden functions in
/// this map on the side rather than within the CXXMethodDecl structure.
typedef llvm::TinyPtrVector<const CXXMethodDecl*> CXXMethodVector;
llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
/// \brief Mapping from each declaration context to its corresponding
/// mangling numbering context (used for constructs like lambdas which
/// need to be consistently numbered for the mangler).
llvm::DenseMap<const DeclContext *, MangleNumberingContext *>
MangleNumberingContexts;
/// \brief Side-table of mangling numbers for declarations which rarely
/// need them (like static local vars).
llvm::DenseMap<const NamedDecl *, unsigned> MangleNumbers;
llvm::DenseMap<const VarDecl *, unsigned> StaticLocalNumbers;
/// \brief Mapping that stores parameterIndex values for ParmVarDecls when
/// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
typedef llvm::DenseMap<const VarDecl *, unsigned> ParameterIndexTable;
ParameterIndexTable ParamIndices;
ImportDecl *FirstLocalImport;
ImportDecl *LastLocalImport;
TranslationUnitDecl *TUDecl;
mutable ExternCContextDecl *ExternCContext;
/// \brief The associated SourceManager object.a
SourceManager &SourceMgr;
/// \brief The language options used to create the AST associated with
/// this ASTContext object.
LangOptions &LangOpts;
/// \brief Blacklist object that is used by sanitizers to decide which
/// entities should not be instrumented.
std::unique_ptr<SanitizerBlacklist> SanitizerBL;
/// \brief The allocator used to create AST objects.
///
/// AST objects are never destructed; rather, all memory associated with the
/// AST objects will be released when the ASTContext itself is destroyed.
mutable llvm::BumpPtrAllocator BumpAlloc;
/// \brief Allocator for partial diagnostics.
PartialDiagnostic::StorageAllocator DiagAllocator;
/// \brief The current C++ ABI.
std::unique_ptr<CXXABI> ABI;
CXXABI *createCXXABI(const TargetInfo &T);
/// \brief The logical -> physical address space map.
const LangAS::Map *AddrSpaceMap;
/// \brief Address space map mangling must be used with language specific
/// address spaces (e.g. OpenCL/CUDA)
bool AddrSpaceMapMangling;
friend class ASTDeclReader;
friend class ASTReader;
friend class ASTWriter;
friend class CXXRecordDecl;
const TargetInfo *Target;
clang::PrintingPolicy PrintingPolicy;
public:
IdentifierTable &Idents;
SelectorTable &Selectors;
Builtin::Context &BuiltinInfo;
mutable DeclarationNameTable DeclarationNames;
IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
ASTMutationListener *Listener;
/// \brief Contains parents of a node.
typedef llvm::SmallVector<ast_type_traits::DynTypedNode, 2> ParentVector;
/// \brief Maps from a node to its parents.
typedef llvm::DenseMap<const void *,
llvm::PointerUnion<ast_type_traits::DynTypedNode *,
ParentVector *>> ParentMap;
/// \brief Returns the parents of the given node.
///
/// Note that this will lazily compute the parents of all nodes
/// and store them for later retrieval. Thus, the first call is O(n)
/// in the number of AST nodes.
///
/// Caveats and FIXMEs:
/// Calculating the parent map over all AST nodes will need to load the
/// full AST. This can be undesirable in the case where the full AST is
/// expensive to create (for example, when using precompiled header
/// preambles). Thus, there are good opportunities for optimization here.
/// One idea is to walk the given node downwards, looking for references
/// to declaration contexts - once a declaration context is found, compute
/// the parent map for the declaration context; if that can satisfy the
/// request, loading the whole AST can be avoided. Note that this is made
/// more complex by statements in templates having multiple parents - those
/// problems can be solved by building closure over the templated parts of
/// the AST, which also avoids touching large parts of the AST.
/// Additionally, we will want to add an interface to already give a hint
/// where to search for the parents, for example when looking at a statement
/// inside a certain function.
///
/// 'NodeT' can be one of Decl, Stmt, Type, TypeLoc,
/// NestedNameSpecifier or NestedNameSpecifierLoc.
template <typename NodeT>
ArrayRef<ast_type_traits::DynTypedNode> getParents(const NodeT &Node) {
return getParents(ast_type_traits::DynTypedNode::create(Node));
}
ArrayRef<ast_type_traits::DynTypedNode>
getParents(const ast_type_traits::DynTypedNode &Node);
const clang::PrintingPolicy &getPrintingPolicy() const {
return PrintingPolicy;
}
void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
PrintingPolicy = Policy;
}
SourceManager& getSourceManager() { return SourceMgr; }
const SourceManager& getSourceManager() const { return SourceMgr; }
llvm::BumpPtrAllocator &getAllocator() const {
return BumpAlloc;
}
void *Allocate(size_t Size, unsigned Align = 8) const {
return BumpAlloc.Allocate(Size, Align);
}
void Deallocate(void *Ptr) const { }
/// Return the total amount of physical memory allocated for representing
/// AST nodes and type information.
size_t getASTAllocatedMemory() const {
return BumpAlloc.getTotalMemory();
}
/// Return the total memory used for various side tables.
size_t getSideTableAllocatedMemory() const;
PartialDiagnostic::StorageAllocator &getDiagAllocator() {
return DiagAllocator;
}
const TargetInfo &getTargetInfo() const { return *Target; }
/// getIntTypeForBitwidth -
/// sets integer QualTy according to specified details:
/// bitwidth, signed/unsigned.
/// Returns empty type if there is no appropriate target types.
QualType getIntTypeForBitwidth(unsigned DestWidth,
unsigned Signed) const;
/// getRealTypeForBitwidth -
/// sets floating point QualTy according to specified bitwidth.
/// Returns empty type if there is no appropriate target types.
QualType getRealTypeForBitwidth(unsigned DestWidth) const;
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
const LangOptions& getLangOpts() const { return LangOpts; }
const SanitizerBlacklist &getSanitizerBlacklist() const {
return *SanitizerBL;
}
DiagnosticsEngine &getDiagnostics() const;
FullSourceLoc getFullLoc(SourceLocation Loc) const {
return FullSourceLoc(Loc,SourceMgr);
}
/// \brief All comments in this translation unit.
RawCommentList Comments;
/// \brief True if comments are already loaded from ExternalASTSource.
mutable bool CommentsLoaded;
class RawCommentAndCacheFlags {
public:
enum Kind {
/// We searched for a comment attached to the particular declaration, but
/// didn't find any.
///
/// getRaw() == 0.
NoCommentInDecl = 0,
/// We have found a comment attached to this particular declaration.
///
/// getRaw() != 0.
FromDecl,
/// This declaration does not have an attached comment, and we have
/// searched the redeclaration chain.
///
/// If getRaw() == 0, the whole redeclaration chain does not have any
/// comments.
///
/// If getRaw() != 0, it is a comment propagated from other
/// redeclaration.
FromRedecl
};
Kind getKind() const LLVM_READONLY {
return Data.getInt();
}
void setKind(Kind K) {
Data.setInt(K);
}
const RawComment *getRaw() const LLVM_READONLY {
return Data.getPointer();
}
void setRaw(const RawComment *RC) {
Data.setPointer(RC);
}
const Decl *getOriginalDecl() const LLVM_READONLY {
return OriginalDecl;
}
void setOriginalDecl(const Decl *Orig) {
OriginalDecl = Orig;
}
private:
llvm::PointerIntPair<const RawComment *, 2, Kind> Data;
const Decl *OriginalDecl;
};
/// \brief Mapping from declarations to comments attached to any
/// redeclaration.
///
/// Raw comments are owned by Comments list. This mapping is populated
/// lazily.
mutable llvm::DenseMap<const Decl *, RawCommentAndCacheFlags> RedeclComments;
/// \brief Mapping from declarations to parsed comments attached to any
/// redeclaration.
mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
/// \brief Return the documentation comment attached to a given declaration,
/// without looking into cache.
RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
public:
RawCommentList &getRawCommentList() {
return Comments;
}
void addComment(const RawComment &RC) {
assert(LangOpts.RetainCommentsFromSystemHeaders ||
!SourceMgr.isInSystemHeader(RC.getSourceRange().getBegin()));
Comments.addComment(RC, BumpAlloc);
}
/// \brief Return the documentation comment attached to a given declaration.
/// Returns NULL if no comment is attached.
///
/// \param OriginalDecl if not NULL, is set to declaration AST node that had
/// the comment, if the comment we found comes from a redeclaration.
const RawComment *
getRawCommentForAnyRedecl(const Decl *D,
const Decl **OriginalDecl = nullptr) const;
/// Return parsed documentation comment attached to a given declaration.
/// Returns NULL if no comment is attached.
///
/// \param PP the Preprocessor used with this TU. Could be NULL if
/// preprocessor is not available.
comments::FullComment *getCommentForDecl(const Decl *D,
const Preprocessor *PP) const;
/// Return parsed documentation comment attached to a given declaration.
/// Returns NULL if no comment is attached. Does not look at any
/// redeclarations of the declaration.
comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
comments::FullComment *cloneFullComment(comments::FullComment *FC,
const Decl *D) const;
private:
mutable comments::CommandTraits CommentCommandTraits;
/// \brief Iterator that visits import declarations.
class import_iterator {
ImportDecl *Import;
public:
typedef ImportDecl *value_type;
typedef ImportDecl *reference;
typedef ImportDecl *pointer;
typedef int difference_type;
typedef std::forward_iterator_tag iterator_category;
import_iterator() : Import() {}
explicit import_iterator(ImportDecl *Import) : Import(Import) {}
reference operator*() const { return Import; }
pointer operator->() const { return Import; }
import_iterator &operator++() {
Import = ASTContext::getNextLocalImport(Import);
return *this;
}
import_iterator operator++(int) {
import_iterator Other(*this);
++(*this);
return Other;
}
friend bool operator==(import_iterator X, import_iterator Y) {
return X.Import == Y.Import;
}
friend bool operator!=(import_iterator X, import_iterator Y) {
return X.Import != Y.Import;
}
};
public:
comments::CommandTraits &getCommentCommandTraits() const {
return CommentCommandTraits;
}
/// \brief Retrieve the attributes for the given declaration.
AttrVec& getDeclAttrs(const Decl *D);
/// \brief Erase the attributes corresponding to the given declaration.
void eraseDeclAttrs(const Decl *D);
/// \brief If this variable is an instantiated static data member of a
/// class template specialization, returns the templated static data member
/// from which it was instantiated.
// FIXME: Remove ?
MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
const VarDecl *Var);
TemplateOrSpecializationInfo
getTemplateOrSpecializationInfo(const VarDecl *Var);
FunctionDecl *getClassScopeSpecializationPattern(const FunctionDecl *FD);
void setClassScopeSpecializationPattern(FunctionDecl *FD,
FunctionDecl *Pattern);
/// \brief Note that the static data member \p Inst is an instantiation of
/// the static data member template \p Tmpl of a class template.
void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
TemplateSpecializationKind TSK,
SourceLocation PointOfInstantiation = SourceLocation());
void setTemplateOrSpecializationInfo(VarDecl *Inst,
TemplateOrSpecializationInfo TSI);
/// \brief If the given using decl \p Inst is an instantiation of a
/// (possibly unresolved) using decl from a template instantiation,
/// return it.
NamedDecl *getInstantiatedFromUsingDecl(UsingDecl *Inst);
/// \brief Remember that the using decl \p Inst is an instantiation
/// of the using decl \p Pattern of a class template.
void setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern);
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
UsingShadowDecl *Pattern);
UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
// Access to the set of methods overridden by the given C++ method.
typedef CXXMethodVector::const_iterator overridden_cxx_method_iterator;
overridden_cxx_method_iterator
overridden_methods_begin(const CXXMethodDecl *Method) const;
overridden_cxx_method_iterator
overridden_methods_end(const CXXMethodDecl *Method) const;
unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
/// \brief Note that the given C++ \p Method overrides the given \p
/// Overridden method.
void addOverriddenMethod(const CXXMethodDecl *Method,
const CXXMethodDecl *Overridden);
/// \brief Return C++ or ObjC overridden methods for the given \p Method.
///
/// An ObjC method is considered to override any method in the class's
/// base classes, its protocols, or its categories' protocols, that has
/// the same selector and is of the same kind (class or instance).
/// A method in an implementation is not considered as overriding the same
/// method in the interface or its categories.
void getOverriddenMethods(
const NamedDecl *Method,
SmallVectorImpl<const NamedDecl *> &Overridden) const;
/// \brief Notify the AST context that a new import declaration has been
/// parsed or implicitly created within this translation unit.
void addedLocalImportDecl(ImportDecl *Import);
static ImportDecl *getNextLocalImport(ImportDecl *Import) {
return Import->NextLocalImport;
}
typedef llvm::iterator_range<import_iterator> import_range;
import_range local_imports() const {
return import_range(import_iterator(FirstLocalImport), import_iterator());
}
Decl *getPrimaryMergedDecl(Decl *D) {
Decl *Result = MergedDecls.lookup(D);
return Result ? Result : D;
}
void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
MergedDecls[D] = Primary;
}
/// \brief Note that the definition \p ND has been merged into module \p M,
/// and should be visible whenever \p M is visible.
void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
bool NotifyListeners = true);
/// \brief Clean up the merged definition list. Call this if you might have
/// added duplicates into the list.
void deduplicateMergedDefinitonsFor(NamedDecl *ND);
/// \brief Get the additional modules in which the definition \p Def has
/// been merged.
ArrayRef<Module*> getModulesWithMergedDefinition(NamedDecl *Def) {
auto MergedIt = MergedDefModules.find(Def);
if (MergedIt == MergedDefModules.end())
return None;
return MergedIt->second;
}
TranslationUnitDecl *getTranslationUnitDecl() const { return TUDecl; }
ExternCContextDecl *getExternCContextDecl() const;
// Builtin Types.
CanQualType VoidTy;
CanQualType BoolTy;
CanQualType CharTy;
CanQualType WCharTy; // [C++ 3.9.1p5].
CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
CanQualType FloatTy, DoubleTy, LongDoubleTy;
CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
CanQualType VoidPtrTy, NullPtrTy;
CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
CanQualType BuiltinFnTy;
CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
CanQualType ObjCBuiltinBoolTy;
CanQualType OCLImage1dTy, OCLImage1dArrayTy, OCLImage1dBufferTy;
CanQualType OCLImage2dTy, OCLImage2dArrayTy;
CanQualType OCLImage3dTy;
CanQualType OCLSamplerTy, OCLEventTy;
// HLSL Changes begin
CanQualType Min12IntTy, Min10FloatTy;
CanQualType LitIntTy, LitFloatTy;
CanQualType HalfFloatTy, Min16FloatTy, Min16IntTy, Min16UIntTy;
CanQualType HLSLStringTy;
CanQualType Int8_4PackedTy, UInt8_4PackedTy;
// HLSL Changes end
// Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
mutable QualType AutoDeductTy; // Deduction against 'auto'.
mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
// Type used to help define __builtin_va_list for some targets.
// The type is built when constructing 'BuiltinVaListDecl'.
mutable QualType VaListTagTy;
ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
SelectorTable &sels, Builtin::Context &builtins);
~ASTContext();
/// \brief Attach an external AST source to the AST context.
///
/// The external AST source provides the ability to load parts of
/// the abstract syntax tree as needed from some external storage,
/// e.g., a precompiled header.
void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
/// \brief Retrieve a pointer to the external AST source associated
/// with this AST context, if any.
ExternalASTSource *getExternalSource() const {
return ExternalSource.get();
}
/// \brief Attach an AST mutation listener to the AST context.
///
/// The AST mutation listener provides the ability to track modifications to
/// the abstract syntax tree entities committed after they were initially
/// created.
void setASTMutationListener(ASTMutationListener *Listener) {
this->Listener = Listener;
}
/// \brief Retrieve a pointer to the AST mutation listener associated
/// with this AST context, if any.
ASTMutationListener *getASTMutationListener() const { return Listener; }
void PrintStats() const;
const SmallVectorImpl<Type *>& getTypes() const { return Types; }
/// \brief Create a new implicit TU-level CXXRecordDecl or RecordDecl
/// declaration.
RecordDecl *buildImplicitRecord(StringRef Name,
RecordDecl::TagKind TK = TTK_Struct) const;
/// \brief Create a new implicit TU-level typedef declaration.
TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
/// \brief Retrieve the declaration for the 128-bit signed integer type.
TypedefDecl *getInt128Decl() const;
/// \brief Retrieve the declaration for the 128-bit unsigned integer type.
TypedefDecl *getUInt128Decl() const;
/// \brief Retrieve the declaration for a 128-bit float stub type.
TypeDecl *getFloat128StubType() const;
// HLSL Change Starts
/// \brief Retrieve the declaration for HLSL string type.
TypedefDecl *getHLSLStringTypedef() const;
// HSLS CHange Ends
//===--------------------------------------------------------------------===//
// Type Constructors
//===--------------------------------------------------------------------===//
private:
/// \brief Return a type with extended qualifiers.
QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
public:
/// \brief Return the uniqued reference to the type for an address space
/// qualified type with the specified type and address space.
///
/// The resulting type has a union of the qualifiers from T and the address
/// space. If T already has an address space specifier, it is silently
/// replaced.
QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const;
/// \brief Return the uniqued reference to the type for an Objective-C
/// gc-qualified type.
///
/// The retulting type has a union of the qualifiers from T and the gc
/// attribute.
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
/// \brief Return the uniqued reference to the type for a \c restrict
/// qualified type.
///
/// The resulting type has a union of the qualifiers from \p T and
/// \c restrict.
QualType getRestrictType(QualType T) const {
return T.withFastQualifiers(Qualifiers::Restrict);
}
/// \brief Return the uniqued reference to the type for a \c volatile
/// qualified type.
///
/// The resulting type has a union of the qualifiers from \p T and
/// \c volatile.
QualType getVolatileType(QualType T) const {
return T.withFastQualifiers(Qualifiers::Volatile);
}
/// \brief Return the uniqued reference to the type for a \c const
/// qualified type.
///
/// The resulting type has a union of the qualifiers from \p T and \c const.
///
/// It can be reasonably expected that this will always be equivalent to
/// calling T.withConst().
QualType getConstType(QualType T) const { return T.withConst(); }
/// \brief Change the ExtInfo on a function type.
const FunctionType *adjustFunctionType(const FunctionType *Fn,
FunctionType::ExtInfo EInfo);
/// \brief Change the result type of a function type once it is deduced.
void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
/// \brief Change the exception specification on a function once it is
/// delay-parsed, instantiated, or computed.
void adjustExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI,
bool AsWritten = false);
/// \brief Return the uniqued reference to the type for a complex
/// number with the specified element type.
QualType getComplexType(QualType T) const;
CanQualType getComplexType(CanQualType T) const {
return CanQualType::CreateUnsafe(getComplexType((QualType) T));
}
/// \brief Return the uniqued reference to the type for a pointer to
/// the specified type.
QualType getPointerType(QualType T) const;
CanQualType getPointerType(CanQualType T) const {
return CanQualType::CreateUnsafe(getPointerType((QualType) T));
}
/// \brief Return the uniqued reference to a type adjusted from the original
/// type to a new type.
QualType getAdjustedType(QualType Orig, QualType New) const;
CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
return CanQualType::CreateUnsafe(
getAdjustedType((QualType)Orig, (QualType)New));
}
/// \brief Return the uniqued reference to the decayed version of the given
/// type. Can only be called on array and function types which decay to
/// pointer types.
QualType getDecayedType(QualType T) const;
CanQualType getDecayedType(CanQualType T) const {
return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
}
/// \brief Return the uniqued reference to the atomic type for the specified
/// type.
QualType getAtomicType(QualType T) const;
/// \brief Return the uniqued reference to the type for a block of the
/// specified type.
QualType getBlockPointerType(QualType T) const;
/// Gets the struct used to keep track of the descriptor for pointer to
/// blocks.
QualType getBlockDescriptorType() const;
/// Gets the struct used to keep track of the extended descriptor for
/// pointer to blocks.
QualType getBlockDescriptorExtendedType() const;
void setcudaConfigureCallDecl(FunctionDecl *FD) {
cudaConfigureCallDecl = FD;
}
FunctionDecl *getcudaConfigureCallDecl() {
return cudaConfigureCallDecl;
}
/// Returns true iff we need copy/dispose helpers for the given type.
bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
/// Returns true, if given type has a known lifetime. HasByrefExtendedLayout is set
/// to false in this case. If HasByrefExtendedLayout returns true, byref variable
/// has extended lifetime.
bool getByrefLifetime(QualType Ty,
Qualifiers::ObjCLifetime &Lifetime,
bool &HasByrefExtendedLayout) const;
/// \brief Return the uniqued reference to the type for an lvalue reference
/// to the specified type.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
const;
/// \brief Return the uniqued reference to the type for an rvalue reference
/// to the specified type.
QualType getRValueReferenceType(QualType T) const;
/// \brief Return the uniqued reference to the type for a member pointer to
/// the specified type in the specified class.
///
/// The class \p Cls is a \c Type because it could be a dependent name.
QualType getMemberPointerType(QualType T, const Type *Cls) const;
/// \brief Return a non-unique reference to the type for a variable array of
/// the specified element type.
QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
ArrayType::ArraySizeModifier ASM,
unsigned IndexTypeQuals,
SourceRange Brackets) const;
/// \brief Return a non-unique reference to the type for a dependently-sized
/// array of the specified element type.
///
/// FIXME: We will need these to be uniqued, or at least comparable, at some
/// point.
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
ArrayType::ArraySizeModifier ASM,
unsigned IndexTypeQuals,
SourceRange Brackets) const;
/// \brief Return a unique reference to the type for an incomplete array of
/// the specified element type.
QualType getIncompleteArrayType(QualType EltTy,
ArrayType::ArraySizeModifier ASM,
unsigned IndexTypeQuals) const;
/// \brief Return the unique reference to the type for a constant array of
/// the specified element type.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
ArrayType::ArraySizeModifier ASM,
unsigned IndexTypeQuals) const;
/// \brief Returns a vla type where known sizes are replaced with [*].
QualType getVariableArrayDecayedType(QualType Ty) const;
/// \brief Return the unique reference to a vector type of the specified
/// element type and size.
///
/// \pre \p VectorType must be a built-in type.
QualType getVectorType(QualType VectorType, unsigned NumElts,
VectorType::VectorKind VecKind) const;
/// \brief Return the unique reference to an extended vector type
/// of the specified element type and size.
///
/// \pre \p VectorType must be a built-in type.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
/// \pre Return a non-unique reference to the type for a dependently-sized
/// vector of the specified element type.
///
/// FIXME: We will need these to be uniqued, or at least comparable, at some
/// point.
QualType getDependentSizedExtVectorType(QualType VectorType,
Expr *SizeExpr,
SourceLocation AttrLoc) const;
/// \brief Return a K&R style C function type like 'int()'.
QualType getFunctionNoProtoType(QualType ResultTy,
const FunctionType::ExtInfo &Info) const;
QualType getFunctionNoProtoType(QualType ResultTy) const {
return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
}
/// \brief Return a normal function type with a typed argument list.
QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
const FunctionProtoType::ExtProtoInfo &EPI,
ArrayRef<hlsl::ParameterModifier> ParamMods) const; // HLSL Change
/// \brief Check whether the function declaration can be used as a patch constant function.
bool IsPatchConstantFunctionDecl(const FunctionDecl *FD) const; // HLSL Change
/// \brief Return the unique reference to the type for the specified type
/// declaration.
QualType getTypeDeclType(const TypeDecl *Decl,
const TypeDecl *PrevDecl = nullptr) const {
assert(Decl && "Passed null for Decl param");
if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
if (PrevDecl) {
assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
Decl->TypeForDecl = PrevDecl->TypeForDecl;
return QualType(PrevDecl->TypeForDecl, 0);
}
return getTypeDeclTypeSlow(Decl);
}
/// \brief Return the unique reference to the type for the specified
/// typedef-name decl.
QualType getTypedefType(const TypedefNameDecl *Decl,
QualType Canon = QualType()) const;
QualType getRecordType(const RecordDecl *Decl) const;
QualType getEnumType(const EnumDecl *Decl) const;
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
QualType getAttributedType(AttributedType::Kind attrKind,
QualType modifiedType,
QualType equivalentType);
QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
QualType Replacement) const;
QualType getSubstTemplateTypeParmPackType(
const TemplateTypeParmType *Replaced,
const TemplateArgument &ArgPack);
QualType
getTemplateTypeParmType(unsigned Depth, unsigned Index,
bool ParameterPack,
TemplateTypeParmDecl *ParmDecl = nullptr) const;
QualType getTemplateSpecializationType(TemplateName T,
const TemplateArgument *Args,
unsigned NumArgs,
QualType Canon = QualType()) const;
QualType getCanonicalTemplateSpecializationType(TemplateName T,
const TemplateArgument *Args,
unsigned NumArgs) const;
QualType getTemplateSpecializationType(TemplateName T,
const TemplateArgumentListInfo &Args,
QualType Canon = QualType()) const;
TypeSourceInfo *
getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
const TemplateArgumentListInfo &Args,
QualType Canon = QualType()) const;
QualType getParenType(QualType NamedType) const;
QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
NestedNameSpecifier *NNS,
QualType NamedType) const;
QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
NestedNameSpecifier *NNS,
const IdentifierInfo *Name,
QualType Canon = QualType()) const;
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
NestedNameSpecifier *NNS,
const IdentifierInfo *Name,
const TemplateArgumentListInfo &Args) const;
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
NestedNameSpecifier *NNS,
const IdentifierInfo *Name,
unsigned NumArgs,
const TemplateArgument *Args) const;
QualType getPackExpansionType(QualType Pattern,
Optional<unsigned> NumExpansions);
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
ObjCInterfaceDecl *PrevDecl = nullptr) const;
/// Legacy interface: cannot provide type arguments or __kindof.
QualType getObjCObjectType(QualType Base,
ObjCProtocolDecl * const *Protocols,
unsigned NumProtocols) const;
QualType getObjCObjectType(QualType Base,
ArrayRef<QualType> typeArgs,
ArrayRef<ObjCProtocolDecl *> protocols,
bool isKindOf) const;
bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
/// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
/// QT's qualified-id protocol list adopt all protocols in IDecl's list
/// of protocols.
bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
ObjCInterfaceDecl *IDecl);
/// \brief Return a ObjCObjectPointerType type for the given ObjCObjectType.
QualType getObjCObjectPointerType(QualType OIT) const;
/// \brief GCC extension.
QualType getTypeOfExprType(Expr *e) const;
QualType getTypeOfType(QualType t) const;
/// \brief C++11 decltype.
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
/// \brief Unary type transforms
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
UnaryTransformType::UTTKind UKind) const;
/// \brief C++11 deduced auto type.
QualType getAutoType(QualType DeducedType, bool IsDecltypeAuto,
bool IsDependent) const;
/// \brief C++11 deduction pattern for 'auto' type.
QualType getAutoDeductType() const;
/// \brief C++11 deduction pattern for 'auto &&' type.
QualType getAutoRRefDeductType() const;
/// \brief Return the unique reference to the type for the specified TagDecl
/// (struct/union/class/enum) decl.
QualType getTagDeclType(const TagDecl *Decl) const;
/// \brief Return the unique type for "size_t" (C99 7.17), defined in
/// <stddef.h>.
///
/// The sizeof operator requires this (C99 6.5.3.4p4).
CanQualType getSizeType() const;
/// \brief Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
/// <stdint.h>.
CanQualType getIntMaxType() const;
/// \brief Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
/// <stdint.h>.
CanQualType getUIntMaxType() const;
/// \brief Return the unique wchar_t type available in C++ (and available as
/// __wchar_t as a Microsoft extension).
QualType getWCharType() const { return WCharTy; }
/// \brief Return the type of wide characters. In C++, this returns the
/// unique wchar_t type. In C99, this returns a type compatible with the type
/// defined in <stddef.h> as defined by the target.
QualType getWideCharType() const { return WideCharTy; }
/// \brief Return the type of "signed wchar_t".
///
/// Used when in C++, as a GCC extension.
QualType getSignedWCharType() const;
/// \brief Return the type of "unsigned wchar_t".
///
/// Used when in C++, as a GCC extension.
QualType getUnsignedWCharType() const;
/// \brief In C99, this returns a type compatible with the type
/// defined in <stddef.h> as defined by the target.
QualType getWIntType() const { return WIntTy; }
/// \brief Return a type compatible with "intptr_t" (C99 7.18.1.4),
/// as defined by the target.
QualType getIntPtrType() const;
/// \brief Return a type compatible with "uintptr_t" (C99 7.18.1.4),
/// as defined by the target.
QualType getUIntPtrType() const;
/// \brief Return the unique type for "ptrdiff_t" (C99 7.17) defined in
/// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
QualType getPointerDiffType() const;
/// \brief Return the unique type for "pid_t" defined in
/// <sys/types.h>. We need this to compute the correct type for vfork().
QualType getProcessIDType() const;
/// \brief Return the C structure type used to represent constant CFStrings.
QualType getCFConstantStringType() const;
/// \brief Returns the C struct type for objc_super
QualType getObjCSuperType() const;
void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
/// Get the structure type used to representation CFStrings, or NULL
/// if it hasn't yet been built.
QualType getRawCFConstantStringType() const {
if (CFConstantStringTypeDecl)
return getTagDeclType(CFConstantStringTypeDecl);
return QualType();
}
void setCFConstantStringType(QualType T);
// This setter/getter represents the ObjC type for an NSConstantString.
void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
QualType getObjCConstantStringInterface() const {
return ObjCConstantStringType;
}
QualType getObjCNSStringType() const {
return ObjCNSStringType;
}
void setObjCNSStringType(QualType T) {
ObjCNSStringType = T;
}
/// \brief Retrieve the type that \c id has been defined to, which may be
/// different from the built-in \c id if \c id has been typedef'd.
QualType getObjCIdRedefinitionType() const {
if (ObjCIdRedefinitionType.isNull())
return getObjCIdType();
return ObjCIdRedefinitionType;
}
/// \brief Set the user-written type that redefines \c id.
void setObjCIdRedefinitionType(QualType RedefType) {
ObjCIdRedefinitionType = RedefType;
}
/// \brief Retrieve the type that \c Class has been defined to, which may be
/// different from the built-in \c Class if \c Class has been typedef'd.
QualType getObjCClassRedefinitionType() const {
if (ObjCClassRedefinitionType.isNull())
return getObjCClassType();
return ObjCClassRedefinitionType;
}
/// \brief Set the user-written type that redefines 'SEL'.
void setObjCClassRedefinitionType(QualType RedefType) {
ObjCClassRedefinitionType = RedefType;
}
/// \brief Retrieve the type that 'SEL' has been defined to, which may be
/// different from the built-in 'SEL' if 'SEL' has been typedef'd.
QualType getObjCSelRedefinitionType() const {
if (ObjCSelRedefinitionType.isNull())
return getObjCSelType();
return ObjCSelRedefinitionType;
}
/// \brief Set the user-written type that redefines 'SEL'.
void setObjCSelRedefinitionType(QualType RedefType) {
ObjCSelRedefinitionType = RedefType;
}
/// Retrieve the identifier 'NSObject'.
IdentifierInfo *getNSObjectName() {
if (!NSObjectName) {
NSObjectName = &Idents.get("NSObject");
}
return NSObjectName;
}
/// Retrieve the identifier 'NSCopying'.
IdentifierInfo *getNSCopyingName() {
if (!NSCopyingName) {
NSCopyingName = &Idents.get("NSCopying");
}
return NSCopyingName;
}
/// \brief Retrieve the Objective-C "instancetype" type, if already known;
/// otherwise, returns a NULL type;
QualType getObjCInstanceType() {
return getTypeDeclType(getObjCInstanceTypeDecl());
}
/// \brief Retrieve the typedef declaration corresponding to the Objective-C
/// "instancetype" type.
TypedefDecl *getObjCInstanceTypeDecl();
/// \brief Set the type for the C FILE type.
void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
/// \brief Retrieve the C FILE type.
QualType getFILEType() const {
if (FILEDecl)
return getTypeDeclType(FILEDecl);
return QualType();
}
/// \brief Set the type for the C jmp_buf type.
void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
this->jmp_bufDecl = jmp_bufDecl;
}
/// \brief Retrieve the C jmp_buf type.
QualType getjmp_bufType() const {
if (jmp_bufDecl)
return getTypeDeclType(jmp_bufDecl);
return QualType();
}
/// \brief Set the type for the C sigjmp_buf type.
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
this->sigjmp_bufDecl = sigjmp_bufDecl;
}
/// \brief Retrieve the C sigjmp_buf type.
QualType getsigjmp_bufType() const {
if (sigjmp_bufDecl)
return getTypeDeclType(sigjmp_bufDecl);
return QualType();
}
/// \brief Set the type for the C ucontext_t type.
void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
this->ucontext_tDecl = ucontext_tDecl;
}
/// \brief Retrieve the C ucontext_t type.
QualType getucontext_tType() const {
if (ucontext_tDecl)
return getTypeDeclType(ucontext_tDecl);
return QualType();
}
/// \brief The result type of logical operations, '<', '>', '!=', etc.
QualType getLogicalOperationType() const {
#pragma warning(push)
#pragma warning(suppress: 6319) // HLSL Change - suppress constant conditional warning
return getLangOpts().CPlusPlus ? BoolTy : IntTy;
#pragma warning(pop)
}
/// \brief Emit the Objective-CC type encoding for the given type \p T into
/// \p S.
///
/// If \p Field is specified then record field names are also encoded.
void getObjCEncodingForType(QualType T, std::string &S,
const FieldDecl *Field=nullptr,
QualType *NotEncodedT=nullptr) const;
/// \brief Emit the Objective-C property type encoding for the given
/// type \p T into \p S.
void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
void getLegacyIntegralTypeEncoding(QualType &t) const;
/// \brief Put the string version of the type qualifiers \p QT into \p S.
void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
std::string &S) const;
/// \brief Emit the encoded type for the function \p Decl into \p S.
///
/// This is in the same format as Objective-C method encodings.
///
/// \returns true if an error occurred (e.g., because one of the parameter
/// types is incomplete), false otherwise.
bool getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, std::string& S);
/// \brief Emit the encoded type for the method declaration \p Decl into
/// \p S.
///
/// \returns true if an error occurred (e.g., because one of the parameter
/// types is incomplete), false otherwise.
bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S,
bool Extended = false)
const;
/// \brief Return the encoded type for this block declaration.
std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
/// getObjCEncodingForPropertyDecl - Return the encoded type for
/// this method declaration. If non-NULL, Container must be either
/// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
/// only be NULL when getting encodings for protocol properties.
void getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
const Decl *Container,
std::string &S) const;
bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
ObjCProtocolDecl *rProto) const;
ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
const ObjCPropertyDecl *PD,
const Decl *Container) const;
/// \brief Return the size of type \p T for Objective-C encoding purpose,
/// in characters.
CharUnits getObjCEncodingTypeSize(QualType T) const;
/// \brief Retrieve the typedef corresponding to the predefined \c id type
/// in Objective-C.
TypedefDecl *getObjCIdDecl() const;
/// \brief Represents the Objective-CC \c id type.
///
/// This is set up lazily, by Sema. \c id is always a (typedef for a)
/// pointer type, a pointer to a struct.
QualType getObjCIdType() const {
return getTypeDeclType(getObjCIdDecl());
}
/// \brief Retrieve the typedef corresponding to the predefined 'SEL' type
/// in Objective-C.
TypedefDecl *getObjCSelDecl() const;
/// \brief Retrieve the type that corresponds to the predefined Objective-C
/// 'SEL' type.
QualType getObjCSelType() const {
return getTypeDeclType(getObjCSelDecl());
}
/// \brief Retrieve the typedef declaration corresponding to the predefined
/// Objective-C 'Class' type.
TypedefDecl *getObjCClassDecl() const;
/// \brief Represents the Objective-C \c Class type.
///
/// This is set up lazily, by Sema. \c Class is always a (typedef for a)
/// pointer type, a pointer to a struct.
QualType getObjCClassType() const {
return getTypeDeclType(getObjCClassDecl());
}
/// \brief Retrieve the Objective-C class declaration corresponding to
/// the predefined \c Protocol class.
ObjCInterfaceDecl *getObjCProtocolDecl() const;
/// \brief Retrieve declaration of 'BOOL' typedef
TypedefDecl *getBOOLDecl() const {
return BOOLDecl;
}
/// \brief Save declaration of 'BOOL' typedef
void setBOOLDecl(TypedefDecl *TD) {
BOOLDecl = TD;
}
/// \brief type of 'BOOL' type.
QualType getBOOLType() const {
return getTypeDeclType(getBOOLDecl());
}
/// \brief Retrieve the type of the Objective-C \c Protocol class.
QualType getObjCProtoType() const {
return getObjCInterfaceType(getObjCProtocolDecl());
}
/// \brief Retrieve the C type declaration corresponding to the predefined
/// \c __builtin_va_list type.
TypedefDecl *getBuiltinVaListDecl() const;
/// \brief Retrieve the type of the \c __builtin_va_list type.
QualType getBuiltinVaListType() const {
return getTypeDeclType(getBuiltinVaListDecl());
}
/// \brief Retrieve the C type declaration corresponding to the predefined
/// \c __va_list_tag type used to help define the \c __builtin_va_list type
/// for some targets.
QualType getVaListTagType() const;
/// \brief Return a type with additional \c const, \c volatile, or
/// \c restrict qualifiers.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
}
/// \brief Un-split a SplitQualType.
QualType getQualifiedType(SplitQualType split) const {
return getQualifiedType(split.Ty, split.Quals);
}
/// \brief Return a type with additional qualifiers.
QualType getQualifiedType(QualType T, Qualifiers Qs) const {
if (!Qs.hasNonFastQualifiers())
return T.withFastQualifiers(Qs.getFastQualifiers());
QualifierCollector Qc(Qs);
const Type *Ptr = Qc.strip(T);
return getExtQualType(Ptr, Qc);
}
/// \brief Return a type with additional qualifiers.
QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
if (!Qs.hasNonFastQualifiers())
return QualType(T, Qs.getFastQualifiers());
return getExtQualType(T, Qs);
}
/// \brief Return a type with the given lifetime qualifier.
///
/// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
QualType getLifetimeQualifiedType(QualType type,
Qualifiers::ObjCLifetime lifetime) {
assert(type.getObjCLifetime() == Qualifiers::OCL_None);
assert(lifetime != Qualifiers::OCL_None);
Qualifiers qs;
qs.addObjCLifetime(lifetime);
return getQualifiedType(type, qs);
}
/// getUnqualifiedObjCPointerType - Returns version of
/// Objective-C pointer type with lifetime qualifier removed.
QualType getUnqualifiedObjCPointerType(QualType type) const {
if (!type.getTypePtr()->isObjCObjectPointerType() ||
!type.getQualifiers().hasObjCLifetime())
return type;
Qualifiers Qs = type.getQualifiers();
Qs.removeObjCLifetime();
return getQualifiedType(type.getUnqualifiedType(), Qs);
}
DeclarationNameInfo getNameForTemplate(TemplateName Name,
SourceLocation NameLoc) const;
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
UnresolvedSetIterator End) const;
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
bool TemplateKeyword,
TemplateDecl *Template) const;
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
const IdentifierInfo *Name) const;
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
OverloadedOperatorKind Operator) const;
TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
TemplateName replacement) const;
TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
const TemplateArgument &ArgPack) const;
enum GetBuiltinTypeError {
GE_None, ///< No error
GE_Missing_stdio, ///< Missing a type from <stdio.h>
GE_Missing_setjmp, ///< Missing a type from <setjmp.h>
GE_Missing_ucontext ///< Missing a type from <ucontext.h>
};
/// \brief Return the type for the specified builtin.
///
/// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
/// arguments to the builtin that are required to be integer constant
/// expressions.
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
unsigned *IntegerConstantArgs = nullptr) const;
private:
CanQualType getFromTargetType(unsigned Type) const;
TypeInfo getTypeInfoImpl(const Type *T) const;
//===--------------------------------------------------------------------===//
// Type Predicates.
//===--------------------------------------------------------------------===//
public:
/// \brief Return one of the GCNone, Weak or Strong Objective-C garbage
/// collection attributes.
Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
/// \brief Return true if the given vector types are of the same unqualified
/// type or if they are equivalent to the same GCC vector type.
///
/// \note This ignores whether they are target-specific (AltiVec or Neon)
/// types.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
/// \brief Return true if this is an \c NSObject object with its \c NSObject
/// attribute set.
static bool isObjCNSObjectType(QualType Ty) {
return Ty->isObjCNSObjectType();
}
//===--------------------------------------------------------------------===//
// Type Sizing and Analysis
//===--------------------------------------------------------------------===//
/// \brief Return the APFloat 'semantics' for the specified scalar floating
/// point type.
const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
/// \brief Get the size and alignment of the specified complete type in bits.
TypeInfo getTypeInfo(const Type *T) const;
TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
/// \brief Get default simd alignment of the specified complete type in bits.
unsigned getOpenMPDefaultSimdAlign(QualType T) const;
/// \brief Return the size of the specified (complete) type \p T, in bits.
uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
/// \brief Return the size of the character type, in bits.
uint64_t getCharWidth() const {
return getTypeSize(CharTy);
}
/// \brief Convert a size in bits to a size in characters.
CharUnits toCharUnitsFromBits(int64_t BitSize) const;
/// \brief Convert a size in characters to a size in bits.
int64_t toBits(CharUnits CharSize) const;
/// \brief Return the size of the specified (complete) type \p T, in
/// characters.
CharUnits getTypeSizeInChars(QualType T) const;
CharUnits getTypeSizeInChars(const Type *T) const;
/// \brief Return the ABI-specified alignment of a (complete) type \p T, in
/// bits.
unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
/// \brief Return the ABI-specified alignment of a (complete) type \p T, in
/// characters.
CharUnits getTypeAlignInChars(QualType T) const;
CharUnits getTypeAlignInChars(const Type *T) const;
// getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
// type is a record, its data size is returned.
std::pair<CharUnits, CharUnits> getTypeInfoDataSizeInChars(QualType T) const;
std::pair<CharUnits, CharUnits> getTypeInfoInChars(const Type *T) const;
std::pair<CharUnits, CharUnits> getTypeInfoInChars(QualType T) const;
/// \brief Determine if the alignment the type has was required using an
/// alignment attribute.
bool isAlignmentRequired(const Type *T) const;
bool isAlignmentRequired(QualType T) const;
/// \brief Return the "preferred" alignment of the specified type \p T for
/// the current target, in bits.
///
/// This can be different than the ABI alignment in cases where it is
/// beneficial for performance to overalign a data type.
unsigned getPreferredTypeAlign(const Type *T) const;
/// \brief Return the default alignment for __attribute__((aligned)) on
/// this target, to be used if no alignment value is specified.
unsigned getTargetDefaultAlignForAttributeAligned(void) const;
/// \brief Return the alignment in bits that should be given to a
/// global variable with type \p T.
unsigned getAlignOfGlobalVar(QualType T) const;
/// \brief Return the alignment in characters that should be given to a
/// global variable with type \p T.
CharUnits getAlignOfGlobalVarInChars(QualType T) const;
/// \brief Return a conservative estimate of the alignment of the specified
/// decl \p D.
///
/// \pre \p D must not be a bitfield type, as bitfields do not have a valid
/// alignment.
///
/// If \p ForAlignof, references are treated like their underlying type
/// and large arrays don't get any special treatment. If not \p ForAlignof
/// it computes the value expected by CodeGen: references are treated like
/// pointers and large arrays get extra alignment.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
/// \brief Get or compute information about the layout of the specified
/// record (struct/union/class) \p D, which indicates its size and field
/// position information.
const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
const ASTRecordLayout *BuildMicrosoftASTRecordLayout(const RecordDecl *D) const;
/// \brief Get or compute information about the layout of the specified
/// Objective-C interface.
const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
const;
void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
bool Simple = false) const;
/// \brief Get or compute information about the layout of the specified
/// Objective-C implementation.
///
/// This may differ from the interface if synthesized ivars are present.
const ASTRecordLayout &
getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
/// \brief Get our current best idea for the key function of the
/// given record decl, or NULL if there isn't one.
///
/// The key function is, according to the Itanium C++ ABI section 5.2.3:
/// ...the first non-pure virtual function that is not inline at the
/// point of class definition.
///
/// Other ABIs use the same idea. However, the ARM C++ ABI ignores
/// virtual functions that are defined 'inline', which means that
/// the result of this computation can change.
const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
/// \brief Observe that the given method cannot be a key function.
/// Checks the key-function cache for the method's class and clears it
/// if matches the given declaration.
///
/// This is used in ABIs where out-of-line definitions marked
/// inline are not considered to be key functions.
///
/// \param method should be the declaration from the class definition
void setNonKeyFunction(const CXXMethodDecl *method);
/// Loading virtual member pointers using the virtual inheritance model
/// always results in an adjustment using the vbtable even if the index is
/// zero.
///
/// This is usually OK because the first slot in the vbtable points
/// backwards to the top of the MDC. However, the MDC might be reusing a
/// vbptr from an nv-base. In this case, the first slot in the vbtable
/// points to the start of the nv-base which introduced the vbptr and *not*
/// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
/// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
uint64_t getFieldOffset(const ValueDecl *FD) const;
bool isNearlyEmpty(const CXXRecordDecl *RD) const;
VTableContextBase *getVTableContext();
MangleContext *createMangleContext();
void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
void CollectInheritedProtocols(const Decl *CDecl,
llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
//===--------------------------------------------------------------------===//
// Type Operators
//===--------------------------------------------------------------------===//
/// \brief Return the canonical (structural) type corresponding to the
/// specified potentially non-canonical type \p T.
///
/// The non-canonical version of a type may have many "decorated" versions of
/// types. Decorators can include typedefs, 'typeof' operators, etc. The
/// returned type is guaranteed to be free of any of these, allowing two
/// canonical types to be compared for exact equality with a simple pointer
/// comparison.
CanQualType getCanonicalType(QualType T) const {
return CanQualType::CreateUnsafe(T.getCanonicalType());
}
const Type *getCanonicalType(const Type *T) const {
return T->getCanonicalTypeInternal().getTypePtr();
}
/// \brief Return the canonical parameter type corresponding to the specific
/// potentially non-canonical one.
///
/// Qualifiers are stripped off, functions are turned into function
/// pointers, and arrays decay one level into pointers.
CanQualType getCanonicalParamType(QualType T) const;
/// \brief Determine whether the given types \p T1 and \p T2 are equivalent.
bool hasSameType(QualType T1, QualType T2) const {
return getCanonicalType(T1) == getCanonicalType(T2);
}
bool hasSameType(const Type *T1, const Type *T2) const {
return getCanonicalType(T1) == getCanonicalType(T2);
}
/// \brief Return this type as a completely-unqualified array type,
/// capturing the qualifiers in \p Quals.
///
/// This will remove the minimal amount of sugaring from the types, similar
/// to the behavior of QualType::getUnqualifiedType().
///
/// \param T is the qualified type, which may be an ArrayType
///
/// \param Quals will receive the full set of qualifiers that were
/// applied to the array.
///
/// \returns if this is an array type, the completely unqualified array type
/// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
/// \brief Determine whether the given types are equivalent after
/// cvr-qualifiers have been removed.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
return getCanonicalType(T1).getTypePtr() ==
getCanonicalType(T2).getTypePtr();
}
bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
bool IsParam) const {
auto SubTnullability = SubT->getNullability(*this);
auto SuperTnullability = SuperT->getNullability(*this);
if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
// Neither has nullability; return true
if (!SubTnullability)
return true;
// Both have nullability qualifier.
if (*SubTnullability == *SuperTnullability ||
*SubTnullability == NullabilityKind::Unspecified ||
*SuperTnullability == NullabilityKind::Unspecified)
return true;
if (IsParam) {
// Ok for the superclass method parameter to be "nonnull" and the subclass
// method parameter to be "nullable"
return (*SuperTnullability == NullabilityKind::NonNull &&
*SubTnullability == NullabilityKind::Nullable);
}
else {
// For the return type, it's okay for the superclass method to specify
// "nullable" and the subclass method specify "nonnull"
return (*SuperTnullability == NullabilityKind::Nullable &&
*SubTnullability == NullabilityKind::NonNull);
}
}
return true;
}
bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
const ObjCMethodDecl *MethodImp);
bool UnwrapSimilarPointerTypes(QualType &T1, QualType &T2);
/// \brief Retrieves the "canonical" nested name specifier for a
/// given nested name specifier.
///
/// The canonical nested name specifier is a nested name specifier
/// that uniquely identifies a type or namespace within the type
/// system. For example, given:
///
/// \code
/// namespace N {
/// struct S {
/// template<typename T> struct X { typename T* type; };
/// };
/// }
///
/// template<typename T> struct Y {
/// typename N::S::X<T>::type member;
/// };
/// \endcode
///
/// Here, the nested-name-specifier for N::S::X<T>:: will be
/// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
/// by declarations in the type system and the canonical type for
/// the template type parameter 'T' is template-param-0-0.
NestedNameSpecifier *
getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
/// \brief Retrieves the default calling convention for the current target.
CallingConv getDefaultCallingConvention(bool isVariadic,
bool IsCXXMethod) const;
/// \brief Retrieves the "canonical" template name that refers to a
/// given template.
///
/// The canonical template name is the simplest expression that can
/// be used to refer to a given template. For most templates, this
/// expression is just the template declaration itself. For example,
/// the template std::vector can be referred to via a variety of
/// names---std::vector, \::std::vector, vector (if vector is in
/// scope), etc.---but all of these names map down to the same
/// TemplateDecl, which is used to form the canonical template name.
///
/// Dependent template names are more interesting. Here, the
/// template name could be something like T::template apply or
/// std::allocator<T>::template rebind, where the nested name
/// specifier itself is dependent. In this case, the canonical
/// template name uses the shortest form of the dependent
/// nested-name-specifier, which itself contains all canonical
/// types, values, and templates.
TemplateName getCanonicalTemplateName(TemplateName Name) const;
/// \brief Determine whether the given template names refer to the same
/// template.
bool hasSameTemplateName(TemplateName X, TemplateName Y);
/// \brief Retrieve the "canonical" template argument.
///
/// The canonical template argument is the simplest template argument
/// (which may be a type, value, expression, or declaration) that
/// expresses the value of the argument.
TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
const;
/// Type Query functions. If the type is an instance of the specified class,
/// return the Type pointer for the underlying maximally pretty type. This
/// is a member of ASTContext because this may need to do some amount of
/// canonicalization, e.g. to move type qualifiers into the element type.
const ArrayType *getAsArrayType(QualType T) const;
const ConstantArrayType *getAsConstantArrayType(QualType T) const {
return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
}
const VariableArrayType *getAsVariableArrayType(QualType T) const {
return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
}
const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
}
const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
const {
return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
}
/// \brief Return the innermost element type of an array type.
///
/// For example, will return "int" for int[m][n]
QualType getBaseElementType(const ArrayType *VAT) const;
/// \brief Return the innermost element type of a type (which needn't
/// actually be an array type).
QualType getBaseElementType(QualType QT) const;
/// \brief Return number of constant array elements.
uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
/// \brief Perform adjustment on the parameter type of a function.
///
/// This routine adjusts the given parameter type @p T to the actual
/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
/// C++ [dcl.fct]p3). The adjusted parameter type is returned.
QualType getAdjustedParameterType(QualType T) const;
/// \brief Retrieve the parameter type as adjusted for use in the signature
/// of a function, decaying array and function types and removing top-level
/// cv-qualifiers.
QualType getSignatureParameterType(QualType T) const;
QualType getExceptionObjectType(QualType T) const;
/// \brief Return the properly qualified result of decaying the specified
/// array type to a pointer.
///
/// This operation is non-trivial when handling typedefs etc. The canonical
/// type of \p T must be an array type, this returns a pointer to a properly
/// qualified element of the array.
///
/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
QualType getArrayDecayedType(QualType T) const;
/// \brief Return the type that \p PromotableType will promote to: C99
/// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
QualType getPromotedIntegerType(QualType PromotableType) const;
/// \brief Recurses in pointer/array types until it finds an Objective-C
/// retainable type and returns its ownership.
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
/// \brief Whether this is a promotable bitfield reference according
/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
///
/// \returns the type this bit-field will promote to, or NULL if no
/// promotion occurs.
QualType isPromotableBitField(Expr *E) const;
/// \brief Return the highest ranked integer type, see C99 6.3.1.8p1.
///
/// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
/// \p LHS < \p RHS, return -1.
int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
/// \brief Compare the rank of the two specified floating point types,
/// ignoring the domain of the type (i.e. 'double' == '_Complex double').
///
/// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
/// \p LHS < \p RHS, return -1.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
/// \brief Return a real floating point or a complex type (based on
/// \p typeDomain/\p typeSize).
///
/// \param typeDomain a real floating point or complex type.
/// \param typeSize a real floating point or complex type.
QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
QualType typeDomain) const;
unsigned getTargetAddressSpace(QualType T) const {
return getTargetAddressSpace(T.getQualifiers());
}
unsigned getTargetAddressSpace(Qualifiers Q) const {
return getTargetAddressSpace(Q.getAddressSpace());
}
unsigned getTargetAddressSpace(unsigned AS) const {
if (AS < LangAS::Offset || AS >= LangAS::Offset + LangAS::Count)
return AS;
else
return (*AddrSpaceMap)[AS - LangAS::Offset];
}
bool addressSpaceMapManglingFor(unsigned AS) const {
return AddrSpaceMapMangling ||
AS < LangAS::Offset ||
AS >= LangAS::Offset + LangAS::Count;
}
private:
// Helper for integer ordering
unsigned getIntegerRank(const Type *T) const;
public:
//===--------------------------------------------------------------------===//
// Type Compatibility Predicates
//===--------------------------------------------------------------------===//
/// Compatibility predicates used to check assignment expressions.
bool typesAreCompatible(QualType T1, QualType T2,
bool CompareUnqualified = false); // C99 6.2.7p1
bool propertyTypesAreCompatible(QualType, QualType);
bool typesAreBlockPointerCompatible(QualType, QualType);
bool isObjCIdType(QualType T) const {
return T == getObjCIdType();
}
bool isObjCClassType(QualType T) const {
return T == getObjCClassType();
}
bool isObjCSelType(QualType T) const {
return T == getObjCSelType();
}
bool ObjCQualifiedIdTypesAreCompatible(QualType LHS, QualType RHS,
bool ForCompare);
bool ObjCQualifiedClassTypesAreCompatible(QualType LHS, QualType RHS);
// Check the safety of assignment from LHS to RHS
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
const ObjCObjectPointerType *RHSOPT);
bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
const ObjCObjectType *RHS);
bool canAssignObjCInterfacesInBlockPointer(
const ObjCObjectPointerType *LHSOPT,
const ObjCObjectPointerType *RHSOPT,
bool BlockReturnType);
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
const ObjCObjectPointerType *RHSOPT);
bool canBindObjCObjectType(QualType To, QualType From);
// Functions for calculating composite types
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
bool Unqualified = false, bool BlockReturnType = false);
QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
bool Unqualified = false);
QualType mergeFunctionParameterTypes(QualType, QualType,
bool OfBlockPointer = false,
bool Unqualified = false);
QualType mergeTransparentUnionType(QualType, QualType,
bool OfBlockPointer=false,
bool Unqualified = false);
QualType mergeObjCGCQualifiers(QualType, QualType);
bool FunctionTypesMatchOnNSConsumedAttrs(
const FunctionProtoType *FromFunctionType,
const FunctionProtoType *ToFunctionType);
void ResetObjCLayout(const ObjCContainerDecl *CD) {
ObjCLayouts[CD] = nullptr;
}
//===--------------------------------------------------------------------===//
// Integer Predicates
//===--------------------------------------------------------------------===//
// The width of an integer, as defined in C99 6.2.6.2. This is the number
// of bits in an integer type excluding any padding bits.
unsigned getIntWidth(QualType T) const;
// Per C99 6.2.5p6, for every signed integer type, there is a corresponding
// unsigned integer type. This method takes a signed type, and returns the
// corresponding unsigned integer type.
QualType getCorrespondingUnsignedType(QualType T) const;
//===--------------------------------------------------------------------===//
// Type Iterators.
//===--------------------------------------------------------------------===//
typedef llvm::iterator_range<SmallVectorImpl<Type *>::const_iterator>
type_const_range;
type_const_range types() const {
return type_const_range(Types.begin(), Types.end());
}
//===--------------------------------------------------------------------===//
// Integer Values
//===--------------------------------------------------------------------===//
/// \brief Make an APSInt of the appropriate width and signedness for the
/// given \p Value and integer \p Type.
llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
llvm::APSInt Res(getIntWidth(Type),
!Type->isSignedIntegerOrEnumerationType());
Res = Value;
return Res;
}
bool isSentinelNullExpr(const Expr *E);
/// \brief Get the implementation of the ObjCInterfaceDecl \p D, or NULL if
/// none exists.
ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
/// \brief Get the implementation of the ObjCCategoryDecl \p D, or NULL if
/// none exists.
ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
/// \brief Return true if there is at least one \@implementation in the TU.
bool AnyObjCImplementation() {
return !ObjCImpls.empty();
}
/// \brief Set the implementation of ObjCInterfaceDecl.
void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
ObjCImplementationDecl *ImplD);
/// \brief Set the implementation of ObjCCategoryDecl.
void setObjCImplementation(ObjCCategoryDecl *CatD,
ObjCCategoryImplDecl *ImplD);
/// \brief Get the duplicate declaration of a ObjCMethod in the same
/// interface, or null if none exists.
const ObjCMethodDecl *getObjCMethodRedeclaration(
const ObjCMethodDecl *MD) const {
return ObjCMethodRedecls.lookup(MD);
}
void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
const ObjCMethodDecl *Redecl) {
assert(!getObjCMethodRedeclaration(MD) && "MD already has a redeclaration");
ObjCMethodRedecls[MD] = Redecl;
}
/// \brief Returns the Objective-C interface that \p ND belongs to if it is
/// an Objective-C method/property/ivar etc. that is part of an interface,
/// otherwise returns null.
const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
/// \brief Set the copy inialization expression of a block var decl.
void setBlockVarCopyInits(VarDecl*VD, Expr* Init);
/// \brief Get the copy initialization expression of the VarDecl \p VD, or
/// NULL if none exists.
Expr *getBlockVarCopyInits(const VarDecl* VD);
/// \brief Allocate an uninitialized TypeSourceInfo.
///
/// The caller should initialize the memory held by TypeSourceInfo using
/// the TypeLoc wrappers.
///
/// \param T the type that will be the basis for type source info. This type
/// should refer to how the declarator was written in source code, not to
/// what type semantic analysis resolved the declarator to.
///
/// \param Size the size of the type info to create, or 0 if the size
/// should be calculated based on the type.
TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
/// \brief Allocate a TypeSourceInfo where all locations have been
/// initialized to a given location, which defaults to the empty
/// location.
TypeSourceInfo *
getTrivialTypeSourceInfo(QualType T,
SourceLocation Loc = SourceLocation()) const;
/// \brief Add a deallocation callback that will be invoked when the
/// ASTContext is destroyed.
///
/// \param Callback A callback function that will be invoked on destruction.
///
/// \param Data Pointer data that will be provided to the callback function
/// when it is called.
void AddDeallocation(void (*Callback)(void*), void *Data);
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
/// \brief Determines if the decl can be CodeGen'ed or deserialized from PCH
/// lazily, only when used; this is only relevant for function or file scoped
/// var definitions.
///
/// \returns true if the function/var must be CodeGen'ed/deserialized even if
/// it is not used.
bool DeclMustBeEmitted(const Decl *D);
const CXXConstructorDecl *
getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
CXXConstructorDecl *CD);
void addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
unsigned ParmIdx, Expr *DAE);
Expr *getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
unsigned ParmIdx);
void setManglingNumber(const NamedDecl *ND, unsigned Number);
unsigned getManglingNumber(const NamedDecl *ND) const;
void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
unsigned getStaticLocalNumber(const VarDecl *VD) const;
/// \brief Retrieve the context for computing mangling numbers in the given
/// DeclContext.
MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
MangleNumberingContext *createMangleNumberingContext() const;
/// \brief Used by ParmVarDecl to store on the side the
/// index of the parameter when it exceeds the size of the normal bitfield.
void setParameterIndex(const ParmVarDecl *D, unsigned index);
/// \brief Used by ParmVarDecl to retrieve on the side the
/// index of the parameter when it exceeds the size of the normal bitfield.
unsigned getParameterIndex(const ParmVarDecl *D) const;
/// \brief Get the storage for the constant value of a materialized temporary
/// of static storage duration.
APValue *getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
bool MayCreate);
//===--------------------------------------------------------------------===//
// Statistics
//===--------------------------------------------------------------------===//
/// \brief The number of implicitly-declared default constructors.
static unsigned NumImplicitDefaultConstructors;
/// \brief The number of implicitly-declared default constructors for
/// which declarations were built.
static unsigned NumImplicitDefaultConstructorsDeclared;
/// \brief The number of implicitly-declared copy constructors.
static unsigned NumImplicitCopyConstructors;
/// \brief The number of implicitly-declared copy constructors for
/// which declarations were built.
static unsigned NumImplicitCopyConstructorsDeclared;
/// \brief The number of implicitly-declared move constructors.
static unsigned NumImplicitMoveConstructors;
/// \brief The number of implicitly-declared move constructors for
/// which declarations were built.
static unsigned NumImplicitMoveConstructorsDeclared;
/// \brief The number of implicitly-declared copy assignment operators.
static unsigned NumImplicitCopyAssignmentOperators;
/// \brief The number of implicitly-declared copy assignment operators for
/// which declarations were built.
static unsigned NumImplicitCopyAssignmentOperatorsDeclared;
/// \brief The number of implicitly-declared move assignment operators.
static unsigned NumImplicitMoveAssignmentOperators;
/// \brief The number of implicitly-declared move assignment operators for
/// which declarations were built.
static unsigned NumImplicitMoveAssignmentOperatorsDeclared;
/// \brief The number of implicitly-declared destructors.
static unsigned NumImplicitDestructors;
/// \brief The number of implicitly-declared destructors for which
/// declarations were built.
static unsigned NumImplicitDestructorsDeclared;
private:
ASTContext(const ASTContext &) = delete;
void operator=(const ASTContext &) = delete;
public:
/// \brief Initialize built-in types.
///
/// This routine may only be invoked once for a given ASTContext object.
/// It is normally invoked after ASTContext construction.
///
/// \param Target The target
void InitBuiltinTypes(const TargetInfo &Target);
private:
void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
// Return the Objective-C type encoding for a given type.
void getObjCEncodingForTypeImpl(QualType t, std::string &S,
bool ExpandPointedToStructures,
bool ExpandStructures,
const FieldDecl *Field,
bool OutermostType = false,
bool EncodingProperty = false,
bool StructField = false,
bool EncodeBlockParameters = false,
bool EncodeClassNames = false,
bool EncodePointerToObjCTypedef = false,
QualType *NotEncodedT=nullptr) const;
// Adds the encoding of the structure's members.
void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
const FieldDecl *Field,
bool includeVBases = true,
QualType *NotEncodedT=nullptr) const;
public:
// Adds the encoding of a method parameter or return type.
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
QualType T, std::string& S,
bool Extended) const;
/// \brief Returns true if this is an inline-initialized static data member
/// which is treated as a definition for MSVC compatibility.
bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
private:
const ASTRecordLayout &
getObjCLayout(const ObjCInterfaceDecl *D,
const ObjCImplementationDecl *Impl) const;
/// \brief A set of deallocations that should be performed when the
/// ASTContext is destroyed.
typedef llvm::SmallDenseMap<void(*)(void*), llvm::SmallVector<void*, 16> >
DeallocationMap;
DeallocationMap Deallocations;
// FIXME: This currently contains the set of StoredDeclMaps used
// by DeclContext objects. This probably should not be in ASTContext,
// but we include it here so that ASTContext can quickly deallocate them.
llvm::PointerIntPair<StoredDeclsMap*,1> LastSDM;
friend class DeclContext;
friend class DeclarationNameTable;
void ReleaseDeclContextMaps();
void ReleaseParentMapEntries();
std::unique_ptr<ParentMap> AllParents;
std::unique_ptr<VTableContextBase> VTContext;
public:
enum PragmaSectionFlag : unsigned {
PSF_None = 0,
PSF_Read = 0x1,
PSF_Write = 0x2,
PSF_Execute = 0x4,
PSF_Implicit = 0x8,
PSF_Invalid = 0x80000000U,
};
struct SectionInfo {
DeclaratorDecl *Decl;
SourceLocation PragmaSectionLocation;
int SectionFlags;
SectionInfo() {}
SectionInfo(DeclaratorDecl *Decl,
SourceLocation PragmaSectionLocation,
int SectionFlags)
: Decl(Decl),
PragmaSectionLocation(PragmaSectionLocation),
SectionFlags(SectionFlags) {}
};
llvm::StringMap<SectionInfo> SectionInfos;
};
/// \brief Utility function for constructing a nullary selector.
static inline Selector GetNullarySelector(StringRef name, ASTContext& Ctx) {
IdentifierInfo* II = &Ctx.Idents.get(name);
return Ctx.Selectors.getSelector(0, &II);
}
/// \brief Utility function for constructing an unary selector.
static inline Selector GetUnarySelector(StringRef name, ASTContext& Ctx) {
IdentifierInfo* II = &Ctx.Idents.get(name);
return Ctx.Selectors.getSelector(1, &II);
}
} // end namespace clang
// operator new and delete aren't allowed inside namespaces.
/// @brief Placement new for using the ASTContext's allocator.
///
/// This placement form of operator new uses the ASTContext's allocator for
/// obtaining memory.
///
/// IMPORTANT: These are also declared in clang/AST/AttrIterator.h! Any changes
/// here need to also be made there.
///
/// We intentionally avoid using a nothrow specification here so that the calls
/// to this operator will not perform a null check on the result -- the
/// underlying allocator never returns null pointers.
///
/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
/// @code
/// // Default alignment (8)
/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
/// // Specific alignment
/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
/// @endcode
/// Memory allocated through this placement new operator does not need to be
/// explicitly freed, as ASTContext will free all of this memory when it gets
/// destroyed. Please note that you cannot use delete on the pointer.
///
/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
/// @param C The ASTContext that provides the allocator.
/// @param Alignment The alignment of the allocated memory (if the underlying
/// allocator supports it).
/// @return The allocated memory. Could be NULL.
inline void *operator new(size_t Bytes, const clang::ASTContext &C,
size_t Alignment) {
return C.Allocate(Bytes, Alignment);
}
/// @brief Placement delete companion to the new above.
///
/// This operator is just a companion to the new above. There is no way of
/// invoking it directly; see the new operator for more details. This operator
/// is called implicitly by the compiler if a placement new expression using
/// the ASTContext throws in the object constructor.
inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
C.Deallocate(Ptr);
}
/// This placement form of operator new[] uses the ASTContext's allocator for
/// obtaining memory.
///
/// We intentionally avoid using a nothrow specification here so that the calls
/// to this operator will not perform a null check on the result -- the
/// underlying allocator never returns null pointers.
///
/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
/// @code
/// // Default alignment (8)
/// char *data = new (Context) char[10];
/// // Specific alignment
/// char *data = new (Context, 4) char[10];
/// @endcode
/// Memory allocated through this placement new[] operator does not need to be
/// explicitly freed, as ASTContext will free all of this memory when it gets
/// destroyed. Please note that you cannot use delete on the pointer.
///
/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
/// @param C The ASTContext that provides the allocator.
/// @param Alignment The alignment of the allocated memory (if the underlying
/// allocator supports it).
/// @return The allocated memory. Could be NULL.
inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
size_t Alignment = 8) {
return C.Allocate(Bytes, Alignment);
}
/// @brief Placement delete[] companion to the new[] above.
///
/// This operator is just a companion to the new[] above. There is no way of
/// invoking it directly; see the new[] operator for more details. This operator
/// is called implicitly by the compiler if a placement new[] expression using
/// the ASTContext throws in the object constructor.
inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
C.Deallocate(Ptr);
}
/// \brief Create the representation of a LazyGenerationalUpdatePtr.
template <typename Owner, typename T,
void (clang::ExternalASTSource::*Update)(Owner)>
typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
const clang::ASTContext &Ctx, T Value) {
// Note, this is implemented here so that ExternalASTSource.h doesn't need to
// include ASTContext.h. We explicitly instantiate it for all relevant types
// in ASTContext.cpp.
if (auto *Source = Ctx.getExternalSource())
return new (Ctx) LazyData(Source, Value);
return Value;
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/BaseSubobject.h | //===--- BaseSubobject.h - BaseSubobject class ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides a definition of the BaseSubobject class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_BASESUBOBJECT_H
#define LLVM_CLANG_AST_BASESUBOBJECT_H
#include "clang/AST/CharUnits.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/type_traits.h"
namespace clang {
class CXXRecordDecl;
// BaseSubobject - Uniquely identifies a direct or indirect base class.
// Stores both the base class decl and the offset from the most derived class to
// the base class. Used for vtable and VTT generation.
class BaseSubobject {
/// Base - The base class declaration.
const CXXRecordDecl *Base;
/// BaseOffset - The offset from the most derived class to the base class.
CharUnits BaseOffset;
public:
BaseSubobject() { }
BaseSubobject(const CXXRecordDecl *Base, CharUnits BaseOffset)
: Base(Base), BaseOffset(BaseOffset) { }
/// getBase - Returns the base class declaration.
const CXXRecordDecl *getBase() const { return Base; }
/// getBaseOffset - Returns the base class offset.
CharUnits getBaseOffset() const { return BaseOffset; }
friend bool operator==(const BaseSubobject &LHS, const BaseSubobject &RHS) {
return LHS.Base == RHS.Base && LHS.BaseOffset == RHS.BaseOffset;
}
};
} // end namespace clang
namespace llvm {
template<> struct DenseMapInfo<clang::BaseSubobject> {
static clang::BaseSubobject getEmptyKey() {
return clang::BaseSubobject(
DenseMapInfo<const clang::CXXRecordDecl *>::getEmptyKey(),
clang::CharUnits::fromQuantity(DenseMapInfo<int64_t>::getEmptyKey()));
}
static clang::BaseSubobject getTombstoneKey() {
return clang::BaseSubobject(
DenseMapInfo<const clang::CXXRecordDecl *>::getTombstoneKey(),
clang::CharUnits::fromQuantity(DenseMapInfo<int64_t>::getTombstoneKey()));
}
static unsigned getHashValue(const clang::BaseSubobject &Base) {
typedef std::pair<const clang::CXXRecordDecl *, clang::CharUnits> PairTy;
return DenseMapInfo<PairTy>::getHashValue(PairTy(Base.getBase(),
Base.getBaseOffset()));
}
static bool isEqual(const clang::BaseSubobject &LHS,
const clang::BaseSubobject &RHS) {
return LHS == RHS;
}
};
// It's OK to treat BaseSubobject as a POD type.
template <> struct isPodLike<clang::BaseSubobject> {
static const bool value = true;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/StmtCXX.h | //===--- StmtCXX.h - Classes for representing C++ statements ----*- 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 C++ statement AST node classes.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_STMTCXX_H
#define LLVM_CLANG_AST_STMTCXX_H
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/Stmt.h"
#include "llvm/Support/Compiler.h"
namespace clang {
class VarDecl;
/// CXXCatchStmt - This represents a C++ catch block.
///
class CXXCatchStmt : public Stmt {
SourceLocation CatchLoc;
/// The exception-declaration of the type.
VarDecl *ExceptionDecl;
/// The handler block.
Stmt *HandlerBlock;
public:
CXXCatchStmt(SourceLocation catchLoc, VarDecl *exDecl, Stmt *handlerBlock)
: Stmt(CXXCatchStmtClass), CatchLoc(catchLoc), ExceptionDecl(exDecl),
HandlerBlock(handlerBlock) {}
CXXCatchStmt(EmptyShell Empty)
: Stmt(CXXCatchStmtClass), ExceptionDecl(nullptr), HandlerBlock(nullptr) {}
SourceLocation getLocStart() const LLVM_READONLY { return CatchLoc; }
SourceLocation getLocEnd() const LLVM_READONLY {
return HandlerBlock->getLocEnd();
}
SourceLocation getCatchLoc() const { return CatchLoc; }
VarDecl *getExceptionDecl() const { return ExceptionDecl; }
QualType getCaughtType() const;
Stmt *getHandlerBlock() const { return HandlerBlock; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXCatchStmtClass;
}
child_range children() { return child_range(&HandlerBlock, &HandlerBlock+1); }
friend class ASTStmtReader;
};
/// CXXTryStmt - A C++ try block, including all handlers.
///
class CXXTryStmt : public Stmt {
SourceLocation TryLoc;
unsigned NumHandlers;
CXXTryStmt(SourceLocation tryLoc, Stmt *tryBlock, ArrayRef<Stmt*> handlers);
CXXTryStmt(EmptyShell Empty, unsigned numHandlers)
: Stmt(CXXTryStmtClass), NumHandlers(numHandlers) { }
Stmt const * const *getStmts() const {
return reinterpret_cast<Stmt const * const*>(this + 1);
}
Stmt **getStmts() {
return reinterpret_cast<Stmt **>(this + 1);
}
public:
static CXXTryStmt *Create(const ASTContext &C, SourceLocation tryLoc,
Stmt *tryBlock, ArrayRef<Stmt*> handlers);
static CXXTryStmt *Create(const ASTContext &C, EmptyShell Empty,
unsigned numHandlers);
SourceLocation getLocStart() const LLVM_READONLY { return getTryLoc(); }
SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
SourceLocation getTryLoc() const { return TryLoc; }
SourceLocation getEndLoc() const {
return getStmts()[NumHandlers]->getLocEnd();
}
CompoundStmt *getTryBlock() {
return cast<CompoundStmt>(getStmts()[0]);
}
const CompoundStmt *getTryBlock() const {
return cast<CompoundStmt>(getStmts()[0]);
}
unsigned getNumHandlers() const { return NumHandlers; }
CXXCatchStmt *getHandler(unsigned i) {
return cast<CXXCatchStmt>(getStmts()[i + 1]);
}
const CXXCatchStmt *getHandler(unsigned i) const {
return cast<CXXCatchStmt>(getStmts()[i + 1]);
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXTryStmtClass;
}
child_range children() {
return child_range(getStmts(), getStmts() + getNumHandlers() + 1);
}
friend class ASTStmtReader;
};
/// CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for
/// statement, represented as 'for (range-declarator : range-expression)'.
///
/// This is stored in a partially-desugared form to allow full semantic
/// analysis of the constituent components. The original syntactic components
/// can be extracted using getLoopVariable and getRangeInit.
class CXXForRangeStmt : public Stmt {
SourceLocation ForLoc;
enum { RANGE, BEGINEND, COND, INC, LOOPVAR, BODY, END };
// SubExprs[RANGE] is an expression or declstmt.
// SubExprs[COND] and SubExprs[INC] are expressions.
Stmt *SubExprs[END];
SourceLocation ColonLoc;
SourceLocation RParenLoc;
public:
CXXForRangeStmt(DeclStmt *Range, DeclStmt *BeginEnd,
Expr *Cond, Expr *Inc, DeclStmt *LoopVar, Stmt *Body,
SourceLocation FL, SourceLocation CL, SourceLocation RPL);
CXXForRangeStmt(EmptyShell Empty) : Stmt(CXXForRangeStmtClass, Empty) { }
VarDecl *getLoopVariable();
Expr *getRangeInit();
const VarDecl *getLoopVariable() const;
const Expr *getRangeInit() const;
DeclStmt *getRangeStmt() { return cast<DeclStmt>(SubExprs[RANGE]); }
DeclStmt *getBeginEndStmt() {
return cast_or_null<DeclStmt>(SubExprs[BEGINEND]);
}
Expr *getCond() { return cast_or_null<Expr>(SubExprs[COND]); }
Expr *getInc() { return cast_or_null<Expr>(SubExprs[INC]); }
DeclStmt *getLoopVarStmt() { return cast<DeclStmt>(SubExprs[LOOPVAR]); }
Stmt *getBody() { return SubExprs[BODY]; }
const DeclStmt *getRangeStmt() const {
return cast<DeclStmt>(SubExprs[RANGE]);
}
const DeclStmt *getBeginEndStmt() const {
return cast_or_null<DeclStmt>(SubExprs[BEGINEND]);
}
const Expr *getCond() const {
return cast_or_null<Expr>(SubExprs[COND]);
}
const Expr *getInc() const {
return cast_or_null<Expr>(SubExprs[INC]);
}
const DeclStmt *getLoopVarStmt() const {
return cast<DeclStmt>(SubExprs[LOOPVAR]);
}
const Stmt *getBody() const { return SubExprs[BODY]; }
void setRangeInit(Expr *E) { SubExprs[RANGE] = reinterpret_cast<Stmt*>(E); }
void setRangeStmt(Stmt *S) { SubExprs[RANGE] = S; }
void setBeginEndStmt(Stmt *S) { SubExprs[BEGINEND] = S; }
void setCond(Expr *E) { SubExprs[COND] = reinterpret_cast<Stmt*>(E); }
void setInc(Expr *E) { SubExprs[INC] = reinterpret_cast<Stmt*>(E); }
void setLoopVarStmt(Stmt *S) { SubExprs[LOOPVAR] = S; }
void setBody(Stmt *S) { SubExprs[BODY] = S; }
SourceLocation getForLoc() const { return ForLoc; }
void setForLoc(SourceLocation Loc) { ForLoc = Loc; }
SourceLocation getColonLoc() const { return ColonLoc; }
void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; }
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
SourceLocation getLocStart() const LLVM_READONLY { return ForLoc; }
SourceLocation getLocEnd() const LLVM_READONLY {
return SubExprs[BODY]->getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXForRangeStmtClass;
}
// Iterators
child_range children() {
return child_range(&SubExprs[0], &SubExprs[END]);
}
};
/// \brief Representation of a Microsoft __if_exists or __if_not_exists
/// statement with a dependent name.
///
/// The __if_exists statement can be used to include a sequence of statements
/// in the program only when a particular dependent name does not exist. For
/// example:
///
/// \code
/// template<typename T>
/// void call_foo(T &t) {
/// __if_exists (T::foo) {
/// t.foo(); // okay: only called when T::foo exists.
/// }
/// }
/// \endcode
///
/// Similarly, the __if_not_exists statement can be used to include the
/// statements when a particular name does not exist.
///
/// Note that this statement only captures __if_exists and __if_not_exists
/// statements whose name is dependent. All non-dependent cases are handled
/// directly in the parser, so that they don't introduce a new scope. Clang
/// introduces scopes in the dependent case to keep names inside the compound
/// statement from leaking out into the surround statements, which would
/// compromise the template instantiation model. This behavior differs from
/// Visual C++ (which never introduces a scope), but is a fairly reasonable
/// approximation of the VC++ behavior.
class MSDependentExistsStmt : public Stmt {
SourceLocation KeywordLoc;
bool IsIfExists;
NestedNameSpecifierLoc QualifierLoc;
DeclarationNameInfo NameInfo;
Stmt *SubStmt;
friend class ASTReader;
friend class ASTStmtReader;
public:
MSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists,
NestedNameSpecifierLoc QualifierLoc,
DeclarationNameInfo NameInfo,
CompoundStmt *SubStmt)
: Stmt(MSDependentExistsStmtClass),
KeywordLoc(KeywordLoc), IsIfExists(IsIfExists),
QualifierLoc(QualifierLoc), NameInfo(NameInfo),
SubStmt(reinterpret_cast<Stmt *>(SubStmt)) { }
/// \brief Retrieve the location of the __if_exists or __if_not_exists
/// keyword.
SourceLocation getKeywordLoc() const { return KeywordLoc; }
/// \brief Determine whether this is an __if_exists statement.
bool isIfExists() const { return IsIfExists; }
/// \brief Determine whether this is an __if_exists statement.
bool isIfNotExists() const { return !IsIfExists; }
/// \brief Retrieve the nested-name-specifier that qualifies this name, if
/// any.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the name of the entity we're testing for, along with
/// location information
DeclarationNameInfo getNameInfo() const { return NameInfo; }
/// \brief Retrieve the compound statement that will be included in the
/// program only if the existence of the symbol matches the initial keyword.
CompoundStmt *getSubStmt() const {
return reinterpret_cast<CompoundStmt *>(SubStmt);
}
SourceLocation getLocStart() const LLVM_READONLY { return KeywordLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();}
child_range children() {
return child_range(&SubStmt, &SubStmt+1);
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == MSDependentExistsStmtClass;
}
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/EvaluatedExprVisitor.h | //===--- EvaluatedExprVisitor.h - Evaluated expression visitor --*- 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 EvaluatedExprVisitor class template, which visits
// the potentially-evaluated subexpressions of a potentially-evaluated
// expression.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_EVALUATEDEXPRVISITOR_H
#define LLVM_CLANG_AST_EVALUATEDEXPRVISITOR_H
#include "clang/AST/DeclCXX.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/StmtVisitor.h"
namespace clang {
class ASTContext;
/// \brief Given a potentially-evaluated expression, this visitor visits all
/// of its potentially-evaluated subexpressions, recursively.
template<template <typename> class Ptr, typename ImplClass>
class EvaluatedExprVisitorBase : public StmtVisitorBase<Ptr, ImplClass, void> {
protected:
const ASTContext &Context;
public:
#define PTR(CLASS) typename Ptr<CLASS>::type
explicit EvaluatedExprVisitorBase(const ASTContext &Context) : Context(Context) { }
// Expressions that have no potentially-evaluated subexpressions (but may have
// other sub-expressions).
void VisitDeclRefExpr(PTR(DeclRefExpr) E) { }
void VisitOffsetOfExpr(PTR(OffsetOfExpr) E) { }
void VisitUnaryExprOrTypeTraitExpr(PTR(UnaryExprOrTypeTraitExpr) E) { }
void VisitExpressionTraitExpr(PTR(ExpressionTraitExpr) E) { }
void VisitBlockExpr(PTR(BlockExpr) E) { }
void VisitCXXUuidofExpr(PTR(CXXUuidofExpr) E) { }
void VisitCXXNoexceptExpr(PTR(CXXNoexceptExpr) E) { }
void VisitMemberExpr(PTR(MemberExpr) E) {
// Only the base matters.
return this->Visit(E->getBase());
}
void VisitChooseExpr(PTR(ChooseExpr) E) {
// Don't visit either child expression if the condition is dependent.
if (E->getCond()->isValueDependent())
return;
// Only the selected subexpression matters; the other one is not evaluated.
return this->Visit(E->getChosenSubExpr());
}
void VisitGenericSelectionExpr(PTR(GenericSelectionExpr) E) {
// The controlling expression of a generic selection is not evaluated.
// Don't visit either child expression if the condition is type-dependent.
if (E->isResultDependent())
return;
// Only the selected subexpression matters; the other subexpressions and the
// controlling expression are not evaluated.
return this->Visit(E->getResultExpr());
}
void VisitDesignatedInitExpr(PTR(DesignatedInitExpr) E) {
// Only the actual initializer matters; the designators are all constant
// expressions.
return this->Visit(E->getInit());
}
void VisitCXXTypeidExpr(PTR(CXXTypeidExpr) E) {
if (E->isPotentiallyEvaluated())
return this->Visit(E->getExprOperand());
}
void VisitCallExpr(PTR(CallExpr) CE) {
if (!CE->isUnevaluatedBuiltinCall(Context))
return static_cast<ImplClass*>(this)->VisitExpr(CE);
}
void VisitLambdaExpr(PTR(LambdaExpr) LE) {
// Only visit the capture initializers, and not the body.
for (LambdaExpr::capture_init_iterator I = LE->capture_init_begin(),
E = LE->capture_init_end();
I != E; ++I)
if (*I)
this->Visit(*I);
}
/// \brief The basis case walks all of the children of the statement or
/// expression, assuming they are all potentially evaluated.
void VisitStmt(PTR(Stmt) S) {
for (auto *SubStmt : S->children())
if (SubStmt)
this->Visit(SubStmt);
}
#undef PTR
};
/// EvaluatedExprVisitor - This class visits 'Expr *'s
template<typename ImplClass>
class EvaluatedExprVisitor
: public EvaluatedExprVisitorBase<make_ptr, ImplClass> {
public:
explicit EvaluatedExprVisitor(const ASTContext &Context) :
EvaluatedExprVisitorBase<make_ptr, ImplClass>(Context) { }
};
/// ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
template<typename ImplClass>
class ConstEvaluatedExprVisitor
: public EvaluatedExprVisitorBase<make_const_ptr, ImplClass> {
public:
explicit ConstEvaluatedExprVisitor(const ASTContext &Context) :
EvaluatedExprVisitorBase<make_const_ptr, ImplClass>(Context) { }
};
}
#endif // LLVM_CLANG_AST_EVALUATEDEXPRVISITOR_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/DeclGroup.h | //===--- DeclGroup.h - Classes for representing groups of Decls -*- 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 DeclGroup, DeclGroupRef, and OwningDeclGroup classes.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_DECLGROUP_H
#define LLVM_CLANG_AST_DECLGROUP_H
#include "llvm/Support/DataTypes.h"
#include <cassert>
namespace clang {
class ASTContext;
class Decl;
class DeclGroup;
class DeclGroupIterator;
class DeclGroup {
// FIXME: Include a TypeSpecifier object.
union {
unsigned NumDecls;
Decl *Aligner;
};
private:
DeclGroup() : NumDecls(0) {}
DeclGroup(unsigned numdecls, Decl** decls);
public:
static DeclGroup *Create(ASTContext &C, Decl **Decls, unsigned NumDecls);
unsigned size() const { return NumDecls; }
Decl*& operator[](unsigned i) {
assert (i < NumDecls && "Out-of-bounds access.");
return ((Decl**) (this+1))[i];
}
Decl* const& operator[](unsigned i) const {
assert (i < NumDecls && "Out-of-bounds access.");
return ((Decl* const*) (this+1))[i];
}
};
class DeclGroupRef {
// Note this is not a PointerIntPair because we need the address of the
// non-group case to be valid as a Decl** for iteration.
enum Kind { SingleDeclKind=0x0, DeclGroupKind=0x1, Mask=0x1 };
Decl* D;
Kind getKind() const {
return (Kind) (reinterpret_cast<uintptr_t>(D) & Mask);
}
public:
DeclGroupRef() : D(nullptr) {}
explicit DeclGroupRef(Decl* d) : D(d) {}
explicit DeclGroupRef(DeclGroup* dg)
: D((Decl*) (reinterpret_cast<uintptr_t>(dg) | DeclGroupKind)) {}
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls) {
if (NumDecls == 0)
return DeclGroupRef();
if (NumDecls == 1)
return DeclGroupRef(Decls[0]);
return DeclGroupRef(DeclGroup::Create(C, Decls, NumDecls));
}
typedef Decl** iterator;
typedef Decl* const * const_iterator;
bool isNull() const { return D == nullptr; }
bool isSingleDecl() const { return getKind() == SingleDeclKind; }
bool isDeclGroup() const { return getKind() == DeclGroupKind; }
Decl *getSingleDecl() {
assert(isSingleDecl() && "Isn't a declgroup");
return D;
}
const Decl *getSingleDecl() const {
return const_cast<DeclGroupRef*>(this)->getSingleDecl();
}
DeclGroup &getDeclGroup() {
assert(isDeclGroup() && "Isn't a declgroup");
return *((DeclGroup*)(reinterpret_cast<uintptr_t>(D) & ~Mask));
}
const DeclGroup &getDeclGroup() const {
return const_cast<DeclGroupRef*>(this)->getDeclGroup();
}
iterator begin() {
if (isSingleDecl())
return D ? &D : nullptr;
return &getDeclGroup()[0];
}
iterator end() {
if (isSingleDecl())
return D ? &D+1 : nullptr;
DeclGroup &G = getDeclGroup();
return &G[0] + G.size();
}
const_iterator begin() const {
if (isSingleDecl())
return D ? &D : nullptr;
return &getDeclGroup()[0];
}
const_iterator end() const {
if (isSingleDecl())
return D ? &D+1 : nullptr;
const DeclGroup &G = getDeclGroup();
return &G[0] + G.size();
}
void *getAsOpaquePtr() const { return D; }
static DeclGroupRef getFromOpaquePtr(void *Ptr) {
DeclGroupRef X;
X.D = static_cast<Decl*>(Ptr);
return X;
}
};
} // end clang namespace
namespace llvm {
// DeclGroupRef is "like a pointer", implement PointerLikeTypeTraits.
template <typename T>
class PointerLikeTypeTraits;
template <>
class PointerLikeTypeTraits<clang::DeclGroupRef> {
public:
static inline void *getAsVoidPointer(clang::DeclGroupRef P) {
return P.getAsOpaquePtr();
}
static inline clang::DeclGroupRef getFromVoidPointer(void *P) {
return clang::DeclGroupRef::getFromOpaquePtr(P);
}
enum { NumLowBitsAvailable = 0 };
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/TemplateBase.h | //===-- TemplateBase.h - Core classes for C++ templates ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides definitions which are common for all kinds of
// template representation.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_TEMPLATEBASE_H
#define LLVM_CLANG_AST_TEMPLATEBASE_H
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
namespace llvm {
class FoldingSetNodeID;
}
namespace clang {
class DiagnosticBuilder;
class Expr;
struct PrintingPolicy;
class TypeSourceInfo;
class ValueDecl;
/// \brief Represents a template argument.
class TemplateArgument {
public:
/// \brief The kind of template argument we're storing.
enum ArgKind {
/// \brief Represents an empty template argument, e.g., one that has not
/// been deduced.
Null = 0,
/// The template argument is a type.
Type,
/// The template argument is a declaration that was provided for a pointer,
/// reference, or pointer to member non-type template parameter.
Declaration,
/// The template argument is a null pointer or null pointer to member that
/// was provided for a non-type template parameter.
NullPtr,
/// The template argument is an integral value stored in an llvm::APSInt
/// that was provided for an integral non-type template parameter.
Integral,
/// The template argument is a template name that was provided for a
/// template template parameter.
Template,
/// The template argument is a pack expansion of a template name that was
/// provided for a template template parameter.
TemplateExpansion,
/// The template argument is an expression, and we've not resolved it to one
/// of the other forms yet, either because it's dependent or because we're
/// representing a non-canonical template argument (for instance, in a
/// TemplateSpecializationType). Also used to represent a non-dependent
/// __uuidof expression (a Microsoft extension).
Expression,
/// The template argument is actually a parameter pack. Arguments are stored
/// in the Args struct.
Pack
};
private:
/// \brief The kind of template argument we're storing.
struct DA {
unsigned Kind;
void *QT;
ValueDecl *D;
};
struct I {
unsigned Kind;
// We store a decomposed APSInt with the data allocated by ASTContext if
// BitWidth > 64. The memory may be shared between multiple
// TemplateArgument instances.
unsigned BitWidth : 31;
unsigned IsUnsigned : 1;
union {
uint64_t VAL; ///< Used to store the <= 64 bits integer value.
const uint64_t *pVal; ///< Used to store the >64 bits integer value.
};
void *Type;
};
struct A {
unsigned Kind;
unsigned NumArgs;
const TemplateArgument *Args;
};
struct TA {
unsigned Kind;
unsigned NumExpansions;
void *Name;
};
struct TV {
unsigned Kind;
uintptr_t V;
};
union {
struct DA DeclArg;
struct I Integer;
struct A Args;
struct TA TemplateArg;
struct TV TypeOrValue;
};
TemplateArgument(TemplateName, bool) = delete;
public:
/// \brief Construct an empty, invalid template argument.
TemplateArgument() {
TypeOrValue.Kind = Null;
TypeOrValue.V = 0;
}
/// \brief Construct a template type argument.
TemplateArgument(QualType T, bool isNullPtr = false) {
TypeOrValue.Kind = isNullPtr ? NullPtr : Type;
TypeOrValue.V = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
}
/// \brief Construct a template argument that refers to a
/// declaration, which is either an external declaration or a
/// template declaration.
TemplateArgument(ValueDecl *D, QualType QT) {
assert(D && "Expected decl");
DeclArg.Kind = Declaration;
DeclArg.QT = QT.getAsOpaquePtr();
DeclArg.D = D;
}
/// \brief Construct an integral constant template argument. The memory to
/// store the value is allocated with Ctx.
TemplateArgument(ASTContext &Ctx, const llvm::APSInt &Value, QualType Type);
/// \brief Construct an integral constant template argument with the same
/// value as Other but a different type.
TemplateArgument(const TemplateArgument &Other, QualType Type) {
Integer = Other.Integer;
Integer.Type = Type.getAsOpaquePtr();
}
/// \brief Construct a template argument that is a template.
///
/// This form of template argument is generally used for template template
/// parameters. However, the template name could be a dependent template
/// name that ends up being instantiated to a function template whose address
/// is taken.
///
/// \param Name The template name.
TemplateArgument(TemplateName Name) {
TemplateArg.Kind = Template;
TemplateArg.Name = Name.getAsVoidPointer();
TemplateArg.NumExpansions = 0;
}
/// \brief Construct a template argument that is a template pack expansion.
///
/// This form of template argument is generally used for template template
/// parameters. However, the template name could be a dependent template
/// name that ends up being instantiated to a function template whose address
/// is taken.
///
/// \param Name The template name.
///
/// \param NumExpansions The number of expansions that will be generated by
/// instantiating
TemplateArgument(TemplateName Name, Optional<unsigned> NumExpansions) {
TemplateArg.Kind = TemplateExpansion;
TemplateArg.Name = Name.getAsVoidPointer();
if (NumExpansions)
TemplateArg.NumExpansions = *NumExpansions + 1;
else
TemplateArg.NumExpansions = 0;
}
/// \brief Construct a template argument that is an expression.
///
/// This form of template argument only occurs in template argument
/// lists used for dependent types and for expression; it will not
/// occur in a non-dependent, canonical template argument list.
TemplateArgument(Expr *E) {
TypeOrValue.Kind = Expression;
TypeOrValue.V = reinterpret_cast<uintptr_t>(E);
}
/// \brief Construct a template argument that is a template argument pack.
///
/// We assume that storage for the template arguments provided
/// outlives the TemplateArgument itself.
TemplateArgument(const TemplateArgument *Args, unsigned NumArgs) {
this->Args.Kind = Pack;
this->Args.Args = Args;
this->Args.NumArgs = NumArgs;
}
static TemplateArgument getEmptyPack() {
return TemplateArgument((TemplateArgument*)nullptr, 0);
}
/// \brief Create a new template argument pack by copying the given set of
/// template arguments.
static TemplateArgument CreatePackCopy(ASTContext &Context,
const TemplateArgument *Args,
unsigned NumArgs);
/// \brief Return the kind of stored template argument.
ArgKind getKind() const { return (ArgKind)TypeOrValue.Kind; }
/// \brief Determine whether this template argument has no value.
bool isNull() const { return getKind() == Null; }
/// \brief Whether this template argument is dependent on a template
/// parameter such that its result can change from one instantiation to
/// another.
bool isDependent() const;
/// \brief Whether this template argument is dependent on a template
/// parameter.
bool isInstantiationDependent() const;
/// \brief Whether this template argument contains an unexpanded
/// parameter pack.
bool containsUnexpandedParameterPack() const;
/// \brief Determine whether this template argument is a pack expansion.
bool isPackExpansion() const;
/// \brief Retrieve the type for a type template argument.
QualType getAsType() const {
assert(getKind() == Type && "Unexpected kind");
return QualType::getFromOpaquePtr(reinterpret_cast<void*>(TypeOrValue.V));
}
/// \brief Retrieve the declaration for a declaration non-type
/// template argument.
ValueDecl *getAsDecl() const {
assert(getKind() == Declaration && "Unexpected kind");
return DeclArg.D;
}
QualType getParamTypeForDecl() const {
assert(getKind() == Declaration && "Unexpected kind");
return QualType::getFromOpaquePtr(DeclArg.QT);
}
/// \brief Retrieve the type for null non-type template argument.
QualType getNullPtrType() const {
assert(getKind() == NullPtr && "Unexpected kind");
return QualType::getFromOpaquePtr(reinterpret_cast<void*>(TypeOrValue.V));
}
/// \brief Retrieve the template name for a template name argument.
TemplateName getAsTemplate() const {
assert(getKind() == Template && "Unexpected kind");
return TemplateName::getFromVoidPointer(TemplateArg.Name);
}
/// \brief Retrieve the template argument as a template name; if the argument
/// is a pack expansion, return the pattern as a template name.
TemplateName getAsTemplateOrTemplatePattern() const {
assert((getKind() == Template || getKind() == TemplateExpansion) &&
"Unexpected kind");
return TemplateName::getFromVoidPointer(TemplateArg.Name);
}
/// \brief Retrieve the number of expansions that a template template argument
/// expansion will produce, if known.
Optional<unsigned> getNumTemplateExpansions() const;
/// \brief Retrieve the template argument as an integral value.
// FIXME: Provide a way to read the integral data without copying the value.
llvm::APSInt getAsIntegral() const {
assert(getKind() == Integral && "Unexpected kind");
using namespace llvm;
if (Integer.BitWidth <= 64)
return APSInt(APInt(Integer.BitWidth, Integer.VAL), Integer.IsUnsigned);
unsigned NumWords = APInt::getNumWords(Integer.BitWidth);
return APSInt(APInt(Integer.BitWidth, makeArrayRef(Integer.pVal, NumWords)),
Integer.IsUnsigned);
}
/// \brief Retrieve the type of the integral value.
QualType getIntegralType() const {
assert(getKind() == Integral && "Unexpected kind");
return QualType::getFromOpaquePtr(Integer.Type);
}
void setIntegralType(QualType T) {
assert(getKind() == Integral && "Unexpected kind");
Integer.Type = T.getAsOpaquePtr();
}
/// \brief Retrieve the template argument as an expression.
Expr *getAsExpr() const {
assert(getKind() == Expression && "Unexpected kind");
return reinterpret_cast<Expr *>(TypeOrValue.V);
}
/// \brief Iterator that traverses the elements of a template argument pack.
typedef const TemplateArgument * pack_iterator;
/// \brief Iterator referencing the first argument of a template argument
/// pack.
pack_iterator pack_begin() const {
assert(getKind() == Pack);
return Args.Args;
}
/// \brief Iterator referencing one past the last argument of a template
/// argument pack.
pack_iterator pack_end() const {
assert(getKind() == Pack);
return Args.Args + Args.NumArgs;
}
/// \brief Iterator range referencing all of the elements of a template
/// argument pack.
llvm::iterator_range<pack_iterator> pack_elements() const {
return llvm::make_range(pack_begin(), pack_end());
}
/// \brief The number of template arguments in the given template argument
/// pack.
unsigned pack_size() const {
assert(getKind() == Pack);
return Args.NumArgs;
}
/// \brief Return the array of arguments in this template argument pack.
ArrayRef<TemplateArgument> getPackAsArray() const {
assert(getKind() == Pack);
return llvm::makeArrayRef(Args.Args, Args.NumArgs);
}
/// \brief Determines whether two template arguments are superficially the
/// same.
bool structurallyEquals(const TemplateArgument &Other) const;
/// \brief When the template argument is a pack expansion, returns
/// the pattern of the pack expansion.
TemplateArgument getPackExpansionPattern() const;
/// \brief Print this template argument to the given output stream.
void print(const PrintingPolicy &Policy, raw_ostream &Out) const;
/// \brief Used to insert TemplateArguments into FoldingSets.
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) const;
};
/// Location information for a TemplateArgument.
struct TemplateArgumentLocInfo {
private:
struct T {
// FIXME: We'd like to just use the qualifier in the TemplateName,
// but template arguments get canonicalized too quickly.
NestedNameSpecifier *Qualifier;
void *QualifierLocData;
unsigned TemplateNameLoc;
unsigned EllipsisLoc;
};
union {
struct T Template;
Expr *Expression;
TypeSourceInfo *Declarator;
};
public:
TemplateArgumentLocInfo();
TemplateArgumentLocInfo(TypeSourceInfo *TInfo) : Declarator(TInfo) {}
TemplateArgumentLocInfo(Expr *E) : Expression(E) {}
TemplateArgumentLocInfo(NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateNameLoc,
SourceLocation EllipsisLoc)
{
Template.Qualifier = QualifierLoc.getNestedNameSpecifier();
Template.QualifierLocData = QualifierLoc.getOpaqueData();
Template.TemplateNameLoc = TemplateNameLoc.getRawEncoding();
Template.EllipsisLoc = EllipsisLoc.getRawEncoding();
}
TypeSourceInfo *getAsTypeSourceInfo() const {
return Declarator;
}
Expr *getAsExpr() const {
return Expression;
}
NestedNameSpecifierLoc getTemplateQualifierLoc() const {
return NestedNameSpecifierLoc(Template.Qualifier,
Template.QualifierLocData);
}
SourceLocation getTemplateNameLoc() const {
return SourceLocation::getFromRawEncoding(Template.TemplateNameLoc);
}
SourceLocation getTemplateEllipsisLoc() const {
return SourceLocation::getFromRawEncoding(Template.EllipsisLoc);
}
};
/// Location wrapper for a TemplateArgument. TemplateArgument is to
/// TemplateArgumentLoc as Type is to TypeLoc.
class TemplateArgumentLoc {
TemplateArgument Argument;
TemplateArgumentLocInfo LocInfo;
public:
TemplateArgumentLoc() {}
TemplateArgumentLoc(const TemplateArgument &Argument,
TemplateArgumentLocInfo Opaque)
: Argument(Argument), LocInfo(Opaque) {
}
TemplateArgumentLoc(const TemplateArgument &Argument, TypeSourceInfo *TInfo)
: Argument(Argument), LocInfo(TInfo) {
assert(Argument.getKind() == TemplateArgument::Type);
}
TemplateArgumentLoc(const TemplateArgument &Argument, Expr *E)
: Argument(Argument), LocInfo(E) {
assert(Argument.getKind() == TemplateArgument::Expression);
}
TemplateArgumentLoc(const TemplateArgument &Argument,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateNameLoc,
SourceLocation EllipsisLoc = SourceLocation())
: Argument(Argument), LocInfo(QualifierLoc, TemplateNameLoc, EllipsisLoc) {
assert(Argument.getKind() == TemplateArgument::Template ||
Argument.getKind() == TemplateArgument::TemplateExpansion);
}
/// \brief - Fetches the primary location of the argument.
SourceLocation getLocation() const {
if (Argument.getKind() == TemplateArgument::Template ||
Argument.getKind() == TemplateArgument::TemplateExpansion)
return getTemplateNameLoc();
return getSourceRange().getBegin();
}
/// \brief - Fetches the full source range of the argument.
SourceRange getSourceRange() const LLVM_READONLY;
const TemplateArgument &getArgument() const {
return Argument;
}
TemplateArgumentLocInfo getLocInfo() const {
return LocInfo;
}
TypeSourceInfo *getTypeSourceInfo() const {
assert(Argument.getKind() == TemplateArgument::Type);
return LocInfo.getAsTypeSourceInfo();
}
Expr *getSourceExpression() const {
assert(Argument.getKind() == TemplateArgument::Expression);
return LocInfo.getAsExpr();
}
Expr *getSourceDeclExpression() const {
assert(Argument.getKind() == TemplateArgument::Declaration);
return LocInfo.getAsExpr();
}
Expr *getSourceNullPtrExpression() const {
assert(Argument.getKind() == TemplateArgument::NullPtr);
return LocInfo.getAsExpr();
}
Expr *getSourceIntegralExpression() const {
assert(Argument.getKind() == TemplateArgument::Integral);
return LocInfo.getAsExpr();
}
NestedNameSpecifierLoc getTemplateQualifierLoc() const {
assert(Argument.getKind() == TemplateArgument::Template ||
Argument.getKind() == TemplateArgument::TemplateExpansion);
return LocInfo.getTemplateQualifierLoc();
}
SourceLocation getTemplateNameLoc() const {
assert(Argument.getKind() == TemplateArgument::Template ||
Argument.getKind() == TemplateArgument::TemplateExpansion);
return LocInfo.getTemplateNameLoc();
}
SourceLocation getTemplateEllipsisLoc() const {
assert(Argument.getKind() == TemplateArgument::TemplateExpansion);
return LocInfo.getTemplateEllipsisLoc();
}
};
/// A convenient class for passing around template argument
/// information. Designed to be passed by reference.
class TemplateArgumentListInfo {
SmallVector<TemplateArgumentLoc, 8> Arguments;
SourceLocation LAngleLoc;
SourceLocation RAngleLoc;
// This can leak if used in an AST node, use ASTTemplateArgumentListInfo
// instead.
void* operator new(size_t bytes, ASTContext& C);
public:
TemplateArgumentListInfo() {}
TemplateArgumentListInfo(SourceLocation LAngleLoc,
SourceLocation RAngleLoc)
: LAngleLoc(LAngleLoc), RAngleLoc(RAngleLoc) {}
SourceLocation getLAngleLoc() const { return LAngleLoc; }
SourceLocation getRAngleLoc() const { return RAngleLoc; }
void setLAngleLoc(SourceLocation Loc) { LAngleLoc = Loc; }
void setRAngleLoc(SourceLocation Loc) { RAngleLoc = Loc; }
unsigned size() const { return Arguments.size(); }
const TemplateArgumentLoc *getArgumentArray() const {
return Arguments.data();
}
const TemplateArgumentLoc &operator[](unsigned I) const {
return Arguments[I];
}
TemplateArgumentLoc &operator[](unsigned I) {
return Arguments[I];
}
void addArgument(const TemplateArgumentLoc &Loc) {
Arguments.push_back(Loc);
}
};
/// \brief Represents an explicit template argument list in C++, e.g.,
/// the "<int>" in "sort<int>".
/// This is safe to be used inside an AST node, in contrast with
/// TemplateArgumentListInfo.
struct ASTTemplateArgumentListInfo {
/// \brief The source location of the left angle bracket ('<').
SourceLocation LAngleLoc;
/// \brief The source location of the right angle bracket ('>').
SourceLocation RAngleLoc;
union {
/// \brief The number of template arguments in TemplateArgs.
/// The actual template arguments (if any) are stored after the
/// ExplicitTemplateArgumentList structure.
unsigned NumTemplateArgs;
/// Force ASTTemplateArgumentListInfo to the right alignment
/// for the following array of TemplateArgumentLocs.
llvm::AlignedCharArray<
llvm::AlignOf<TemplateArgumentLoc>::Alignment, 1> Aligner;
};
/// \brief Retrieve the template arguments
TemplateArgumentLoc *getTemplateArgs() {
return reinterpret_cast<TemplateArgumentLoc *> (this + 1);
}
/// \brief Retrieve the template arguments
const TemplateArgumentLoc *getTemplateArgs() const {
return reinterpret_cast<const TemplateArgumentLoc *> (this + 1);
}
const TemplateArgumentLoc &operator[](unsigned I) const {
return getTemplateArgs()[I];
}
static const ASTTemplateArgumentListInfo *Create(ASTContext &C,
const TemplateArgumentListInfo &List);
void initializeFrom(const TemplateArgumentListInfo &List);
void initializeFrom(const TemplateArgumentListInfo &List,
bool &Dependent, bool &InstantiationDependent,
bool &ContainsUnexpandedParameterPack);
void copyInto(TemplateArgumentListInfo &List) const;
static std::size_t sizeFor(unsigned NumTemplateArgs);
};
/// \brief Extends ASTTemplateArgumentListInfo with the source location
/// information for the template keyword; this is used as part of the
/// representation of qualified identifiers, such as S<T>::template apply<T>.
struct ASTTemplateKWAndArgsInfo : public ASTTemplateArgumentListInfo {
typedef ASTTemplateArgumentListInfo Base;
// NOTE: the source location of the (optional) template keyword is
// stored after all template arguments.
/// \brief Get the source location of the template keyword.
SourceLocation getTemplateKeywordLoc() const {
return *reinterpret_cast<const SourceLocation*>
(getTemplateArgs() + NumTemplateArgs);
}
/// \brief Sets the source location of the template keyword.
void setTemplateKeywordLoc(SourceLocation TemplateKWLoc) {
*reinterpret_cast<SourceLocation*>
(getTemplateArgs() + NumTemplateArgs) = TemplateKWLoc;
}
static const ASTTemplateKWAndArgsInfo*
Create(ASTContext &C, SourceLocation TemplateKWLoc,
const TemplateArgumentListInfo &List);
void initializeFrom(SourceLocation TemplateKWLoc,
const TemplateArgumentListInfo &List);
void initializeFrom(SourceLocation TemplateKWLoc,
const TemplateArgumentListInfo &List,
bool &Dependent, bool &InstantiationDependent,
bool &ContainsUnexpandedParameterPack);
void initializeFrom(SourceLocation TemplateKWLoc);
static std::size_t sizeFor(unsigned NumTemplateArgs);
};
const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
const TemplateArgument &Arg);
inline TemplateSpecializationType::iterator
TemplateSpecializationType::end() const {
return getArgs() + getNumArgs();
}
inline DependentTemplateSpecializationType::iterator
DependentTemplateSpecializationType::end() const {
return getArgs() + getNumArgs();
}
inline const TemplateArgument &
TemplateSpecializationType::getArg(unsigned Idx) const {
assert(Idx < getNumArgs() && "Template argument out of range");
return getArgs()[Idx];
}
inline const TemplateArgument &
DependentTemplateSpecializationType::getArg(unsigned Idx) const {
assert(Idx < getNumArgs() && "Template argument out of range");
return getArgs()[Idx];
}
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/ExternalASTSource.h | //===--- ExternalASTSource.h - Abstract External AST Interface --*- 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 ExternalASTSource interface, which enables
// construction of AST nodes from some external source.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_EXTERNALASTSOURCE_H
#define LLVM_CLANG_AST_EXTERNALASTSOURCE_H
#include "clang/AST/CharUnits.h"
#include "clang/AST/DeclBase.h"
#include "llvm/ADT/DenseMap.h"
namespace clang {
class ASTConsumer;
class CXXBaseSpecifier;
class CXXCtorInitializer;
class DeclarationName;
class ExternalSemaSource; // layering violation required for downcasting
class FieldDecl;
class Module;
class NamedDecl;
class RecordDecl;
class Selector;
class Stmt;
class TagDecl;
/// \brief Enumeration describing the result of loading information from
/// an external source.
enum ExternalLoadResult {
/// \brief Loading the external information has succeeded.
ELR_Success,
/// \brief Loading the external information has failed.
ELR_Failure,
/// \brief The external information has already been loaded, and therefore
/// no additional processing is required.
ELR_AlreadyLoaded
};
/// \brief Abstract interface for external sources of AST nodes.
///
/// External AST sources provide AST nodes constructed from some
/// external source, such as a precompiled header. External AST
/// sources can resolve types and declarations from abstract IDs into
/// actual type and declaration nodes, and read parts of declaration
/// contexts.
class ExternalASTSource : public RefCountedBase<ExternalASTSource> {
/// Generation number for this external AST source. Must be increased
/// whenever we might have added new redeclarations for existing decls.
uint32_t CurrentGeneration;
/// \brief Whether this AST source also provides information for
/// semantic analysis.
bool SemaSource;
friend class ExternalSemaSource;
public:
ExternalASTSource() : CurrentGeneration(0), SemaSource(false) { }
virtual ~ExternalASTSource();
/// \brief RAII class for safely pairing a StartedDeserializing call
/// with FinishedDeserializing.
class Deserializing {
ExternalASTSource *Source;
public:
explicit Deserializing(ExternalASTSource *source) : Source(source) {
assert(Source);
Source->StartedDeserializing();
}
~Deserializing() {
Source->FinishedDeserializing();
}
};
/// \brief Get the current generation of this AST source. This number
/// is incremented each time the AST source lazily extends an existing
/// entity.
uint32_t getGeneration() const { return CurrentGeneration; }
/// \brief Resolve a declaration ID into a declaration, potentially
/// building a new declaration.
///
/// This method only needs to be implemented if the AST source ever
/// passes back decl sets as VisibleDeclaration objects.
///
/// The default implementation of this method is a no-op.
virtual Decl *GetExternalDecl(uint32_t ID);
/// \brief Resolve a selector ID into a selector.
///
/// This operation only needs to be implemented if the AST source
/// returns non-zero for GetNumKnownSelectors().
///
/// The default implementation of this method is a no-op.
virtual Selector GetExternalSelector(uint32_t ID);
/// \brief Returns the number of selectors known to the external AST
/// source.
///
/// The default implementation of this method is a no-op.
virtual uint32_t GetNumExternalSelectors();
/// \brief Resolve the offset of a statement in the decl stream into
/// a statement.
///
/// This operation is meant to be used via a LazyOffsetPtr. It only
/// needs to be implemented if the AST source uses methods like
/// FunctionDecl::setLazyBody when building decls.
///
/// The default implementation of this method is a no-op.
virtual Stmt *GetExternalDeclStmt(uint64_t Offset);
/// \brief Resolve the offset of a set of C++ constructor initializers in
/// the decl stream into an array of initializers.
///
/// The default implementation of this method is a no-op.
virtual CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset);
/// \brief Resolve the offset of a set of C++ base specifiers in the decl
/// stream into an array of specifiers.
///
/// The default implementation of this method is a no-op.
virtual CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset);
/// \brief Update an out-of-date identifier.
virtual void updateOutOfDateIdentifier(IdentifierInfo &II) { }
/// \brief Find all declarations with the given name in the given context,
/// and add them to the context by calling SetExternalVisibleDeclsForName
/// or SetNoExternalVisibleDeclsForName.
/// \return \c true if any declarations might have been found, \c false if
/// we definitely have no declarations with tbis name.
///
/// The default implementation of this method is a no-op returning \c false.
virtual bool
FindExternalVisibleDeclsByName(const DeclContext *DC, DeclarationName Name);
/// \brief Ensures that the table of all visible declarations inside this
/// context is up to date.
///
/// The default implementation of this function is a no-op.
virtual void completeVisibleDeclsMap(const DeclContext *DC);
/// \brief Retrieve the module that corresponds to the given module ID.
virtual Module *getModule(unsigned ID) { return nullptr; }
/// \brief Holds everything needed to generate debug info for an
/// imported module or precompiled header file.
struct ASTSourceDescriptor {
std::string ModuleName;
std::string Path;
std::string ASTFile;
uint64_t Signature;
};
/// \brief Return a descriptor for the corresponding module, if one exists.
virtual llvm::Optional<ASTSourceDescriptor> getSourceDescriptor(unsigned ID);
/// \brief Return a descriptor for the module.
virtual ASTSourceDescriptor getSourceDescriptor(const Module &M);
/// \brief Finds all declarations lexically contained within the given
/// DeclContext, after applying an optional filter predicate.
///
/// \param isKindWeWant a predicate function that returns true if the passed
/// declaration kind is one we are looking for. If NULL, all declarations
/// are returned.
///
/// \return an indication of whether the load succeeded or failed.
///
/// The default implementation of this method is a no-op.
virtual ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
bool (*isKindWeWant)(Decl::Kind),
SmallVectorImpl<Decl*> &Result);
/// \brief Finds all declarations lexically contained within the given
/// DeclContext.
///
/// \return true if an error occurred
ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
SmallVectorImpl<Decl*> &Result) {
return FindExternalLexicalDecls(DC, nullptr, Result);
}
template <typename DeclTy>
ExternalLoadResult FindExternalLexicalDeclsBy(const DeclContext *DC,
SmallVectorImpl<Decl*> &Result) {
return FindExternalLexicalDecls(DC, DeclTy::classofKind, Result);
}
/// \brief Get the decls that are contained in a file in the Offset/Length
/// range. \p Length can be 0 to indicate a point at \p Offset instead of
/// a range.
virtual void FindFileRegionDecls(FileID File, unsigned Offset,
unsigned Length,
SmallVectorImpl<Decl *> &Decls);
/// \brief Gives the external AST source an opportunity to complete
/// the redeclaration chain for a declaration. Called each time we
/// need the most recent declaration of a declaration after the
/// generation count is incremented.
virtual void CompleteRedeclChain(const Decl *D);
/// \brief Gives the external AST source an opportunity to complete
/// an incomplete type.
virtual void CompleteType(TagDecl *Tag);
/// \brief Gives the external AST source an opportunity to complete an
/// incomplete Objective-C class.
///
/// This routine will only be invoked if the "externally completed" bit is
/// set on the ObjCInterfaceDecl via the function
/// \c ObjCInterfaceDecl::setExternallyCompleted().
virtual void CompleteType(ObjCInterfaceDecl *Class);
/// \brief Loads comment ranges.
virtual void ReadComments();
/// \brief Notify ExternalASTSource that we started deserialization of
/// a decl or type so until FinishedDeserializing is called there may be
/// decls that are initializing. Must be paired with FinishedDeserializing.
///
/// The default implementation of this method is a no-op.
virtual void StartedDeserializing();
/// \brief Notify ExternalASTSource that we finished the deserialization of
/// a decl or type. Must be paired with StartedDeserializing.
///
/// The default implementation of this method is a no-op.
virtual void FinishedDeserializing();
/// \brief Function that will be invoked when we begin parsing a new
/// translation unit involving this external AST source.
///
/// The default implementation of this method is a no-op.
virtual void StartTranslationUnit(ASTConsumer *Consumer);
/// \brief Print any statistics that have been gathered regarding
/// the external AST source.
///
/// The default implementation of this method is a no-op.
virtual void PrintStats();
/// \brief Perform layout on the given record.
///
/// This routine allows the external AST source to provide an specific
/// layout for a record, overriding the layout that would normally be
/// constructed. It is intended for clients who receive specific layout
/// details rather than source code (such as LLDB). The client is expected
/// to fill in the field offsets, base offsets, virtual base offsets, and
/// complete object size.
///
/// \param Record The record whose layout is being requested.
///
/// \param Size The final size of the record, in bits.
///
/// \param Alignment The final alignment of the record, in bits.
///
/// \param FieldOffsets The offset of each of the fields within the record,
/// expressed in bits. All of the fields must be provided with offsets.
///
/// \param BaseOffsets The offset of each of the direct, non-virtual base
/// classes. If any bases are not given offsets, the bases will be laid
/// out according to the ABI.
///
/// \param VirtualBaseOffsets The offset of each of the virtual base classes
/// (either direct or not). If any bases are not given offsets, the bases will be laid
/// out according to the ABI.
///
/// \returns true if the record layout was provided, false otherwise.
virtual bool layoutRecordType(
const RecordDecl *Record, uint64_t &Size, uint64_t &Alignment,
llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffsets,
llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets,
llvm::DenseMap<const CXXRecordDecl *, CharUnits> &VirtualBaseOffsets);
//===--------------------------------------------------------------------===//
// Queries for performance analysis.
//===--------------------------------------------------------------------===//
struct MemoryBufferSizes {
size_t malloc_bytes;
size_t mmap_bytes;
MemoryBufferSizes(size_t malloc_bytes, size_t mmap_bytes)
: malloc_bytes(malloc_bytes), mmap_bytes(mmap_bytes) {}
};
/// Return the amount of memory used by memory buffers, breaking down
/// by heap-backed versus mmap'ed memory.
MemoryBufferSizes getMemoryBufferSizes() const {
MemoryBufferSizes sizes(0, 0);
getMemoryBufferSizes(sizes);
return sizes;
}
virtual void getMemoryBufferSizes(MemoryBufferSizes &sizes) const;
protected:
static DeclContextLookupResult
SetExternalVisibleDeclsForName(const DeclContext *DC,
DeclarationName Name,
ArrayRef<NamedDecl*> Decls);
static DeclContextLookupResult
SetNoExternalVisibleDeclsForName(const DeclContext *DC,
DeclarationName Name);
/// \brief Increment the current generation.
uint32_t incrementGeneration(ASTContext &C);
};
/// \brief A lazy pointer to an AST node (of base type T) that resides
/// within an external AST source.
///
/// The AST node is identified within the external AST source by a
/// 63-bit offset, and can be retrieved via an operation on the
/// external AST source itself.
template<typename T, typename OffsT, T* (ExternalASTSource::*Get)(OffsT Offset)>
struct LazyOffsetPtr {
/// \brief Either a pointer to an AST node or the offset within the
/// external AST source where the AST node can be found.
///
/// If the low bit is clear, a pointer to the AST node. If the low
/// bit is set, the upper 63 bits are the offset.
mutable uint64_t Ptr;
public:
LazyOffsetPtr() : Ptr(0) { }
explicit LazyOffsetPtr(T *Ptr) : Ptr(reinterpret_cast<uint64_t>(Ptr)) { }
explicit LazyOffsetPtr(uint64_t Offset) : Ptr((Offset << 1) | 0x01) {
assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits");
if (Offset == 0)
Ptr = 0;
}
LazyOffsetPtr &operator=(T *Ptr) {
this->Ptr = reinterpret_cast<uint64_t>(Ptr);
return *this;
}
LazyOffsetPtr &operator=(uint64_t Offset) {
assert((Offset << 1 >> 1) == Offset && "Offsets must require < 63 bits");
if (Offset == 0)
Ptr = 0;
else
Ptr = (Offset << 1) | 0x01;
return *this;
}
/// \brief Whether this pointer is non-NULL.
///
/// This operation does not require the AST node to be deserialized.
explicit operator bool() const { return Ptr != 0; }
/// \brief Whether this pointer is non-NULL.
///
/// This operation does not require the AST node to be deserialized.
bool isValid() const { return Ptr != 0; }
/// \brief Whether this pointer is currently stored as an offset.
bool isOffset() const { return Ptr & 0x01; }
/// \brief Retrieve the pointer to the AST node that this lazy pointer
///
/// \param Source the external AST source.
///
/// \returns a pointer to the AST node.
T* get(ExternalASTSource *Source) const {
if (isOffset()) {
assert(Source &&
"Cannot deserialize a lazy pointer without an AST source");
Ptr = reinterpret_cast<uint64_t>((Source->*Get)(Ptr >> 1));
}
return reinterpret_cast<T*>(Ptr);
}
};
/// \brief A lazy value (of type T) that is within an AST node of type Owner,
/// where the value might change in later generations of the external AST
/// source.
template<typename Owner, typename T, void (ExternalASTSource::*Update)(Owner)>
struct LazyGenerationalUpdatePtr {
/// A cache of the value of this pointer, in the most recent generation in
/// which we queried it.
struct LazyData {
LazyData(ExternalASTSource *Source, T Value)
: ExternalSource(Source), LastGeneration(0), LastValue(Value) {}
ExternalASTSource *ExternalSource;
uint32_t LastGeneration;
T LastValue;
};
// Our value is represented as simply T if there is no external AST source.
typedef llvm::PointerUnion<T, LazyData*> ValueType;
ValueType Value;
LazyGenerationalUpdatePtr(ValueType V) : Value(V) {}
// Defined in ASTContext.h
static ValueType makeValue(const ASTContext &Ctx, T Value);
public:
explicit LazyGenerationalUpdatePtr(const ASTContext &Ctx, T Value = T())
: Value(makeValue(Ctx, Value)) {}
/// Create a pointer that is not potentially updated by later generations of
/// the external AST source.
enum NotUpdatedTag { NotUpdated };
LazyGenerationalUpdatePtr(NotUpdatedTag, T Value = T())
: Value(Value) {}
/// Forcibly set this pointer (which must be lazy) as needing updates.
void markIncomplete() {
Value.template get<LazyData *>()->LastGeneration = 0;
}
/// Set the value of this pointer, in the current generation.
void set(T NewValue) {
if (LazyData *LazyVal = Value.template dyn_cast<LazyData*>()) {
LazyVal->LastValue = NewValue;
return;
}
Value = NewValue;
}
/// Set the value of this pointer, for this and all future generations.
void setNotUpdated(T NewValue) { Value = NewValue; }
/// Get the value of this pointer, updating its owner if necessary.
T get(Owner O) {
if (LazyData *LazyVal = Value.template dyn_cast<LazyData*>()) {
if (LazyVal->LastGeneration != LazyVal->ExternalSource->getGeneration()) {
LazyVal->LastGeneration = LazyVal->ExternalSource->getGeneration();
(LazyVal->ExternalSource->*Update)(O);
}
return LazyVal->LastValue;
}
return Value.template get<T>();
}
/// Get the most recently computed value of this pointer without updating it.
T getNotUpdated() const {
if (LazyData *LazyVal = Value.template dyn_cast<LazyData*>())
return LazyVal->LastValue;
return Value.template get<T>();
}
void *getOpaqueValue() { return Value.getOpaqueValue(); }
static LazyGenerationalUpdatePtr getFromOpaqueValue(void *Ptr) {
return LazyGenerationalUpdatePtr(ValueType::getFromOpaqueValue(Ptr));
}
};
} // end namespace clang
/// Specialize PointerLikeTypeTraits to allow LazyGenerationalUpdatePtr to be
/// placed into a PointerUnion.
namespace llvm {
template<typename Owner, typename T,
void (clang::ExternalASTSource::*Update)(Owner)>
struct PointerLikeTypeTraits<
clang::LazyGenerationalUpdatePtr<Owner, T, Update>> {
typedef clang::LazyGenerationalUpdatePtr<Owner, T, Update> Ptr;
static void *getAsVoidPointer(Ptr P) { return P.getOpaqueValue(); }
static Ptr getFromVoidPointer(void *P) { return Ptr::getFromOpaqueValue(P); }
enum {
NumLowBitsAvailable = PointerLikeTypeTraits<T>::NumLowBitsAvailable - 1
};
};
}
namespace clang {
/// \brief Represents a lazily-loaded vector of data.
///
/// The lazily-loaded vector of data contains data that is partially loaded
/// from an external source and partially added by local translation. The
/// items loaded from the external source are loaded lazily, when needed for
/// iteration over the complete vector.
template<typename T, typename Source,
void (Source::*Loader)(SmallVectorImpl<T>&),
unsigned LoadedStorage = 2, unsigned LocalStorage = 4>
class LazyVector {
SmallVector<T, LoadedStorage> Loaded;
SmallVector<T, LocalStorage> Local;
public:
/// Iteration over the elements in the vector.
///
/// In a complete iteration, the iterator walks the range [-M, N),
/// where negative values are used to indicate elements
/// loaded from the external source while non-negative values are used to
/// indicate elements added via \c push_back().
/// However, to provide iteration in source order (for, e.g., chained
/// precompiled headers), dereferencing the iterator flips the negative
/// values (corresponding to loaded entities), so that position -M
/// corresponds to element 0 in the loaded entities vector, position -M+1
/// corresponds to element 1 in the loaded entities vector, etc. This
/// gives us a reasonably efficient, source-order walk.
///
/// We define this as a wrapping iterator around an int. The
/// iterator_adaptor_base class forwards the iterator methods to basic integer
/// arithmetic.
class iterator : public llvm::iterator_adaptor_base<
iterator, int, std::random_access_iterator_tag, T, int> {
LazyVector *Self;
iterator(LazyVector *Self, int Position)
: iterator::iterator_adaptor_base(Position), Self(Self) {}
bool isLoaded() const { return this->I < 0; }
friend class LazyVector;
public:
iterator() : iterator(nullptr, 0) {}
typename iterator::reference operator*() const {
if (isLoaded())
return Self->Loaded.end()[this->I];
return Self->Local.begin()[this->I];
}
};
iterator begin(Source *source, bool LocalOnly = false) {
if (LocalOnly)
return iterator(this, 0);
if (source)
(source->*Loader)(Loaded);
return iterator(this, -(int)Loaded.size());
}
iterator end() {
return iterator(this, Local.size());
}
void push_back(const T& LocalValue) {
Local.push_back(LocalValue);
}
void erase(iterator From, iterator To) {
if (From.isLoaded() && To.isLoaded()) {
Loaded.erase(&*From, &*To);
return;
}
if (From.isLoaded()) {
Loaded.erase(&*From, Loaded.end());
From = begin(nullptr, true);
}
Local.erase(&*From, &*To);
}
};
/// \brief A lazy pointer to a statement.
typedef LazyOffsetPtr<Stmt, uint64_t, &ExternalASTSource::GetExternalDeclStmt>
LazyDeclStmtPtr;
/// \brief A lazy pointer to a declaration.
typedef LazyOffsetPtr<Decl, uint32_t, &ExternalASTSource::GetExternalDecl>
LazyDeclPtr;
/// \brief A lazy pointer to a set of CXXCtorInitializers.
typedef LazyOffsetPtr<CXXCtorInitializer *, uint64_t,
&ExternalASTSource::GetExternalCXXCtorInitializers>
LazyCXXCtorInitializersPtr;
/// \brief A lazy pointer to a set of CXXBaseSpecifiers.
typedef LazyOffsetPtr<CXXBaseSpecifier, uint64_t,
&ExternalASTSource::GetExternalCXXBaseSpecifiers>
LazyCXXBaseSpecifiersPtr;
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/TypeOrdering.h | //===-------------- TypeOrdering.h - Total ordering for types -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Allows QualTypes to be sorted and hence used in maps and sets.
///
/// Defines clang::QualTypeOrdering, a total ordering on clang::QualType,
/// and hence enables QualType values to be sorted and to be used in
/// std::maps, std::sets, llvm::DenseMaps, and llvm::DenseSets.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_TYPEORDERING_H
#define LLVM_CLANG_AST_TYPEORDERING_H
#include "clang/AST/CanonicalType.h"
#include "clang/AST/Type.h"
#include <functional>
namespace clang {
/// \brief Function object that provides a total ordering on QualType values.
struct QualTypeOrdering {
bool operator()(QualType T1, QualType T2) const {
return std::less<void*>()(T1.getAsOpaquePtr(), T2.getAsOpaquePtr());
}
};
}
namespace llvm {
template<class> struct DenseMapInfo;
template<> struct DenseMapInfo<clang::QualType> {
static inline clang::QualType getEmptyKey() { return clang::QualType(); }
static inline clang::QualType getTombstoneKey() {
using clang::QualType;
return QualType::getFromOpaquePtr(reinterpret_cast<clang::Type *>(-1));
}
static unsigned getHashValue(clang::QualType Val) {
return (unsigned)((uintptr_t)Val.getAsOpaquePtr()) ^
((unsigned)((uintptr_t)Val.getAsOpaquePtr() >> 9));
}
static bool isEqual(clang::QualType LHS, clang::QualType RHS) {
return LHS == RHS;
}
};
template<> struct DenseMapInfo<clang::CanQualType> {
static inline clang::CanQualType getEmptyKey() {
return clang::CanQualType();
}
static inline clang::CanQualType getTombstoneKey() {
using clang::CanQualType;
return CanQualType::getFromOpaquePtr(reinterpret_cast<clang::Type *>(-1));
}
static unsigned getHashValue(clang::CanQualType Val) {
return (unsigned)((uintptr_t)Val.getAsOpaquePtr()) ^
((unsigned)((uintptr_t)Val.getAsOpaquePtr() >> 9));
}
static bool isEqual(clang::CanQualType LHS, clang::CanQualType RHS) {
return LHS == RHS;
}
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/StmtIterator.h | //===--- StmtIterator.h - Iterators for Statements --------------*- 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 StmtIterator and ConstStmtIterator classes.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_STMTITERATOR_H
#define LLVM_CLANG_AST_STMTITERATOR_H
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DataTypes.h"
#include <cassert>
#include <cstddef>
#include <iterator>
#include <utility>
namespace clang {
class Stmt;
class Decl;
class VariableArrayType;
class StmtIteratorBase {
protected:
enum { StmtMode = 0x0, SizeOfTypeVAMode = 0x1, DeclGroupMode = 0x2,
Flags = 0x3 };
union {
Stmt **stmt;
Decl **DGI;
};
uintptr_t RawVAPtr;
Decl **DGE;
bool inDeclGroup() const {
return (RawVAPtr & Flags) == DeclGroupMode;
}
bool inSizeOfTypeVA() const {
return (RawVAPtr & Flags) == SizeOfTypeVAMode;
}
bool inStmt() const {
return (RawVAPtr & Flags) == StmtMode;
}
const VariableArrayType *getVAPtr() const {
return reinterpret_cast<const VariableArrayType*>(RawVAPtr & ~Flags);
}
void setVAPtr(const VariableArrayType *P) {
assert (inDeclGroup() || inSizeOfTypeVA());
RawVAPtr = reinterpret_cast<uintptr_t>(P) | (RawVAPtr & Flags);
}
void NextDecl(bool ImmediateAdvance = true);
bool HandleDecl(Decl* D);
void NextVA();
Stmt*& GetDeclExpr() const;
StmtIteratorBase(Stmt **s) : stmt(s), RawVAPtr(0) {}
StmtIteratorBase(const VariableArrayType *t);
StmtIteratorBase(Decl **dgi, Decl **dge);
StmtIteratorBase() : stmt(nullptr), RawVAPtr(0) {}
};
template <typename DERIVED, typename REFERENCE>
class StmtIteratorImpl : public StmtIteratorBase {
protected:
StmtIteratorImpl(const StmtIteratorBase& RHS) : StmtIteratorBase(RHS) {}
public:
using iterator_category = std::forward_iterator_tag;
using value_type = REFERENCE;
using difference_type = std::ptrdiff_t;
using pointer = REFERENCE;
using reference = REFERENCE;
StmtIteratorImpl() {}
StmtIteratorImpl(Stmt **s) : StmtIteratorBase(s) {}
StmtIteratorImpl(Decl **dgi, Decl **dge) : StmtIteratorBase(dgi, dge) {}
StmtIteratorImpl(const VariableArrayType *t) : StmtIteratorBase(t) {}
DERIVED& operator++() {
if (inStmt())
++stmt;
else if (getVAPtr())
NextVA();
else
NextDecl();
return static_cast<DERIVED&>(*this);
}
DERIVED operator++(int) {
DERIVED tmp = static_cast<DERIVED&>(*this);
operator++();
return tmp;
}
bool operator==(const DERIVED& RHS) const {
return stmt == RHS.stmt && DGI == RHS.DGI && RawVAPtr == RHS.RawVAPtr;
}
bool operator!=(const DERIVED& RHS) const {
return stmt != RHS.stmt || DGI != RHS.DGI || RawVAPtr != RHS.RawVAPtr;
}
REFERENCE operator*() const {
return inStmt() ? *stmt : GetDeclExpr();
}
REFERENCE operator->() const { return operator*(); }
};
struct StmtIterator : public StmtIteratorImpl<StmtIterator,Stmt*&> {
explicit StmtIterator() : StmtIteratorImpl<StmtIterator,Stmt*&>() {}
StmtIterator(Stmt** S) : StmtIteratorImpl<StmtIterator,Stmt*&>(S) {}
StmtIterator(Decl** dgi, Decl** dge)
: StmtIteratorImpl<StmtIterator,Stmt*&>(dgi, dge) {}
StmtIterator(const VariableArrayType *t)
: StmtIteratorImpl<StmtIterator,Stmt*&>(t) {}
};
struct ConstStmtIterator : public StmtIteratorImpl<ConstStmtIterator,
const Stmt*> {
explicit ConstStmtIterator() :
StmtIteratorImpl<ConstStmtIterator,const Stmt*>() {}
ConstStmtIterator(const StmtIterator& RHS) :
StmtIteratorImpl<ConstStmtIterator,const Stmt*>(RHS) {}
};
/// A range of statement iterators.
///
/// This class provides some extra functionality beyond std::pair
/// in order to allow the following idiom:
/// for (StmtRange range = stmt->children(); range; ++range)
struct StmtRange : std::pair<StmtIterator,StmtIterator> {
StmtRange() {}
StmtRange(const StmtIterator &begin, const StmtIterator &end)
: std::pair<StmtIterator,StmtIterator>(begin, end) {}
bool empty() const { return first == second; }
explicit operator bool() const { return !empty(); }
Stmt *operator->() const { return first.operator->(); }
Stmt *&operator*() const { return first.operator*(); }
StmtRange &operator++() {
assert(!empty() && "incrementing on empty range");
++first;
return *this;
}
StmtRange operator++(int) {
assert(!empty() && "incrementing on empty range");
StmtRange copy = *this;
++first;
return copy;
}
friend const StmtIterator &begin(const StmtRange &range) {
return range.first;
}
friend const StmtIterator &end(const StmtRange &range) {
return range.second;
}
};
/// A range of const statement iterators.
///
/// This class provides some extra functionality beyond std::pair
/// in order to allow the following idiom:
/// for (ConstStmtRange range = stmt->children(); range; ++range)
struct ConstStmtRange : std::pair<ConstStmtIterator,ConstStmtIterator> {
ConstStmtRange() {}
ConstStmtRange(const ConstStmtIterator &begin,
const ConstStmtIterator &end)
: std::pair<ConstStmtIterator,ConstStmtIterator>(begin, end) {}
ConstStmtRange(const StmtRange &range)
: std::pair<ConstStmtIterator,ConstStmtIterator>(range.first, range.second)
{}
ConstStmtRange(const StmtIterator &begin, const StmtIterator &end)
: std::pair<ConstStmtIterator,ConstStmtIterator>(begin, end) {}
bool empty() const { return first == second; }
explicit operator bool() const { return !empty(); }
const Stmt *operator->() const { return first.operator->(); }
const Stmt *operator*() const { return first.operator*(); }
ConstStmtRange &operator++() {
assert(!empty() && "incrementing on empty range");
++first;
return *this;
}
ConstStmtRange operator++(int) {
assert(!empty() && "incrementing on empty range");
ConstStmtRange copy = *this;
++first;
return copy;
}
friend const ConstStmtIterator &begin(const ConstStmtRange &range) {
return range.first;
}
friend const ConstStmtIterator &end(const ConstStmtRange &range) {
return range.second;
}
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/CXXInheritance.h | //===------ CXXInheritance.h - C++ Inheritance ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides routines that help analyzing C++ inheritance hierarchies.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_CXXINHERITANCE_H
#define LLVM_CLANG_AST_CXXINHERITANCE_H
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeOrdering.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include <cassert>
#include <list>
#include <map>
namespace clang {
class CXXBaseSpecifier;
class CXXMethodDecl;
class CXXRecordDecl;
class NamedDecl;
/// \brief Represents an element in a path from a derived class to a
/// base class.
///
/// Each step in the path references the link from a
/// derived class to one of its direct base classes, along with a
/// base "number" that identifies which base subobject of the
/// original derived class we are referencing.
struct CXXBasePathElement {
/// \brief The base specifier that states the link from a derived
/// class to a base class, which will be followed by this base
/// path element.
const CXXBaseSpecifier *Base;
/// \brief The record decl of the class that the base is a base of.
const CXXRecordDecl *Class;
/// \brief Identifies which base class subobject (of type
/// \c Base->getType()) this base path element refers to.
///
/// This value is only valid if \c !Base->isVirtual(), because there
/// is no base numbering for the zero or one virtual bases of a
/// given type.
int SubobjectNumber;
};
/// \brief Represents a path from a specific derived class
/// (which is not represented as part of the path) to a particular
/// (direct or indirect) base class subobject.
///
/// Individual elements in the path are described by the \c CXXBasePathElement
/// structure, which captures both the link from a derived class to one of its
/// direct bases and identification describing which base class
/// subobject is being used.
class CXXBasePath : public SmallVector<CXXBasePathElement, 4> {
public:
CXXBasePath() : Access(AS_public) {}
/// \brief The access along this inheritance path. This is only
/// calculated when recording paths. AS_none is a special value
/// used to indicate a path which permits no legal access.
AccessSpecifier Access;
/// \brief The set of declarations found inside this base class
/// subobject.
DeclContext::lookup_result Decls;
void clear() {
SmallVectorImpl<CXXBasePathElement>::clear();
Access = AS_public;
}
};
/// BasePaths - Represents the set of paths from a derived class to
/// one of its (direct or indirect) bases. For example, given the
/// following class hierarchy:
///
/// @code
/// class A { };
/// class B : public A { };
/// class C : public A { };
/// class D : public B, public C{ };
/// @endcode
///
/// There are two potential BasePaths to represent paths from D to a
/// base subobject of type A. One path is (D,0) -> (B,0) -> (A,0)
/// and another is (D,0)->(C,0)->(A,1). These two paths actually
/// refer to two different base class subobjects of the same type,
/// so the BasePaths object refers to an ambiguous path. On the
/// other hand, consider the following class hierarchy:
///
/// @code
/// class A { };
/// class B : public virtual A { };
/// class C : public virtual A { };
/// class D : public B, public C{ };
/// @endcode
///
/// Here, there are two potential BasePaths again, (D, 0) -> (B, 0)
/// -> (A,v) and (D, 0) -> (C, 0) -> (A, v), but since both of them
/// refer to the same base class subobject of type A (the virtual
/// one), there is no ambiguity.
class CXXBasePaths {
/// \brief The type from which this search originated.
CXXRecordDecl *Origin;
/// Paths - The actual set of paths that can be taken from the
/// derived class to the same base class.
std::list<CXXBasePath> Paths;
/// ClassSubobjects - Records the class subobjects for each class
/// type that we've seen. The first element in the pair says
/// whether we found a path to a virtual base for that class type,
/// while the element contains the number of non-virtual base
/// class subobjects for that class type. The key of the map is
/// the cv-unqualified canonical type of the base class subobject.
llvm::SmallDenseMap<QualType, std::pair<bool, unsigned>, 8> ClassSubobjects;
/// FindAmbiguities - Whether Sema::IsDerivedFrom should try find
/// ambiguous paths while it is looking for a path from a derived
/// type to a base type.
bool FindAmbiguities;
/// RecordPaths - Whether Sema::IsDerivedFrom should record paths
/// while it is determining whether there are paths from a derived
/// type to a base type.
bool RecordPaths;
/// DetectVirtual - Whether Sema::IsDerivedFrom should abort the search
/// if it finds a path that goes across a virtual base. The virtual class
/// is also recorded.
bool DetectVirtual;
/// ScratchPath - A BasePath that is used by Sema::lookupInBases
/// to help build the set of paths.
CXXBasePath ScratchPath;
/// DetectedVirtual - The base class that is virtual.
const RecordType *DetectedVirtual;
/// \brief Array of the declarations that have been found. This
/// array is constructed only if needed, e.g., to iterate over the
/// results within LookupResult.
NamedDecl **DeclsFound;
unsigned NumDeclsFound;
friend class CXXRecordDecl;
void ComputeDeclsFound();
bool lookupInBases(ASTContext &Context,
const CXXRecordDecl *Record,
CXXRecordDecl::BaseMatchesCallback *BaseMatches,
void *UserData);
public:
typedef std::list<CXXBasePath>::iterator paths_iterator;
typedef std::list<CXXBasePath>::const_iterator const_paths_iterator;
typedef NamedDecl **decl_iterator;
/// BasePaths - Construct a new BasePaths structure to record the
/// paths for a derived-to-base search.
explicit CXXBasePaths(bool FindAmbiguities = true,
bool RecordPaths = true,
bool DetectVirtual = true)
: FindAmbiguities(FindAmbiguities), RecordPaths(RecordPaths),
DetectVirtual(DetectVirtual), DetectedVirtual(nullptr),
DeclsFound(nullptr), NumDeclsFound(0) { }
~CXXBasePaths() { delete [] DeclsFound; }
paths_iterator begin() { return Paths.begin(); }
paths_iterator end() { return Paths.end(); }
const_paths_iterator begin() const { return Paths.begin(); }
const_paths_iterator end() const { return Paths.end(); }
CXXBasePath& front() { return Paths.front(); }
const CXXBasePath& front() const { return Paths.front(); }
typedef llvm::iterator_range<decl_iterator> decl_range;
decl_range found_decls();
/// \brief Determine whether the path from the most-derived type to the
/// given base type is ambiguous (i.e., it refers to multiple subobjects of
/// the same base type).
bool isAmbiguous(CanQualType BaseType);
/// \brief Whether we are finding multiple paths to detect ambiguities.
bool isFindingAmbiguities() const { return FindAmbiguities; }
/// \brief Whether we are recording paths.
bool isRecordingPaths() const { return RecordPaths; }
/// \brief Specify whether we should be recording paths or not.
void setRecordingPaths(bool RP) { RecordPaths = RP; }
/// \brief Whether we are detecting virtual bases.
bool isDetectingVirtual() const { return DetectVirtual; }
/// \brief The virtual base discovered on the path (if we are merely
/// detecting virtuals).
const RecordType* getDetectedVirtual() const {
return DetectedVirtual;
}
/// \brief Retrieve the type from which this base-paths search
/// began
CXXRecordDecl *getOrigin() const { return Origin; }
void setOrigin(CXXRecordDecl *Rec) { Origin = Rec; }
/// \brief Clear the base-paths results.
void clear();
/// \brief Swap this data structure's contents with another CXXBasePaths
/// object.
void swap(CXXBasePaths &Other);
};
/// \brief Uniquely identifies a virtual method within a class
/// hierarchy by the method itself and a class subobject number.
struct UniqueVirtualMethod {
UniqueVirtualMethod()
: Method(nullptr), Subobject(0), InVirtualSubobject(nullptr) { }
UniqueVirtualMethod(CXXMethodDecl *Method, unsigned Subobject,
const CXXRecordDecl *InVirtualSubobject)
: Method(Method), Subobject(Subobject),
InVirtualSubobject(InVirtualSubobject) { }
/// \brief The overriding virtual method.
CXXMethodDecl *Method;
/// \brief The subobject in which the overriding virtual method
/// resides.
unsigned Subobject;
/// \brief The virtual base class subobject of which this overridden
/// virtual method is a part. Note that this records the closest
/// derived virtual base class subobject.
const CXXRecordDecl *InVirtualSubobject;
friend bool operator==(const UniqueVirtualMethod &X,
const UniqueVirtualMethod &Y) {
return X.Method == Y.Method && X.Subobject == Y.Subobject &&
X.InVirtualSubobject == Y.InVirtualSubobject;
}
friend bool operator!=(const UniqueVirtualMethod &X,
const UniqueVirtualMethod &Y) {
return !(X == Y);
}
};
/// \brief The set of methods that override a given virtual method in
/// each subobject where it occurs.
///
/// The first part of the pair is the subobject in which the
/// overridden virtual function occurs, while the second part of the
/// pair is the virtual method that overrides it (including the
/// subobject in which that virtual function occurs).
class OverridingMethods {
typedef SmallVector<UniqueVirtualMethod, 4> ValuesT;
typedef llvm::MapVector<unsigned, ValuesT> MapType;
MapType Overrides;
public:
// Iterate over the set of subobjects that have overriding methods.
typedef MapType::iterator iterator;
typedef MapType::const_iterator const_iterator;
iterator begin() { return Overrides.begin(); }
const_iterator begin() const { return Overrides.begin(); }
iterator end() { return Overrides.end(); }
const_iterator end() const { return Overrides.end(); }
unsigned size() const { return Overrides.size(); }
// Iterate over the set of overriding virtual methods in a given
// subobject.
typedef SmallVectorImpl<UniqueVirtualMethod>::iterator
overriding_iterator;
typedef SmallVectorImpl<UniqueVirtualMethod>::const_iterator
overriding_const_iterator;
// Add a new overriding method for a particular subobject.
void add(unsigned OverriddenSubobject, UniqueVirtualMethod Overriding);
// Add all of the overriding methods from "other" into overrides for
// this method. Used when merging the overrides from multiple base
// class subobjects.
void add(const OverridingMethods &Other);
// Replace all overriding virtual methods in all subobjects with the
// given virtual method.
void replaceAll(UniqueVirtualMethod Overriding);
};
/// \brief A mapping from each virtual member function to its set of
/// final overriders.
///
/// Within a class hierarchy for a given derived class, each virtual
/// member function in that hierarchy has one or more "final
/// overriders" (C++ [class.virtual]p2). A final overrider for a
/// virtual function "f" is the virtual function that will actually be
/// invoked when dispatching a call to "f" through the
/// vtable. Well-formed classes have a single final overrider for each
/// virtual function; in abstract classes, the final overrider for at
/// least one virtual function is a pure virtual function. Due to
/// multiple, virtual inheritance, it is possible for a class to have
/// more than one final overrider. Athough this is an error (per C++
/// [class.virtual]p2), it is not considered an error here: the final
/// overrider map can represent multiple final overriders for a
/// method, and it is up to the client to determine whether they are
/// problem. For example, the following class \c D has two final
/// overriders for the virtual function \c A::f(), one in \c C and one
/// in \c D:
///
/// \code
/// struct A { virtual void f(); };
/// struct B : virtual A { virtual void f(); };
/// struct C : virtual A { virtual void f(); };
/// struct D : B, C { };
/// \endcode
///
/// This data structure contains a mapping from every virtual
/// function *that does not override an existing virtual function* and
/// in every subobject where that virtual function occurs to the set
/// of virtual functions that override it. Thus, the same virtual
/// function \c A::f can actually occur in multiple subobjects of type
/// \c A due to multiple inheritance, and may be overridden by
/// different virtual functions in each, as in the following example:
///
/// \code
/// struct A { virtual void f(); };
/// struct B : A { virtual void f(); };
/// struct C : A { virtual void f(); };
/// struct D : B, C { };
/// \endcode
///
/// Unlike in the previous example, where the virtual functions \c
/// B::f and \c C::f both overrode \c A::f in the same subobject of
/// type \c A, in this example the two virtual functions both override
/// \c A::f but in *different* subobjects of type A. This is
/// represented by numbering the subobjects in which the overridden
/// and the overriding virtual member functions are located. Subobject
/// 0 represents the virtual base class subobject of that type, while
/// subobject numbers greater than 0 refer to non-virtual base class
/// subobjects of that type.
class CXXFinalOverriderMap
: public llvm::MapVector<const CXXMethodDecl *, OverridingMethods> { };
/// \brief A set of all the primary bases for a class.
class CXXIndirectPrimaryBaseSet
: public llvm::SmallSet<const CXXRecordDecl*, 32> { };
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/StmtObjC.h | //===--- StmtObjC.h - Classes for representing ObjC statements --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// \brief Defines the Objective-C statement AST node classes.
#ifndef LLVM_CLANG_AST_STMTOBJC_H
#define LLVM_CLANG_AST_STMTOBJC_H
#include "clang/AST/Stmt.h"
#include "llvm/Support/Compiler.h"
namespace clang {
/// \brief Represents Objective-C's collection statement.
///
/// This is represented as 'for (element 'in' collection-expression)' stmt.
class ObjCForCollectionStmt : public Stmt {
enum { ELEM, COLLECTION, BODY, END_EXPR };
Stmt* SubExprs[END_EXPR]; // SubExprs[ELEM] is an expression or declstmt.
SourceLocation ForLoc;
SourceLocation RParenLoc;
public:
ObjCForCollectionStmt(Stmt *Elem, Expr *Collect, Stmt *Body,
SourceLocation FCL, SourceLocation RPL);
explicit ObjCForCollectionStmt(EmptyShell Empty) :
Stmt(ObjCForCollectionStmtClass, Empty) { }
Stmt *getElement() { return SubExprs[ELEM]; }
Expr *getCollection() {
return reinterpret_cast<Expr*>(SubExprs[COLLECTION]);
}
Stmt *getBody() { return SubExprs[BODY]; }
const Stmt *getElement() const { return SubExprs[ELEM]; }
const Expr *getCollection() const {
return reinterpret_cast<Expr*>(SubExprs[COLLECTION]);
}
const Stmt *getBody() const { return SubExprs[BODY]; }
void setElement(Stmt *S) { SubExprs[ELEM] = S; }
void setCollection(Expr *E) {
SubExprs[COLLECTION] = reinterpret_cast<Stmt*>(E);
}
void setBody(Stmt *S) { SubExprs[BODY] = S; }
SourceLocation getForLoc() const { return ForLoc; }
void setForLoc(SourceLocation Loc) { ForLoc = Loc; }
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
SourceLocation getLocStart() const LLVM_READONLY { return ForLoc; }
SourceLocation getLocEnd() const LLVM_READONLY {
return SubExprs[BODY]->getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == ObjCForCollectionStmtClass;
}
// Iterators
child_range children() {
return child_range(&SubExprs[0], &SubExprs[END_EXPR]);
}
};
/// \brief Represents Objective-C's \@catch statement.
class ObjCAtCatchStmt : public Stmt {
private:
VarDecl *ExceptionDecl;
Stmt *Body;
SourceLocation AtCatchLoc, RParenLoc;
public:
ObjCAtCatchStmt(SourceLocation atCatchLoc, SourceLocation rparenloc,
VarDecl *catchVarDecl,
Stmt *atCatchStmt)
: Stmt(ObjCAtCatchStmtClass), ExceptionDecl(catchVarDecl),
Body(atCatchStmt), AtCatchLoc(atCatchLoc), RParenLoc(rparenloc) { }
explicit ObjCAtCatchStmt(EmptyShell Empty) :
Stmt(ObjCAtCatchStmtClass, Empty) { }
const Stmt *getCatchBody() const { return Body; }
Stmt *getCatchBody() { return Body; }
void setCatchBody(Stmt *S) { Body = S; }
const VarDecl *getCatchParamDecl() const {
return ExceptionDecl;
}
VarDecl *getCatchParamDecl() {
return ExceptionDecl;
}
void setCatchParamDecl(VarDecl *D) { ExceptionDecl = D; }
SourceLocation getAtCatchLoc() const { return AtCatchLoc; }
void setAtCatchLoc(SourceLocation Loc) { AtCatchLoc = Loc; }
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation Loc) { RParenLoc = Loc; }
SourceLocation getLocStart() const LLVM_READONLY { return AtCatchLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return Body->getLocEnd(); }
bool hasEllipsis() const { return getCatchParamDecl() == nullptr; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == ObjCAtCatchStmtClass;
}
child_range children() { return child_range(&Body, &Body + 1); }
};
/// \brief Represents Objective-C's \@finally statement
class ObjCAtFinallyStmt : public Stmt {
SourceLocation AtFinallyLoc;
Stmt *AtFinallyStmt;
public:
ObjCAtFinallyStmt(SourceLocation atFinallyLoc, Stmt *atFinallyStmt)
: Stmt(ObjCAtFinallyStmtClass), AtFinallyLoc(atFinallyLoc),
AtFinallyStmt(atFinallyStmt) {}
explicit ObjCAtFinallyStmt(EmptyShell Empty) :
Stmt(ObjCAtFinallyStmtClass, Empty) { }
const Stmt *getFinallyBody() const { return AtFinallyStmt; }
Stmt *getFinallyBody() { return AtFinallyStmt; }
void setFinallyBody(Stmt *S) { AtFinallyStmt = S; }
SourceLocation getLocStart() const LLVM_READONLY { return AtFinallyLoc; }
SourceLocation getLocEnd() const LLVM_READONLY {
return AtFinallyStmt->getLocEnd();
}
SourceLocation getAtFinallyLoc() const { return AtFinallyLoc; }
void setAtFinallyLoc(SourceLocation Loc) { AtFinallyLoc = Loc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == ObjCAtFinallyStmtClass;
}
child_range children() {
return child_range(&AtFinallyStmt, &AtFinallyStmt+1);
}
};
/// \brief Represents Objective-C's \@try ... \@catch ... \@finally statement.
class ObjCAtTryStmt : public Stmt {
private:
// The location of the @ in the \@try.
SourceLocation AtTryLoc;
// The number of catch blocks in this statement.
unsigned NumCatchStmts : 16;
// Whether this statement has a \@finally statement.
bool HasFinally : 1;
/// \brief Retrieve the statements that are stored after this \@try statement.
///
/// The order of the statements in memory follows the order in the source,
/// with the \@try body first, followed by the \@catch statements (if any)
/// and, finally, the \@finally (if it exists).
Stmt **getStmts() { return reinterpret_cast<Stmt **> (this + 1); }
const Stmt* const *getStmts() const {
return reinterpret_cast<const Stmt * const*> (this + 1);
}
ObjCAtTryStmt(SourceLocation atTryLoc, Stmt *atTryStmt,
Stmt **CatchStmts, unsigned NumCatchStmts,
Stmt *atFinallyStmt);
explicit ObjCAtTryStmt(EmptyShell Empty, unsigned NumCatchStmts,
bool HasFinally)
: Stmt(ObjCAtTryStmtClass, Empty), NumCatchStmts(NumCatchStmts),
HasFinally(HasFinally) { }
public:
static ObjCAtTryStmt *Create(const ASTContext &Context,
SourceLocation atTryLoc, Stmt *atTryStmt,
Stmt **CatchStmts, unsigned NumCatchStmts,
Stmt *atFinallyStmt);
static ObjCAtTryStmt *CreateEmpty(const ASTContext &Context,
unsigned NumCatchStmts, bool HasFinally);
/// \brief Retrieve the location of the @ in the \@try.
SourceLocation getAtTryLoc() const { return AtTryLoc; }
void setAtTryLoc(SourceLocation Loc) { AtTryLoc = Loc; }
/// \brief Retrieve the \@try body.
const Stmt *getTryBody() const { return getStmts()[0]; }
Stmt *getTryBody() { return getStmts()[0]; }
void setTryBody(Stmt *S) { getStmts()[0] = S; }
/// \brief Retrieve the number of \@catch statements in this try-catch-finally
/// block.
unsigned getNumCatchStmts() const { return NumCatchStmts; }
/// \brief Retrieve a \@catch statement.
const ObjCAtCatchStmt *getCatchStmt(unsigned I) const {
assert(I < NumCatchStmts && "Out-of-bounds @catch index");
return cast_or_null<ObjCAtCatchStmt>(getStmts()[I + 1]);
}
/// \brief Retrieve a \@catch statement.
ObjCAtCatchStmt *getCatchStmt(unsigned I) {
assert(I < NumCatchStmts && "Out-of-bounds @catch index");
return cast_or_null<ObjCAtCatchStmt>(getStmts()[I + 1]);
}
/// \brief Set a particular catch statement.
void setCatchStmt(unsigned I, ObjCAtCatchStmt *S) {
assert(I < NumCatchStmts && "Out-of-bounds @catch index");
getStmts()[I + 1] = S;
}
/// \brief Retrieve the \@finally statement, if any.
const ObjCAtFinallyStmt *getFinallyStmt() const {
if (!HasFinally)
return nullptr;
return cast_or_null<ObjCAtFinallyStmt>(getStmts()[1 + NumCatchStmts]);
}
ObjCAtFinallyStmt *getFinallyStmt() {
if (!HasFinally)
return nullptr;
return cast_or_null<ObjCAtFinallyStmt>(getStmts()[1 + NumCatchStmts]);
}
void setFinallyStmt(Stmt *S) {
assert(HasFinally && "@try does not have a @finally slot!");
getStmts()[1 + NumCatchStmts] = S;
}
SourceLocation getLocStart() const LLVM_READONLY { return AtTryLoc; }
SourceLocation getLocEnd() const LLVM_READONLY;
static bool classof(const Stmt *T) {
return T->getStmtClass() == ObjCAtTryStmtClass;
}
child_range children() {
return child_range(getStmts(),
getStmts() + 1 + NumCatchStmts + HasFinally);
}
};
/// \brief Represents Objective-C's \@synchronized statement.
///
/// Example:
/// \code
/// @synchronized (sem) {
/// do-something;
/// }
/// \endcode
class ObjCAtSynchronizedStmt : public Stmt {
private:
SourceLocation AtSynchronizedLoc;
enum { SYNC_EXPR, SYNC_BODY, END_EXPR };
Stmt* SubStmts[END_EXPR];
public:
ObjCAtSynchronizedStmt(SourceLocation atSynchronizedLoc, Stmt *synchExpr,
Stmt *synchBody)
: Stmt(ObjCAtSynchronizedStmtClass) {
SubStmts[SYNC_EXPR] = synchExpr;
SubStmts[SYNC_BODY] = synchBody;
AtSynchronizedLoc = atSynchronizedLoc;
}
explicit ObjCAtSynchronizedStmt(EmptyShell Empty) :
Stmt(ObjCAtSynchronizedStmtClass, Empty) { }
SourceLocation getAtSynchronizedLoc() const { return AtSynchronizedLoc; }
void setAtSynchronizedLoc(SourceLocation Loc) { AtSynchronizedLoc = Loc; }
const CompoundStmt *getSynchBody() const {
return reinterpret_cast<CompoundStmt*>(SubStmts[SYNC_BODY]);
}
CompoundStmt *getSynchBody() {
return reinterpret_cast<CompoundStmt*>(SubStmts[SYNC_BODY]);
}
void setSynchBody(Stmt *S) { SubStmts[SYNC_BODY] = S; }
const Expr *getSynchExpr() const {
return reinterpret_cast<Expr*>(SubStmts[SYNC_EXPR]);
}
Expr *getSynchExpr() {
return reinterpret_cast<Expr*>(SubStmts[SYNC_EXPR]);
}
void setSynchExpr(Stmt *S) { SubStmts[SYNC_EXPR] = S; }
SourceLocation getLocStart() const LLVM_READONLY { return AtSynchronizedLoc; }
SourceLocation getLocEnd() const LLVM_READONLY {
return getSynchBody()->getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == ObjCAtSynchronizedStmtClass;
}
child_range children() {
return child_range(&SubStmts[0], &SubStmts[0]+END_EXPR);
}
};
/// \brief Represents Objective-C's \@throw statement.
class ObjCAtThrowStmt : public Stmt {
SourceLocation AtThrowLoc;
Stmt *Throw;
public:
ObjCAtThrowStmt(SourceLocation atThrowLoc, Stmt *throwExpr)
: Stmt(ObjCAtThrowStmtClass), Throw(throwExpr) {
AtThrowLoc = atThrowLoc;
}
explicit ObjCAtThrowStmt(EmptyShell Empty) :
Stmt(ObjCAtThrowStmtClass, Empty) { }
const Expr *getThrowExpr() const { return reinterpret_cast<Expr*>(Throw); }
Expr *getThrowExpr() { return reinterpret_cast<Expr*>(Throw); }
void setThrowExpr(Stmt *S) { Throw = S; }
SourceLocation getThrowLoc() { return AtThrowLoc; }
void setThrowLoc(SourceLocation Loc) { AtThrowLoc = Loc; }
SourceLocation getLocStart() const LLVM_READONLY { return AtThrowLoc; }
SourceLocation getLocEnd() const LLVM_READONLY {
return Throw ? Throw->getLocEnd() : AtThrowLoc;
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == ObjCAtThrowStmtClass;
}
child_range children() { return child_range(&Throw, &Throw+1); }
};
/// \brief Represents Objective-C's \@autoreleasepool Statement
class ObjCAutoreleasePoolStmt : public Stmt {
SourceLocation AtLoc;
Stmt *SubStmt;
public:
ObjCAutoreleasePoolStmt(SourceLocation atLoc, Stmt *subStmt)
: Stmt(ObjCAutoreleasePoolStmtClass), AtLoc(atLoc), SubStmt(subStmt) {}
explicit ObjCAutoreleasePoolStmt(EmptyShell Empty) :
Stmt(ObjCAutoreleasePoolStmtClass, Empty) { }
const Stmt *getSubStmt() const { return SubStmt; }
Stmt *getSubStmt() { return SubStmt; }
void setSubStmt(Stmt *S) { SubStmt = S; }
SourceLocation getLocStart() const LLVM_READONLY { return AtLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return SubStmt->getLocEnd();}
SourceLocation getAtLoc() const { return AtLoc; }
void setAtLoc(SourceLocation Loc) { AtLoc = Loc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == ObjCAutoreleasePoolStmtClass;
}
child_range children() { return child_range(&SubStmt, &SubStmt + 1); }
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/DeclContextInternals.h | //===-- DeclContextInternals.h - DeclContext Representation -----*- 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 data structures used in the implementation
// of DeclContext.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_DECLCONTEXTINTERNALS_H
#define LLVM_CLANG_AST_DECLCONTEXTINTERNALS_H
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclarationName.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallVector.h"
#include <algorithm>
namespace clang {
class DependentDiagnostic;
/// \brief An array of decls optimized for the common case of only containing
/// one entry.
struct StoredDeclsList {
/// \brief When in vector form, this is what the Data pointer points to.
typedef SmallVector<NamedDecl *, 4> DeclsTy;
/// \brief A collection of declarations, with a flag to indicate if we have
/// further external declarations.
typedef llvm::PointerIntPair<DeclsTy *, 1, bool> DeclsAndHasExternalTy;
/// \brief The stored data, which will be either a pointer to a NamedDecl,
/// or a pointer to a vector with a flag to indicate if there are further
/// external declarations.
llvm::PointerUnion<NamedDecl*, DeclsAndHasExternalTy> Data;
public:
StoredDeclsList() {}
StoredDeclsList(StoredDeclsList &&RHS) : Data(RHS.Data) {
RHS.Data = (NamedDecl *)nullptr;
}
~StoredDeclsList() {
// If this is a vector-form, free the vector.
if (DeclsTy *Vector = getAsVector())
delete Vector;
}
StoredDeclsList &operator=(StoredDeclsList &&RHS) {
if (DeclsTy *Vector = getAsVector())
delete Vector;
Data = RHS.Data;
RHS.Data = (NamedDecl *)nullptr;
return *this;
}
bool isNull() const { return Data.isNull(); }
NamedDecl *getAsDecl() const {
return Data.dyn_cast<NamedDecl *>();
}
DeclsAndHasExternalTy getAsVectorAndHasExternal() const {
return Data.dyn_cast<DeclsAndHasExternalTy>();
}
DeclsTy *getAsVector() const {
return getAsVectorAndHasExternal().getPointer();
}
bool hasExternalDecls() const {
return getAsVectorAndHasExternal().getInt();
}
void setHasExternalDecls() {
if (DeclsTy *Vec = getAsVector())
Data = DeclsAndHasExternalTy(Vec, true);
else {
DeclsTy *VT = new DeclsTy();
if (NamedDecl *OldD = getAsDecl())
VT->push_back(OldD);
Data = DeclsAndHasExternalTy(VT, true);
}
}
void setOnlyValue(NamedDecl *ND) {
assert(!getAsVector() && "Not inline");
Data = ND;
// Make sure that Data is a plain NamedDecl* so we can use its address
// at getLookupResult.
assert(*(NamedDecl **)&Data == ND &&
"PointerUnion mangles the NamedDecl pointer!");
}
void remove(NamedDecl *D) {
assert(!isNull() && "removing from empty list");
if (NamedDecl *Singleton = getAsDecl()) {
assert(Singleton == D && "list is different singleton");
(void)Singleton;
Data = (NamedDecl *)nullptr;
return;
}
DeclsTy &Vec = *getAsVector();
DeclsTy::iterator I = std::find(Vec.begin(), Vec.end(), D);
assert(I != Vec.end() && "list does not contain decl");
Vec.erase(I);
assert(std::find(Vec.begin(), Vec.end(), D)
== Vec.end() && "list still contains decl");
}
/// \brief Remove any declarations which were imported from an external
/// AST source.
void removeExternalDecls() {
if (isNull()) {
// Nothing to do.
} else if (NamedDecl *Singleton = getAsDecl()) {
if (Singleton->isFromASTFile())
*this = StoredDeclsList();
} else {
DeclsTy &Vec = *getAsVector();
Vec.erase(std::remove_if(Vec.begin(), Vec.end(),
std::mem_fn(&Decl::isFromASTFile)),
Vec.end());
// Don't have any external decls any more.
Data = DeclsAndHasExternalTy(&Vec, false);
}
}
/// getLookupResult - Return an array of all the decls that this list
/// represents.
DeclContext::lookup_result getLookupResult() {
if (isNull())
return DeclContext::lookup_result();
// If we have a single NamedDecl, return it.
if (NamedDecl *ND = getAsDecl()) {
assert(!isNull() && "Empty list isn't allowed");
// Data is a raw pointer to a NamedDecl*, return it.
return DeclContext::lookup_result(ND);
}
assert(getAsVector() && "Must have a vector at this point");
DeclsTy &Vector = *getAsVector();
// Otherwise, we have a range result.
return DeclContext::lookup_result(Vector);
}
/// HandleRedeclaration - If this is a redeclaration of an existing decl,
/// replace the old one with D and return true. Otherwise return false.
bool HandleRedeclaration(NamedDecl *D, bool IsKnownNewer) {
// Most decls only have one entry in their list, special case it.
if (NamedDecl *OldD = getAsDecl()) {
if (!D->declarationReplaces(OldD, IsKnownNewer))
return false;
setOnlyValue(D);
return true;
}
// Determine if this declaration is actually a redeclaration.
DeclsTy &Vec = *getAsVector();
for (DeclsTy::iterator OD = Vec.begin(), ODEnd = Vec.end();
OD != ODEnd; ++OD) {
NamedDecl *OldD = *OD;
if (D->declarationReplaces(OldD, IsKnownNewer)) {
*OD = D;
return true;
}
}
return false;
}
/// AddSubsequentDecl - This is called on the second and later decl when it is
/// not a redeclaration to merge it into the appropriate place in our list.
///
void AddSubsequentDecl(NamedDecl *D) {
assert(!isNull() && "don't AddSubsequentDecl when we have no decls");
// If this is the second decl added to the list, convert this to vector
// form.
if (NamedDecl *OldD = getAsDecl()) {
DeclsTy *VT = new DeclsTy();
VT->push_back(OldD);
Data = DeclsAndHasExternalTy(VT, false);
}
DeclsTy &Vec = *getAsVector();
// Using directives end up in a special entry which contains only
// other using directives, so all this logic is wasted for them.
// But avoiding the logic wastes time in the far-more-common case
// that we're *not* adding a new using directive.
// Tag declarations always go at the end of the list so that an
// iterator which points at the first tag will start a span of
// decls that only contains tags.
if (D->hasTagIdentifierNamespace())
Vec.push_back(D);
// Resolved using declarations go at the front of the list so that
// they won't show up in other lookup results. Unresolved using
// declarations (which are always in IDNS_Using | IDNS_Ordinary)
// follow that so that the using declarations will be contiguous.
else if (D->getIdentifierNamespace() & Decl::IDNS_Using) {
DeclsTy::iterator I = Vec.begin();
if (D->getIdentifierNamespace() != Decl::IDNS_Using) {
while (I != Vec.end() &&
(*I)->getIdentifierNamespace() == Decl::IDNS_Using)
++I;
}
Vec.insert(I, D);
// All other declarations go at the end of the list, but before any
// tag declarations. But we can be clever about tag declarations
// because there can only ever be one in a scope.
} else if (!Vec.empty() && Vec.back()->hasTagIdentifierNamespace()) {
NamedDecl *TagD = Vec.back();
Vec.back() = D;
Vec.push_back(TagD);
} else
Vec.push_back(D);
}
};
class StoredDeclsMap
: public llvm::SmallDenseMap<DeclarationName, StoredDeclsList, 4> {
public:
static void DestroyAll(StoredDeclsMap *Map, bool Dependent);
private:
friend class ASTContext; // walks the chain deleting these
friend class DeclContext;
llvm::PointerIntPair<StoredDeclsMap*, 1> Previous;
};
class DependentStoredDeclsMap : public StoredDeclsMap {
public:
DependentStoredDeclsMap() : FirstDiagnostic(nullptr) {}
private:
friend class DependentDiagnostic;
friend class DeclContext; // iterates over diagnostics
DependentDiagnostic *FirstDiagnostic;
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/DeclAccessPair.h | //===--- DeclAccessPair.h - A decl bundled with its path access -*- 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 DeclAccessPair class, which provides an
// efficient representation of a pair of a NamedDecl* and an
// AccessSpecifier. Generally the access specifier gives the
// natural access of a declaration when named in a class, as
// defined in C++ [class.access.base]p1.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_DECLACCESSPAIR_H
#define LLVM_CLANG_AST_DECLACCESSPAIR_H
#include "clang/Basic/Specifiers.h"
#include "llvm/Support/DataTypes.h"
namespace clang {
class NamedDecl;
/// A POD class for pairing a NamedDecl* with an access specifier.
/// Can be put into unions.
class DeclAccessPair {
uintptr_t Ptr; // we'd use llvm::PointerUnion, but it isn't trivial
enum { Mask = 0x3 };
public:
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS) {
DeclAccessPair p;
p.set(D, AS);
return p;
}
NamedDecl *getDecl() const {
return reinterpret_cast<NamedDecl*>(~Mask & Ptr);
}
AccessSpecifier getAccess() const {
return AccessSpecifier(Mask & Ptr);
}
void setDecl(NamedDecl *D) {
set(D, getAccess());
}
void setAccess(AccessSpecifier AS) {
set(getDecl(), AS);
}
void set(NamedDecl *D, AccessSpecifier AS) {
Ptr = uintptr_t(AS) | reinterpret_cast<uintptr_t>(D);
}
operator NamedDecl*() const { return getDecl(); }
NamedDecl *operator->() const { return getDecl(); }
};
}
// Take a moment to tell SmallVector that DeclAccessPair is POD.
namespace llvm {
template<typename> struct isPodLike;
template<> struct isPodLike<clang::DeclAccessPair> {
static const bool value = true;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/Decl.h | //===--- Decl.h - Classes for representing declarations ---------*- 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 Decl subclasses.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_DECL_H
#define LLVM_CLANG_AST_DECL_H
#include "clang/AST/APValue.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/Redeclarable.h"
#include "clang/AST/Type.h"
#include "clang/Basic/Linkage.h"
#include "clang/Basic/OperatorKinds.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
// HLSL Change Starts
namespace hlsl {
struct UnusualAnnotation;
}
// HLSL Change Ends
namespace clang {
struct ASTTemplateArgumentListInfo;
class CXXTemporary;
class CompoundStmt;
class DependentFunctionTemplateSpecializationInfo;
class Expr;
class FunctionTemplateDecl;
class FunctionTemplateSpecializationInfo;
class LabelStmt;
class MemberSpecializationInfo;
class Module;
class NestedNameSpecifier;
class ParmVarDecl;
class Stmt;
class StringLiteral;
class TemplateArgumentList;
class TemplateParameterList;
class TypeAliasTemplateDecl;
class TypeLoc;
class UnresolvedSetImpl;
class VarTemplateDecl;
/// \brief A container of type source information.
///
/// A client can read the relevant info using TypeLoc wrappers, e.g:
/// @code
/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
/// TL.getStartLoc().print(OS, SrcMgr);
/// @endcode
///
class TypeSourceInfo {
QualType Ty;
// Contains a memory block after the class, used for type source information,
// allocated by ASTContext.
friend class ASTContext;
TypeSourceInfo(QualType ty) : Ty(ty) { }
public:
/// \brief Return the type wrapped by this type source info.
QualType getType() const { return Ty; }
/// \brief Return the TypeLoc wrapper for the type source info.
TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
/// \brief Override the type stored in this TypeSourceInfo. Use with caution!
void overrideType(QualType T) { Ty = T; }
};
/// TranslationUnitDecl - The top declaration context.
class TranslationUnitDecl : public Decl, public DeclContext {
virtual void anchor();
ASTContext &Ctx;
/// The (most recently entered) anonymous namespace for this
/// translation unit, if one has been created.
NamespaceDecl *AnonymousNamespace;
explicit TranslationUnitDecl(ASTContext &ctx);
public:
ASTContext &getASTContext() const { return Ctx; }
NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
static TranslationUnitDecl *Create(ASTContext &C);
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == TranslationUnit; }
static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
}
static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
}
};
/// \brief Declaration context for names declared as extern "C" in C++. This
/// is neither the semantic nor lexical context for such declarations, but is
/// used to check for conflicts with other extern "C" declarations. Example:
///
/// \code
/// namespace N { extern "C" void f(); } // #1
/// void N::f() {} // #2
/// namespace M { extern "C" void f(); } // #3
/// \endcode
///
/// The semantic context of #1 is namespace N and its lexical context is the
/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
/// context is the TU. However, both declarations are also visible in the
/// extern "C" context.
///
/// The declaration at #3 finds it is a redeclaration of \c N::f through
/// lookup in the extern "C" context.
class ExternCContextDecl : public Decl, public DeclContext {
virtual void anchor();
explicit ExternCContextDecl(TranslationUnitDecl *TU)
: Decl(ExternCContext, TU, SourceLocation()),
DeclContext(ExternCContext) {}
public:
static ExternCContextDecl *Create(const ASTContext &C,
TranslationUnitDecl *TU);
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == ExternCContext; }
static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
}
static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
}
};
/// NamedDecl - This represents a decl with a name. Many decls have names such
/// as ObjCMethodDecl, but not \@class, etc.
class NamedDecl : public Decl {
virtual void anchor();
/// Name - The name of this declaration, which is typically a normal
/// identifier but may also be a special kind of name (C++
/// constructor, Objective-C selector, etc.)
DeclarationName Name;
ArrayRef<hlsl::UnusualAnnotation*> UnusualAnnotations; // HLSL Change
private:
NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY;
protected:
NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
: Decl(DK, DC, L), Name(N), UnusualAnnotations() { }
public:
/// getIdentifier - Get the identifier that names this declaration,
/// if there is one. This will return NULL if this declaration has
/// no name (e.g., for an unnamed class) or if the name is a special
/// name (C++ constructor, Objective-C selector, etc.).
IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
/// getName - Get the name of identifier for this declaration as a StringRef.
/// This requires that the declaration have a name and that it be a simple
/// identifier.
StringRef getName() const {
assert(Name.isIdentifier() && "Name is not a simple identifier");
return getIdentifier() ? getIdentifier()->getName() : "";
}
// HLSL Changes Start
/// getName - Get the name of IR identifier for this declaration as a StringRef.
/// This requires that the declaration have a name and that it be a simple
/// identifier.
virtual StringRef getNameForIR() const {
return getName();
}
void setUnusualAnnotations(ArrayRef<hlsl::UnusualAnnotation*> annotations) {
UnusualAnnotations = annotations;
}
ArrayRef<hlsl::UnusualAnnotation*> getUnusualAnnotations() {
return UnusualAnnotations;
}
const ArrayRef<hlsl::UnusualAnnotation*> getUnusualAnnotations() const {
return UnusualAnnotations;
}
// HLSL Changes Ends
/// getNameAsString - Get a human-readable name for the declaration, even if
/// it is one of the special kinds of names (C++ constructor, Objective-C
/// selector, etc). Creating this name requires expensive string
/// manipulation, so it should be called only when performance doesn't matter.
/// For simple declarations, getNameAsCString() should suffice.
//
// FIXME: This function should be renamed to indicate that it is not just an
// alternate form of getName(), and clients should move as appropriate.
//
// FIXME: Deprecated, move clients to getName().
std::string getNameAsString() const { return Name.getAsString(); }
void printName(raw_ostream &os) const { os << Name; }
/// getDeclName - Get the actual, stored name of the declaration,
/// which may be a special name.
DeclarationName getDeclName() const { return Name; }
/// \brief Set the name of this declaration.
void setDeclName(DeclarationName N) { Name = N; }
/// printQualifiedName - Returns human-readable qualified name for
/// declaration, like A::B::i, for i being member of namespace A::B.
/// If declaration is not member of context which can be named (record,
/// namespace), it will return same result as printName().
/// Creating this name is expensive, so it should be called only when
/// performance doesn't matter.
void printQualifiedName(raw_ostream &OS) const;
void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
// FIXME: Remove string version.
std::string getQualifiedNameAsString() const;
/// getNameForDiagnostic - Appends a human-readable name for this
/// declaration into the given stream.
///
/// This is the method invoked by Sema when displaying a NamedDecl
/// in a diagnostic. It does not necessarily produce the same
/// result as printName(); for example, class template
/// specializations are printed with their template arguments.
virtual void getNameForDiagnostic(raw_ostream &OS,
const PrintingPolicy &Policy,
bool Qualified) const;
/// \brief Determine whether this declaration, if
/// known to be well-formed within its context, will replace the
/// declaration OldD if introduced into scope. A declaration will
/// replace another declaration if, for example, it is a
/// redeclaration of the same variable or function, but not if it is
/// a declaration of a different kind (function vs. class) or an
/// overloaded function.
///
/// \param IsKnownNewer \c true if this declaration is known to be newer
/// than \p OldD (for instance, if this declaration is newly-created).
bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
/// \brief Determine whether this declaration has linkage.
bool hasLinkage() const;
using Decl::isModulePrivate;
using Decl::setModulePrivate;
/// \brief Determine whether this declaration is hidden from name lookup.
bool isHidden() const { return Hidden; }
/// \brief Set whether this declaration is hidden from name lookup.
void setHidden(bool Hide) {
assert((!Hide || isFromASTFile() || hasLocalOwningModuleStorage()) &&
"declaration with no owning module can't be hidden");
Hidden = Hide;
}
/// \brief Determine whether this declaration is a C++ class member.
bool isCXXClassMember() const {
const DeclContext *DC = getDeclContext();
// C++0x [class.mem]p1:
// The enumerators of an unscoped enumeration defined in
// the class are members of the class.
if (isa<EnumDecl>(DC))
DC = DC->getRedeclContext();
return DC->isRecord();
}
/// \brief Determine whether the given declaration is an instance member of
/// a C++ class.
bool isCXXInstanceMember() const;
/// \brief Determine what kind of linkage this entity has.
/// This is not the linkage as defined by the standard or the codegen notion
/// of linkage. It is just an implementation detail that is used to compute
/// those.
Linkage getLinkageInternal() const;
/// \brief Get the linkage from a semantic point of view. Entities in
/// anonymous namespaces are external (in c++98).
Linkage getFormalLinkage() const {
return clang::getFormalLinkage(getLinkageInternal());
}
/// \brief True if this decl has external linkage.
bool hasExternalFormalLinkage() const {
return isExternalFormalLinkage(getLinkageInternal());
}
bool isExternallyVisible() const {
return clang::isExternallyVisible(getLinkageInternal());
}
/// \brief Determines the visibility of this entity.
Visibility getVisibility() const {
return getLinkageAndVisibility().getVisibility();
}
/// \brief Determines the linkage and visibility of this entity.
LinkageInfo getLinkageAndVisibility() const;
/// Kinds of explicit visibility.
enum ExplicitVisibilityKind {
VisibilityForType,
VisibilityForValue
};
/// \brief If visibility was explicitly specified for this
/// declaration, return that visibility.
Optional<Visibility>
getExplicitVisibility(ExplicitVisibilityKind kind) const;
/// \brief True if the computed linkage is valid. Used for consistency
/// checking. Should always return true.
bool isLinkageValid() const;
/// \brief True if something has required us to compute the linkage
/// of this declaration.
///
/// Language features which can retroactively change linkage (like a
/// typedef name for linkage purposes) may need to consider this,
/// but hopefully only in transitory ways during parsing.
bool hasLinkageBeenComputed() const {
return hasCachedLinkage();
}
/// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
/// the underlying named decl.
NamedDecl *getUnderlyingDecl() {
// Fast-path the common case.
if (this->getKind() != UsingShadow &&
this->getKind() != ObjCCompatibleAlias)
return this;
return getUnderlyingDeclImpl();
}
const NamedDecl *getUnderlyingDecl() const {
return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
}
NamedDecl *getMostRecentDecl() {
return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
}
const NamedDecl *getMostRecentDecl() const {
return const_cast<NamedDecl*>(this)->getMostRecentDecl();
}
ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
};
inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
ND.printName(OS);
return OS;
}
/// LabelDecl - Represents the declaration of a label. Labels also have a
/// corresponding LabelStmt, which indicates the position that the label was
/// defined at. For normal labels, the location of the decl is the same as the
/// location of the statement. For GNU local labels (__label__), the decl
/// location is where the __label__ is.
class LabelDecl : public NamedDecl {
void anchor() override;
LabelStmt *TheStmt;
StringRef MSAsmName;
bool MSAsmNameResolved;
/// LocStart - For normal labels, this is the same as the main declaration
/// label, i.e., the location of the identifier; for GNU local labels,
/// this is the location of the __label__ keyword.
SourceLocation LocStart;
LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
LabelStmt *S, SourceLocation StartL)
: NamedDecl(Label, DC, IdentL, II),
TheStmt(S),
MSAsmNameResolved(false),
LocStart(StartL) {}
public:
static LabelDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation IdentL, IdentifierInfo *II);
static LabelDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation IdentL, IdentifierInfo *II,
SourceLocation GnuLabelL);
static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
LabelStmt *getStmt() const { return TheStmt; }
void setStmt(LabelStmt *T) { TheStmt = T; }
bool isGnuLocal() const { return LocStart != getLocation(); }
void setLocStart(SourceLocation L) { LocStart = L; }
SourceRange getSourceRange() const override LLVM_READONLY {
return SourceRange(LocStart, getLocation());
}
bool isMSAsmLabel() const { return MSAsmName.size() != 0; }
bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
void setMSAsmLabel(StringRef Name);
StringRef getMSAsmLabel() const { return MSAsmName; }
void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Label; }
};
/// NamespaceDecl - Represent a C++ namespace.
class NamespaceDecl : public NamedDecl, public DeclContext,
public Redeclarable<NamespaceDecl>
{
/// LocStart - The starting location of the source range, pointing
/// to either the namespace or the inline keyword.
SourceLocation LocStart;
/// RBraceLoc - The ending location of the source range.
SourceLocation RBraceLoc;
/// \brief A pointer to either the anonymous namespace that lives just inside
/// this namespace or to the first namespace in the chain (the latter case
/// only when this is not the first in the chain), along with a
/// boolean value indicating whether this is an inline namespace.
llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, NamespaceDecl *PrevDecl);
typedef Redeclarable<NamespaceDecl> redeclarable_base;
NamespaceDecl *getNextRedeclarationImpl() override;
NamespaceDecl *getPreviousDeclImpl() override;
NamespaceDecl *getMostRecentDeclImpl() override;
public:
static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
bool Inline, SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
NamespaceDecl *PrevDecl);
static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
typedef redeclarable_base::redecl_range redecl_range;
typedef redeclarable_base::redecl_iterator redecl_iterator;
using redeclarable_base::redecls_begin;
using redeclarable_base::redecls_end;
using redeclarable_base::redecls;
using redeclarable_base::getPreviousDecl;
using redeclarable_base::getMostRecentDecl;
using redeclarable_base::isFirstDecl;
/// \brief Returns true if this is an anonymous namespace declaration.
///
/// For example:
/// \code
/// namespace {
/// ...
/// };
/// \endcode
/// q.v. C++ [namespace.unnamed]
bool isAnonymousNamespace() const {
return !getIdentifier();
}
/// \brief Returns true if this is an inline namespace declaration.
bool isInline() const {
return AnonOrFirstNamespaceAndInline.getInt();
}
/// \brief Set whether this is an inline namespace declaration.
void setInline(bool Inline) {
AnonOrFirstNamespaceAndInline.setInt(Inline);
}
/// \brief Get the original (first) namespace declaration.
NamespaceDecl *getOriginalNamespace() {
if (isFirstDecl())
return this;
return AnonOrFirstNamespaceAndInline.getPointer();
}
/// \brief Get the original (first) namespace declaration.
const NamespaceDecl *getOriginalNamespace() const {
if (isFirstDecl())
return this;
return AnonOrFirstNamespaceAndInline.getPointer();
}
/// \brief Return true if this declaration is an original (first) declaration
/// of the namespace. This is false for non-original (subsequent) namespace
/// declarations and anonymous namespaces.
bool isOriginalNamespace() const { return isFirstDecl(); }
/// \brief Retrieve the anonymous namespace nested inside this namespace,
/// if any.
NamespaceDecl *getAnonymousNamespace() const {
return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
}
void setAnonymousNamespace(NamespaceDecl *D) {
getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
}
/// Retrieves the canonical declaration of this namespace.
NamespaceDecl *getCanonicalDecl() override {
return getOriginalNamespace();
}
const NamespaceDecl *getCanonicalDecl() const {
return getOriginalNamespace();
}
SourceRange getSourceRange() const override LLVM_READONLY {
return SourceRange(LocStart, RBraceLoc);
}
SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
SourceLocation getRBraceLoc() const { return RBraceLoc; }
void setLocStart(SourceLocation L) { LocStart = L; }
void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Namespace; }
static DeclContext *castToDeclContext(const NamespaceDecl *D) {
return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
}
static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
}
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// ValueDecl - Represent the declaration of a variable (in which case it is
/// an lvalue) a function (in which case it is a function designator) or
/// an enum constant.
class ValueDecl : public NamedDecl {
void anchor() override;
QualType DeclType;
protected:
ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
DeclarationName N, QualType T)
: NamedDecl(DK, DC, L, N), DeclType(T) {}
public:
QualType getType() const { return DeclType; }
void setType(QualType newType) { DeclType = newType; }
/// \brief Determine whether this symbol is weakly-imported,
/// or declared with the weak or weak-ref attr.
bool isWeak() const;
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
};
/// QualifierInfo - A struct with extended info about a syntactic
/// name qualifier, to be used for the case of out-of-line declarations.
struct QualifierInfo {
NestedNameSpecifierLoc QualifierLoc;
/// NumTemplParamLists - The number of "outer" template parameter lists.
/// The count includes all of the template parameter lists that were matched
/// against the template-ids occurring into the NNS and possibly (in the
/// case of an explicit specialization) a final "template <>".
unsigned NumTemplParamLists;
/// TemplParamLists - A new-allocated array of size NumTemplParamLists,
/// containing pointers to the "outer" template parameter lists.
/// It includes all of the template parameter lists that were matched
/// against the template-ids occurring into the NNS and possibly (in the
/// case of an explicit specialization) a final "template <>".
TemplateParameterList** TemplParamLists;
/// Default constructor.
QualifierInfo()
: QualifierLoc(), NumTemplParamLists(0), TemplParamLists(nullptr) {}
/// setTemplateParameterListsInfo - Sets info about "outer" template
/// parameter lists.
void setTemplateParameterListsInfo(ASTContext &Context,
unsigned NumTPLists,
TemplateParameterList **TPLists);
private:
// Copy constructor and copy assignment are disabled.
QualifierInfo(const QualifierInfo&) = delete;
QualifierInfo& operator=(const QualifierInfo&) = delete;
};
/// \brief Represents a ValueDecl that came out of a declarator.
/// Contains type source information through TypeSourceInfo.
class DeclaratorDecl : public ValueDecl {
// A struct representing both a TInfo and a syntactic qualifier,
// to be used for the (uncommon) case of out-of-line declarations.
struct ExtInfo : public QualifierInfo {
TypeSourceInfo *TInfo;
};
llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo;
/// InnerLocStart - The start of the source range for this declaration,
/// ignoring outer template declarations.
SourceLocation InnerLocStart;
bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
protected:
DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
DeclarationName N, QualType T, TypeSourceInfo *TInfo,
SourceLocation StartL)
: ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {
}
public:
TypeSourceInfo *getTypeSourceInfo() const {
return hasExtInfo()
? getExtInfo()->TInfo
: DeclInfo.get<TypeSourceInfo*>();
}
void setTypeSourceInfo(TypeSourceInfo *TI) {
if (hasExtInfo())
getExtInfo()->TInfo = TI;
else
DeclInfo = TI;
}
/// getInnerLocStart - Return SourceLocation representing start of source
/// range ignoring outer template declarations.
SourceLocation getInnerLocStart() const { return InnerLocStart; }
void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
/// getOuterLocStart - Return SourceLocation representing start of source
/// range taking into account any outer template declarations.
SourceLocation getOuterLocStart() const;
SourceRange getSourceRange() const override LLVM_READONLY;
SourceLocation getLocStart() const LLVM_READONLY {
return getOuterLocStart();
}
/// \brief Retrieve the nested-name-specifier that qualifies the name of this
/// declaration, if it was present in the source.
NestedNameSpecifier *getQualifier() const {
return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
: nullptr;
}
/// \brief Retrieve the nested-name-specifier (with source-location
/// information) that qualifies the name of this declaration, if it was
/// present in the source.
NestedNameSpecifierLoc getQualifierLoc() const {
return hasExtInfo() ? getExtInfo()->QualifierLoc
: NestedNameSpecifierLoc();
}
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
unsigned getNumTemplateParameterLists() const {
return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
}
TemplateParameterList *getTemplateParameterList(unsigned index) const {
assert(index < getNumTemplateParameterLists());
return getExtInfo()->TemplParamLists[index];
}
void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
TemplateParameterList **TPLists);
SourceLocation getTypeSpecStartLoc() const;
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) {
return K >= firstDeclarator && K <= lastDeclarator;
}
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// \brief Structure used to store a statement, the constant value to
/// which it was evaluated (if any), and whether or not the statement
/// is an integral constant expression (if known).
struct EvaluatedStmt {
EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
CheckingICE(false), IsICE(false) { }
/// \brief Whether this statement was already evaluated.
bool WasEvaluated : 1;
/// \brief Whether this statement is being evaluated.
bool IsEvaluating : 1;
/// \brief Whether we already checked whether this statement was an
/// integral constant expression.
bool CheckedICE : 1;
/// \brief Whether we are checking whether this statement is an
/// integral constant expression.
bool CheckingICE : 1;
/// \brief Whether this statement is an integral constant expression,
/// or in C++11, whether the statement is a constant expression. Only
/// valid if CheckedICE is true.
bool IsICE : 1;
Stmt *Value;
APValue Evaluated;
};
/// VarDecl - An instance of this class is created to represent a variable
/// declaration or definition.
class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
public:
/// getStorageClassSpecifierString - Return the string used to
/// specify the storage class \p SC.
///
/// It is illegal to call this function with SC == None.
static const char *getStorageClassSpecifierString(StorageClass SC);
/// \brief Initialization styles.
enum InitializationStyle {
CInit, ///< C-style initialization with assignment
CallInit, ///< Call-style initialization (C++98)
ListInit ///< Direct list-initialization (C++11)
};
/// \brief Kinds of thread-local storage.
enum TLSKind {
TLS_None, ///< Not a TLS variable.
TLS_Static, ///< TLS with a known-constant initializer.
TLS_Dynamic ///< TLS with a dynamic initializer.
};
protected:
/// \brief Placeholder type used in Init to denote an unparsed C++ default
/// argument.
struct UnparsedDefaultArgument;
/// \brief Placeholder type used in Init to denote an uninstantiated C++
/// default argument.
struct UninstantiatedDefaultArgument;
typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *,
UnparsedDefaultArgument *,
UninstantiatedDefaultArgument *> InitType;
/// \brief The initializer for this variable or, for a ParmVarDecl, the
/// C++ default argument.
mutable InitType Init;
private:
class VarDeclBitfields {
friend class VarDecl;
friend class ASTDeclReader;
unsigned SClass : 3;
unsigned TSCSpec : 2;
unsigned InitStyle : 2;
};
enum { NumVarDeclBits = 7 };
friend class ASTDeclReader;
friend class StmtIteratorBase;
friend class ASTNodeImporter;
protected:
enum { NumParameterIndexBits = 8 };
class ParmVarDeclBitfields {
friend class ParmVarDecl;
friend class ASTDeclReader;
unsigned : NumVarDeclBits;
/// Whether this parameter inherits a default argument from a
/// prior declaration.
unsigned HasInheritedDefaultArg : 1;
/// Whether this parameter undergoes K&R argument promotion.
unsigned IsKNRPromoted : 1;
/// Whether this parameter is an ObjC method parameter or not.
unsigned IsObjCMethodParam : 1;
/// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
/// Otherwise, the number of function parameter scopes enclosing
/// the function parameter scope in which this parameter was
/// declared.
unsigned ScopeDepthOrObjCQuals : 7;
/// Whether the parameter is copied out.
unsigned IsModifierOut : 1;
/// The number of parameters preceding this parameter in the
/// function parameter scope in which it was declared.
unsigned ParameterIndex : NumParameterIndexBits;
};
class NonParmVarDeclBitfields {
friend class VarDecl;
friend class ASTDeclReader;
unsigned : NumVarDeclBits;
/// \brief Whether this variable is the exception variable in a C++ catch
/// or an Objective-C @catch statement.
unsigned ExceptionVar : 1;
/// \brief Whether this local variable could be allocated in the return
/// slot of its function, enabling the named return value optimization
/// (NRVO).
unsigned NRVOVariable : 1;
/// \brief Whether this variable is the for-range-declaration in a C++0x
/// for-range statement.
unsigned CXXForRangeDecl : 1;
/// \brief Whether this variable is an ARC pseudo-__strong
/// variable; see isARCPseudoStrong() for details.
unsigned ARCPseudoStrong : 1;
/// \brief Whether this variable is (C++0x) constexpr.
unsigned IsConstexpr : 1;
/// \brief Whether this variable is the implicit variable for a lambda
/// init-capture.
unsigned IsInitCapture : 1;
/// \brief Whether this local extern variable's previous declaration was
/// declared in the same block scope. This controls whether we should merge
/// the type of this declaration with its previous declaration.
unsigned PreviousDeclInSameBlockScope : 1;
};
union {
unsigned AllBits;
VarDeclBitfields VarDeclBits;
ParmVarDeclBitfields ParmVarDeclBits;
NonParmVarDeclBitfields NonParmVarDeclBits;
};
VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
TypeSourceInfo *TInfo, StorageClass SC);
typedef Redeclarable<VarDecl> redeclarable_base;
VarDecl *getNextRedeclarationImpl() override {
return getNextRedeclaration();
}
VarDecl *getPreviousDeclImpl() override {
return getPreviousDecl();
}
VarDecl *getMostRecentDeclImpl() override {
return getMostRecentDecl();
}
public:
typedef redeclarable_base::redecl_range redecl_range;
typedef redeclarable_base::redecl_iterator redecl_iterator;
using redeclarable_base::redecls_begin;
using redeclarable_base::redecls_end;
using redeclarable_base::redecls;
using redeclarable_base::getPreviousDecl;
using redeclarable_base::getMostRecentDecl;
using redeclarable_base::isFirstDecl;
static VarDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
StorageClass S);
static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
SourceRange getSourceRange() const override LLVM_READONLY;
/// \brief Returns the storage class as written in the source. For the
/// computed linkage of symbol, see getLinkage.
StorageClass getStorageClass() const {
return (StorageClass) VarDeclBits.SClass;
}
void setStorageClass(StorageClass SC);
void setTSCSpec(ThreadStorageClassSpecifier TSC) {
VarDeclBits.TSCSpec = TSC;
assert(VarDeclBits.TSCSpec == TSC && "truncation");
}
ThreadStorageClassSpecifier getTSCSpec() const {
return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
}
TLSKind getTLSKind() const;
/// hasLocalStorage - Returns true if a variable with function scope
/// is a non-static local variable.
bool hasLocalStorage() const {
if (getStorageClass() == SC_None)
// Second check is for C++11 [dcl.stc]p4.
return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
// Global Named Register (GNU extension)
if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
return false;
// Return true for: Auto, Register.
// Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
return getStorageClass() >= SC_Auto;
}
/// isStaticLocal - Returns true if a variable with function scope is a
/// static local variable.
bool isStaticLocal() const {
return (getStorageClass() == SC_Static ||
// C++11 [dcl.stc]p4
(getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
&& !isFileVarDecl();
}
/// \brief Returns true if a variable has extern or __private_extern__
/// storage.
bool hasExternalStorage() const {
return getStorageClass() == SC_Extern ||
getStorageClass() == SC_PrivateExtern;
}
/// \brief Returns true for all variables that do not have local storage.
///
/// This includes all global variables as well as static variables declared
/// within a function.
bool hasGlobalStorage() const { return !hasLocalStorage(); }
/// \brief Get the storage duration of this variable, per C++ [basic.stc].
StorageDuration getStorageDuration() const {
return hasLocalStorage() ? SD_Automatic :
getTSCSpec() ? SD_Thread : SD_Static;
}
/// \brief Compute the language linkage.
LanguageLinkage getLanguageLinkage() const;
/// \brief Determines whether this variable is a variable with
/// external, C linkage.
bool isExternC() const;
/// \brief Determines whether this variable's context is, or is nested within,
/// a C++ extern "C" linkage spec.
bool isInExternCContext() const;
/// \brief Determines whether this variable's context is, or is nested within,
/// a C++ extern "C++" linkage spec.
bool isInExternCXXContext() const;
/// isLocalVarDecl - Returns true for local variable declarations
/// other than parameters. Note that this includes static variables
/// inside of functions. It also includes variables inside blocks.
///
/// void foo() { int x; static int y; extern int z; }
///
bool isLocalVarDecl() const {
if (getKind() != Decl::Var)
return false;
if (const DeclContext *DC = getLexicalDeclContext())
return DC->getRedeclContext()->isFunctionOrMethod();
return false;
}
/// \brief Similar to isLocalVarDecl but also includes parameters.
bool isLocalVarDeclOrParm() const {
return isLocalVarDecl() || getKind() == Decl::ParmVar;
}
/// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
/// excludes variables declared in blocks.
bool isFunctionOrMethodVarDecl() const {
if (getKind() != Decl::Var)
return false;
const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
}
/// \brief Determines whether this is a static data member.
///
/// This will only be true in C++, and applies to, e.g., the
/// variable 'x' in:
/// \code
/// struct S {
/// static int x;
/// };
/// \endcode
bool isStaticDataMember() const {
// If it wasn't static, it would be a FieldDecl.
return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
}
VarDecl *getCanonicalDecl() override;
const VarDecl *getCanonicalDecl() const {
return const_cast<VarDecl*>(this)->getCanonicalDecl();
}
enum DefinitionKind {
DeclarationOnly, ///< This declaration is only a declaration.
TentativeDefinition, ///< This declaration is a tentative definition.
Definition ///< This declaration is definitely a definition.
};
/// \brief Check whether this declaration is a definition. If this could be
/// a tentative definition (in C), don't check whether there's an overriding
/// definition.
DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
DefinitionKind isThisDeclarationADefinition() const {
return isThisDeclarationADefinition(getASTContext());
}
/// \brief Check whether this variable is defined in this
/// translation unit.
DefinitionKind hasDefinition(ASTContext &) const;
DefinitionKind hasDefinition() const {
return hasDefinition(getASTContext());
}
/// \brief Get the tentative definition that acts as the real definition in
/// a TU. Returns null if there is a proper definition available.
VarDecl *getActingDefinition();
const VarDecl *getActingDefinition() const {
return const_cast<VarDecl*>(this)->getActingDefinition();
}
/// \brief Get the real (not just tentative) definition for this declaration.
VarDecl *getDefinition(ASTContext &);
const VarDecl *getDefinition(ASTContext &C) const {
return const_cast<VarDecl*>(this)->getDefinition(C);
}
VarDecl *getDefinition() {
return getDefinition(getASTContext());
}
const VarDecl *getDefinition() const {
return const_cast<VarDecl*>(this)->getDefinition();
}
/// \brief Determine whether this is or was instantiated from an out-of-line
/// definition of a static data member.
bool isOutOfLine() const override;
/// \brief If this is a static data member, find its out-of-line definition.
VarDecl *getOutOfLineDefinition();
/// isFileVarDecl - Returns true for file scoped variable declaration.
bool isFileVarDecl() const {
Kind K = getKind();
if (K == ParmVar || K == ImplicitParam)
return false;
if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
return true;
if (isStaticDataMember())
return true;
return false;
}
/// getAnyInitializer - Get the initializer for this variable, no matter which
/// declaration it is attached to.
const Expr *getAnyInitializer() const {
const VarDecl *D;
return getAnyInitializer(D);
}
/// getAnyInitializer - Get the initializer for this variable, no matter which
/// declaration it is attached to. Also get that declaration.
const Expr *getAnyInitializer(const VarDecl *&D) const;
bool hasInit() const {
return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>());
}
const Expr *getInit() const {
if (Init.isNull())
return nullptr;
const Stmt *S = Init.dyn_cast<Stmt *>();
if (!S) {
if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
S = ES->Value;
}
return (const Expr*) S;
}
Expr *getInit() {
if (Init.isNull())
return nullptr;
Stmt *S = Init.dyn_cast<Stmt *>();
if (!S) {
if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
S = ES->Value;
}
return (Expr*) S;
}
/// \brief Retrieve the address of the initializer expression.
Stmt **getInitAddress() {
if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>())
return &ES->Value;
// This union hack tip-toes around strict-aliasing rules.
union {
InitType *InitPtr;
Stmt **StmtPtr;
};
InitPtr = &Init;
return StmtPtr;
}
void setInit(Expr *I);
/// \brief Determine whether this variable's value can be used in a
/// constant expression, according to the relevant language standard.
/// This only checks properties of the declaration, and does not check
/// whether the initializer is in fact a constant expression.
bool isUsableInConstantExpressions(ASTContext &C) const;
EvaluatedStmt *ensureEvaluatedStmt() const;
/// \brief Attempt to evaluate the value of the initializer attached to this
/// declaration, and produce notes explaining why it cannot be evaluated or is
/// not a constant expression. Returns a pointer to the value if evaluation
/// succeeded, 0 otherwise.
APValue *evaluateValue() const;
APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
/// \brief Return the already-evaluated value of this variable's
/// initializer, or NULL if the value is not yet known. Returns pointer
/// to untyped APValue if the value could not be evaluated.
APValue *getEvaluatedValue() const {
if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
if (Eval->WasEvaluated)
return &Eval->Evaluated;
return nullptr;
}
/// \brief Determines whether it is already known whether the
/// initializer is an integral constant expression or not.
bool isInitKnownICE() const {
if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
return Eval->CheckedICE;
return false;
}
/// \brief Determines whether the initializer is an integral constant
/// expression, or in C++11, whether the initializer is a constant
/// expression.
///
/// \pre isInitKnownICE()
bool isInitICE() const {
assert(isInitKnownICE() &&
"Check whether we already know that the initializer is an ICE");
return Init.get<EvaluatedStmt *>()->IsICE;
}
/// \brief Determine whether the value of the initializer attached to this
/// declaration is an integral constant expression.
bool checkInitIsICE() const;
void setInitStyle(InitializationStyle Style) {
VarDeclBits.InitStyle = Style;
}
/// \brief The style of initialization for this declaration.
///
/// C-style initialization is "int x = 1;". Call-style initialization is
/// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be
/// the expression inside the parens or a "ClassType(a,b,c)" class constructor
/// expression for class types. List-style initialization is C++11 syntax,
/// e.g. "int x{1};". Clients can distinguish between different forms of
/// initialization by checking this value. In particular, "int x = {1};" is
/// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the
/// Init expression in all three cases is an InitListExpr.
InitializationStyle getInitStyle() const {
return static_cast<InitializationStyle>(VarDeclBits.InitStyle);
}
/// \brief Whether the initializer is a direct-initializer (list or call).
bool isDirectInit() const {
return getInitStyle() != CInit;
}
/// \brief Determine whether this variable is the exception variable in a
/// C++ catch statememt or an Objective-C \@catch statement.
bool isExceptionVariable() const {
return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar;
}
void setExceptionVariable(bool EV) {
assert(!isa<ParmVarDecl>(this));
NonParmVarDeclBits.ExceptionVar = EV;
}
/// \brief Determine whether this local variable can be used with the named
/// return value optimization (NRVO).
///
/// The named return value optimization (NRVO) works by marking certain
/// non-volatile local variables of class type as NRVO objects. These
/// locals can be allocated within the return slot of their containing
/// function, in which case there is no need to copy the object to the
/// return slot when returning from the function. Within the function body,
/// each return that returns the NRVO object will have this variable as its
/// NRVO candidate.
bool isNRVOVariable() const {
return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable;
}
void setNRVOVariable(bool NRVO) {
assert(!isa<ParmVarDecl>(this));
NonParmVarDeclBits.NRVOVariable = NRVO;
}
/// \brief Determine whether this variable is the for-range-declaration in
/// a C++0x for-range statement.
bool isCXXForRangeDecl() const {
return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl;
}
void setCXXForRangeDecl(bool FRD) {
assert(!isa<ParmVarDecl>(this));
NonParmVarDeclBits.CXXForRangeDecl = FRD;
}
/// \brief Determine whether this variable is an ARC pseudo-__strong
/// variable. A pseudo-__strong variable has a __strong-qualified
/// type but does not actually retain the object written into it.
/// Generally such variables are also 'const' for safety.
bool isARCPseudoStrong() const {
return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ARCPseudoStrong;
}
void setARCPseudoStrong(bool ps) {
assert(!isa<ParmVarDecl>(this));
NonParmVarDeclBits.ARCPseudoStrong = ps;
}
/// Whether this variable is (C++11) constexpr.
bool isConstexpr() const {
return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr;
}
void setConstexpr(bool IC) {
assert(!isa<ParmVarDecl>(this));
NonParmVarDeclBits.IsConstexpr = IC;
}
/// Whether this variable is the implicit variable for a lambda init-capture.
bool isInitCapture() const {
return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture;
}
void setInitCapture(bool IC) {
assert(!isa<ParmVarDecl>(this));
NonParmVarDeclBits.IsInitCapture = IC;
}
/// Whether this local extern variable declaration's previous declaration
/// was declared in the same block scope. Only correct in C++.
bool isPreviousDeclInSameBlockScope() const {
return isa<ParmVarDecl>(this)
? false
: NonParmVarDeclBits.PreviousDeclInSameBlockScope;
}
void setPreviousDeclInSameBlockScope(bool Same) {
assert(!isa<ParmVarDecl>(this));
NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same;
}
/// \brief If this variable is an instantiated static data member of a
/// class template specialization, returns the templated static data member
/// from which it was instantiated.
VarDecl *getInstantiatedFromStaticDataMember() const;
/// \brief If this variable is an instantiation of a variable template or a
/// static data member of a class template, determine what kind of
/// template specialization or instantiation this is.
TemplateSpecializationKind getTemplateSpecializationKind() const;
/// \brief If this variable is an instantiation of a variable template or a
/// static data member of a class template, determine its point of
/// instantiation.
SourceLocation getPointOfInstantiation() const;
/// \brief If this variable is an instantiation of a static data member of a
/// class template specialization, retrieves the member specialization
/// information.
MemberSpecializationInfo *getMemberSpecializationInfo() const;
/// \brief For a static data member that was instantiated from a static
/// data member of a class template, set the template specialiation kind.
void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
SourceLocation PointOfInstantiation = SourceLocation());
/// \brief Specify that this variable is an instantiation of the
/// static data member VD.
void setInstantiationOfStaticDataMember(VarDecl *VD,
TemplateSpecializationKind TSK);
/// \brief Retrieves the variable template that is described by this
/// variable declaration.
///
/// Every variable template is represented as a VarTemplateDecl and a
/// VarDecl. The former contains template properties (such as
/// the template parameter lists) while the latter contains the
/// actual description of the template's
/// contents. VarTemplateDecl::getTemplatedDecl() retrieves the
/// VarDecl that from a VarTemplateDecl, while
/// getDescribedVarTemplate() retrieves the VarTemplateDecl from
/// a VarDecl.
VarTemplateDecl *getDescribedVarTemplate() const;
void setDescribedVarTemplate(VarTemplateDecl *Template);
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; }
};
class ImplicitParamDecl : public VarDecl {
void anchor() override;
public:
static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation IdLoc, IdentifierInfo *Id,
QualType T);
static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID);
ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc,
IdentifierInfo *Id, QualType Type)
: VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type,
/*tinfo*/ nullptr, SC_None) {
setImplicit();
}
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == ImplicitParam; }
};
/// ParmVarDecl - Represents a parameter to a function.
class ParmVarDecl : public VarDecl {
public:
enum { MaxFunctionScopeDepth = 255 };
enum { MaxFunctionScopeIndex = 255 };
protected:
ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg,
hlsl::ParameterModifier ParamMod) // HLSL Change
: VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) {
assert(ParmVarDeclBits.HasInheritedDefaultArg == false);
assert(ParmVarDeclBits.IsKNRPromoted == false);
assert(ParmVarDeclBits.IsObjCMethodParam == false);
setDefaultArg(DefArg);
// HLSL Change Start
setModifierIn(ParamMod.isAnyIn());
setModifierOut(ParamMod.isAnyOut());
// change to reference type for out param
if (ParamMod.isAnyOut())
updateOutParamToRefType(C);
// HLSL Change End
}
public:
static ParmVarDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
QualType T, TypeSourceInfo *TInfo,
StorageClass S, Expr *DefArg,
hlsl::ParameterModifier ParamMod = hlsl::ParameterModifier()); // HLSL Change
static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
SourceRange getSourceRange() const override LLVM_READONLY;
void setObjCMethodScopeInfo(unsigned parameterIndex) {
ParmVarDeclBits.IsObjCMethodParam = true;
setParameterIndex(parameterIndex);
}
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) {
assert(!ParmVarDeclBits.IsObjCMethodParam);
ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth;
assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth
&& "truncation!");
setParameterIndex(parameterIndex);
}
bool isObjCMethodParameter() const {
return ParmVarDeclBits.IsObjCMethodParam;
}
unsigned getFunctionScopeDepth() const {
if (ParmVarDeclBits.IsObjCMethodParam) return 0;
return ParmVarDeclBits.ScopeDepthOrObjCQuals;
}
/// Returns the index of this parameter in its prototype or method scope.
unsigned getFunctionScopeIndex() const {
return getParameterIndex();
}
ObjCDeclQualifier getObjCDeclQualifier() const {
if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None;
return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals);
}
void setObjCDeclQualifier(ObjCDeclQualifier QTVal) {
assert(ParmVarDeclBits.IsObjCMethodParam);
ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal;
}
/// True if the value passed to this parameter must undergo
/// K&R-style default argument promotion:
///
/// C99 6.5.2.2.
/// If the expression that denotes the called function has a type
/// that does not include a prototype, the integer promotions are
/// performed on each argument, and arguments that have type float
/// are promoted to double.
bool isKNRPromoted() const {
return ParmVarDeclBits.IsKNRPromoted;
}
void setKNRPromoted(bool promoted) {
ParmVarDeclBits.IsKNRPromoted = promoted;
}
// HLSL Change Starts
// IsKNRPromoted maps to 'in' bit (flipped).
bool isModifierIn() const { return !ParmVarDeclBits.IsKNRPromoted; }
void setModifierIn(bool value) { ParmVarDeclBits.IsKNRPromoted = !value; }
bool isModifierOut() const { return ParmVarDeclBits.IsModifierOut; }
void setModifierOut(bool value) { ParmVarDeclBits.IsModifierOut = value; }
/// Synthesize a ParameterModifier value for this parameter.
hlsl::ParameterModifier getParamModifiers() const {
if (isModifierIn() && !isModifierOut())
return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In);
if (isModifierIn() && isModifierOut())
return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::InOut);
return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::Out);
}
void updateOutParamToRefType(ASTContext &C);
// HLSL Change Ends
Expr *getDefaultArg();
const Expr *getDefaultArg() const {
return const_cast<ParmVarDecl *>(this)->getDefaultArg();
}
void setDefaultArg(Expr *defarg) {
Init = reinterpret_cast<Stmt *>(defarg);
}
/// \brief Retrieve the source range that covers the entire default
/// argument.
SourceRange getDefaultArgRange() const;
void setUninstantiatedDefaultArg(Expr *arg) {
Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg);
}
Expr *getUninstantiatedDefaultArg() {
return (Expr *)Init.get<UninstantiatedDefaultArgument *>();
}
const Expr *getUninstantiatedDefaultArg() const {
return (const Expr *)Init.get<UninstantiatedDefaultArgument *>();
}
/// hasDefaultArg - Determines whether this parameter has a default argument,
/// either parsed or not.
bool hasDefaultArg() const {
return getInit() || hasUnparsedDefaultArg() ||
hasUninstantiatedDefaultArg();
}
/// hasUnparsedDefaultArg - Determines whether this parameter has a
/// default argument that has not yet been parsed. This will occur
/// during the processing of a C++ class whose member functions have
/// default arguments, e.g.,
/// @code
/// class X {
/// public:
/// void f(int x = 17); // x has an unparsed default argument now
/// }; // x has a regular default argument now
/// @endcode
bool hasUnparsedDefaultArg() const {
return Init.is<UnparsedDefaultArgument*>();
}
bool hasUninstantiatedDefaultArg() const {
return Init.is<UninstantiatedDefaultArgument*>();
}
/// setUnparsedDefaultArg - Specify that this parameter has an
/// unparsed default argument. The argument will be replaced with a
/// real default argument via setDefaultArg when the class
/// definition enclosing the function declaration that owns this
/// default argument is completed.
void setUnparsedDefaultArg() { Init = (UnparsedDefaultArgument *)nullptr; }
bool hasInheritedDefaultArg() const {
return ParmVarDeclBits.HasInheritedDefaultArg;
}
void setHasInheritedDefaultArg(bool I = true) {
ParmVarDeclBits.HasInheritedDefaultArg = I;
}
QualType getOriginalType() const;
/// \brief Determine whether this parameter is actually a function
/// parameter pack.
bool isParameterPack() const;
/// setOwningFunction - Sets the function declaration that owns this
/// ParmVarDecl. Since ParmVarDecls are often created before the
/// FunctionDecls that own them, this routine is required to update
/// the DeclContext appropriately.
void setOwningFunction(DeclContext *FD) { setDeclContext(FD); }
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == ParmVar; }
private:
enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 };
void setParameterIndex(unsigned parameterIndex) {
if (parameterIndex >= ParameterIndexSentinel) {
setParameterIndexLarge(parameterIndex);
return;
}
ParmVarDeclBits.ParameterIndex = parameterIndex;
assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!");
}
unsigned getParameterIndex() const {
unsigned d = ParmVarDeclBits.ParameterIndex;
return d == ParameterIndexSentinel ? getParameterIndexLarge() : d;
}
void setParameterIndexLarge(unsigned parameterIndex);
unsigned getParameterIndexLarge() const;
};
/// FunctionDecl - An instance of this class is created to represent a
/// function declaration or definition.
///
/// Since a given function can be declared several times in a program,
/// there may be several FunctionDecls that correspond to that
/// function. Only one of those FunctionDecls will be found when
/// traversing the list of declarations in the context of the
/// FunctionDecl (e.g., the translation unit); this FunctionDecl
/// contains all of the information known about the function. Other,
/// previous declarations of the function are available via the
/// getPreviousDecl() chain.
class FunctionDecl : public DeclaratorDecl, public DeclContext,
public Redeclarable<FunctionDecl> {
public:
/// \brief The kind of templated function a FunctionDecl can be.
enum TemplatedKind {
TK_NonTemplate,
TK_FunctionTemplate,
TK_MemberSpecialization,
TK_FunctionTemplateSpecialization,
TK_DependentFunctionTemplateSpecialization
};
private:
/// ParamInfo - new[]'d array of pointers to VarDecls for the formal
/// parameters of this function. This is null if a prototype or if there are
/// no formals.
ParmVarDecl **ParamInfo;
/// DeclsInPrototypeScope - Array of pointers to NamedDecls for
/// decls defined in the function prototype that are not parameters. E.g.
/// 'enum Y' in 'void f(enum Y {AA} x) {}'.
ArrayRef<NamedDecl *> DeclsInPrototypeScope;
LazyDeclStmtPtr Body;
// FIXME: This can be packed into the bitfields in Decl.
// NOTE: VC++ treats enums as signed, avoid using the StorageClass enum
unsigned SClass : 2;
bool IsInline : 1;
bool IsInlineSpecified : 1;
bool IsVirtualAsWritten : 1;
bool IsPure : 1;
bool HasInheritedPrototype : 1;
bool HasWrittenPrototype : 1;
bool IsDeleted : 1;
bool IsTrivial : 1; // sunk from CXXMethodDecl
bool IsDefaulted : 1; // sunk from CXXMethoDecl
bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl
bool HasImplicitReturnZero : 1;
bool IsLateTemplateParsed : 1;
bool IsConstexpr : 1;
/// \brief Indicates if the function uses __try.
bool UsesSEHTry : 1;
/// \brief Indicates if the function was a definition but its body was
/// skipped.
unsigned HasSkippedBody : 1;
/// \brief End part of this FunctionDecl's source range.
///
/// We could compute the full range in getSourceRange(). However, when we're
/// dealing with a function definition deserialized from a PCH/AST file,
/// we can only compute the full range once the function body has been
/// de-serialized, so it's far better to have the (sometimes-redundant)
/// EndRangeLoc.
SourceLocation EndRangeLoc;
/// \brief The template or declaration that this declaration
/// describes or was instantiated from, respectively.
///
/// For non-templates, this value will be NULL. For function
/// declarations that describe a function template, this will be a
/// pointer to a FunctionTemplateDecl. For member functions
/// of class template specializations, this will be a MemberSpecializationInfo
/// pointer containing information about the specialization.
/// For function template specializations, this will be a
/// FunctionTemplateSpecializationInfo, which contains information about
/// the template being specialized and the template arguments involved in
/// that specialization.
llvm::PointerUnion4<FunctionTemplateDecl *,
MemberSpecializationInfo *,
FunctionTemplateSpecializationInfo *,
DependentFunctionTemplateSpecializationInfo *>
TemplateOrSpecialization;
/// DNLoc - Provides source/type location info for the
/// declaration name embedded in the DeclaratorDecl base class.
DeclarationNameLoc DNLoc;
/// \brief Specify that this function declaration is actually a function
/// template specialization.
///
/// \param C the ASTContext.
///
/// \param Template the function template that this function template
/// specialization specializes.
///
/// \param TemplateArgs the template arguments that produced this
/// function template specialization from the template.
///
/// \param InsertPos If non-NULL, the position in the function template
/// specialization set where the function template specialization data will
/// be inserted.
///
/// \param TSK the kind of template specialization this is.
///
/// \param TemplateArgsAsWritten location info of template arguments.
///
/// \param PointOfInstantiation point at which the function template
/// specialization was first instantiated.
void setFunctionTemplateSpecialization(ASTContext &C,
FunctionTemplateDecl *Template,
const TemplateArgumentList *TemplateArgs,
void *InsertPos,
TemplateSpecializationKind TSK,
const TemplateArgumentListInfo *TemplateArgsAsWritten,
SourceLocation PointOfInstantiation);
/// \brief Specify that this record is an instantiation of the
/// member function FD.
void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD,
TemplateSpecializationKind TSK);
void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo);
protected:
FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo *TInfo,
StorageClass S, bool isInlineSpecified,
bool isConstexprSpecified)
: DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
StartLoc),
DeclContext(DK),
redeclarable_base(C),
ParamInfo(nullptr), Body(),
SClass(S),
IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified),
IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false),
HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false),
IsDefaulted(false), IsExplicitlyDefaulted(false),
HasImplicitReturnZero(false), IsLateTemplateParsed(false),
IsConstexpr(isConstexprSpecified), UsesSEHTry(false),
HasSkippedBody(false), EndRangeLoc(NameInfo.getEndLoc()),
TemplateOrSpecialization(),
DNLoc(NameInfo.getInfo()) {}
typedef Redeclarable<FunctionDecl> redeclarable_base;
FunctionDecl *getNextRedeclarationImpl() override {
return getNextRedeclaration();
}
FunctionDecl *getPreviousDeclImpl() override {
return getPreviousDecl();
}
FunctionDecl *getMostRecentDeclImpl() override {
return getMostRecentDecl();
}
public:
typedef redeclarable_base::redecl_range redecl_range;
typedef redeclarable_base::redecl_iterator redecl_iterator;
using redeclarable_base::redecls_begin;
using redeclarable_base::redecls_end;
using redeclarable_base::redecls;
using redeclarable_base::getPreviousDecl;
using redeclarable_base::getMostRecentDecl;
using redeclarable_base::isFirstDecl;
static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation NLoc,
DeclarationName N, QualType T,
TypeSourceInfo *TInfo,
StorageClass SC,
bool isInlineSpecified = false,
bool hasWrittenPrototype = true,
bool isConstexprSpecified = false) {
DeclarationNameInfo NameInfo(N, NLoc);
return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo,
SC,
isInlineSpecified, hasWrittenPrototype,
isConstexprSpecified);
}
static FunctionDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc,
const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo *TInfo,
StorageClass SC,
bool isInlineSpecified,
bool hasWrittenPrototype,
bool isConstexprSpecified = false);
static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
DeclarationNameInfo getNameInfo() const {
return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
}
void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
bool Qualified) const override;
void setRangeEnd(SourceLocation E) { EndRangeLoc = E; }
SourceRange getSourceRange() const override LLVM_READONLY;
/// \brief Returns true if the function has a body (definition). The
/// function body might be in any of the (re-)declarations of this
/// function. The variant that accepts a FunctionDecl pointer will
/// set that function declaration to the actual declaration
/// containing the body (if there is one).
bool hasBody(const FunctionDecl *&Definition) const;
bool hasBody() const override {
const FunctionDecl* Definition;
return hasBody(Definition);
}
/// hasTrivialBody - Returns whether the function has a trivial body that does
/// not require any specific codegen.
bool hasTrivialBody() const;
/// isDefined - Returns true if the function is defined at all, including
/// a deleted definition. Except for the behavior when the function is
/// deleted, behaves like hasBody.
bool isDefined(const FunctionDecl *&Definition) const;
virtual bool isDefined() const {
const FunctionDecl* Definition;
return isDefined(Definition);
}
/// getBody - Retrieve the body (definition) of the function. The
/// function body might be in any of the (re-)declarations of this
/// function. The variant that accepts a FunctionDecl pointer will
/// set that function declaration to the actual declaration
/// containing the body (if there is one).
/// NOTE: For checking if there is a body, use hasBody() instead, to avoid
/// unnecessary AST de-serialization of the body.
Stmt *getBody(const FunctionDecl *&Definition) const;
Stmt *getBody() const override {
const FunctionDecl* Definition;
return getBody(Definition);
}
/// isThisDeclarationADefinition - Returns whether this specific
/// declaration of the function is also a definition. This does not
/// determine whether the function has been defined (e.g., in a
/// previous definition); for that information, use isDefined. Note
/// that this returns false for a defaulted function unless that function
/// has been implicitly defined (possibly as deleted).
bool isThisDeclarationADefinition() const {
return IsDeleted || Body || IsLateTemplateParsed;
}
/// doesThisDeclarationHaveABody - Returns whether this specific
/// declaration of the function has a body - that is, if it is a non-
/// deleted definition.
bool doesThisDeclarationHaveABody() const {
return Body || IsLateTemplateParsed;
}
void setBody(Stmt *B);
void setLazyBody(uint64_t Offset) { Body = Offset; }
/// Whether this function is variadic.
bool isVariadic() const;
/// Whether this function is marked as virtual explicitly.
bool isVirtualAsWritten() const { return IsVirtualAsWritten; }
void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; }
/// Whether this virtual function is pure, i.e. makes the containing class
/// abstract.
bool isPure() const { return IsPure; }
void setPure(bool P = true);
/// Whether this templated function will be late parsed.
bool isLateTemplateParsed() const { return IsLateTemplateParsed; }
void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; }
/// Whether this function is "trivial" in some specialized C++ senses.
/// Can only be true for default constructors, copy constructors,
/// copy assignment operators, and destructors. Not meaningful until
/// the class has been fully built by Sema.
bool isTrivial() const { return IsTrivial; }
void setTrivial(bool IT) { IsTrivial = IT; }
/// Whether this function is defaulted per C++0x. Only valid for
/// special member functions.
bool isDefaulted() const { return IsDefaulted; }
void setDefaulted(bool D = true) { IsDefaulted = D; }
/// Whether this function is explicitly defaulted per C++0x. Only valid
/// for special member functions.
bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; }
void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; }
/// Whether falling off this function implicitly returns null/zero.
/// If a more specific implicit return value is required, front-ends
/// should synthesize the appropriate return statements.
bool hasImplicitReturnZero() const { return HasImplicitReturnZero; }
void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; }
/// \brief Whether this function has a prototype, either because one
/// was explicitly written or because it was "inherited" by merging
/// a declaration without a prototype with a declaration that has a
/// prototype.
bool hasPrototype() const {
return HasWrittenPrototype || HasInheritedPrototype;
}
bool hasWrittenPrototype() const { return HasWrittenPrototype; }
/// \brief Whether this function inherited its prototype from a
/// previous declaration.
bool hasInheritedPrototype() const { return HasInheritedPrototype; }
void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; }
/// Whether this is a (C++11) constexpr function or constexpr constructor.
bool isConstexpr() const { return IsConstexpr; }
void setConstexpr(bool IC) { IsConstexpr = IC; }
/// Whether this is a (C++11) constexpr function or constexpr constructor.
bool usesSEHTry() const { return UsesSEHTry; }
void setUsesSEHTry(bool UST) { UsesSEHTry = UST; }
/// \brief Whether this function has been deleted.
///
/// A function that is "deleted" (via the C++0x "= delete" syntax)
/// acts like a normal function, except that it cannot actually be
/// called or have its address taken. Deleted functions are
/// typically used in C++ overload resolution to attract arguments
/// whose type or lvalue/rvalue-ness would permit the use of a
/// different overload that would behave incorrectly. For example,
/// one might use deleted functions to ban implicit conversion from
/// a floating-point number to an Integer type:
///
/// @code
/// struct Integer {
/// Integer(long); // construct from a long
/// Integer(double) = delete; // no construction from float or double
/// Integer(long double) = delete; // no construction from long double
/// };
/// @endcode
// If a function is deleted, its first declaration must be.
bool isDeleted() const { return getCanonicalDecl()->IsDeleted; }
bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; }
void setDeletedAsWritten(bool D = true) { IsDeleted = D; }
/// \brief Determines whether this function is "main", which is the
/// entry point into an executable program.
bool isMain() const;
/// \brief Determines whether this function is a MSVCRT user defined entry
/// point.
bool isMSVCRTEntryPoint() const;
/// \brief Determines whether this operator new or delete is one
/// of the reserved global placement operators:
/// void *operator new(size_t, void *);
/// void *operator new[](size_t, void *);
/// void operator delete(void *, void *);
/// void operator delete[](void *, void *);
/// These functions have special behavior under [new.delete.placement]:
/// These functions are reserved, a C++ program may not define
/// functions that displace the versions in the Standard C++ library.
/// The provisions of [basic.stc.dynamic] do not apply to these
/// reserved placement forms of operator new and operator delete.
///
/// This function must be an allocation or deallocation function.
bool isReservedGlobalPlacementOperator() const;
/// \brief Determines whether this function is one of the replaceable
/// global allocation functions:
/// void *operator new(size_t);
/// void *operator new(size_t, const std::nothrow_t &) noexcept;
/// void *operator new[](size_t);
/// void *operator new[](size_t, const std::nothrow_t &) noexcept;
/// void operator delete(void *) noexcept;
/// void operator delete(void *, std::size_t) noexcept; [C++1y]
/// void operator delete(void *, const std::nothrow_t &) noexcept;
/// void operator delete[](void *) noexcept;
/// void operator delete[](void *, std::size_t) noexcept; [C++1y]
/// void operator delete[](void *, const std::nothrow_t &) noexcept;
/// These functions have special behavior under C++1y [expr.new]:
/// An implementation is allowed to omit a call to a replaceable global
/// allocation function. [...]
bool isReplaceableGlobalAllocationFunction() const;
/// Compute the language linkage.
LanguageLinkage getLanguageLinkage() const;
/// \brief Determines whether this function is a function with
/// external, C linkage.
bool isExternC() const;
/// \brief Determines whether this function's context is, or is nested within,
/// a C++ extern "C" linkage spec.
bool isInExternCContext() const;
/// \brief Determines whether this function's context is, or is nested within,
/// a C++ extern "C++" linkage spec.
bool isInExternCXXContext() const;
/// \brief Determines whether this is a global function.
bool isGlobal() const;
/// \brief Determines whether this function is known to be 'noreturn', through
/// an attribute on its declaration or its type.
bool isNoReturn() const;
/// \brief True if the function was a definition but its body was skipped.
bool hasSkippedBody() const { return HasSkippedBody; }
void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; }
void setPreviousDeclaration(FunctionDecl * PrevDecl);
FunctionDecl *getCanonicalDecl() override;
const FunctionDecl *getCanonicalDecl() const {
return const_cast<FunctionDecl*>(this)->getCanonicalDecl();
}
unsigned getBuiltinID() const;
// Iterator access to formal parameters.
unsigned param_size() const { return getNumParams(); }
typedef ParmVarDecl **param_iterator;
typedef ParmVarDecl * const *param_const_iterator;
typedef llvm::iterator_range<param_iterator> param_range;
typedef llvm::iterator_range<param_const_iterator> param_const_range;
param_iterator param_begin() { return param_iterator(ParamInfo); }
param_iterator param_end() {
return param_iterator(ParamInfo + param_size());
}
param_range params() { return param_range(param_begin(), param_end()); }
param_const_iterator param_begin() const {
return param_const_iterator(ParamInfo);
}
param_const_iterator param_end() const {
return param_const_iterator(ParamInfo + param_size());
}
param_const_range params() const {
return param_const_range(param_begin(), param_end());
}
/// getNumParams - Return the number of parameters this function must have
/// based on its FunctionType. This is the length of the ParamInfo array
/// after it has been created.
unsigned getNumParams() const;
const ParmVarDecl *getParamDecl(unsigned i) const {
assert(i < getNumParams() && "Illegal param #");
return ParamInfo[i];
}
ParmVarDecl *getParamDecl(unsigned i) {
assert(i < getNumParams() && "Illegal param #");
return ParamInfo[i];
}
void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
setParams(getASTContext(), NewParamInfo);
}
// ArrayRef iterface to parameters.
// FIXME: Should one day replace iterator interface.
ArrayRef<ParmVarDecl*> parameters() const {
return llvm::makeArrayRef(ParamInfo, getNumParams());
}
ArrayRef<NamedDecl *> getDeclsInPrototypeScope() const {
return DeclsInPrototypeScope;
}
void setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls);
/// getMinRequiredArguments - Returns the minimum number of arguments
/// needed to call this function. This may be fewer than the number of
/// function parameters, if some of the parameters have default
/// arguments (in C++).
unsigned getMinRequiredArguments() const;
QualType getReturnType() const {
return getType()->getAs<FunctionType>()->getReturnType();
}
/// \brief Attempt to compute an informative source range covering the
/// function return type. This may omit qualifiers and other information with
/// limited representation in the AST.
SourceRange getReturnTypeSourceRange() const;
/// \brief Determine the type of an expression that calls this function.
QualType getCallResultType() const {
return getType()->getAs<FunctionType>()->getCallResultType(getASTContext());
}
/// \brief Returns true if this function or its return type has the
/// warn_unused_result attribute. If the return type has the attribute and
/// this function is a method of the return type's class, then false will be
/// returned to avoid spurious warnings on member methods such as assignment
/// operators.
bool hasUnusedResultAttr() const;
/// \brief Returns the storage class as written in the source. For the
/// computed linkage of symbol, see getLinkage.
StorageClass getStorageClass() const { return StorageClass(SClass); }
/// \brief Determine whether the "inline" keyword was specified for this
/// function.
bool isInlineSpecified() const { return IsInlineSpecified; }
/// Set whether the "inline" keyword was specified for this function.
void setInlineSpecified(bool I) {
IsInlineSpecified = I;
IsInline = I;
}
/// Flag that this function is implicitly inline.
void setImplicitlyInline() {
IsInline = true;
}
/// \brief Determine whether this function should be inlined, because it is
/// either marked "inline" or "constexpr" or is a member function of a class
/// that was defined in the class body.
bool isInlined() const { return IsInline; }
bool isInlineDefinitionExternallyVisible() const;
bool isMSExternInline() const;
bool doesDeclarationForceExternallyVisibleDefinition() const;
/// isOverloadedOperator - Whether this function declaration
/// represents an C++ overloaded operator, e.g., "operator+".
bool isOverloadedOperator() const {
return getOverloadedOperator() != OO_None;
}
OverloadedOperatorKind getOverloadedOperator() const;
const IdentifierInfo *getLiteralIdentifier() const;
/// \brief If this function is an instantiation of a member function
/// of a class template specialization, retrieves the function from
/// which it was instantiated.
///
/// This routine will return non-NULL for (non-templated) member
/// functions of class templates and for instantiations of function
/// templates. For example, given:
///
/// \code
/// template<typename T>
/// struct X {
/// void f(T);
/// };
/// \endcode
///
/// The declaration for X<int>::f is a (non-templated) FunctionDecl
/// whose parent is the class template specialization X<int>. For
/// this declaration, getInstantiatedFromFunction() will return
/// the FunctionDecl X<T>::A. When a complete definition of
/// X<int>::A is required, it will be instantiated from the
/// declaration returned by getInstantiatedFromMemberFunction().
FunctionDecl *getInstantiatedFromMemberFunction() const;
/// \brief What kind of templated function this is.
TemplatedKind getTemplatedKind() const;
/// \brief If this function is an instantiation of a member function of a
/// class template specialization, retrieves the member specialization
/// information.
MemberSpecializationInfo *getMemberSpecializationInfo() const {
return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
}
/// \brief Specify that this record is an instantiation of the
/// member function FD.
void setInstantiationOfMemberFunction(FunctionDecl *FD,
TemplateSpecializationKind TSK) {
setInstantiationOfMemberFunction(getASTContext(), FD, TSK);
}
/// \brief Retrieves the function template that is described by this
/// function declaration.
///
/// Every function template is represented as a FunctionTemplateDecl
/// and a FunctionDecl (or something derived from FunctionDecl). The
/// former contains template properties (such as the template
/// parameter lists) while the latter contains the actual
/// description of the template's
/// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the
/// FunctionDecl that describes the function template,
/// getDescribedFunctionTemplate() retrieves the
/// FunctionTemplateDecl from a FunctionDecl.
FunctionTemplateDecl *getDescribedFunctionTemplate() const {
return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>();
}
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
TemplateOrSpecialization = Template;
}
/// \brief Determine whether this function is a function template
/// specialization.
bool isFunctionTemplateSpecialization() const {
return getPrimaryTemplate() != nullptr;
}
/// \brief Retrieve the class scope template pattern that this function
/// template specialization is instantiated from.
FunctionDecl *getClassScopeSpecializationPattern() const;
/// \brief If this function is actually a function template specialization,
/// retrieve information about this function template specialization.
/// Otherwise, returns NULL.
FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const {
return TemplateOrSpecialization.
dyn_cast<FunctionTemplateSpecializationInfo*>();
}
/// \brief Determines whether this function is a function template
/// specialization or a member of a class template specialization that can
/// be implicitly instantiated.
bool isImplicitlyInstantiable() const;
/// \brief Determines if the given function was instantiated from a
/// function template.
bool isTemplateInstantiation() const;
/// \brief Retrieve the function declaration from which this function could
/// be instantiated, if it is an instantiation (rather than a non-template
/// or a specialization, for example).
FunctionDecl *getTemplateInstantiationPattern() const;
/// \brief Retrieve the primary template that this function template
/// specialization either specializes or was instantiated from.
///
/// If this function declaration is not a function template specialization,
/// returns NULL.
FunctionTemplateDecl *getPrimaryTemplate() const;
/// \brief Retrieve the template arguments used to produce this function
/// template specialization from the primary template.
///
/// If this function declaration is not a function template specialization,
/// returns NULL.
const TemplateArgumentList *getTemplateSpecializationArgs() const;
/// \brief Retrieve the template argument list as written in the sources,
/// if any.
///
/// If this function declaration is not a function template specialization
/// or if it had no explicit template argument list, returns NULL.
/// Note that it an explicit template argument list may be written empty,
/// e.g., template<> void foo<>(char* s);
const ASTTemplateArgumentListInfo*
getTemplateSpecializationArgsAsWritten() const;
/// \brief Specify that this function declaration is actually a function
/// template specialization.
///
/// \param Template the function template that this function template
/// specialization specializes.
///
/// \param TemplateArgs the template arguments that produced this
/// function template specialization from the template.
///
/// \param InsertPos If non-NULL, the position in the function template
/// specialization set where the function template specialization data will
/// be inserted.
///
/// \param TSK the kind of template specialization this is.
///
/// \param TemplateArgsAsWritten location info of template arguments.
///
/// \param PointOfInstantiation point at which the function template
/// specialization was first instantiated.
void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template,
const TemplateArgumentList *TemplateArgs,
void *InsertPos,
TemplateSpecializationKind TSK = TSK_ImplicitInstantiation,
const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr,
SourceLocation PointOfInstantiation = SourceLocation()) {
setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs,
InsertPos, TSK, TemplateArgsAsWritten,
PointOfInstantiation);
}
/// \brief Specifies that this function declaration is actually a
/// dependent function template specialization.
void setDependentTemplateSpecialization(ASTContext &Context,
const UnresolvedSetImpl &Templates,
const TemplateArgumentListInfo &TemplateArgs);
DependentFunctionTemplateSpecializationInfo *
getDependentSpecializationInfo() const {
return TemplateOrSpecialization.
dyn_cast<DependentFunctionTemplateSpecializationInfo*>();
}
/// \brief Determine what kind of template instantiation this function
/// represents.
TemplateSpecializationKind getTemplateSpecializationKind() const;
/// \brief Determine what kind of template instantiation this function
/// represents.
void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
SourceLocation PointOfInstantiation = SourceLocation());
/// \brief Retrieve the (first) point of instantiation of a function template
/// specialization or a member of a class template specialization.
///
/// \returns the first point of instantiation, if this function was
/// instantiated from a template; otherwise, returns an invalid source
/// location.
SourceLocation getPointOfInstantiation() const;
/// \brief Determine whether this is or was instantiated from an out-of-line
/// definition of a member function.
bool isOutOfLine() const override;
/// \brief Identify a memory copying or setting function.
/// If the given function is a memory copy or setting function, returns
/// the corresponding Builtin ID. If the function is not a memory function,
/// returns 0.
unsigned getMemoryFunctionKind() const;
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) {
return K >= firstFunction && K <= lastFunction;
}
static DeclContext *castToDeclContext(const FunctionDecl *D) {
return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D));
}
static FunctionDecl *castFromDeclContext(const DeclContext *DC) {
return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC));
}
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// FieldDecl - An instance of this class is created by Sema::ActOnField to
/// represent a member of a struct/union/class.
class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> {
// FIXME: This can be packed into the bitfields in Decl.
bool Mutable : 1;
mutable unsigned CachedFieldIndex : 31;
/// The kinds of value we can store in InitializerOrBitWidth.
///
/// Note that this is compatible with InClassInitStyle except for
/// ISK_CapturedVLAType.
enum InitStorageKind {
/// If the pointer is null, there's nothing special. Otherwise,
/// this is a bitfield and the pointer is the Expr* storing the
/// bit-width.
ISK_BitWidthOrNothing = (unsigned) ICIS_NoInit,
/// The pointer is an (optional due to delayed parsing) Expr*
/// holding the copy-initializer.
ISK_InClassCopyInit = (unsigned) ICIS_CopyInit,
/// The pointer is an (optional due to delayed parsing) Expr*
/// holding the list-initializer.
ISK_InClassListInit = (unsigned) ICIS_ListInit,
/// The pointer is a VariableArrayType* that's been captured;
/// the enclosing context is a lambda or captured statement.
ISK_CapturedVLAType,
};
/// \brief Storage for either the bit-width, the in-class
/// initializer, or the captured variable length array bound.
///
/// We can safely combine these because in-class initializers are
/// not permitted for bit-fields, and both are exclusive with VLA
/// captures.
///
/// If the storage kind is ISK_InClassCopyInit or
/// ISK_InClassListInit, but the initializer is null, then this
/// field has an in-class initializer which has not yet been parsed
/// and attached.
llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage;
protected:
FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
InClassInitStyle InitStyle)
: DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
Mutable(Mutable), CachedFieldIndex(0),
InitStorage(BW, (InitStorageKind) InitStyle) {
assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield");
}
public:
static FieldDecl *Create(const ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, QualType T,
TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
InClassInitStyle InitStyle);
static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
/// getFieldIndex - Returns the index of this field within its record,
/// as appropriate for passing to ASTRecordLayout::getFieldOffset.
unsigned getFieldIndex() const;
/// isMutable - Determines whether this field is mutable (C++ only).
bool isMutable() const { return Mutable; }
/// \brief Determines whether this field is a bitfield.
bool isBitField() const {
return InitStorage.getInt() == ISK_BitWidthOrNothing &&
InitStorage.getPointer() != nullptr;
}
/// @brief Determines whether this is an unnamed bitfield.
bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); }
/// isAnonymousStructOrUnion - Determines whether this field is a
/// representative for an anonymous struct or union. Such fields are
/// unnamed and are implicitly generated by the implementation to
/// store the data for the anonymous union or struct.
bool isAnonymousStructOrUnion() const;
Expr *getBitWidth() const {
return isBitField()
? static_cast<Expr *>(InitStorage.getPointer())
: nullptr;
}
unsigned getBitWidthValue(const ASTContext &Ctx) const;
/// setBitWidth - Set the bit-field width for this member.
// Note: used by some clients (i.e., do not remove it).
void setBitWidth(Expr *Width) {
assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
InitStorage.getPointer() == nullptr &&
"bit width, initializer or captured type already set");
InitStorage.setPointerAndInt(Width, ISK_BitWidthOrNothing);
}
/// removeBitWidth - Remove the bit-field width from this member.
// Note: used by some clients (i.e., do not remove it).
void removeBitWidth() {
assert(isBitField() && "no bitfield width to remove");
InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
}
/// getInClassInitStyle - Get the kind of (C++11) in-class initializer which
/// this field has.
InClassInitStyle getInClassInitStyle() const {
InitStorageKind storageKind = InitStorage.getInt();
return (storageKind == ISK_CapturedVLAType
? ICIS_NoInit : (InClassInitStyle) storageKind);
}
/// hasInClassInitializer - Determine whether this member has a C++11 in-class
/// initializer.
bool hasInClassInitializer() const {
return getInClassInitStyle() != ICIS_NoInit;
}
/// getInClassInitializer - Get the C++11 in-class initializer for this
/// member, or null if one has not been set. If a valid declaration has an
/// in-class initializer, but this returns null, then we have not parsed and
/// attached it yet.
Expr *getInClassInitializer() const {
return hasInClassInitializer()
? static_cast<Expr *>(InitStorage.getPointer())
: nullptr;
}
/// setInClassInitializer - Set the C++11 in-class initializer for this
/// member.
void setInClassInitializer(Expr *Init) {
assert(hasInClassInitializer() &&
InitStorage.getPointer() == nullptr &&
"bit width, initializer or captured type already set");
InitStorage.setPointer(Init);
}
/// removeInClassInitializer - Remove the C++11 in-class initializer from this
/// member.
void removeInClassInitializer() {
assert(hasInClassInitializer() && "no initializer to remove");
InitStorage.setPointerAndInt(nullptr, ISK_BitWidthOrNothing);
}
/// \brief Determine whether this member captures the variable length array
/// type.
bool hasCapturedVLAType() const {
return InitStorage.getInt() == ISK_CapturedVLAType;
}
/// \brief Get the captured variable length array type.
const VariableArrayType *getCapturedVLAType() const {
return hasCapturedVLAType() ? static_cast<const VariableArrayType *>(
InitStorage.getPointer())
: nullptr;
}
/// \brief Set the captured variable length array type for this field.
void setCapturedVLAType(const VariableArrayType *VLAType);
/// getParent - Returns the parent of this field declaration, which
/// is the struct in which this method is defined.
const RecordDecl *getParent() const {
return cast<RecordDecl>(getDeclContext());
}
RecordDecl *getParent() {
return cast<RecordDecl>(getDeclContext());
}
SourceRange getSourceRange() const override LLVM_READONLY;
/// Retrieves the canonical declaration of this field.
FieldDecl *getCanonicalDecl() override { return getFirstDecl(); }
const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); }
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K >= firstField && K <= lastField; }
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// EnumConstantDecl - An instance of this object exists for each enum constant
/// that is defined. For example, in "enum X {a,b}", each of a/b are
/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a
/// TagType for the X EnumDecl.
class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> {
Stmt *Init; // an integer constant expression
llvm::APSInt Val; // The value.
protected:
EnumConstantDecl(DeclContext *DC, SourceLocation L,
IdentifierInfo *Id, QualType T, Expr *E,
const llvm::APSInt &V)
: ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {}
public:
static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC,
SourceLocation L, IdentifierInfo *Id,
QualType T, Expr *E,
const llvm::APSInt &V);
static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID);
const Expr *getInitExpr() const { return (const Expr*) Init; }
Expr *getInitExpr() { return (Expr*) Init; }
const llvm::APSInt &getInitVal() const { return Val; }
void setInitExpr(Expr *E) { Init = (Stmt*) E; }
void setInitVal(const llvm::APSInt &V) { Val = V; }
SourceRange getSourceRange() const override LLVM_READONLY;
/// Retrieves the canonical declaration of this enumerator.
EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); }
const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); }
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == EnumConstant; }
friend class StmtIteratorBase;
};
/// IndirectFieldDecl - An instance of this class is created to represent a
/// field injected from an anonymous union/struct into the parent scope.
/// IndirectFieldDecl are always implicit.
class IndirectFieldDecl : public ValueDecl {
void anchor() override;
NamedDecl **Chaining;
unsigned ChainingSize;
IndirectFieldDecl(DeclContext *DC, SourceLocation L,
DeclarationName N, QualType T,
NamedDecl **CH, unsigned CHS)
: ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {}
public:
static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation L, IdentifierInfo *Id,
QualType T, NamedDecl **CH, unsigned CHS);
static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID);
typedef NamedDecl * const *chain_iterator;
typedef llvm::iterator_range<chain_iterator> chain_range;
chain_range chain() const { return chain_range(chain_begin(), chain_end()); }
chain_iterator chain_begin() const { return chain_iterator(Chaining); }
chain_iterator chain_end() const {
return chain_iterator(Chaining + ChainingSize);
}
unsigned getChainingSize() const { return ChainingSize; }
FieldDecl *getAnonField() const {
assert(ChainingSize >= 2);
return cast<FieldDecl>(Chaining[ChainingSize - 1]);
}
VarDecl *getVarDecl() const {
assert(ChainingSize >= 2);
return dyn_cast<VarDecl>(*chain_begin());
}
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == IndirectField; }
friend class ASTDeclReader;
};
/// TypeDecl - Represents a declaration of a type.
///
class TypeDecl : public NamedDecl {
void anchor() override;
/// TypeForDecl - This indicates the Type object that represents
/// this TypeDecl. It is a cache maintained by
/// ASTContext::getTypedefType, ASTContext::getTagDeclType, and
/// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl.
mutable const Type *TypeForDecl;
/// LocStart - The start of the source range for this declaration.
SourceLocation LocStart;
friend class ASTContext;
protected:
TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id,
SourceLocation StartL = SourceLocation())
: NamedDecl(DK, DC, L, Id), TypeForDecl(nullptr), LocStart(StartL) {}
public:
// Low-level accessor. If you just want the type defined by this node,
// check out ASTContext::getTypeDeclType or one of
// ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you
// already know the specific kind of node this is.
const Type *getTypeForDecl() const { return TypeForDecl; }
void setTypeForDecl(const Type *TD) { TypeForDecl = TD; }
SourceLocation getLocStart() const LLVM_READONLY { return LocStart; }
void setLocStart(SourceLocation L) { LocStart = L; }
SourceRange getSourceRange() const override LLVM_READONLY {
if (LocStart.isValid())
return SourceRange(LocStart, getLocation());
else
return SourceRange(getLocation());
}
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K >= firstType && K <= lastType; }
};
/// Base class for declarations which introduce a typedef-name.
class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> {
void anchor() override;
typedef std::pair<TypeSourceInfo*, QualType> ModedTInfo;
llvm::PointerUnion<TypeSourceInfo*, ModedTInfo*> MaybeModedTInfo;
protected:
TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, TypeSourceInfo *TInfo)
: TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C),
MaybeModedTInfo(TInfo) {}
typedef Redeclarable<TypedefNameDecl> redeclarable_base;
TypedefNameDecl *getNextRedeclarationImpl() override {
return getNextRedeclaration();
}
TypedefNameDecl *getPreviousDeclImpl() override {
return getPreviousDecl();
}
TypedefNameDecl *getMostRecentDeclImpl() override {
return getMostRecentDecl();
}
public:
typedef redeclarable_base::redecl_range redecl_range;
typedef redeclarable_base::redecl_iterator redecl_iterator;
using redeclarable_base::redecls_begin;
using redeclarable_base::redecls_end;
using redeclarable_base::redecls;
using redeclarable_base::getPreviousDecl;
using redeclarable_base::getMostRecentDecl;
using redeclarable_base::isFirstDecl;
bool isModed() const { return MaybeModedTInfo.is<ModedTInfo*>(); }
TypeSourceInfo *getTypeSourceInfo() const {
return isModed()
? MaybeModedTInfo.get<ModedTInfo*>()->first
: MaybeModedTInfo.get<TypeSourceInfo*>();
}
QualType getUnderlyingType() const {
return isModed()
? MaybeModedTInfo.get<ModedTInfo*>()->second
: MaybeModedTInfo.get<TypeSourceInfo*>()->getType();
}
void setTypeSourceInfo(TypeSourceInfo *newType) {
MaybeModedTInfo = newType;
}
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) {
MaybeModedTInfo = new (getASTContext()) ModedTInfo(unmodedTSI, modedTy);
}
/// Retrieves the canonical declaration of this typedef-name.
TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); }
const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); }
/// Retrieves the tag declaration for which this is the typedef name for
/// linkage purposes, if any.
///
/// \param AnyRedecl Look for the tag declaration in any redeclaration of
/// this typedef declaration.
TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const;
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) {
return K >= firstTypedefName && K <= lastTypedefName;
}
};
/// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef'
/// type specifier.
class TypedefDecl : public TypedefNameDecl {
TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
: TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {}
public:
static TypedefDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, TypeSourceInfo *TInfo);
static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID);
SourceRange getSourceRange() const override LLVM_READONLY;
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Typedef; }
};
/// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x
/// alias-declaration.
class TypeAliasDecl : public TypedefNameDecl {
/// The template for which this is the pattern, if any.
TypeAliasTemplateDecl *Template;
TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
: TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo),
Template(nullptr) {}
public:
static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, TypeSourceInfo *TInfo);
static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
SourceRange getSourceRange() const override LLVM_READONLY;
TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; }
void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; }
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == TypeAlias; }
};
/// TagDecl - Represents the declaration of a struct/union/class/enum.
class TagDecl
: public TypeDecl, public DeclContext, public Redeclarable<TagDecl> {
public:
// This is really ugly.
typedef TagTypeKind TagKind;
private:
// FIXME: This can be packed into the bitfields in Decl.
/// TagDeclKind - The TagKind enum.
unsigned TagDeclKind : 3;
/// IsCompleteDefinition - True if this is a definition ("struct foo
/// {};"), false if it is a declaration ("struct foo;"). It is not
/// a definition until the definition has been fully processed.
bool IsCompleteDefinition : 1;
protected:
/// IsBeingDefined - True if this is currently being defined.
bool IsBeingDefined : 1;
private:
/// IsEmbeddedInDeclarator - True if this tag declaration is
/// "embedded" (i.e., defined or declared for the very first time)
/// in the syntax of a declarator.
bool IsEmbeddedInDeclarator : 1;
/// \brief True if this tag is free standing, e.g. "struct foo;".
bool IsFreeStanding : 1;
protected:
// These are used by (and only defined for) EnumDecl.
unsigned NumPositiveBits : 8;
unsigned NumNegativeBits : 8;
/// IsScoped - True if this tag declaration is a scoped enumeration. Only
/// possible in C++11 mode.
bool IsScoped : 1;
/// IsScopedUsingClassTag - If this tag declaration is a scoped enum,
/// then this is true if the scoped enum was declared using the class
/// tag, false if it was declared with the struct tag. No meaning is
/// associated if this tag declaration is not a scoped enum.
bool IsScopedUsingClassTag : 1;
/// IsFixed - True if this is an enumeration with fixed underlying type. Only
/// possible in C++11, Microsoft extensions, or Objective C mode.
bool IsFixed : 1;
/// \brief Indicates whether it is possible for declarations of this kind
/// to have an out-of-date definition.
///
/// This option is only enabled when modules are enabled.
bool MayHaveOutOfDateDef : 1;
/// Has the full definition of this type been required by a use somewhere in
/// the TU.
bool IsCompleteDefinitionRequired : 1;
private:
SourceLocation RBraceLoc;
// A struct representing syntactic qualifier info,
// to be used for the (uncommon) case of out-of-line declarations.
typedef QualifierInfo ExtInfo;
/// \brief If the (out-of-line) tag declaration name
/// is qualified, it points to the qualifier info (nns and range);
/// otherwise, if the tag declaration is anonymous and it is part of
/// a typedef or alias, it points to the TypedefNameDecl (used for mangling);
/// otherwise, if the tag declaration is anonymous and it is used as a
/// declaration specifier for variables, it points to the first VarDecl (used
/// for mangling);
/// otherwise, it is a null (TypedefNameDecl) pointer.
llvm::PointerUnion<NamedDecl *, ExtInfo *> NamedDeclOrQualifier;
bool hasExtInfo() const { return NamedDeclOrQualifier.is<ExtInfo *>(); }
ExtInfo *getExtInfo() { return NamedDeclOrQualifier.get<ExtInfo *>(); }
const ExtInfo *getExtInfo() const {
return NamedDeclOrQualifier.get<ExtInfo *>();
}
protected:
TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
SourceLocation StartL)
: TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
TagDeclKind(TK), IsCompleteDefinition(false), IsBeingDefined(false),
IsEmbeddedInDeclarator(false), IsFreeStanding(false),
IsCompleteDefinitionRequired(false),
NamedDeclOrQualifier((NamedDecl *)nullptr) {
assert((DK != Enum || TK == TTK_Enum) &&
"EnumDecl not matched with TTK_Enum");
setPreviousDecl(PrevDecl);
}
typedef Redeclarable<TagDecl> redeclarable_base;
TagDecl *getNextRedeclarationImpl() override {
return getNextRedeclaration();
}
TagDecl *getPreviousDeclImpl() override {
return getPreviousDecl();
}
TagDecl *getMostRecentDeclImpl() override {
return getMostRecentDecl();
}
/// @brief Completes the definition of this tag declaration.
///
/// This is a helper function for derived classes.
void completeDefinition();
public:
typedef redeclarable_base::redecl_range redecl_range;
typedef redeclarable_base::redecl_iterator redecl_iterator;
using redeclarable_base::redecls_begin;
using redeclarable_base::redecls_end;
using redeclarable_base::redecls;
using redeclarable_base::getPreviousDecl;
using redeclarable_base::getMostRecentDecl;
using redeclarable_base::isFirstDecl;
SourceLocation getRBraceLoc() const { return RBraceLoc; }
void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
/// getInnerLocStart - Return SourceLocation representing start of source
/// range ignoring outer template declarations.
SourceLocation getInnerLocStart() const { return getLocStart(); }
/// getOuterLocStart - Return SourceLocation representing start of source
/// range taking into account any outer template declarations.
SourceLocation getOuterLocStart() const;
SourceRange getSourceRange() const override LLVM_READONLY;
TagDecl *getCanonicalDecl() override;
const TagDecl *getCanonicalDecl() const {
return const_cast<TagDecl*>(this)->getCanonicalDecl();
}
/// isThisDeclarationADefinition() - Return true if this declaration
/// is a completion definition of the type. Provided for consistency.
bool isThisDeclarationADefinition() const {
return isCompleteDefinition();
}
/// isCompleteDefinition - Return true if this decl has its body
/// fully specified.
bool isCompleteDefinition() const {
return IsCompleteDefinition;
}
/// \brief Return true if this complete decl is
/// required to be complete for some existing use.
bool isCompleteDefinitionRequired() const {
return IsCompleteDefinitionRequired;
}
/// isBeingDefined - Return true if this decl is currently being defined.
bool isBeingDefined() const {
return IsBeingDefined;
}
bool isEmbeddedInDeclarator() const {
return IsEmbeddedInDeclarator;
}
void setEmbeddedInDeclarator(bool isInDeclarator) {
IsEmbeddedInDeclarator = isInDeclarator;
}
bool isFreeStanding() const { return IsFreeStanding; }
void setFreeStanding(bool isFreeStanding = true) {
IsFreeStanding = isFreeStanding;
}
/// \brief Whether this declaration declares a type that is
/// dependent, i.e., a type that somehow depends on template
/// parameters.
bool isDependentType() const { return isDependentContext(); }
/// @brief Starts the definition of this tag declaration.
///
/// This method should be invoked at the beginning of the definition
/// of this tag declaration. It will set the tag type into a state
/// where it is in the process of being defined.
void startDefinition();
/// getDefinition - Returns the TagDecl that actually defines this
/// struct/union/class/enum. When determining whether or not a
/// struct/union/class/enum has a definition, one should use this
/// method as opposed to 'isDefinition'. 'isDefinition' indicates
/// whether or not a specific TagDecl is defining declaration, not
/// whether or not the struct/union/class/enum type is defined.
/// This method returns NULL if there is no TagDecl that defines
/// the struct/union/class/enum.
TagDecl *getDefinition() const;
void setCompleteDefinition(bool V) { IsCompleteDefinition = V; }
void setCompleteDefinitionRequired(bool V = true) {
IsCompleteDefinitionRequired = V;
}
StringRef getKindName() const {
return TypeWithKeyword::getTagTypeKindName(getTagKind());
}
TagKind getTagKind() const {
return TagKind(TagDeclKind);
}
void setTagKind(TagKind TK) { TagDeclKind = TK; }
bool isStruct() const { return getTagKind() == TTK_Struct; }
bool isInterface() const { return getTagKind() == TTK_Interface; }
bool isClass() const { return getTagKind() == TTK_Class; }
bool isUnion() const { return getTagKind() == TTK_Union; }
bool isEnum() const { return getTagKind() == TTK_Enum; }
/// Is this tag type named, either directly or via being defined in
/// a typedef of this type?
///
/// C++11 [basic.link]p8:
/// A type is said to have linkage if and only if:
/// - it is a class or enumeration type that is named (or has a
/// name for linkage purposes) and the name has linkage; ...
/// C++11 [dcl.typedef]p9:
/// If the typedef declaration defines an unnamed class (or enum),
/// the first typedef-name declared by the declaration to be that
/// class type (or enum type) is used to denote the class type (or
/// enum type) for linkage purposes only.
///
/// C does not have an analogous rule, but the same concept is
/// nonetheless useful in some places.
bool hasNameForLinkage() const {
return (getDeclName() || getTypedefNameForAnonDecl());
}
bool hasDeclaratorForAnonDecl() const {
return dyn_cast_or_null<DeclaratorDecl>(
NamedDeclOrQualifier.get<NamedDecl *>());
}
DeclaratorDecl *getDeclaratorForAnonDecl() const {
return hasExtInfo() ? nullptr : dyn_cast_or_null<DeclaratorDecl>(
NamedDeclOrQualifier.get<NamedDecl *>());
}
TypedefNameDecl *getTypedefNameForAnonDecl() const {
return hasExtInfo() ? nullptr : dyn_cast_or_null<TypedefNameDecl>(
NamedDeclOrQualifier.get<NamedDecl *>());
}
void setDeclaratorForAnonDecl(DeclaratorDecl *DD) { NamedDeclOrQualifier = DD; }
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD);
/// \brief Retrieve the nested-name-specifier that qualifies the name of this
/// declaration, if it was present in the source.
NestedNameSpecifier *getQualifier() const {
return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
: nullptr;
}
/// \brief Retrieve the nested-name-specifier (with source-location
/// information) that qualifies the name of this declaration, if it was
/// present in the source.
NestedNameSpecifierLoc getQualifierLoc() const {
return hasExtInfo() ? getExtInfo()->QualifierLoc
: NestedNameSpecifierLoc();
}
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
unsigned getNumTemplateParameterLists() const {
return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
}
TemplateParameterList *getTemplateParameterList(unsigned i) const {
assert(i < getNumTemplateParameterLists());
return getExtInfo()->TemplParamLists[i];
}
void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists,
TemplateParameterList **TPLists);
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; }
static DeclContext *castToDeclContext(const TagDecl *D) {
return static_cast<DeclContext *>(const_cast<TagDecl*>(D));
}
static TagDecl *castFromDeclContext(const DeclContext *DC) {
return static_cast<TagDecl *>(const_cast<DeclContext*>(DC));
}
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// EnumDecl - Represents an enum. In C++11, enums can be forward-declared
/// with a fixed underlying type, and in C we allow them to be forward-declared
/// with no underlying type as an extension.
class EnumDecl : public TagDecl {
void anchor() override;
/// IntegerType - This represent the integer type that the enum corresponds
/// to for code generation purposes. Note that the enumerator constants may
/// have a different type than this does.
///
/// If the underlying integer type was explicitly stated in the source
/// code, this is a TypeSourceInfo* for that type. Otherwise this type
/// was automatically deduced somehow, and this is a Type*.
///
/// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in
/// some cases it won't.
///
/// The underlying type of an enumeration never has any qualifiers, so
/// we can get away with just storing a raw Type*, and thus save an
/// extra pointer when TypeSourceInfo is needed.
llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType;
/// PromotionType - The integer type that values of this type should
/// promote to. In C, enumerators are generally of an integer type
/// directly, but gcc-style large enumerators (and all enumerators
/// in C++) are of the enum type instead.
QualType PromotionType;
/// \brief If this enumeration is an instantiation of a member enumeration
/// of a class template specialization, this is the member specialization
/// information.
MemberSpecializationInfo *SpecializationInfo;
EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
bool Scoped, bool ScopedUsingClassTag, bool Fixed)
: TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc),
SpecializationInfo(nullptr) {
assert(Scoped || !ScopedUsingClassTag);
IntegerType = (const Type *)nullptr;
NumNegativeBits = 0;
NumPositiveBits = 0;
IsScoped = Scoped;
IsScopedUsingClassTag = ScopedUsingClassTag;
IsFixed = Fixed;
}
void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
TemplateSpecializationKind TSK);
public:
EnumDecl *getCanonicalDecl() override {
return cast<EnumDecl>(TagDecl::getCanonicalDecl());
}
const EnumDecl *getCanonicalDecl() const {
return const_cast<EnumDecl*>(this)->getCanonicalDecl();
}
EnumDecl *getPreviousDecl() {
return cast_or_null<EnumDecl>(
static_cast<TagDecl *>(this)->getPreviousDecl());
}
const EnumDecl *getPreviousDecl() const {
return const_cast<EnumDecl*>(this)->getPreviousDecl();
}
EnumDecl *getMostRecentDecl() {
return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
}
const EnumDecl *getMostRecentDecl() const {
return const_cast<EnumDecl*>(this)->getMostRecentDecl();
}
EnumDecl *getDefinition() const {
return cast_or_null<EnumDecl>(TagDecl::getDefinition());
}
static EnumDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, EnumDecl *PrevDecl,
bool IsScoped, bool IsScopedUsingClassTag,
bool IsFixed);
static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID);
/// completeDefinition - When created, the EnumDecl corresponds to a
/// forward-declared enum. This method is used to mark the
/// declaration as being defined; it's enumerators have already been
/// added (via DeclContext::addDecl). NewType is the new underlying
/// type of the enumeration type.
void completeDefinition(QualType NewType,
QualType PromotionType,
unsigned NumPositiveBits,
unsigned NumNegativeBits);
// enumerator_iterator - Iterates through the enumerators of this
// enumeration.
typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator;
typedef llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>
enumerator_range;
enumerator_range enumerators() const {
return enumerator_range(enumerator_begin(), enumerator_end());
}
enumerator_iterator enumerator_begin() const {
const EnumDecl *E = getDefinition();
if (!E)
E = this;
return enumerator_iterator(E->decls_begin());
}
enumerator_iterator enumerator_end() const {
const EnumDecl *E = getDefinition();
if (!E)
E = this;
return enumerator_iterator(E->decls_end());
}
/// getPromotionType - Return the integer type that enumerators
/// should promote to.
QualType getPromotionType() const { return PromotionType; }
/// \brief Set the promotion type.
void setPromotionType(QualType T) { PromotionType = T; }
/// getIntegerType - Return the integer type this enum decl corresponds to.
/// This returns a null QualType for an enum forward definition with no fixed
/// underlying type.
QualType getIntegerType() const {
if (!IntegerType)
return QualType();
if (const Type *T = IntegerType.dyn_cast<const Type*>())
return QualType(T, 0);
return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType();
}
/// \brief Set the underlying integer type.
void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); }
/// \brief Set the underlying integer type source info.
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; }
/// \brief Return the type source info for the underlying integer type,
/// if no type source info exists, return 0.
TypeSourceInfo *getIntegerTypeSourceInfo() const {
return IntegerType.dyn_cast<TypeSourceInfo*>();
}
/// \brief Retrieve the source range that covers the underlying type if
/// specified.
SourceRange getIntegerTypeRange() const LLVM_READONLY;
/// \brief Returns the width in bits required to store all the
/// non-negative enumerators of this enum.
unsigned getNumPositiveBits() const {
return NumPositiveBits;
}
void setNumPositiveBits(unsigned Num) {
NumPositiveBits = Num;
assert(NumPositiveBits == Num && "can't store this bitcount");
}
/// \brief Returns the width in bits required to store all the
/// negative enumerators of this enum. These widths include
/// the rightmost leading 1; that is:
///
/// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS
/// ------------------------ ------- -----------------
/// -1 1111111 1
/// -10 1110110 5
/// -101 1001011 8
unsigned getNumNegativeBits() const {
return NumNegativeBits;
}
void setNumNegativeBits(unsigned Num) {
NumNegativeBits = Num;
}
/// \brief Returns true if this is a C++11 scoped enumeration.
bool isScoped() const {
return IsScoped;
}
/// \brief Returns true if this is a C++11 scoped enumeration.
bool isScopedUsingClassTag() const {
return IsScopedUsingClassTag;
}
/// \brief Returns true if this is an Objective-C, C++11, or
/// Microsoft-style enumeration with a fixed underlying type.
bool isFixed() const {
return IsFixed;
}
/// \brief Returns true if this can be considered a complete type.
bool isComplete() const {
return isCompleteDefinition() || isFixed();
}
/// \brief Returns the enumeration (declared within the template)
/// from which this enumeration type was instantiated, or NULL if
/// this enumeration was not instantiated from any template.
EnumDecl *getInstantiatedFromMemberEnum() const;
/// \brief If this enumeration is a member of a specialization of a
/// templated class, determine what kind of template specialization
/// or instantiation this is.
TemplateSpecializationKind getTemplateSpecializationKind() const;
/// \brief For an enumeration member that was instantiated from a member
/// enumeration of a templated class, set the template specialiation kind.
void setTemplateSpecializationKind(TemplateSpecializationKind TSK,
SourceLocation PointOfInstantiation = SourceLocation());
/// \brief If this enumeration is an instantiation of a member enumeration of
/// a class template specialization, retrieves the member specialization
/// information.
MemberSpecializationInfo *getMemberSpecializationInfo() const {
return SpecializationInfo;
}
/// \brief Specify that this enumeration is an instantiation of the
/// member enumeration ED.
void setInstantiationOfMemberEnum(EnumDecl *ED,
TemplateSpecializationKind TSK) {
setInstantiationOfMemberEnum(getASTContext(), ED, TSK);
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Enum; }
friend class ASTDeclReader;
};
/// RecordDecl - Represents a struct/union/class. For example:
/// struct X; // Forward declaration, no "body".
/// union Y { int A, B; }; // Has body with members A and B (FieldDecls).
/// This decl will be marked invalid if *any* members are invalid.
///
class RecordDecl : public TagDecl {
// FIXME: This can be packed into the bitfields in Decl.
/// HasFlexibleArrayMember - This is true if this struct ends with a flexible
/// array member (e.g. int X[]) or if this union contains a struct that does.
/// If so, this cannot be contained in arrays or other structs as a member.
bool HasFlexibleArrayMember : 1;
/// AnonymousStructOrUnion - Whether this is the type of an anonymous struct
/// or union.
bool AnonymousStructOrUnion : 1;
/// HasObjectMember - This is true if this struct has at least one member
/// containing an Objective-C object pointer type.
bool HasObjectMember : 1;
/// HasVolatileMember - This is true if struct has at least one member of
/// 'volatile' type.
bool HasVolatileMember : 1;
/// \brief Whether the field declarations of this record have been loaded
/// from external storage. To avoid unnecessary deserialization of
/// methods/nested types we allow deserialization of just the fields
/// when needed.
mutable bool LoadedFieldsFromExternalStorage : 1;
friend class DeclContext;
protected:
RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, RecordDecl *PrevDecl);
public:
static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr);
static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
RecordDecl *getPreviousDecl() {
return cast_or_null<RecordDecl>(
static_cast<TagDecl *>(this)->getPreviousDecl());
}
const RecordDecl *getPreviousDecl() const {
return const_cast<RecordDecl*>(this)->getPreviousDecl();
}
RecordDecl *getMostRecentDecl() {
return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl());
}
const RecordDecl *getMostRecentDecl() const {
return const_cast<RecordDecl*>(this)->getMostRecentDecl();
}
bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; }
void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; }
/// isAnonymousStructOrUnion - Whether this is an anonymous struct
/// or union. To be an anonymous struct or union, it must have been
/// declared without a name and there must be no objects of this
/// type declared, e.g.,
/// @code
/// union { int i; float f; };
/// @endcode
/// is an anonymous union but neither of the following are:
/// @code
/// union X { int i; float f; };
/// union { int i; float f; } obj;
/// @endcode
bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; }
void setAnonymousStructOrUnion(bool Anon) {
AnonymousStructOrUnion = Anon;
}
bool hasObjectMember() const { return HasObjectMember; }
void setHasObjectMember (bool val) { HasObjectMember = val; }
bool hasVolatileMember() const { return HasVolatileMember; }
void setHasVolatileMember (bool val) { HasVolatileMember = val; }
/// \brief Determines whether this declaration represents the
/// injected class name.
///
/// The injected class name in C++ is the name of the class that
/// appears inside the class itself. For example:
///
/// \code
/// struct C {
/// // C is implicitly declared here as a synonym for the class name.
/// };
///
/// C::C c; // same as "C c;"
/// \endcode
bool isInjectedClassName() const;
/// \brief Determine whether this record is a class describing a lambda
/// function object.
bool isLambda() const;
/// \brief Determine whether this record is a record for captured variables in
/// CapturedStmt construct.
bool isCapturedRecord() const;
/// \brief Mark the record as a record for captured variables in CapturedStmt
/// construct.
void setCapturedRecord();
/// getDefinition - Returns the RecordDecl that actually defines
/// this struct/union/class. When determining whether or not a
/// struct/union/class is completely defined, one should use this
/// method as opposed to 'isCompleteDefinition'.
/// 'isCompleteDefinition' indicates whether or not a specific
/// RecordDecl is a completed definition, not whether or not the
/// record type is defined. This method returns NULL if there is
/// no RecordDecl that defines the struct/union/tag.
RecordDecl *getDefinition() const {
return cast_or_null<RecordDecl>(TagDecl::getDefinition());
}
// Iterator access to field members. The field iterator only visits
// the non-static data members of this class, ignoring any static
// data members, functions, constructors, destructors, etc.
typedef specific_decl_iterator<FieldDecl> field_iterator;
typedef llvm::iterator_range<specific_decl_iterator<FieldDecl>> field_range;
field_range fields() const { return field_range(field_begin(), field_end()); }
field_iterator field_begin() const;
field_iterator field_end() const {
return field_iterator(decl_iterator());
}
// field_empty - Whether there are any fields (non-static data
// members) in this record.
bool field_empty() const {
return field_begin() == field_end();
}
/// completeDefinition - Notes that the definition of this type is
/// now complete.
virtual void completeDefinition();
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) {
return K >= firstRecord && K <= lastRecord;
}
/// isMsStrust - Get whether or not this is an ms_struct which can
/// be turned on with an attribute, pragma, or -mms-bitfields
/// commandline option.
bool isMsStruct(const ASTContext &C) const;
/// \brief Whether we are allowed to insert extra padding between fields.
/// These padding are added to help AddressSanitizer detect
/// intra-object-overflow bugs.
bool mayInsertExtraPadding(bool EmitRemark = false) const;
/// Finds the first data member which has a name.
/// nullptr is returned if no named data member exists.
const FieldDecl *findFirstNamedDataMember() const;
private:
/// \brief Deserialize just the fields.
void LoadFieldsFromExternalStorage() const;
};
class FileScopeAsmDecl : public Decl {
virtual void anchor();
StringLiteral *AsmString;
SourceLocation RParenLoc;
FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring,
SourceLocation StartL, SourceLocation EndL)
: Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {}
public:
static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC,
StringLiteral *Str, SourceLocation AsmLoc,
SourceLocation RParenLoc);
static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID);
SourceLocation getAsmLoc() const { return getLocation(); }
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation L) { RParenLoc = L; }
SourceRange getSourceRange() const override LLVM_READONLY {
return SourceRange(getAsmLoc(), getRParenLoc());
}
const StringLiteral *getAsmString() const { return AsmString; }
StringLiteral *getAsmString() { return AsmString; }
void setAsmString(StringLiteral *Asm) { AsmString = Asm; }
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == FileScopeAsm; }
};
/// BlockDecl - This represents a block literal declaration, which is like an
/// unnamed FunctionDecl. For example:
/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body }
///
class BlockDecl : public Decl, public DeclContext {
public:
/// A class which contains all the information about a particular
/// captured value.
class Capture {
enum {
flag_isByRef = 0x1,
flag_isNested = 0x2
};
/// The variable being captured.
llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags;
/// The copy expression, expressed in terms of a DeclRef (or
/// BlockDeclRef) to the captured variable. Only required if the
/// variable has a C++ class type.
Expr *CopyExpr;
public:
Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
: VariableAndFlags(variable,
(byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)),
CopyExpr(copy) {}
/// The variable being captured.
VarDecl *getVariable() const { return VariableAndFlags.getPointer(); }
/// Whether this is a "by ref" capture, i.e. a capture of a __block
/// variable.
bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; }
/// Whether this is a nested capture, i.e. the variable captured
/// is not from outside the immediately enclosing function/block.
bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; }
bool hasCopyExpr() const { return CopyExpr != nullptr; }
Expr *getCopyExpr() const { return CopyExpr; }
void setCopyExpr(Expr *e) { CopyExpr = e; }
};
private:
// FIXME: This can be packed into the bitfields in Decl.
bool IsVariadic : 1;
bool CapturesCXXThis : 1;
bool BlockMissingReturnType : 1;
bool IsConversionFromLambda : 1;
/// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal
/// parameters of this function. This is null if a prototype or if there are
/// no formals.
ParmVarDecl **ParamInfo;
unsigned NumParams;
Stmt *Body;
TypeSourceInfo *SignatureAsWritten;
Capture *Captures;
unsigned NumCaptures;
unsigned ManglingNumber;
Decl *ManglingContextDecl;
protected:
BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
: Decl(Block, DC, CaretLoc), DeclContext(Block),
IsVariadic(false), CapturesCXXThis(false),
BlockMissingReturnType(true), IsConversionFromLambda(false),
ParamInfo(nullptr), NumParams(0), Body(nullptr),
SignatureAsWritten(nullptr), Captures(nullptr), NumCaptures(0),
ManglingNumber(0), ManglingContextDecl(nullptr) {}
public:
static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L);
static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID);
SourceLocation getCaretLocation() const { return getLocation(); }
bool isVariadic() const { return IsVariadic; }
void setIsVariadic(bool value) { IsVariadic = value; }
CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; }
Stmt *getBody() const override { return (Stmt*) Body; }
void setBody(CompoundStmt *B) { Body = (Stmt*) B; }
void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; }
TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; }
// Iterator access to formal parameters.
unsigned param_size() const { return getNumParams(); }
typedef ParmVarDecl **param_iterator;
typedef ParmVarDecl * const *param_const_iterator;
typedef llvm::iterator_range<param_iterator> param_range;
typedef llvm::iterator_range<param_const_iterator> param_const_range;
// ArrayRef access to formal parameters.
// FIXME: Should eventual replace iterator access.
ArrayRef<ParmVarDecl*> parameters() const {
return llvm::makeArrayRef(ParamInfo, param_size());
}
bool param_empty() const { return NumParams == 0; }
param_range params() { return param_range(param_begin(), param_end()); }
param_iterator param_begin() { return param_iterator(ParamInfo); }
param_iterator param_end() {
return param_iterator(ParamInfo + param_size());
}
param_const_range params() const {
return param_const_range(param_begin(), param_end());
}
param_const_iterator param_begin() const {
return param_const_iterator(ParamInfo);
}
param_const_iterator param_end() const {
return param_const_iterator(ParamInfo + param_size());
}
unsigned getNumParams() const { return NumParams; }
const ParmVarDecl *getParamDecl(unsigned i) const {
assert(i < getNumParams() && "Illegal param #");
return ParamInfo[i];
}
ParmVarDecl *getParamDecl(unsigned i) {
assert(i < getNumParams() && "Illegal param #");
return ParamInfo[i];
}
void setParams(ArrayRef<ParmVarDecl *> NewParamInfo);
/// hasCaptures - True if this block (or its nested blocks) captures
/// anything of local storage from its enclosing scopes.
bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; }
/// getNumCaptures - Returns the number of captured variables.
/// Does not include an entry for 'this'.
unsigned getNumCaptures() const { return NumCaptures; }
typedef const Capture *capture_iterator;
typedef const Capture *capture_const_iterator;
typedef llvm::iterator_range<capture_iterator> capture_range;
typedef llvm::iterator_range<capture_const_iterator> capture_const_range;
capture_range captures() {
return capture_range(capture_begin(), capture_end());
}
capture_const_range captures() const {
return capture_const_range(capture_begin(), capture_end());
}
capture_iterator capture_begin() { return Captures; }
capture_iterator capture_end() { return Captures + NumCaptures; }
capture_const_iterator capture_begin() const { return Captures; }
capture_const_iterator capture_end() const { return Captures + NumCaptures; }
bool capturesCXXThis() const { return CapturesCXXThis; }
bool blockMissingReturnType() const { return BlockMissingReturnType; }
void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; }
bool isConversionFromLambda() const { return IsConversionFromLambda; }
void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; }
bool capturesVariable(const VarDecl *var) const;
void setCaptures(ASTContext &Context,
const Capture *begin,
const Capture *end,
bool capturesCXXThis);
unsigned getBlockManglingNumber() const {
return ManglingNumber;
}
Decl *getBlockManglingContextDecl() const {
return ManglingContextDecl;
}
void setBlockMangling(unsigned Number, Decl *Ctx) {
ManglingNumber = Number;
ManglingContextDecl = Ctx;
}
SourceRange getSourceRange() const override LLVM_READONLY;
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Block; }
static DeclContext *castToDeclContext(const BlockDecl *D) {
return static_cast<DeclContext *>(const_cast<BlockDecl*>(D));
}
static BlockDecl *castFromDeclContext(const DeclContext *DC) {
return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC));
}
};
/// \brief This represents the body of a CapturedStmt, and serves as its
/// DeclContext.
class CapturedDecl : public Decl, public DeclContext {
private:
/// \brief The number of parameters to the outlined function.
unsigned NumParams;
/// \brief The position of context parameter in list of parameters.
unsigned ContextParam;
/// \brief The body of the outlined function.
llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow;
explicit CapturedDecl(DeclContext *DC, unsigned NumParams)
: Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) { }
ImplicitParamDecl **getParams() const {
return reinterpret_cast<ImplicitParamDecl **>(
const_cast<CapturedDecl *>(this) + 1);
}
public:
static CapturedDecl *Create(ASTContext &C, DeclContext *DC,
unsigned NumParams);
static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID,
unsigned NumParams);
Stmt *getBody() const override { return BodyAndNothrow.getPointer(); }
void setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
bool isNothrow() const { return BodyAndNothrow.getInt(); }
void setNothrow(bool Nothrow = true) { BodyAndNothrow.setInt(Nothrow); }
unsigned getNumParams() const { return NumParams; }
ImplicitParamDecl *getParam(unsigned i) const {
assert(i < NumParams);
return getParams()[i];
}
void setParam(unsigned i, ImplicitParamDecl *P) {
assert(i < NumParams);
getParams()[i] = P;
}
/// \brief Retrieve the parameter containing captured variables.
ImplicitParamDecl *getContextParam() const {
assert(ContextParam < NumParams);
return getParam(ContextParam);
}
void setContextParam(unsigned i, ImplicitParamDecl *P) {
assert(i < NumParams);
ContextParam = i;
setParam(i, P);
}
unsigned getContextParamPosition() const { return ContextParam; }
typedef ImplicitParamDecl **param_iterator;
typedef llvm::iterator_range<param_iterator> param_range;
/// \brief Retrieve an iterator pointing to the first parameter decl.
param_iterator param_begin() const { return getParams(); }
/// \brief Retrieve an iterator one past the last parameter decl.
param_iterator param_end() const { return getParams() + NumParams; }
/// \brief Retrieve an iterator range for the parameter declarations.
param_range params() const { return param_range(param_begin(), param_end()); }
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Captured; }
static DeclContext *castToDeclContext(const CapturedDecl *D) {
return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D));
}
static CapturedDecl *castFromDeclContext(const DeclContext *DC) {
return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC));
}
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// \brief Describes a module import declaration, which makes the contents
/// of the named module visible in the current translation unit.
///
/// An import declaration imports the named module (or submodule). For example:
/// \code
/// @import std.vector;
/// \endcode
///
/// Import declarations can also be implicitly generated from
/// \#include/\#import directives.
class ImportDecl : public Decl {
/// \brief The imported module, along with a bit that indicates whether
/// we have source-location information for each identifier in the module
/// name.
///
/// When the bit is false, we only have a single source location for the
/// end of the import declaration.
llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete;
/// \brief The next import in the list of imports local to the translation
/// unit being parsed (not loaded from an AST file).
ImportDecl *NextLocalImport;
friend class ASTReader;
friend class ASTDeclReader;
friend class ASTContext;
ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
ArrayRef<SourceLocation> IdentifierLocs);
ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported,
SourceLocation EndLoc);
ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { }
public:
/// \brief Create a new module import declaration.
static ImportDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, Module *Imported,
ArrayRef<SourceLocation> IdentifierLocs);
/// \brief Create a new module import declaration for an implicitly-generated
/// import.
static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, Module *Imported,
SourceLocation EndLoc);
/// \brief Create a new, deserialized module import declaration.
static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID,
unsigned NumLocations);
/// \brief Retrieve the module that was imported by the import declaration.
Module *getImportedModule() const { return ImportedAndComplete.getPointer(); }
/// \brief Retrieves the locations of each of the identifiers that make up
/// the complete module name in the import declaration.
///
/// This will return an empty array if the locations of the individual
/// identifiers aren't available.
ArrayRef<SourceLocation> getIdentifierLocs() const;
SourceRange getSourceRange() const override LLVM_READONLY;
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Import; }
};
/// \brief Represents an empty-declaration.
class EmptyDecl : public Decl {
virtual void anchor();
EmptyDecl(DeclContext *DC, SourceLocation L)
: Decl(Empty, DC, L) { }
public:
static EmptyDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation L);
static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Empty; }
};
// HLSL Change Starts
/// HLSLBufferDecl - Represent a cbuffer or tbuffer declaration.
class HLSLBufferDecl : public NamedDecl, public DeclContext {
/// LBraceLoc - The ending location of the source range.
SourceLocation LBraceLoc;
/// RBraceLoc - The ending location of the source range.
SourceLocation RBraceLoc;
/// KwLoc - The location of the cbuffer or tbuffer keyword.
SourceLocation KwLoc;
/// IsCBuffer - Whether the buffer is a cbuffer (and not a tbuffer).
bool IsCBuffer;
/// IsConstantBufferView - Whether the buffer is ConstantBufferView.
bool IsConstantBufferView;
HLSLBufferDecl(DeclContext *DC, bool cbuffer, bool constantbuf,
SourceLocation KwLoc, IdentifierInfo *Id, SourceLocation IdLoc,
std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
SourceLocation LBrace);
public:
static HLSLBufferDecl *Create(ASTContext &C, DeclContext* lexicalParent,
bool cbuffer, bool constantbuf, SourceLocation KwLoc,
IdentifierInfo *Id, SourceLocation IdLoc,
std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
SourceLocation LBrace);
virtual SourceRange getSourceRange() const LLVM_READONLY{
return SourceRange(getLocStart(), RBraceLoc);
}
const char *getDeclKindName() const;
SourceLocation getLocStart() const LLVM_READONLY{ return KwLoc; }
SourceLocation getRBraceLoc() const { return RBraceLoc; }
void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
bool isCBuffer() const { return IsCBuffer; }
bool isConstantBufferView() const { return IsConstantBufferView; }
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == HLSLBuffer; }
static DeclContext *castToDeclContext(const HLSLBufferDecl *D) {
return static_cast<DeclContext *>(const_cast<HLSLBufferDecl*>(D));
}
static HLSLBufferDecl *castFromDeclContext(const DeclContext *DC) {
return static_cast<HLSLBufferDecl *>(const_cast<DeclContext*>(DC));
}
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
// HLSL Change Ends
/// Insertion operator for diagnostics. This allows sending NamedDecl's
/// into a diagnostic with <<.
inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
const NamedDecl* ND) {
DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
DiagnosticsEngine::ak_nameddecl);
return DB;
}
inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
const NamedDecl* ND) {
PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND),
DiagnosticsEngine::ak_nameddecl);
return PD;
}
template<typename decl_type>
void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) {
// Note: This routine is implemented here because we need both NamedDecl
// and Redeclarable to be defined.
assert(RedeclLink.NextIsLatest() &&
"setPreviousDecl on a decl already in a redeclaration chain");
if (PrevDecl) {
// Point to previous. Make sure that this is actually the most recent
// redeclaration, or we can build invalid chains. If the most recent
// redeclaration is invalid, it won't be PrevDecl, but we want it anyway.
First = PrevDecl->getFirstDecl();
assert(First->RedeclLink.NextIsLatest() && "Expected first");
decl_type *MostRecent = First->getNextRedeclaration();
RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent));
// If the declaration was previously visible, a redeclaration of it remains
// visible even if it wouldn't be visible by itself.
static_cast<decl_type*>(this)->IdentifierNamespace |=
MostRecent->getIdentifierNamespace() &
(Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
} else {
// Make this first.
First = static_cast<decl_type*>(this);
}
// First one will point to this one as latest.
First->RedeclLink.setLatest(static_cast<decl_type*>(this));
assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||
cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid());
}
// Inline function definitions.
/// \brief Check if the given decl is complete.
///
/// We use this function to break a cycle between the inline definitions in
/// Type.h and Decl.h.
inline bool IsEnumDeclComplete(EnumDecl *ED) {
return ED->isComplete();
}
/// \brief Check if the given decl is scoped.
///
/// We use this function to break a cycle between the inline definitions in
/// Type.h and Decl.h.
inline bool IsEnumDeclScoped(EnumDecl *ED) {
return ED->isScoped();
}
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/RecursiveASTVisitor.h | //===--- RecursiveASTVisitor.h - Recursive AST Visitor ----------*- 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 RecursiveASTVisitor interface, which recursively
// traverses the entire AST.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_RECURSIVEASTVISITOR_H
#define LLVM_CLANG_AST_RECURSIVEASTVISITOR_H
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclFriend.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclOpenMP.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/StmtObjC.h"
#include "clang/AST/StmtOpenMP.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
// The following three macros are used for meta programming. The code
// using them is responsible for defining macro OPERATOR().
// All unary operators.
#define UNARYOP_LIST() \
OPERATOR(PostInc) OPERATOR(PostDec) OPERATOR(PreInc) OPERATOR(PreDec) \
OPERATOR(AddrOf) OPERATOR(Deref) OPERATOR(Plus) OPERATOR(Minus) \
OPERATOR(Not) OPERATOR(LNot) OPERATOR(Real) OPERATOR(Imag) \
OPERATOR(Extension)
// All binary operators (excluding compound assign operators).
#define BINOP_LIST() \
OPERATOR(PtrMemD) OPERATOR(PtrMemI) OPERATOR(Mul) OPERATOR(Div) \
OPERATOR(Rem) OPERATOR(Add) OPERATOR(Sub) OPERATOR(Shl) OPERATOR(Shr) \
OPERATOR(LT) OPERATOR(GT) OPERATOR(LE) OPERATOR(GE) OPERATOR(EQ) \
OPERATOR(NE) OPERATOR(And) OPERATOR(Xor) OPERATOR(Or) OPERATOR(LAnd) \
OPERATOR(LOr) OPERATOR(Assign) OPERATOR(Comma)
// All compound assign operators.
#define CAO_LIST() \
OPERATOR(Mul) OPERATOR(Div) OPERATOR(Rem) OPERATOR(Add) OPERATOR(Sub) \
OPERATOR(Shl) OPERATOR(Shr) OPERATOR(And) OPERATOR(Or) OPERATOR(Xor)
namespace clang {
// A helper macro to implement short-circuiting when recursing. It
// invokes CALL_EXPR, which must be a method call, on the derived
// object (s.t. a user of RecursiveASTVisitor can override the method
// in CALL_EXPR).
#define TRY_TO(CALL_EXPR) \
do { \
if (!getDerived().CALL_EXPR) \
return false; \
} while (0)
/// \brief A class that does preorder depth-first traversal on the
/// entire Clang AST and visits each node.
///
/// This class performs three distinct tasks:
/// 1. traverse the AST (i.e. go to each node);
/// 2. at a given node, walk up the class hierarchy, starting from
/// the node's dynamic type, until the top-most class (e.g. Stmt,
/// Decl, or Type) is reached.
/// 3. given a (node, class) combination, where 'class' is some base
/// class of the dynamic type of 'node', call a user-overridable
/// function to actually visit the node.
///
/// These tasks are done by three groups of methods, respectively:
/// 1. TraverseDecl(Decl *x) does task #1. It is the entry point
/// for traversing an AST rooted at x. This method simply
/// dispatches (i.e. forwards) to TraverseFoo(Foo *x) where Foo
/// is the dynamic type of *x, which calls WalkUpFromFoo(x) and
/// then recursively visits the child nodes of x.
/// TraverseStmt(Stmt *x) and TraverseType(QualType x) work
/// similarly.
/// 2. WalkUpFromFoo(Foo *x) does task #2. It does not try to visit
/// any child node of x. Instead, it first calls WalkUpFromBar(x)
/// where Bar is the direct parent class of Foo (unless Foo has
/// no parent), and then calls VisitFoo(x) (see the next list item).
/// 3. VisitFoo(Foo *x) does task #3.
///
/// These three method groups are tiered (Traverse* > WalkUpFrom* >
/// Visit*). A method (e.g. Traverse*) may call methods from the same
/// tier (e.g. other Traverse*) or one tier lower (e.g. WalkUpFrom*).
/// It may not call methods from a higher tier.
///
/// Note that since WalkUpFromFoo() calls WalkUpFromBar() (where Bar
/// is Foo's super class) before calling VisitFoo(), the result is
/// that the Visit*() methods for a given node are called in the
/// top-down order (e.g. for a node of type NamespaceDecl, the order will
/// be VisitDecl(), VisitNamedDecl(), and then VisitNamespaceDecl()).
///
/// This scheme guarantees that all Visit*() calls for the same AST
/// node are grouped together. In other words, Visit*() methods for
/// different nodes are never interleaved.
///
/// Clients of this visitor should subclass the visitor (providing
/// themselves as the template argument, using the curiously recurring
/// template pattern) and override any of the Traverse*, WalkUpFrom*,
/// and Visit* methods for declarations, types, statements,
/// expressions, or other AST nodes where the visitor should customize
/// behavior. Most users only need to override Visit*. Advanced
/// users may override Traverse* and WalkUpFrom* to implement custom
/// traversal strategies. Returning false from one of these overridden
/// functions will abort the entire traversal.
///
/// By default, this visitor tries to visit every part of the explicit
/// source code exactly once. The default policy towards templates
/// is to descend into the 'pattern' class or function body, not any
/// explicit or implicit instantiations. Explicit specializations
/// are still visited, and the patterns of partial specializations
/// are visited separately. This behavior can be changed by
/// overriding shouldVisitTemplateInstantiations() in the derived class
/// to return true, in which case all known implicit and explicit
/// instantiations will be visited at the same time as the pattern
/// from which they were produced.
template <typename Derived> class RecursiveASTVisitor {
public:
/// \brief Return a reference to the derived class.
Derived &getDerived() { return *static_cast<Derived *>(this); }
/// \brief Return whether this visitor should recurse into
/// template instantiations.
bool shouldVisitTemplateInstantiations() const { return false; }
/// \brief Return whether this visitor should recurse into the types of
/// TypeLocs.
bool shouldWalkTypesOfTypeLocs() const { return true; }
/// \brief Return whether this visitor should recurse into implicit
/// code, e.g., implicit constructors and destructors.
bool shouldVisitImplicitCode() const { return false; }
/// \brief Return whether \param S should be traversed using data recursion
/// to avoid a stack overflow with extreme cases.
bool shouldUseDataRecursionFor(Stmt *S) const {
return isa<BinaryOperator>(S) || isa<UnaryOperator>(S) ||
isa<CaseStmt>(S) || isa<CXXOperatorCallExpr>(S);
}
/// \brief Recursively visit a statement or expression, by
/// dispatching to Traverse*() based on the argument's dynamic type.
///
/// \returns false if the visitation was terminated early, true
/// otherwise (including when the argument is NULL).
bool TraverseStmt(Stmt *S);
/// \brief Recursively visit a type, by dispatching to
/// Traverse*Type() based on the argument's getTypeClass() property.
///
/// \returns false if the visitation was terminated early, true
/// otherwise (including when the argument is a Null type).
bool TraverseType(QualType T);
/// \brief Recursively visit a type with location, by dispatching to
/// Traverse*TypeLoc() based on the argument type's getTypeClass() property.
///
/// \returns false if the visitation was terminated early, true
/// otherwise (including when the argument is a Null type location).
bool TraverseTypeLoc(TypeLoc TL);
/// \brief Recursively visit an attribute, by dispatching to
/// Traverse*Attr() based on the argument's dynamic type.
///
/// \returns false if the visitation was terminated early, true
/// otherwise (including when the argument is a Null type location).
bool TraverseAttr(Attr *At);
/// \brief Recursively visit a declaration, by dispatching to
/// Traverse*Decl() based on the argument's dynamic type.
///
/// \returns false if the visitation was terminated early, true
/// otherwise (including when the argument is NULL).
bool TraverseDecl(Decl *D);
/// \brief Recursively visit a C++ nested-name-specifier.
///
/// \returns false if the visitation was terminated early, true otherwise.
bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS);
/// \brief Recursively visit a C++ nested-name-specifier with location
/// information.
///
/// \returns false if the visitation was terminated early, true otherwise.
bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS);
/// \brief Recursively visit a name with its location information.
///
/// \returns false if the visitation was terminated early, true otherwise.
bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo);
/// \brief Recursively visit a template name and dispatch to the
/// appropriate method.
///
/// \returns false if the visitation was terminated early, true otherwise.
bool TraverseTemplateName(TemplateName Template);
/// \brief Recursively visit a template argument and dispatch to the
/// appropriate method for the argument type.
///
/// \returns false if the visitation was terminated early, true otherwise.
// FIXME: migrate callers to TemplateArgumentLoc instead.
bool TraverseTemplateArgument(const TemplateArgument &Arg);
/// \brief Recursively visit a template argument location and dispatch to the
/// appropriate method for the argument type.
///
/// \returns false if the visitation was terminated early, true otherwise.
bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc);
/// \brief Recursively visit a set of template arguments.
/// This can be overridden by a subclass, but it's not expected that
/// will be needed -- this visitor always dispatches to another.
///
/// \returns false if the visitation was terminated early, true otherwise.
// FIXME: take a TemplateArgumentLoc* (or TemplateArgumentListInfo) instead.
bool TraverseTemplateArguments(const TemplateArgument *Args,
unsigned NumArgs);
/// \brief Recursively visit a constructor initializer. This
/// automatically dispatches to another visitor for the initializer
/// expression, but not for the name of the initializer, so may
/// be overridden for clients that need access to the name.
///
/// \returns false if the visitation was terminated early, true otherwise.
bool TraverseConstructorInitializer(CXXCtorInitializer *Init);
/// \brief Recursively visit a lambda capture.
///
/// \returns false if the visitation was terminated early, true otherwise.
bool TraverseLambdaCapture(LambdaExpr *LE, const LambdaCapture *C);
/// \brief Recursively visit the body of a lambda expression.
///
/// This provides a hook for visitors that need more context when visiting
/// \c LE->getBody().
///
/// \returns false if the visitation was terminated early, true otherwise.
bool TraverseLambdaBody(LambdaExpr *LE);
// ---- Methods on Attrs ----
// \brief Visit an attribute.
bool VisitAttr(Attr *A) { return true; }
// Declare Traverse* and empty Visit* for all Attr classes.
#define ATTR_VISITOR_DECLS_ONLY
#include "clang/AST/AttrVisitor.inc"
#undef ATTR_VISITOR_DECLS_ONLY
// ---- Methods on Stmts ----
// Declare Traverse*() for all concrete Stmt classes.
#define ABSTRACT_STMT(STMT)
#define STMT(CLASS, PARENT) bool Traverse##CLASS(CLASS *S);
#include "clang/AST/StmtNodes.inc"
// The above header #undefs ABSTRACT_STMT and STMT upon exit.
// Define WalkUpFrom*() and empty Visit*() for all Stmt classes.
bool WalkUpFromStmt(Stmt *S) { return getDerived().VisitStmt(S); }
bool VisitStmt(Stmt *S) { return true; }
#define STMT(CLASS, PARENT) \
bool WalkUpFrom##CLASS(CLASS *S) { \
TRY_TO(WalkUpFrom##PARENT(S)); \
TRY_TO(Visit##CLASS(S)); \
return true; \
} \
bool Visit##CLASS(CLASS *S) { return true; }
#include "clang/AST/StmtNodes.inc"
// Define Traverse*(), WalkUpFrom*(), and Visit*() for unary
// operator methods. Unary operators are not classes in themselves
// (they're all opcodes in UnaryOperator) but do have visitors.
#define OPERATOR(NAME) \
bool TraverseUnary##NAME(UnaryOperator *S) { \
TRY_TO(WalkUpFromUnary##NAME(S)); \
TRY_TO(TraverseStmt(S->getSubExpr())); \
return true; \
} \
bool WalkUpFromUnary##NAME(UnaryOperator *S) { \
TRY_TO(WalkUpFromUnaryOperator(S)); \
TRY_TO(VisitUnary##NAME(S)); \
return true; \
} \
bool VisitUnary##NAME(UnaryOperator *S) { return true; }
UNARYOP_LIST()
#undef OPERATOR
// Define Traverse*(), WalkUpFrom*(), and Visit*() for binary
// operator methods. Binary operators are not classes in themselves
// (they're all opcodes in BinaryOperator) but do have visitors.
#define GENERAL_BINOP_FALLBACK(NAME, BINOP_TYPE) \
bool TraverseBin##NAME(BINOP_TYPE *S) { \
TRY_TO(WalkUpFromBin##NAME(S)); \
TRY_TO(TraverseStmt(S->getLHS())); \
TRY_TO(TraverseStmt(S->getRHS())); \
return true; \
} \
bool WalkUpFromBin##NAME(BINOP_TYPE *S) { \
TRY_TO(WalkUpFrom##BINOP_TYPE(S)); \
TRY_TO(VisitBin##NAME(S)); \
return true; \
} \
bool VisitBin##NAME(BINOP_TYPE *S) { return true; }
#define OPERATOR(NAME) GENERAL_BINOP_FALLBACK(NAME, BinaryOperator)
BINOP_LIST()
#undef OPERATOR
// Define Traverse*(), WalkUpFrom*(), and Visit*() for compound
// assignment methods. Compound assignment operators are not
// classes in themselves (they're all opcodes in
// CompoundAssignOperator) but do have visitors.
#define OPERATOR(NAME) \
GENERAL_BINOP_FALLBACK(NAME##Assign, CompoundAssignOperator)
CAO_LIST()
#undef OPERATOR
#undef GENERAL_BINOP_FALLBACK
// ---- Methods on Types ----
// FIXME: revamp to take TypeLoc's rather than Types.
// Declare Traverse*() for all concrete Type classes.
#define ABSTRACT_TYPE(CLASS, BASE)
#define TYPE(CLASS, BASE) bool Traverse##CLASS##Type(CLASS##Type *T);
#include "clang/AST/TypeNodes.def"
// The above header #undefs ABSTRACT_TYPE and TYPE upon exit.
// Define WalkUpFrom*() and empty Visit*() for all Type classes.
bool WalkUpFromType(Type *T) { return getDerived().VisitType(T); }
bool VisitType(Type *T) { return true; }
#define TYPE(CLASS, BASE) \
bool WalkUpFrom##CLASS##Type(CLASS##Type *T) { \
TRY_TO(WalkUpFrom##BASE(T)); \
TRY_TO(Visit##CLASS##Type(T)); \
return true; \
} \
bool Visit##CLASS##Type(CLASS##Type *T) { return true; }
#include "clang/AST/TypeNodes.def"
// ---- Methods on TypeLocs ----
// FIXME: this currently just calls the matching Type methods
// Declare Traverse*() for all concrete TypeLoc classes.
#define ABSTRACT_TYPELOC(CLASS, BASE)
#define TYPELOC(CLASS, BASE) bool Traverse##CLASS##TypeLoc(CLASS##TypeLoc TL);
#include "clang/AST/TypeLocNodes.def"
// The above header #undefs ABSTRACT_TYPELOC and TYPELOC upon exit.
// Define WalkUpFrom*() and empty Visit*() for all TypeLoc classes.
bool WalkUpFromTypeLoc(TypeLoc TL) { return getDerived().VisitTypeLoc(TL); }
bool VisitTypeLoc(TypeLoc TL) { return true; }
// QualifiedTypeLoc and UnqualTypeLoc are not declared in
// TypeNodes.def and thus need to be handled specially.
bool WalkUpFromQualifiedTypeLoc(QualifiedTypeLoc TL) {
return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
}
bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { return true; }
bool WalkUpFromUnqualTypeLoc(UnqualTypeLoc TL) {
return getDerived().VisitUnqualTypeLoc(TL.getUnqualifiedLoc());
}
bool VisitUnqualTypeLoc(UnqualTypeLoc TL) { return true; }
// Note that BASE includes trailing 'Type' which CLASS doesn't.
#define TYPE(CLASS, BASE) \
bool WalkUpFrom##CLASS##TypeLoc(CLASS##TypeLoc TL) { \
TRY_TO(WalkUpFrom##BASE##Loc(TL)); \
TRY_TO(Visit##CLASS##TypeLoc(TL)); \
return true; \
} \
bool Visit##CLASS##TypeLoc(CLASS##TypeLoc TL) { return true; }
#include "clang/AST/TypeNodes.def"
// ---- Methods on Decls ----
// Declare Traverse*() for all concrete Decl classes.
#define ABSTRACT_DECL(DECL)
#define DECL(CLASS, BASE) bool Traverse##CLASS##Decl(CLASS##Decl *D);
#include "clang/AST/DeclNodes.inc"
// The above header #undefs ABSTRACT_DECL and DECL upon exit.
// Define WalkUpFrom*() and empty Visit*() for all Decl classes.
bool WalkUpFromDecl(Decl *D) { return getDerived().VisitDecl(D); }
bool VisitDecl(Decl *D) { return true; }
#define DECL(CLASS, BASE) \
bool WalkUpFrom##CLASS##Decl(CLASS##Decl *D) { \
TRY_TO(WalkUpFrom##BASE(D)); \
TRY_TO(Visit##CLASS##Decl(D)); \
return true; \
} \
bool Visit##CLASS##Decl(CLASS##Decl *D) { return true; }
#include "clang/AST/DeclNodes.inc"
private:
// These are helper methods used by more than one Traverse* method.
bool TraverseTemplateParameterListHelper(TemplateParameterList *TPL);
#define DEF_TRAVERSE_TMPL_INST(TMPLDECLKIND) \
bool TraverseTemplateInstantiations(TMPLDECLKIND##TemplateDecl *D);
DEF_TRAVERSE_TMPL_INST(Class)
DEF_TRAVERSE_TMPL_INST(Var)
DEF_TRAVERSE_TMPL_INST(Function)
#undef DEF_TRAVERSE_TMPL_INST
bool TraverseTemplateArgumentLocsHelper(const TemplateArgumentLoc *TAL,
unsigned Count);
bool TraverseArrayTypeLocHelper(ArrayTypeLoc TL);
bool TraverseRecordHelper(RecordDecl *D);
bool TraverseCXXRecordHelper(CXXRecordDecl *D);
bool TraverseDeclaratorHelper(DeclaratorDecl *D);
bool TraverseDeclContextHelper(DeclContext *DC);
bool TraverseFunctionHelper(FunctionDecl *D);
bool TraverseVarHelper(VarDecl *D);
bool TraverseOMPExecutableDirective(OMPExecutableDirective *S);
bool TraverseOMPLoopDirective(OMPLoopDirective *S);
bool TraverseOMPClause(OMPClause *C);
#define OPENMP_CLAUSE(Name, Class) bool Visit##Class(Class *C);
#include "clang/Basic/OpenMPKinds.def"
/// \brief Process clauses with list of variables.
template <typename T> bool VisitOMPClauseList(T *Node);
struct EnqueueJob {
Stmt *S;
Stmt::child_iterator StmtIt;
EnqueueJob(Stmt *S) : S(S), StmtIt() {}
};
bool dataTraverse(Stmt *S);
bool dataTraverseNode(Stmt *S, bool &EnqueueChildren);
};
template <typename Derived>
bool RecursiveASTVisitor<Derived>::dataTraverse(Stmt *S) {
SmallVector<EnqueueJob, 16> Queue;
Queue.push_back(S);
while (!Queue.empty()) {
EnqueueJob &job = Queue.back();
Stmt *CurrS = job.S;
if (!CurrS) {
Queue.pop_back();
continue;
}
if (getDerived().shouldUseDataRecursionFor(CurrS)) {
if (job.StmtIt == Stmt::child_iterator()) {
bool EnqueueChildren = true;
if (!dataTraverseNode(CurrS, EnqueueChildren))
return false;
if (!EnqueueChildren) {
Queue.pop_back();
continue;
}
job.StmtIt = CurrS->child_begin();
} else {
++job.StmtIt;
}
if (job.StmtIt != CurrS->child_end())
Queue.push_back(*job.StmtIt);
else
Queue.pop_back();
continue;
}
Queue.pop_back();
TRY_TO(TraverseStmt(CurrS));
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::dataTraverseNode(Stmt *S,
bool &EnqueueChildren) {
// Dispatch to the corresponding WalkUpFrom* function only if the derived
// class didn't override Traverse* (and thus the traversal is trivial).
#define DISPATCH_WALK(NAME, CLASS, VAR) \
{ \
bool (Derived::*DerivedFn)(CLASS *) = &Derived::Traverse##NAME; \
bool (Derived::*BaseFn)(CLASS *) = &RecursiveASTVisitor::Traverse##NAME; \
if (DerivedFn == BaseFn) \
return getDerived().WalkUpFrom##NAME(static_cast<CLASS *>(VAR)); \
} \
EnqueueChildren = false; \
return getDerived().Traverse##NAME(static_cast<CLASS *>(VAR));
if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
switch (BinOp->getOpcode()) {
#define OPERATOR(NAME) \
case BO_##NAME: \
DISPATCH_WALK(Bin##NAME, BinaryOperator, S);
BINOP_LIST()
#undef OPERATOR
#define OPERATOR(NAME) \
case BO_##NAME##Assign: \
DISPATCH_WALK(Bin##NAME##Assign, CompoundAssignOperator, S);
CAO_LIST()
#undef OPERATOR
}
} else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(S)) {
switch (UnOp->getOpcode()) {
#define OPERATOR(NAME) \
case UO_##NAME: \
DISPATCH_WALK(Unary##NAME, UnaryOperator, S);
UNARYOP_LIST()
#undef OPERATOR
}
}
// Top switch stmt: dispatch to TraverseFooStmt for each concrete FooStmt.
switch (S->getStmtClass()) {
case Stmt::NoStmtClass:
break;
#define ABSTRACT_STMT(STMT)
#define STMT(CLASS, PARENT) \
case Stmt::CLASS##Class: \
DISPATCH_WALK(CLASS, CLASS, S);
#include "clang/AST/StmtNodes.inc"
}
#undef DISPATCH_WALK
return true;
}
#define DISPATCH(NAME, CLASS, VAR) \
return getDerived().Traverse##NAME(static_cast<CLASS *>(VAR))
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseStmt(Stmt *S) {
if (!S)
return true;
#define DISPATCH_STMT(NAME, CLASS, VAR) DISPATCH(NAME, CLASS, VAR)
if (getDerived().shouldUseDataRecursionFor(S))
return dataTraverse(S);
// If we have a binary expr, dispatch to the subcode of the binop. A smart
// optimizer (e.g. LLVM) will fold this comparison into the switch stmt
// below.
if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
switch (BinOp->getOpcode()) {
#define OPERATOR(NAME) \
case BO_##NAME: \
DISPATCH_STMT(Bin##NAME, BinaryOperator, S);
BINOP_LIST()
#undef OPERATOR
#undef BINOP_LIST
#define OPERATOR(NAME) \
case BO_##NAME##Assign: \
DISPATCH_STMT(Bin##NAME##Assign, CompoundAssignOperator, S);
CAO_LIST()
#undef OPERATOR
#undef CAO_LIST
}
} else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(S)) {
switch (UnOp->getOpcode()) {
#define OPERATOR(NAME) \
case UO_##NAME: \
DISPATCH_STMT(Unary##NAME, UnaryOperator, S);
UNARYOP_LIST()
#undef OPERATOR
#undef UNARYOP_LIST
}
}
// Top switch stmt: dispatch to TraverseFooStmt for each concrete FooStmt.
switch (S->getStmtClass()) {
case Stmt::NoStmtClass:
break;
#define ABSTRACT_STMT(STMT)
#define STMT(CLASS, PARENT) \
case Stmt::CLASS##Class: \
DISPATCH_STMT(CLASS, CLASS, S);
#include "clang/AST/StmtNodes.inc"
}
return true;
}
#undef DISPATCH_STMT
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseType(QualType T) {
if (T.isNull())
return true;
switch (T->getTypeClass()) {
#define ABSTRACT_TYPE(CLASS, BASE)
#define TYPE(CLASS, BASE) \
case Type::CLASS: \
DISPATCH(CLASS##Type, CLASS##Type, const_cast<Type *>(T.getTypePtr()));
#include "clang/AST/TypeNodes.def"
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTypeLoc(TypeLoc TL) {
if (TL.isNull())
return true;
switch (TL.getTypeLocClass()) {
#define ABSTRACT_TYPELOC(CLASS, BASE)
#define TYPELOC(CLASS, BASE) \
case TypeLoc::CLASS: \
return getDerived().Traverse##CLASS##TypeLoc(TL.castAs<CLASS##TypeLoc>());
#include "clang/AST/TypeLocNodes.def"
}
return true;
}
// Define the Traverse*Attr(Attr* A) methods
#define VISITORCLASS RecursiveASTVisitor
#include "clang/AST/AttrVisitor.inc"
#undef VISITORCLASS
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseDecl(Decl *D) {
if (!D)
return true;
// As a syntax visitor, by default we want to ignore declarations for
// implicit declarations (ones not typed explicitly by the user).
if (!getDerived().shouldVisitImplicitCode() && D->isImplicit())
return true;
switch (D->getKind()) {
#define ABSTRACT_DECL(DECL)
#define DECL(CLASS, BASE) \
case Decl::CLASS: \
if (!getDerived().Traverse##CLASS##Decl(static_cast<CLASS##Decl *>(D))) \
return false; \
break;
#include "clang/AST/DeclNodes.inc"
}
// Visit any attributes attached to this declaration.
for (auto *I : D->attrs()) {
if (!getDerived().TraverseAttr(I))
return false;
}
return true;
}
#undef DISPATCH
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseNestedNameSpecifier(
NestedNameSpecifier *NNS) {
if (!NNS)
return true;
if (NNS->getPrefix())
TRY_TO(TraverseNestedNameSpecifier(NNS->getPrefix()));
switch (NNS->getKind()) {
case NestedNameSpecifier::Identifier:
case NestedNameSpecifier::Namespace:
case NestedNameSpecifier::NamespaceAlias:
case NestedNameSpecifier::Global:
case NestedNameSpecifier::Super:
return true;
case NestedNameSpecifier::TypeSpec:
case NestedNameSpecifier::TypeSpecWithTemplate:
TRY_TO(TraverseType(QualType(NNS->getAsType(), 0)));
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseNestedNameSpecifierLoc(
NestedNameSpecifierLoc NNS) {
if (!NNS)
return true;
if (NestedNameSpecifierLoc Prefix = NNS.getPrefix())
TRY_TO(TraverseNestedNameSpecifierLoc(Prefix));
switch (NNS.getNestedNameSpecifier()->getKind()) {
case NestedNameSpecifier::Identifier:
case NestedNameSpecifier::Namespace:
case NestedNameSpecifier::NamespaceAlias:
case NestedNameSpecifier::Global:
case NestedNameSpecifier::Super:
return true;
case NestedNameSpecifier::TypeSpec:
case NestedNameSpecifier::TypeSpecWithTemplate:
TRY_TO(TraverseTypeLoc(NNS.getTypeLoc()));
break;
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseDeclarationNameInfo(
DeclarationNameInfo NameInfo) {
switch (NameInfo.getName().getNameKind()) {
case DeclarationName::CXXConstructorName:
case DeclarationName::CXXDestructorName:
case DeclarationName::CXXConversionFunctionName:
if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
TRY_TO(TraverseTypeLoc(TSInfo->getTypeLoc()));
break;
case DeclarationName::Identifier:
case DeclarationName::ObjCZeroArgSelector:
case DeclarationName::ObjCOneArgSelector:
case DeclarationName::ObjCMultiArgSelector:
case DeclarationName::CXXOperatorName:
case DeclarationName::CXXLiteralOperatorName:
case DeclarationName::CXXUsingDirective:
break;
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTemplateName(TemplateName Template) {
if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
TRY_TO(TraverseNestedNameSpecifier(DTN->getQualifier()));
else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
TRY_TO(TraverseNestedNameSpecifier(QTN->getQualifier()));
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTemplateArgument(
const TemplateArgument &Arg) {
switch (Arg.getKind()) {
case TemplateArgument::Null:
case TemplateArgument::Declaration:
case TemplateArgument::Integral:
case TemplateArgument::NullPtr:
return true;
case TemplateArgument::Type:
return getDerived().TraverseType(Arg.getAsType());
case TemplateArgument::Template:
case TemplateArgument::TemplateExpansion:
return getDerived().TraverseTemplateName(
Arg.getAsTemplateOrTemplatePattern());
case TemplateArgument::Expression:
return getDerived().TraverseStmt(Arg.getAsExpr());
case TemplateArgument::Pack:
return getDerived().TraverseTemplateArguments(Arg.pack_begin(),
Arg.pack_size());
}
return true;
}
// FIXME: no template name location?
// FIXME: no source locations for a template argument pack?
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTemplateArgumentLoc(
const TemplateArgumentLoc &ArgLoc) {
const TemplateArgument &Arg = ArgLoc.getArgument();
switch (Arg.getKind()) {
case TemplateArgument::Null:
case TemplateArgument::Declaration:
case TemplateArgument::Integral:
case TemplateArgument::NullPtr:
return true;
case TemplateArgument::Type: {
// FIXME: how can TSI ever be NULL?
if (TypeSourceInfo *TSI = ArgLoc.getTypeSourceInfo())
return getDerived().TraverseTypeLoc(TSI->getTypeLoc());
else
return getDerived().TraverseType(Arg.getAsType());
}
case TemplateArgument::Template:
case TemplateArgument::TemplateExpansion:
if (ArgLoc.getTemplateQualifierLoc())
TRY_TO(getDerived().TraverseNestedNameSpecifierLoc(
ArgLoc.getTemplateQualifierLoc()));
return getDerived().TraverseTemplateName(
Arg.getAsTemplateOrTemplatePattern());
case TemplateArgument::Expression:
return getDerived().TraverseStmt(ArgLoc.getSourceExpression());
case TemplateArgument::Pack:
return getDerived().TraverseTemplateArguments(Arg.pack_begin(),
Arg.pack_size());
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTemplateArguments(
const TemplateArgument *Args, unsigned NumArgs) {
for (unsigned I = 0; I != NumArgs; ++I) {
TRY_TO(TraverseTemplateArgument(Args[I]));
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseConstructorInitializer(
CXXCtorInitializer *Init) {
if (TypeSourceInfo *TInfo = Init->getTypeSourceInfo())
TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
if (Init->isWritten() || getDerived().shouldVisitImplicitCode())
TRY_TO(TraverseStmt(Init->getInit()));
return true;
}
template <typename Derived>
bool
RecursiveASTVisitor<Derived>::TraverseLambdaCapture(LambdaExpr *LE,
const LambdaCapture *C) {
if (LE->isInitCapture(C))
TRY_TO(TraverseDecl(C->getCapturedVar()));
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseLambdaBody(LambdaExpr *LE) {
TRY_TO(TraverseStmt(LE->getBody()));
return true;
}
// ----------------- Type traversal -----------------
// This macro makes available a variable T, the passed-in type.
#define DEF_TRAVERSE_TYPE(TYPE, CODE) \
template <typename Derived> \
bool RecursiveASTVisitor<Derived>::Traverse##TYPE(TYPE *T) { \
TRY_TO(WalkUpFrom##TYPE(T)); \
{ CODE; } \
return true; \
}
DEF_TRAVERSE_TYPE(BuiltinType, {})
DEF_TRAVERSE_TYPE(ComplexType, { TRY_TO(TraverseType(T->getElementType())); })
DEF_TRAVERSE_TYPE(PointerType, { TRY_TO(TraverseType(T->getPointeeType())); })
DEF_TRAVERSE_TYPE(BlockPointerType,
{ TRY_TO(TraverseType(T->getPointeeType())); })
DEF_TRAVERSE_TYPE(LValueReferenceType,
{ TRY_TO(TraverseType(T->getPointeeType())); })
DEF_TRAVERSE_TYPE(RValueReferenceType,
{ TRY_TO(TraverseType(T->getPointeeType())); })
DEF_TRAVERSE_TYPE(MemberPointerType, {
TRY_TO(TraverseType(QualType(T->getClass(), 0)));
TRY_TO(TraverseType(T->getPointeeType()));
})
DEF_TRAVERSE_TYPE(AdjustedType, { TRY_TO(TraverseType(T->getOriginalType())); })
DEF_TRAVERSE_TYPE(DecayedType, { TRY_TO(TraverseType(T->getOriginalType())); })
DEF_TRAVERSE_TYPE(ConstantArrayType,
{ TRY_TO(TraverseType(T->getElementType())); })
DEF_TRAVERSE_TYPE(IncompleteArrayType,
{ TRY_TO(TraverseType(T->getElementType())); })
DEF_TRAVERSE_TYPE(VariableArrayType, {
TRY_TO(TraverseType(T->getElementType()));
TRY_TO(TraverseStmt(T->getSizeExpr()));
})
DEF_TRAVERSE_TYPE(DependentSizedArrayType, {
TRY_TO(TraverseType(T->getElementType()));
if (T->getSizeExpr())
TRY_TO(TraverseStmt(T->getSizeExpr()));
})
DEF_TRAVERSE_TYPE(DependentSizedExtVectorType, {
if (T->getSizeExpr())
TRY_TO(TraverseStmt(T->getSizeExpr()));
TRY_TO(TraverseType(T->getElementType()));
})
DEF_TRAVERSE_TYPE(VectorType, { TRY_TO(TraverseType(T->getElementType())); })
DEF_TRAVERSE_TYPE(ExtVectorType, { TRY_TO(TraverseType(T->getElementType())); })
DEF_TRAVERSE_TYPE(FunctionNoProtoType,
{ TRY_TO(TraverseType(T->getReturnType())); })
DEF_TRAVERSE_TYPE(FunctionProtoType, {
TRY_TO(TraverseType(T->getReturnType()));
for (const auto &A : T->param_types()) {
TRY_TO(TraverseType(A));
}
for (const auto &E : T->exceptions()) {
TRY_TO(TraverseType(E));
}
if (Expr *NE = T->getNoexceptExpr())
TRY_TO(TraverseStmt(NE));
})
DEF_TRAVERSE_TYPE(UnresolvedUsingType, {})
DEF_TRAVERSE_TYPE(TypedefType, {})
DEF_TRAVERSE_TYPE(TypeOfExprType,
{ TRY_TO(TraverseStmt(T->getUnderlyingExpr())); })
DEF_TRAVERSE_TYPE(TypeOfType, { TRY_TO(TraverseType(T->getUnderlyingType())); })
DEF_TRAVERSE_TYPE(DecltypeType,
{ TRY_TO(TraverseStmt(T->getUnderlyingExpr())); })
DEF_TRAVERSE_TYPE(UnaryTransformType, {
TRY_TO(TraverseType(T->getBaseType()));
TRY_TO(TraverseType(T->getUnderlyingType()));
})
DEF_TRAVERSE_TYPE(AutoType, { TRY_TO(TraverseType(T->getDeducedType())); })
DEF_TRAVERSE_TYPE(RecordType, {})
DEF_TRAVERSE_TYPE(EnumType, {})
DEF_TRAVERSE_TYPE(TemplateTypeParmType, {})
DEF_TRAVERSE_TYPE(SubstTemplateTypeParmType, {})
DEF_TRAVERSE_TYPE(SubstTemplateTypeParmPackType, {})
DEF_TRAVERSE_TYPE(TemplateSpecializationType, {
TRY_TO(TraverseTemplateName(T->getTemplateName()));
TRY_TO(TraverseTemplateArguments(T->getArgs(), T->getNumArgs()));
})
DEF_TRAVERSE_TYPE(InjectedClassNameType, {})
DEF_TRAVERSE_TYPE(AttributedType,
{ TRY_TO(TraverseType(T->getModifiedType())); })
DEF_TRAVERSE_TYPE(ParenType, { TRY_TO(TraverseType(T->getInnerType())); })
DEF_TRAVERSE_TYPE(ElaboratedType, {
if (T->getQualifier()) {
TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
}
TRY_TO(TraverseType(T->getNamedType()));
})
DEF_TRAVERSE_TYPE(DependentNameType,
{ TRY_TO(TraverseNestedNameSpecifier(T->getQualifier())); })
DEF_TRAVERSE_TYPE(DependentTemplateSpecializationType, {
TRY_TO(TraverseNestedNameSpecifier(T->getQualifier()));
TRY_TO(TraverseTemplateArguments(T->getArgs(), T->getNumArgs()));
})
DEF_TRAVERSE_TYPE(PackExpansionType, { TRY_TO(TraverseType(T->getPattern())); })
DEF_TRAVERSE_TYPE(ObjCInterfaceType, {})
DEF_TRAVERSE_TYPE(ObjCObjectType, {
// We have to watch out here because an ObjCInterfaceType's base
// type is itself.
if (T->getBaseType().getTypePtr() != T)
TRY_TO(TraverseType(T->getBaseType()));
for (auto typeArg : T->getTypeArgsAsWritten()) {
TRY_TO(TraverseType(typeArg));
}
})
DEF_TRAVERSE_TYPE(ObjCObjectPointerType,
{ TRY_TO(TraverseType(T->getPointeeType())); })
DEF_TRAVERSE_TYPE(AtomicType, { TRY_TO(TraverseType(T->getValueType())); })
#undef DEF_TRAVERSE_TYPE
// ----------------- TypeLoc traversal -----------------
// This macro makes available a variable TL, the passed-in TypeLoc.
// If requested, it calls WalkUpFrom* for the Type in the given TypeLoc,
// in addition to WalkUpFrom* for the TypeLoc itself, such that existing
// clients that override the WalkUpFrom*Type() and/or Visit*Type() methods
// continue to work.
#define DEF_TRAVERSE_TYPELOC(TYPE, CODE) \
template <typename Derived> \
bool RecursiveASTVisitor<Derived>::Traverse##TYPE##Loc(TYPE##Loc TL) { \
if (getDerived().shouldWalkTypesOfTypeLocs()) \
TRY_TO(WalkUpFrom##TYPE(const_cast<TYPE *>(TL.getTypePtr()))); \
TRY_TO(WalkUpFrom##TYPE##Loc(TL)); \
{ CODE; } \
return true; \
}
template <typename Derived>
bool
RecursiveASTVisitor<Derived>::TraverseQualifiedTypeLoc(QualifiedTypeLoc TL) {
// Move this over to the 'main' typeloc tree. Note that this is a
// move -- we pretend that we were really looking at the unqualified
// typeloc all along -- rather than a recursion, so we don't follow
// the normal CRTP plan of going through
// getDerived().TraverseTypeLoc. If we did, we'd be traversing
// twice for the same type (once as a QualifiedTypeLoc version of
// the type, once as an UnqualifiedTypeLoc version of the type),
// which in effect means we'd call VisitTypeLoc twice with the
// 'same' type. This solves that problem, at the cost of never
// seeing the qualified version of the type (unless the client
// subclasses TraverseQualifiedTypeLoc themselves). It's not a
// perfect solution. A perfect solution probably requires making
// QualifiedTypeLoc a wrapper around TypeLoc -- like QualType is a
// wrapper around Type* -- rather than being its own class in the
// type hierarchy.
return TraverseTypeLoc(TL.getUnqualifiedLoc());
}
DEF_TRAVERSE_TYPELOC(BuiltinType, {})
// FIXME: ComplexTypeLoc is unfinished
DEF_TRAVERSE_TYPELOC(ComplexType, {
TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
})
DEF_TRAVERSE_TYPELOC(PointerType,
{ TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
DEF_TRAVERSE_TYPELOC(BlockPointerType,
{ TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
DEF_TRAVERSE_TYPELOC(LValueReferenceType,
{ TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
DEF_TRAVERSE_TYPELOC(RValueReferenceType,
{ TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
// FIXME: location of base class?
// We traverse this in the type case as well, but how is it not reached through
// the pointee type?
DEF_TRAVERSE_TYPELOC(MemberPointerType, {
TRY_TO(TraverseType(QualType(TL.getTypePtr()->getClass(), 0)));
TRY_TO(TraverseTypeLoc(TL.getPointeeLoc()));
})
DEF_TRAVERSE_TYPELOC(AdjustedType,
{ TRY_TO(TraverseTypeLoc(TL.getOriginalLoc())); })
DEF_TRAVERSE_TYPELOC(DecayedType,
{ TRY_TO(TraverseTypeLoc(TL.getOriginalLoc())); })
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseArrayTypeLocHelper(ArrayTypeLoc TL) {
// This isn't available for ArrayType, but is for the ArrayTypeLoc.
TRY_TO(TraverseStmt(TL.getSizeExpr()));
return true;
}
DEF_TRAVERSE_TYPELOC(ConstantArrayType, {
TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
return TraverseArrayTypeLocHelper(TL);
})
DEF_TRAVERSE_TYPELOC(IncompleteArrayType, {
TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
return TraverseArrayTypeLocHelper(TL);
})
DEF_TRAVERSE_TYPELOC(VariableArrayType, {
TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
return TraverseArrayTypeLocHelper(TL);
})
DEF_TRAVERSE_TYPELOC(DependentSizedArrayType, {
TRY_TO(TraverseTypeLoc(TL.getElementLoc()));
return TraverseArrayTypeLocHelper(TL);
})
// FIXME: order? why not size expr first?
// FIXME: base VectorTypeLoc is unfinished
DEF_TRAVERSE_TYPELOC(DependentSizedExtVectorType, {
if (TL.getTypePtr()->getSizeExpr())
TRY_TO(TraverseStmt(TL.getTypePtr()->getSizeExpr()));
TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
})
// FIXME: VectorTypeLoc is unfinished
DEF_TRAVERSE_TYPELOC(VectorType, {
TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
})
// FIXME: size and attributes
// FIXME: base VectorTypeLoc is unfinished
DEF_TRAVERSE_TYPELOC(ExtVectorType, {
TRY_TO(TraverseType(TL.getTypePtr()->getElementType()));
})
DEF_TRAVERSE_TYPELOC(FunctionNoProtoType,
{ TRY_TO(TraverseTypeLoc(TL.getReturnLoc())); })
// FIXME: location of exception specifications (attributes?)
DEF_TRAVERSE_TYPELOC(FunctionProtoType, {
TRY_TO(TraverseTypeLoc(TL.getReturnLoc()));
const FunctionProtoType *T = TL.getTypePtr();
for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
if (TL.getParam(I)) {
TRY_TO(TraverseDecl(TL.getParam(I)));
} else if (I < T->getNumParams()) {
TRY_TO(TraverseType(T->getParamType(I)));
}
}
for (const auto &E : T->exceptions()) {
TRY_TO(TraverseType(E));
}
if (Expr *NE = T->getNoexceptExpr())
TRY_TO(TraverseStmt(NE));
})
DEF_TRAVERSE_TYPELOC(UnresolvedUsingType, {})
DEF_TRAVERSE_TYPELOC(TypedefType, {})
DEF_TRAVERSE_TYPELOC(TypeOfExprType,
{ TRY_TO(TraverseStmt(TL.getUnderlyingExpr())); })
DEF_TRAVERSE_TYPELOC(TypeOfType, {
TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
})
// FIXME: location of underlying expr
DEF_TRAVERSE_TYPELOC(DecltypeType, {
TRY_TO(TraverseStmt(TL.getTypePtr()->getUnderlyingExpr()));
})
DEF_TRAVERSE_TYPELOC(UnaryTransformType, {
TRY_TO(TraverseTypeLoc(TL.getUnderlyingTInfo()->getTypeLoc()));
})
DEF_TRAVERSE_TYPELOC(AutoType, {
TRY_TO(TraverseType(TL.getTypePtr()->getDeducedType()));
})
DEF_TRAVERSE_TYPELOC(RecordType, {})
DEF_TRAVERSE_TYPELOC(EnumType, {})
DEF_TRAVERSE_TYPELOC(TemplateTypeParmType, {})
DEF_TRAVERSE_TYPELOC(SubstTemplateTypeParmType, {})
DEF_TRAVERSE_TYPELOC(SubstTemplateTypeParmPackType, {})
// FIXME: use the loc for the template name?
DEF_TRAVERSE_TYPELOC(TemplateSpecializationType, {
TRY_TO(TraverseTemplateName(TL.getTypePtr()->getTemplateName()));
for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
}
})
DEF_TRAVERSE_TYPELOC(InjectedClassNameType, {})
DEF_TRAVERSE_TYPELOC(ParenType, { TRY_TO(TraverseTypeLoc(TL.getInnerLoc())); })
DEF_TRAVERSE_TYPELOC(AttributedType,
{ TRY_TO(TraverseTypeLoc(TL.getModifiedLoc())); })
DEF_TRAVERSE_TYPELOC(ElaboratedType, {
if (TL.getQualifierLoc()) {
TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
}
TRY_TO(TraverseTypeLoc(TL.getNamedTypeLoc()));
})
DEF_TRAVERSE_TYPELOC(DependentNameType, {
TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
})
DEF_TRAVERSE_TYPELOC(DependentTemplateSpecializationType, {
if (TL.getQualifierLoc()) {
TRY_TO(TraverseNestedNameSpecifierLoc(TL.getQualifierLoc()));
}
for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
TRY_TO(TraverseTemplateArgumentLoc(TL.getArgLoc(I)));
}
})
DEF_TRAVERSE_TYPELOC(PackExpansionType,
{ TRY_TO(TraverseTypeLoc(TL.getPatternLoc())); })
DEF_TRAVERSE_TYPELOC(ObjCInterfaceType, {})
DEF_TRAVERSE_TYPELOC(ObjCObjectType, {
// We have to watch out here because an ObjCInterfaceType's base
// type is itself.
if (TL.getTypePtr()->getBaseType().getTypePtr() != TL.getTypePtr())
TRY_TO(TraverseTypeLoc(TL.getBaseLoc()));
for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
TRY_TO(TraverseTypeLoc(TL.getTypeArgTInfo(i)->getTypeLoc()));
})
DEF_TRAVERSE_TYPELOC(ObjCObjectPointerType,
{ TRY_TO(TraverseTypeLoc(TL.getPointeeLoc())); })
DEF_TRAVERSE_TYPELOC(AtomicType, { TRY_TO(TraverseTypeLoc(TL.getValueLoc())); })
#undef DEF_TRAVERSE_TYPELOC
// ----------------- Decl traversal -----------------
//
// For a Decl, we automate (in the DEF_TRAVERSE_DECL macro) traversing
// the children that come from the DeclContext associated with it.
// Therefore each Traverse* only needs to worry about children other
// than those.
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseDeclContextHelper(DeclContext *DC) {
if (!DC)
return true;
for (auto *Child : DC->decls()) {
// BlockDecls and CapturedDecls are traversed through BlockExprs and
// CapturedStmts respectively.
if (!isa<BlockDecl>(Child) && !isa<CapturedDecl>(Child))
TRY_TO(TraverseDecl(Child));
}
return true;
}
// This macro makes available a variable D, the passed-in decl.
#define DEF_TRAVERSE_DECL(DECL, CODE) \
template <typename Derived> \
bool RecursiveASTVisitor<Derived>::Traverse##DECL(DECL *D) { \
TRY_TO(WalkUpFrom##DECL(D)); \
{ CODE; } \
TRY_TO(TraverseDeclContextHelper(dyn_cast<DeclContext>(D))); \
return true; \
}
DEF_TRAVERSE_DECL(AccessSpecDecl, {})
DEF_TRAVERSE_DECL(BlockDecl, {
if (TypeSourceInfo *TInfo = D->getSignatureAsWritten())
TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
TRY_TO(TraverseStmt(D->getBody()));
for (const auto &I : D->captures()) {
if (I.hasCopyExpr()) {
TRY_TO(TraverseStmt(I.getCopyExpr()));
}
}
// This return statement makes sure the traversal of nodes in
// decls_begin()/decls_end() (done in the DEF_TRAVERSE_DECL macro)
// is skipped - don't remove it.
return true;
})
DEF_TRAVERSE_DECL(CapturedDecl, {
TRY_TO(TraverseStmt(D->getBody()));
// This return statement makes sure the traversal of nodes in
// decls_begin()/decls_end() (done in the DEF_TRAVERSE_DECL macro)
// is skipped - don't remove it.
return true;
})
DEF_TRAVERSE_DECL(EmptyDecl, {})
DEF_TRAVERSE_DECL(HLSLBufferDecl, {}) // HLSL Change
DEF_TRAVERSE_DECL(FileScopeAsmDecl,
{ TRY_TO(TraverseStmt(D->getAsmString())); })
DEF_TRAVERSE_DECL(ImportDecl, {})
DEF_TRAVERSE_DECL(FriendDecl, {
// Friend is either decl or a type.
if (D->getFriendType())
TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
else
TRY_TO(TraverseDecl(D->getFriendDecl()));
})
DEF_TRAVERSE_DECL(FriendTemplateDecl, {
if (D->getFriendType())
TRY_TO(TraverseTypeLoc(D->getFriendType()->getTypeLoc()));
else
TRY_TO(TraverseDecl(D->getFriendDecl()));
for (unsigned I = 0, E = D->getNumTemplateParameters(); I < E; ++I) {
TemplateParameterList *TPL = D->getTemplateParameterList(I);
for (TemplateParameterList::iterator ITPL = TPL->begin(), ETPL = TPL->end();
ITPL != ETPL; ++ITPL) {
TRY_TO(TraverseDecl(*ITPL));
}
}
})
DEF_TRAVERSE_DECL(ClassScopeFunctionSpecializationDecl, {
TRY_TO(TraverseDecl(D->getSpecialization()));
if (D->hasExplicitTemplateArgs()) {
const TemplateArgumentListInfo &args = D->templateArgs();
TRY_TO(TraverseTemplateArgumentLocsHelper(args.getArgumentArray(),
args.size()));
}
})
DEF_TRAVERSE_DECL(LinkageSpecDecl, {})
DEF_TRAVERSE_DECL(ObjCPropertyImplDecl, {// FIXME: implement this
})
DEF_TRAVERSE_DECL(StaticAssertDecl, {
TRY_TO(TraverseStmt(D->getAssertExpr()));
TRY_TO(TraverseStmt(D->getMessage()));
})
DEF_TRAVERSE_DECL(
TranslationUnitDecl,
{// Code in an unnamed namespace shows up automatically in
// decls_begin()/decls_end(). Thus we don't need to recurse on
// D->getAnonymousNamespace().
})
DEF_TRAVERSE_DECL(ExternCContextDecl, {})
DEF_TRAVERSE_DECL(NamespaceAliasDecl, {
// We shouldn't traverse an aliased namespace, since it will be
// defined (and, therefore, traversed) somewhere else.
//
// This return statement makes sure the traversal of nodes in
// decls_begin()/decls_end() (done in the DEF_TRAVERSE_DECL macro)
// is skipped - don't remove it.
return true;
})
DEF_TRAVERSE_DECL(LabelDecl, {// There is no code in a LabelDecl.
})
DEF_TRAVERSE_DECL(
NamespaceDecl,
{// Code in an unnamed namespace shows up automatically in
// decls_begin()/decls_end(). Thus we don't need to recurse on
// D->getAnonymousNamespace().
})
DEF_TRAVERSE_DECL(ObjCCompatibleAliasDecl, {// FIXME: implement
})
DEF_TRAVERSE_DECL(ObjCCategoryDecl, {// FIXME: implement
if (ObjCTypeParamList *typeParamList = D->getTypeParamList()) {
for (auto typeParam : *typeParamList) {
TRY_TO(TraverseObjCTypeParamDecl(typeParam));
}
}
})
DEF_TRAVERSE_DECL(ObjCCategoryImplDecl, {// FIXME: implement
})
DEF_TRAVERSE_DECL(ObjCImplementationDecl, {// FIXME: implement
})
DEF_TRAVERSE_DECL(ObjCInterfaceDecl, {// FIXME: implement
if (ObjCTypeParamList *typeParamList = D->getTypeParamListAsWritten()) {
for (auto typeParam : *typeParamList) {
TRY_TO(TraverseObjCTypeParamDecl(typeParam));
}
}
if (TypeSourceInfo *superTInfo = D->getSuperClassTInfo()) {
TRY_TO(TraverseTypeLoc(superTInfo->getTypeLoc()));
}
})
DEF_TRAVERSE_DECL(ObjCProtocolDecl, {// FIXME: implement
})
DEF_TRAVERSE_DECL(ObjCMethodDecl, {
if (D->getReturnTypeSourceInfo()) {
TRY_TO(TraverseTypeLoc(D->getReturnTypeSourceInfo()->getTypeLoc()));
}
for (ObjCMethodDecl::param_iterator I = D->param_begin(), E = D->param_end();
I != E; ++I) {
TRY_TO(TraverseDecl(*I));
}
if (D->isThisDeclarationADefinition()) {
TRY_TO(TraverseStmt(D->getBody()));
}
return true;
})
DEF_TRAVERSE_DECL(ObjCTypeParamDecl, {
if (D->hasExplicitBound()) {
TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
// We shouldn't traverse D->getTypeForDecl(); it's a result of
// declaring the type alias, not something that was written in the
// source.
}
})
DEF_TRAVERSE_DECL(ObjCPropertyDecl, {
if (D->getTypeSourceInfo())
TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
else
TRY_TO(TraverseType(D->getType()));
return true;
})
DEF_TRAVERSE_DECL(UsingDecl, {
TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
})
DEF_TRAVERSE_DECL(UsingDirectiveDecl, {
TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
})
DEF_TRAVERSE_DECL(UsingShadowDecl, {})
DEF_TRAVERSE_DECL(OMPThreadPrivateDecl, {
for (auto *I : D->varlists()) {
TRY_TO(TraverseStmt(I));
}
})
// A helper method for TemplateDecl's children.
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTemplateParameterListHelper(
TemplateParameterList *TPL) {
if (TPL) {
for (TemplateParameterList::iterator I = TPL->begin(), E = TPL->end();
I != E; ++I) {
TRY_TO(TraverseDecl(*I));
}
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
ClassTemplateDecl *D) {
for (auto *SD : D->specializations()) {
for (auto *RD : SD->redecls()) {
// We don't want to visit injected-class-names in this traversal.
if (cast<CXXRecordDecl>(RD)->isInjectedClassName())
continue;
switch (
cast<ClassTemplateSpecializationDecl>(RD)->getSpecializationKind()) {
// Visit the implicit instantiations with the requested pattern.
case TSK_Undeclared:
case TSK_ImplicitInstantiation:
TRY_TO(TraverseDecl(RD));
break;
// We don't need to do anything on an explicit instantiation
// or explicit specialization because there will be an explicit
// node for it elsewhere.
case TSK_ExplicitInstantiationDeclaration:
case TSK_ExplicitInstantiationDefinition:
case TSK_ExplicitSpecialization:
break;
}
}
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
VarTemplateDecl *D) {
for (auto *SD : D->specializations()) {
for (auto *RD : SD->redecls()) {
switch (
cast<VarTemplateSpecializationDecl>(RD)->getSpecializationKind()) {
case TSK_Undeclared:
case TSK_ImplicitInstantiation:
TRY_TO(TraverseDecl(RD));
break;
case TSK_ExplicitInstantiationDeclaration:
case TSK_ExplicitInstantiationDefinition:
case TSK_ExplicitSpecialization:
break;
}
}
}
return true;
}
// A helper method for traversing the instantiations of a
// function while skipping its specializations.
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTemplateInstantiations(
FunctionTemplateDecl *D) {
for (auto *FD : D->specializations()) {
for (auto *RD : FD->redecls()) {
switch (RD->getTemplateSpecializationKind()) {
case TSK_Undeclared:
case TSK_ImplicitInstantiation:
// We don't know what kind of FunctionDecl this is.
TRY_TO(TraverseDecl(RD));
break;
// FIXME: For now traverse explicit instantiations here. Change that
// once they are represented as dedicated nodes in the AST.
case TSK_ExplicitInstantiationDeclaration:
case TSK_ExplicitInstantiationDefinition:
TRY_TO(TraverseDecl(RD));
break;
case TSK_ExplicitSpecialization:
break;
}
}
}
return true;
}
// This macro unifies the traversal of class, variable and function
// template declarations.
#define DEF_TRAVERSE_TMPL_DECL(TMPLDECLKIND) \
DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateDecl, { \
TRY_TO(TraverseDecl(D->getTemplatedDecl())); \
TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters())); \
\
/* By default, we do not traverse the instantiations of \
class templates since they do not appear in the user code. The \
following code optionally traverses them. \
\
We only traverse the class instantiations when we see the canonical \
declaration of the template, to ensure we only visit them once. */ \
if (getDerived().shouldVisitTemplateInstantiations() && \
D == D->getCanonicalDecl()) \
TRY_TO(TraverseTemplateInstantiations(D)); \
\
/* Note that getInstantiatedFromMemberTemplate() is just a link \
from a template instantiation back to the template from which \
it was instantiated, and thus should not be traversed. */ \
})
DEF_TRAVERSE_TMPL_DECL(Class)
DEF_TRAVERSE_TMPL_DECL(Var)
DEF_TRAVERSE_TMPL_DECL(Function)
DEF_TRAVERSE_DECL(TemplateTemplateParmDecl, {
// D is the "T" in something like
// template <template <typename> class T> class container { };
TRY_TO(TraverseDecl(D->getTemplatedDecl()));
if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
TRY_TO(TraverseTemplateArgumentLoc(D->getDefaultArgument()));
}
TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
})
DEF_TRAVERSE_DECL(TemplateTypeParmDecl, {
// D is the "T" in something like "template<typename T> class vector;"
if (D->getTypeForDecl())
TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
TRY_TO(TraverseTypeLoc(D->getDefaultArgumentInfo()->getTypeLoc()));
})
DEF_TRAVERSE_DECL(TypedefDecl, {
TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
// We shouldn't traverse D->getTypeForDecl(); it's a result of
// declaring the typedef, not something that was written in the
// source.
})
DEF_TRAVERSE_DECL(TypeAliasDecl, {
TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
// We shouldn't traverse D->getTypeForDecl(); it's a result of
// declaring the type alias, not something that was written in the
// source.
})
DEF_TRAVERSE_DECL(TypeAliasTemplateDecl, {
TRY_TO(TraverseDecl(D->getTemplatedDecl()));
TRY_TO(TraverseTemplateParameterListHelper(D->getTemplateParameters()));
})
DEF_TRAVERSE_DECL(UnresolvedUsingTypenameDecl, {
// A dependent using declaration which was marked with 'typename'.
// template<class T> class A : public B<T> { using typename B<T>::foo; };
TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
// We shouldn't traverse D->getTypeForDecl(); it's a result of
// declaring the type, not something that was written in the
// source.
})
DEF_TRAVERSE_DECL(EnumDecl, {
if (D->getTypeForDecl())
TRY_TO(TraverseType(QualType(D->getTypeForDecl(), 0)));
TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
// The enumerators are already traversed by
// decls_begin()/decls_end().
})
// Helper methods for RecordDecl and its children.
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseRecordHelper(RecordDecl *D) {
// We shouldn't traverse D->getTypeForDecl(); it's a result of
// declaring the type, not something that was written in the source.
TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseCXXRecordHelper(CXXRecordDecl *D) {
if (!TraverseRecordHelper(D))
return false;
if (D->isCompleteDefinition()) {
for (const auto &I : D->bases()) {
TRY_TO(TraverseTypeLoc(I.getTypeSourceInfo()->getTypeLoc()));
}
// We don't traverse the friends or the conversions, as they are
// already in decls_begin()/decls_end().
}
return true;
}
DEF_TRAVERSE_DECL(RecordDecl, { TRY_TO(TraverseRecordHelper(D)); })
DEF_TRAVERSE_DECL(CXXRecordDecl, { TRY_TO(TraverseCXXRecordHelper(D)); })
#define DEF_TRAVERSE_TMPL_SPEC_DECL(TMPLDECLKIND) \
DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplateSpecializationDecl, { \
/* For implicit instantiations ("set<int> x;"), we don't want to \
recurse at all, since the instatiated template isn't written in \
the source code anywhere. (Note the instatiated *type* -- \
set<int> -- is written, and will still get a callback of \
TemplateSpecializationType). For explicit instantiations \
("template set<int>;"), we do need a callback, since this \
is the only callback that's made for this instantiation. \
We use getTypeAsWritten() to distinguish. */ \
if (TypeSourceInfo *TSI = D->getTypeAsWritten()) \
TRY_TO(TraverseTypeLoc(TSI->getTypeLoc())); \
\
if (!getDerived().shouldVisitTemplateInstantiations() && \
D->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) \
/* Returning from here skips traversing the \
declaration context of the *TemplateSpecializationDecl \
(embedded in the DEF_TRAVERSE_DECL() macro) \
which contains the instantiated members of the template. */ \
return true; \
})
DEF_TRAVERSE_TMPL_SPEC_DECL(Class)
DEF_TRAVERSE_TMPL_SPEC_DECL(Var)
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseTemplateArgumentLocsHelper(
const TemplateArgumentLoc *TAL, unsigned Count) {
for (unsigned I = 0; I < Count; ++I) {
TRY_TO(TraverseTemplateArgumentLoc(TAL[I]));
}
return true;
}
#define DEF_TRAVERSE_TMPL_PART_SPEC_DECL(TMPLDECLKIND, DECLKIND) \
DEF_TRAVERSE_DECL(TMPLDECLKIND##TemplatePartialSpecializationDecl, { \
/* The partial specialization. */ \
if (TemplateParameterList *TPL = D->getTemplateParameters()) { \
for (TemplateParameterList::iterator I = TPL->begin(), E = TPL->end(); \
I != E; ++I) { \
TRY_TO(TraverseDecl(*I)); \
} \
} \
/* The args that remains unspecialized. */ \
TRY_TO(TraverseTemplateArgumentLocsHelper( \
D->getTemplateArgsAsWritten()->getTemplateArgs(), \
D->getTemplateArgsAsWritten()->NumTemplateArgs)); \
\
/* Don't need the *TemplatePartialSpecializationHelper, even \
though that's our parent class -- we already visit all the \
template args here. */ \
TRY_TO(Traverse##DECLKIND##Helper(D)); \
\
/* Instantiations will have been visited with the primary template. */ \
})
DEF_TRAVERSE_TMPL_PART_SPEC_DECL(Class, CXXRecord)
DEF_TRAVERSE_TMPL_PART_SPEC_DECL(Var, Var)
DEF_TRAVERSE_DECL(EnumConstantDecl, { TRY_TO(TraverseStmt(D->getInitExpr())); })
DEF_TRAVERSE_DECL(UnresolvedUsingValueDecl, {
// Like UnresolvedUsingTypenameDecl, but without the 'typename':
// template <class T> Class A : public Base<T> { using Base<T>::foo; };
TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
})
DEF_TRAVERSE_DECL(IndirectFieldDecl, {})
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseDeclaratorHelper(DeclaratorDecl *D) {
TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
if (D->getTypeSourceInfo())
TRY_TO(TraverseTypeLoc(D->getTypeSourceInfo()->getTypeLoc()));
else
TRY_TO(TraverseType(D->getType()));
return true;
}
DEF_TRAVERSE_DECL(MSPropertyDecl, { TRY_TO(TraverseDeclaratorHelper(D)); })
DEF_TRAVERSE_DECL(FieldDecl, {
TRY_TO(TraverseDeclaratorHelper(D));
if (D->isBitField())
TRY_TO(TraverseStmt(D->getBitWidth()));
else if (D->hasInClassInitializer())
TRY_TO(TraverseStmt(D->getInClassInitializer()));
})
DEF_TRAVERSE_DECL(ObjCAtDefsFieldDecl, {
TRY_TO(TraverseDeclaratorHelper(D));
if (D->isBitField())
TRY_TO(TraverseStmt(D->getBitWidth()));
// FIXME: implement the rest.
})
DEF_TRAVERSE_DECL(ObjCIvarDecl, {
TRY_TO(TraverseDeclaratorHelper(D));
if (D->isBitField())
TRY_TO(TraverseStmt(D->getBitWidth()));
// FIXME: implement the rest.
})
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseFunctionHelper(FunctionDecl *D) {
TRY_TO(TraverseNestedNameSpecifierLoc(D->getQualifierLoc()));
TRY_TO(TraverseDeclarationNameInfo(D->getNameInfo()));
// If we're an explicit template specialization, iterate over the
// template args that were explicitly specified. If we were doing
// this in typing order, we'd do it between the return type and
// the function args, but both are handled by the FunctionTypeLoc
// above, so we have to choose one side. I've decided to do before.
if (const FunctionTemplateSpecializationInfo *FTSI =
D->getTemplateSpecializationInfo()) {
if (FTSI->getTemplateSpecializationKind() != TSK_Undeclared &&
FTSI->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) {
// A specialization might not have explicit template arguments if it has
// a templated return type and concrete arguments.
if (const ASTTemplateArgumentListInfo *TALI =
FTSI->TemplateArgumentsAsWritten) {
TRY_TO(TraverseTemplateArgumentLocsHelper(TALI->getTemplateArgs(),
TALI->NumTemplateArgs));
}
}
}
// Visit the function type itself, which can be either
// FunctionNoProtoType or FunctionProtoType, or a typedef. This
// also covers the return type and the function parameters,
// including exception specifications.
if (TypeSourceInfo *TSI = D->getTypeSourceInfo()) {
TRY_TO(TraverseTypeLoc(TSI->getTypeLoc()));
} else if (getDerived().shouldVisitImplicitCode()) {
// Visit parameter variable declarations of the implicit function
// if the traverser is visiting implicit code. Parameter variable
// declarations do not have valid TypeSourceInfo, so to visit them
// we need to traverse the declarations explicitly.
for (FunctionDecl::param_const_iterator I = D->param_begin(),
E = D->param_end();
I != E; ++I)
TRY_TO(TraverseDecl(*I));
}
if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
// Constructor initializers.
for (auto *I : Ctor->inits()) {
TRY_TO(TraverseConstructorInitializer(I));
}
}
if (D->isThisDeclarationADefinition()) {
TRY_TO(TraverseStmt(D->getBody())); // Function body.
}
return true;
}
DEF_TRAVERSE_DECL(FunctionDecl, {
// We skip decls_begin/decls_end, which are already covered by
// TraverseFunctionHelper().
return TraverseFunctionHelper(D);
})
DEF_TRAVERSE_DECL(CXXMethodDecl, {
// We skip decls_begin/decls_end, which are already covered by
// TraverseFunctionHelper().
return TraverseFunctionHelper(D);
})
DEF_TRAVERSE_DECL(CXXConstructorDecl, {
// We skip decls_begin/decls_end, which are already covered by
// TraverseFunctionHelper().
return TraverseFunctionHelper(D);
})
// CXXConversionDecl is the declaration of a type conversion operator.
// It's not a cast expression.
DEF_TRAVERSE_DECL(CXXConversionDecl, {
// We skip decls_begin/decls_end, which are already covered by
// TraverseFunctionHelper().
return TraverseFunctionHelper(D);
})
DEF_TRAVERSE_DECL(CXXDestructorDecl, {
// We skip decls_begin/decls_end, which are already covered by
// TraverseFunctionHelper().
return TraverseFunctionHelper(D);
})
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseVarHelper(VarDecl *D) {
TRY_TO(TraverseDeclaratorHelper(D));
// Default params are taken care of when we traverse the ParmVarDecl.
if (!isa<ParmVarDecl>(D) &&
(!D->isCXXForRangeDecl() || getDerived().shouldVisitImplicitCode()))
TRY_TO(TraverseStmt(D->getInit()));
return true;
}
DEF_TRAVERSE_DECL(VarDecl, { TRY_TO(TraverseVarHelper(D)); })
DEF_TRAVERSE_DECL(ImplicitParamDecl, { TRY_TO(TraverseVarHelper(D)); })
DEF_TRAVERSE_DECL(NonTypeTemplateParmDecl, {
// A non-type template parameter, e.g. "S" in template<int S> class Foo ...
TRY_TO(TraverseDeclaratorHelper(D));
if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
TRY_TO(TraverseStmt(D->getDefaultArgument()));
})
DEF_TRAVERSE_DECL(ParmVarDecl, {
TRY_TO(TraverseVarHelper(D));
if (D->hasDefaultArg() && D->hasUninstantiatedDefaultArg() &&
!D->hasUnparsedDefaultArg())
TRY_TO(TraverseStmt(D->getUninstantiatedDefaultArg()));
if (D->hasDefaultArg() && !D->hasUninstantiatedDefaultArg() &&
!D->hasUnparsedDefaultArg())
TRY_TO(TraverseStmt(D->getDefaultArg()));
})
#undef DEF_TRAVERSE_DECL
// ----------------- Stmt traversal -----------------
//
// For stmts, we automate (in the DEF_TRAVERSE_STMT macro) iterating
// over the children defined in children() (every stmt defines these,
// though sometimes the range is empty). Each individual Traverse*
// method only needs to worry about children other than those. To see
// what children() does for a given class, see, e.g.,
// http://clang.llvm.org/doxygen/Stmt_8cpp_source.html
// This macro makes available a variable S, the passed-in stmt.
#define DEF_TRAVERSE_STMT(STMT, CODE) \
template <typename Derived> \
bool RecursiveASTVisitor<Derived>::Traverse##STMT(STMT *S) { \
TRY_TO(WalkUpFrom##STMT(S)); \
{ CODE; } \
for (Stmt *SubStmt : S->children()) { \
TRY_TO(TraverseStmt(SubStmt)); \
} \
return true; \
}
DEF_TRAVERSE_STMT(GCCAsmStmt, {
TRY_TO(TraverseStmt(S->getAsmString()));
for (unsigned I = 0, E = S->getNumInputs(); I < E; ++I) {
TRY_TO(TraverseStmt(S->getInputConstraintLiteral(I)));
}
for (unsigned I = 0, E = S->getNumOutputs(); I < E; ++I) {
TRY_TO(TraverseStmt(S->getOutputConstraintLiteral(I)));
}
for (unsigned I = 0, E = S->getNumClobbers(); I < E; ++I) {
TRY_TO(TraverseStmt(S->getClobberStringLiteral(I)));
}
// children() iterates over inputExpr and outputExpr.
})
DEF_TRAVERSE_STMT(
MSAsmStmt,
{// FIXME: MS Asm doesn't currently parse Constraints, Clobbers, etc. Once
// added this needs to be implemented.
})
DEF_TRAVERSE_STMT(CXXCatchStmt, {
TRY_TO(TraverseDecl(S->getExceptionDecl()));
// children() iterates over the handler block.
})
DEF_TRAVERSE_STMT(DeclStmt, {
for (auto *I : S->decls()) {
TRY_TO(TraverseDecl(I));
}
// Suppress the default iteration over children() by
// returning. Here's why: A DeclStmt looks like 'type var [=
// initializer]'. The decls above already traverse over the
// initializers, so we don't have to do it again (which
// children() would do).
return true;
})
// These non-expr stmts (most of them), do not need any action except
// iterating over the children.
DEF_TRAVERSE_STMT(BreakStmt, {})
DEF_TRAVERSE_STMT(CXXTryStmt, {})
DEF_TRAVERSE_STMT(CaseStmt, {})
DEF_TRAVERSE_STMT(CompoundStmt, {})
DEF_TRAVERSE_STMT(ContinueStmt, {})
DEF_TRAVERSE_STMT(DefaultStmt, {})
DEF_TRAVERSE_STMT(DoStmt, {})
DEF_TRAVERSE_STMT(ForStmt, {})
DEF_TRAVERSE_STMT(GotoStmt, {})
DEF_TRAVERSE_STMT(IfStmt, {})
DEF_TRAVERSE_STMT(IndirectGotoStmt, {})
DEF_TRAVERSE_STMT(LabelStmt, {})
DEF_TRAVERSE_STMT(AttributedStmt, {})
DEF_TRAVERSE_STMT(NullStmt, {})
DEF_TRAVERSE_STMT(DiscardStmt, {}) // HLSL Change: add support for HLSL Discard Stmt
DEF_TRAVERSE_STMT(ObjCAtCatchStmt, {})
DEF_TRAVERSE_STMT(ObjCAtFinallyStmt, {})
DEF_TRAVERSE_STMT(ObjCAtSynchronizedStmt, {})
DEF_TRAVERSE_STMT(ObjCAtThrowStmt, {})
DEF_TRAVERSE_STMT(ObjCAtTryStmt, {})
DEF_TRAVERSE_STMT(ObjCForCollectionStmt, {})
DEF_TRAVERSE_STMT(ObjCAutoreleasePoolStmt, {})
DEF_TRAVERSE_STMT(CXXForRangeStmt, {
if (!getDerived().shouldVisitImplicitCode()) {
TRY_TO(TraverseStmt(S->getLoopVarStmt()));
TRY_TO(TraverseStmt(S->getRangeInit()));
TRY_TO(TraverseStmt(S->getBody()));
// Visit everything else only if shouldVisitImplicitCode().
return true;
}
})
DEF_TRAVERSE_STMT(MSDependentExistsStmt, {
TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
})
DEF_TRAVERSE_STMT(ReturnStmt, {})
DEF_TRAVERSE_STMT(SwitchStmt, {})
DEF_TRAVERSE_STMT(WhileStmt, {})
DEF_TRAVERSE_STMT(CXXDependentScopeMemberExpr, {
TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
TRY_TO(TraverseDeclarationNameInfo(S->getMemberNameInfo()));
if (S->hasExplicitTemplateArgs()) {
TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
S->getNumTemplateArgs()));
}
})
DEF_TRAVERSE_STMT(DeclRefExpr, {
TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
S->getNumTemplateArgs()));
})
DEF_TRAVERSE_STMT(DependentScopeDeclRefExpr, {
TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
TRY_TO(TraverseDeclarationNameInfo(S->getNameInfo()));
if (S->hasExplicitTemplateArgs()) {
TRY_TO(TraverseTemplateArgumentLocsHelper(
S->getExplicitTemplateArgs().getTemplateArgs(),
S->getNumTemplateArgs()));
}
})
DEF_TRAVERSE_STMT(MemberExpr, {
TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
TRY_TO(TraverseDeclarationNameInfo(S->getMemberNameInfo()));
TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
S->getNumTemplateArgs()));
})
DEF_TRAVERSE_STMT(
ImplicitCastExpr,
{// We don't traverse the cast type, as it's not written in the
// source code.
})
DEF_TRAVERSE_STMT(CStyleCastExpr, {
TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXFunctionalCastExpr, {
TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXConstCastExpr, {
TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXDynamicCastExpr, {
TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXReinterpretCastExpr, {
TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXStaticCastExpr, {
TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
})
// InitListExpr is a tricky one, because we want to do all our work on
// the syntactic form of the listexpr, but this method takes the
// semantic form by default. We can't use the macro helper because it
// calls WalkUp*() on the semantic form, before our code can convert
// to the syntactic form.
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseInitListExpr(InitListExpr *S) {
InitListExpr *Syn = S->isSemanticForm() ? S->getSyntacticForm() : S;
if (Syn) {
TRY_TO(WalkUpFromInitListExpr(Syn));
// All we need are the default actions. FIXME: use a helper function.
for (Stmt *SubStmt : Syn->children()) {
TRY_TO(TraverseStmt(SubStmt));
}
}
InitListExpr *Sem = S->isSemanticForm() ? S : S->getSemanticForm();
if (Sem) {
TRY_TO(WalkUpFromInitListExpr(Sem));
for (Stmt *SubStmt : Sem->children()) {
TRY_TO(TraverseStmt(SubStmt));
}
}
return true;
}
// GenericSelectionExpr is a special case because the types and expressions
// are interleaved. We also need to watch out for null types (default
// generic associations).
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseGenericSelectionExpr(
GenericSelectionExpr *S) {
TRY_TO(WalkUpFromGenericSelectionExpr(S));
TRY_TO(TraverseStmt(S->getControllingExpr()));
for (unsigned i = 0; i != S->getNumAssocs(); ++i) {
if (TypeSourceInfo *TS = S->getAssocTypeSourceInfo(i))
TRY_TO(TraverseTypeLoc(TS->getTypeLoc()));
TRY_TO(TraverseStmt(S->getAssocExpr(i)));
}
return true;
}
// PseudoObjectExpr is a special case because of the wierdness with
// syntactic expressions and opaque values.
template <typename Derived>
bool
RecursiveASTVisitor<Derived>::TraversePseudoObjectExpr(PseudoObjectExpr *S) {
TRY_TO(WalkUpFromPseudoObjectExpr(S));
TRY_TO(TraverseStmt(S->getSyntacticForm()));
for (PseudoObjectExpr::semantics_iterator i = S->semantics_begin(),
e = S->semantics_end();
i != e; ++i) {
Expr *sub = *i;
if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(sub))
sub = OVE->getSourceExpr();
TRY_TO(TraverseStmt(sub));
}
return true;
}
DEF_TRAVERSE_STMT(CXXScalarValueInitExpr, {
// This is called for code like 'return T()' where T is a built-in
// (i.e. non-class) type.
TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXNewExpr, {
// The child-iterator will pick up the other arguments.
TRY_TO(TraverseTypeLoc(S->getAllocatedTypeSourceInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(OffsetOfExpr, {
// The child-iterator will pick up the expression representing
// the field.
// FIMXE: for code like offsetof(Foo, a.b.c), should we get
// making a MemberExpr callbacks for Foo.a, Foo.a.b, and Foo.a.b.c?
TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(UnaryExprOrTypeTraitExpr, {
// The child-iterator will pick up the arg if it's an expression,
// but not if it's a type.
if (S->isArgumentType())
TRY_TO(TraverseTypeLoc(S->getArgumentTypeInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXTypeidExpr, {
// The child-iterator will pick up the arg if it's an expression,
// but not if it's a type.
if (S->isTypeOperand())
TRY_TO(TraverseTypeLoc(S->getTypeOperandSourceInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(MSPropertyRefExpr, {
TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
})
DEF_TRAVERSE_STMT(CXXUuidofExpr, {
// The child-iterator will pick up the arg if it's an expression,
// but not if it's a type.
if (S->isTypeOperand())
TRY_TO(TraverseTypeLoc(S->getTypeOperandSourceInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(TypeTraitExpr, {
for (unsigned I = 0, N = S->getNumArgs(); I != N; ++I)
TRY_TO(TraverseTypeLoc(S->getArg(I)->getTypeLoc()));
})
DEF_TRAVERSE_STMT(ArrayTypeTraitExpr, {
TRY_TO(TraverseTypeLoc(S->getQueriedTypeSourceInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(ExpressionTraitExpr,
{ TRY_TO(TraverseStmt(S->getQueriedExpression())); })
DEF_TRAVERSE_STMT(VAArgExpr, {
// The child-iterator will pick up the expression argument.
TRY_TO(TraverseTypeLoc(S->getWrittenTypeInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXTemporaryObjectExpr, {
// This is called for code like 'return T()' where T is a class type.
TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
})
// Walk only the visible parts of lambda expressions.
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseLambdaExpr(LambdaExpr *S) {
TRY_TO(WalkUpFromLambdaExpr(S));
for (LambdaExpr::capture_iterator C = S->explicit_capture_begin(),
CEnd = S->explicit_capture_end();
C != CEnd; ++C) {
TRY_TO(TraverseLambdaCapture(S, C));
}
TypeLoc TL = S->getCallOperator()->getTypeSourceInfo()->getTypeLoc();
FunctionProtoTypeLoc Proto = TL.castAs<FunctionProtoTypeLoc>();
if (S->hasExplicitParameters() && S->hasExplicitResultType()) {
// Visit the whole type.
TRY_TO(TraverseTypeLoc(TL));
} else {
if (S->hasExplicitParameters()) {
// Visit parameters.
for (unsigned I = 0, N = Proto.getNumParams(); I != N; ++I) {
TRY_TO(TraverseDecl(Proto.getParam(I)));
}
} else if (S->hasExplicitResultType()) {
TRY_TO(TraverseTypeLoc(Proto.getReturnLoc()));
}
auto *T = Proto.getTypePtr();
for (const auto &E : T->exceptions()) {
TRY_TO(TraverseType(E));
}
if (Expr *NE = T->getNoexceptExpr())
TRY_TO(TraverseStmt(NE));
}
TRY_TO(TraverseLambdaBody(S));
return true;
}
DEF_TRAVERSE_STMT(CXXUnresolvedConstructExpr, {
// This is called for code like 'T()', where T is a template argument.
TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
})
// These expressions all might take explicit template arguments.
// We traverse those if so. FIXME: implement these.
DEF_TRAVERSE_STMT(CXXConstructExpr, {})
DEF_TRAVERSE_STMT(CallExpr, {})
DEF_TRAVERSE_STMT(CXXMemberCallExpr, {})
// These exprs (most of them), do not need any action except iterating
// over the children.
DEF_TRAVERSE_STMT(AddrLabelExpr, {})
DEF_TRAVERSE_STMT(ArraySubscriptExpr, {})
DEF_TRAVERSE_STMT(BlockExpr, {
TRY_TO(TraverseDecl(S->getBlockDecl()));
return true; // no child statements to loop through.
})
DEF_TRAVERSE_STMT(ChooseExpr, {})
DEF_TRAVERSE_STMT(CompoundLiteralExpr, {
TRY_TO(TraverseTypeLoc(S->getTypeSourceInfo()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXBindTemporaryExpr, {})
DEF_TRAVERSE_STMT(CXXBoolLiteralExpr, {})
DEF_TRAVERSE_STMT(CXXDefaultArgExpr, {})
DEF_TRAVERSE_STMT(CXXDefaultInitExpr, {})
DEF_TRAVERSE_STMT(CXXDeleteExpr, {})
DEF_TRAVERSE_STMT(ExprWithCleanups, {})
DEF_TRAVERSE_STMT(CXXNullPtrLiteralExpr, {})
DEF_TRAVERSE_STMT(CXXStdInitializerListExpr, {})
DEF_TRAVERSE_STMT(CXXPseudoDestructorExpr, {
TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
if (TypeSourceInfo *ScopeInfo = S->getScopeTypeInfo())
TRY_TO(TraverseTypeLoc(ScopeInfo->getTypeLoc()));
if (TypeSourceInfo *DestroyedTypeInfo = S->getDestroyedTypeInfo())
TRY_TO(TraverseTypeLoc(DestroyedTypeInfo->getTypeLoc()));
})
DEF_TRAVERSE_STMT(CXXThisExpr, {})
DEF_TRAVERSE_STMT(CXXThrowExpr, {})
DEF_TRAVERSE_STMT(UserDefinedLiteral, {})
DEF_TRAVERSE_STMT(DesignatedInitExpr, {})
DEF_TRAVERSE_STMT(DesignatedInitUpdateExpr, {})
DEF_TRAVERSE_STMT(ExtVectorElementExpr, {})
DEF_TRAVERSE_STMT(ExtMatrixElementExpr, {}) // HLSL Change
DEF_TRAVERSE_STMT(HLSLVectorElementExpr, {}) // HLSL Change
DEF_TRAVERSE_STMT(GNUNullExpr, {})
DEF_TRAVERSE_STMT(ImplicitValueInitExpr, {})
DEF_TRAVERSE_STMT(NoInitExpr, {})
DEF_TRAVERSE_STMT(ObjCBoolLiteralExpr, {})
DEF_TRAVERSE_STMT(ObjCEncodeExpr, {
if (TypeSourceInfo *TInfo = S->getEncodedTypeSourceInfo())
TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
})
DEF_TRAVERSE_STMT(ObjCIsaExpr, {})
DEF_TRAVERSE_STMT(ObjCIvarRefExpr, {})
DEF_TRAVERSE_STMT(ObjCMessageExpr, {
if (TypeSourceInfo *TInfo = S->getClassReceiverTypeInfo())
TRY_TO(TraverseTypeLoc(TInfo->getTypeLoc()));
})
DEF_TRAVERSE_STMT(ObjCPropertyRefExpr, {})
DEF_TRAVERSE_STMT(ObjCSubscriptRefExpr, {})
DEF_TRAVERSE_STMT(ObjCProtocolExpr, {})
DEF_TRAVERSE_STMT(ObjCSelectorExpr, {})
DEF_TRAVERSE_STMT(ObjCIndirectCopyRestoreExpr, {})
DEF_TRAVERSE_STMT(ObjCBridgedCastExpr, {
TRY_TO(TraverseTypeLoc(S->getTypeInfoAsWritten()->getTypeLoc()));
})
DEF_TRAVERSE_STMT(ParenExpr, {})
DEF_TRAVERSE_STMT(ParenListExpr, {})
DEF_TRAVERSE_STMT(PredefinedExpr, {})
DEF_TRAVERSE_STMT(ShuffleVectorExpr, {})
DEF_TRAVERSE_STMT(ConvertVectorExpr, {})
DEF_TRAVERSE_STMT(StmtExpr, {})
DEF_TRAVERSE_STMT(UnresolvedLookupExpr, {
TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
if (S->hasExplicitTemplateArgs()) {
TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
S->getNumTemplateArgs()));
}
})
DEF_TRAVERSE_STMT(UnresolvedMemberExpr, {
TRY_TO(TraverseNestedNameSpecifierLoc(S->getQualifierLoc()));
if (S->hasExplicitTemplateArgs()) {
TRY_TO(TraverseTemplateArgumentLocsHelper(S->getTemplateArgs(),
S->getNumTemplateArgs()));
}
})
DEF_TRAVERSE_STMT(SEHTryStmt, {})
DEF_TRAVERSE_STMT(SEHExceptStmt, {})
DEF_TRAVERSE_STMT(SEHFinallyStmt, {})
DEF_TRAVERSE_STMT(SEHLeaveStmt, {})
DEF_TRAVERSE_STMT(CapturedStmt, { TRY_TO(TraverseDecl(S->getCapturedDecl())); })
DEF_TRAVERSE_STMT(CXXOperatorCallExpr, {})
DEF_TRAVERSE_STMT(OpaqueValueExpr, {})
DEF_TRAVERSE_STMT(TypoExpr, {})
DEF_TRAVERSE_STMT(CUDAKernelCallExpr, {})
// These operators (all of them) do not need any action except
// iterating over the children.
DEF_TRAVERSE_STMT(BinaryConditionalOperator, {})
DEF_TRAVERSE_STMT(ConditionalOperator, {})
DEF_TRAVERSE_STMT(UnaryOperator, {})
DEF_TRAVERSE_STMT(BinaryOperator, {})
DEF_TRAVERSE_STMT(CompoundAssignOperator, {})
DEF_TRAVERSE_STMT(CXXNoexceptExpr, {})
DEF_TRAVERSE_STMT(PackExpansionExpr, {})
DEF_TRAVERSE_STMT(SizeOfPackExpr, {})
DEF_TRAVERSE_STMT(SubstNonTypeTemplateParmPackExpr, {})
DEF_TRAVERSE_STMT(SubstNonTypeTemplateParmExpr, {})
DEF_TRAVERSE_STMT(FunctionParmPackExpr, {})
DEF_TRAVERSE_STMT(MaterializeTemporaryExpr, {})
DEF_TRAVERSE_STMT(CXXFoldExpr, {})
DEF_TRAVERSE_STMT(AtomicExpr, {})
// These literals (all of them) do not need any action.
DEF_TRAVERSE_STMT(IntegerLiteral, {})
DEF_TRAVERSE_STMT(CharacterLiteral, {})
DEF_TRAVERSE_STMT(FloatingLiteral, {})
DEF_TRAVERSE_STMT(ImaginaryLiteral, {})
DEF_TRAVERSE_STMT(StringLiteral, {})
DEF_TRAVERSE_STMT(ObjCStringLiteral, {})
DEF_TRAVERSE_STMT(ObjCBoxedExpr, {})
DEF_TRAVERSE_STMT(ObjCArrayLiteral, {})
DEF_TRAVERSE_STMT(ObjCDictionaryLiteral, {})
// Traverse OpenCL: AsType, Convert.
DEF_TRAVERSE_STMT(AsTypeExpr, {})
// OpenMP directives.
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseOMPExecutableDirective(
OMPExecutableDirective *S) {
for (auto *C : S->clauses()) {
TRY_TO(TraverseOMPClause(C));
}
return true;
}
template <typename Derived>
bool
RecursiveASTVisitor<Derived>::TraverseOMPLoopDirective(OMPLoopDirective *S) {
return TraverseOMPExecutableDirective(S);
}
DEF_TRAVERSE_STMT(OMPParallelDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPSimdDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPForDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPForSimdDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPSectionsDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPSectionDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPSingleDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPMasterDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPCriticalDirective, {
TRY_TO(TraverseDeclarationNameInfo(S->getDirectiveName()));
TRY_TO(TraverseOMPExecutableDirective(S));
})
DEF_TRAVERSE_STMT(OMPParallelForDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPParallelForSimdDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPParallelSectionsDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPTaskDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPTaskyieldDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPBarrierDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPTaskwaitDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPTaskgroupDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPCancellationPointDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPCancelDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPFlushDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPOrderedDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPAtomicDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPTargetDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
DEF_TRAVERSE_STMT(OMPTeamsDirective,
{ TRY_TO(TraverseOMPExecutableDirective(S)); })
// OpenMP clauses.
template <typename Derived>
bool RecursiveASTVisitor<Derived>::TraverseOMPClause(OMPClause *C) {
if (!C)
return true;
switch (C->getClauseKind()) {
#define OPENMP_CLAUSE(Name, Class) \
case OMPC_##Name: \
TRY_TO(Visit##Class(static_cast<Class *>(C))); \
break;
#include "clang/Basic/OpenMPKinds.def"
case OMPC_threadprivate:
case OMPC_unknown:
break;
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPIfClause(OMPIfClause *C) {
TRY_TO(TraverseStmt(C->getCondition()));
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPFinalClause(OMPFinalClause *C) {
TRY_TO(TraverseStmt(C->getCondition()));
return true;
}
template <typename Derived>
bool
RecursiveASTVisitor<Derived>::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
TRY_TO(TraverseStmt(C->getNumThreads()));
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPSafelenClause(OMPSafelenClause *C) {
TRY_TO(TraverseStmt(C->getSafelen()));
return true;
}
template <typename Derived>
bool
RecursiveASTVisitor<Derived>::VisitOMPCollapseClause(OMPCollapseClause *C) {
TRY_TO(TraverseStmt(C->getNumForLoops()));
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPDefaultClause(OMPDefaultClause *) {
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPProcBindClause(OMPProcBindClause *) {
return true;
}
template <typename Derived>
bool
RecursiveASTVisitor<Derived>::VisitOMPScheduleClause(OMPScheduleClause *C) {
TRY_TO(TraverseStmt(C->getChunkSize()));
TRY_TO(TraverseStmt(C->getHelperChunkSize()));
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPOrderedClause(OMPOrderedClause *) {
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPNowaitClause(OMPNowaitClause *) {
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPUntiedClause(OMPUntiedClause *) {
return true;
}
template <typename Derived>
bool
RecursiveASTVisitor<Derived>::VisitOMPMergeableClause(OMPMergeableClause *) {
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPReadClause(OMPReadClause *) {
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPWriteClause(OMPWriteClause *) {
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPUpdateClause(OMPUpdateClause *) {
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPCaptureClause(OMPCaptureClause *) {
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPSeqCstClause(OMPSeqCstClause *) {
return true;
}
template <typename Derived>
template <typename T>
bool RecursiveASTVisitor<Derived>::VisitOMPClauseList(T *Node) {
for (auto *E : Node->varlists()) {
TRY_TO(TraverseStmt(E));
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPPrivateClause(OMPPrivateClause *C) {
TRY_TO(VisitOMPClauseList(C));
for (auto *E : C->private_copies()) {
TRY_TO(TraverseStmt(E));
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPFirstprivateClause(
OMPFirstprivateClause *C) {
TRY_TO(VisitOMPClauseList(C));
for (auto *E : C->private_copies()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->inits()) {
TRY_TO(TraverseStmt(E));
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPLastprivateClause(
OMPLastprivateClause *C) {
TRY_TO(VisitOMPClauseList(C));
for (auto *E : C->private_copies()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->source_exprs()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->destination_exprs()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->assignment_ops()) {
TRY_TO(TraverseStmt(E));
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPSharedClause(OMPSharedClause *C) {
TRY_TO(VisitOMPClauseList(C));
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPLinearClause(OMPLinearClause *C) {
TRY_TO(TraverseStmt(C->getStep()));
TRY_TO(TraverseStmt(C->getCalcStep()));
TRY_TO(VisitOMPClauseList(C));
for (auto *E : C->inits()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->updates()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->finals()) {
TRY_TO(TraverseStmt(E));
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPAlignedClause(OMPAlignedClause *C) {
TRY_TO(TraverseStmt(C->getAlignment()));
TRY_TO(VisitOMPClauseList(C));
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPCopyinClause(OMPCopyinClause *C) {
TRY_TO(VisitOMPClauseList(C));
for (auto *E : C->source_exprs()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->destination_exprs()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->assignment_ops()) {
TRY_TO(TraverseStmt(E));
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPCopyprivateClause(
OMPCopyprivateClause *C) {
TRY_TO(VisitOMPClauseList(C));
for (auto *E : C->source_exprs()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->destination_exprs()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->assignment_ops()) {
TRY_TO(TraverseStmt(E));
}
return true;
}
template <typename Derived>
bool
RecursiveASTVisitor<Derived>::VisitOMPReductionClause(OMPReductionClause *C) {
TRY_TO(TraverseNestedNameSpecifierLoc(C->getQualifierLoc()));
TRY_TO(TraverseDeclarationNameInfo(C->getNameInfo()));
TRY_TO(VisitOMPClauseList(C));
for (auto *E : C->lhs_exprs()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->rhs_exprs()) {
TRY_TO(TraverseStmt(E));
}
for (auto *E : C->reduction_ops()) {
TRY_TO(TraverseStmt(E));
}
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPFlushClause(OMPFlushClause *C) {
TRY_TO(VisitOMPClauseList(C));
return true;
}
template <typename Derived>
bool RecursiveASTVisitor<Derived>::VisitOMPDependClause(OMPDependClause *C) {
TRY_TO(VisitOMPClauseList(C));
return true;
}
// FIXME: look at the following tricky-seeming exprs to see if we
// need to recurse on anything. These are ones that have methods
// returning decls or qualtypes or nestednamespecifier -- though I'm
// not sure if they own them -- or just seemed very complicated, or
// had lots of sub-types to explore.
//
// VisitOverloadExpr and its children: recurse on template args? etc?
// FIXME: go through all the stmts and exprs again, and see which of them
// create new types, and recurse on the types (TypeLocs?) of those.
// Candidates:
//
// http://clang.llvm.org/doxygen/classclang_1_1CXXTypeidExpr.html
// http://clang.llvm.org/doxygen/classclang_1_1UnaryExprOrTypeTraitExpr.html
// http://clang.llvm.org/doxygen/classclang_1_1TypesCompatibleExpr.html
// Every class that has getQualifier.
#undef DEF_TRAVERSE_STMT
#undef TRY_TO
} // end namespace clang
#endif // LLVM_CLANG_AST_RECURSIVEASTVISITOR_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/BuiltinTypes.def | //===-- BuiltinTypeNodes.def - Metadata about BuiltinTypes ------*- 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 database about various builtin singleton types.
//
// BuiltinType::Id is the enumerator defining the type.
//
// Context.SingletonId is the global singleton of this type. Some global
// singletons are shared by multiple types.
//
// BUILTIN_TYPE(Id, SingletonId) - A builtin type that has not been
// covered by any other #define. Defining this macro covers all
// the builtins.
//
// SIGNED_TYPE(Id, SingletonId) - A signed integral type.
//
// UNSIGNED_TYPE(Id, SingletonId) - An unsigned integral type.
//
// FLOATING_TYPE(Id, SingletonId) - A floating-point type.
//
// PLACEHOLDER_TYPE(Id, SingletonId) - A placeholder type. Placeholder
// types are used to perform context-sensitive checking of specific
// forms of expression.
//
// SHARED_SINGLETON_TYPE(Expansion) - The given expansion corresponds
// to a builtin which uses a shared singleton type.
//
//===----------------------------------------------------------------------===//
#ifndef SIGNED_TYPE
#define SIGNED_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId)
#endif
#ifndef UNSIGNED_TYPE
#define UNSIGNED_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId)
#endif
#ifndef FLOATING_TYPE
#define FLOATING_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId)
#endif
#ifndef PLACEHOLDER_TYPE
#define PLACEHOLDER_TYPE(Id, SingletonId) BUILTIN_TYPE(Id, SingletonId)
#endif
#ifndef SHARED_SINGLETON_TYPE
#define SHARED_SINGLETON_TYPE(Expansion) Expansion
#endif
//===- Builtin Types ------------------------------------------------------===//
// void
BUILTIN_TYPE(Void, VoidTy)
//===- Unsigned Types -----------------------------------------------------===//
// 'bool' in C++, '_Bool' in C99
UNSIGNED_TYPE(Bool, BoolTy)
// 'char' for targets where it's unsigned
SHARED_SINGLETON_TYPE(UNSIGNED_TYPE(Char_U, CharTy))
// 'unsigned char', explicitly qualified
UNSIGNED_TYPE(UChar, UnsignedCharTy)
// 'wchar_t' for targets where it's unsigned
SHARED_SINGLETON_TYPE(UNSIGNED_TYPE(WChar_U, WCharTy))
// 'char16_t' in C++
UNSIGNED_TYPE(Char16, Char16Ty)
// 'char32_t' in C++
UNSIGNED_TYPE(Char32, Char32Ty)
// 'unsigned short'
UNSIGNED_TYPE(UShort, UnsignedShortTy)
// HLSL Change - 'min16uint' in HLSL
UNSIGNED_TYPE(Min16UInt, Min16UIntTy)
// 'unsigned int'
UNSIGNED_TYPE(UInt, UnsignedIntTy)
// 'unsigned long'
UNSIGNED_TYPE(ULong, UnsignedLongTy)
// HLSL Change - 'int8_t4_packed'
UNSIGNED_TYPE(Int8_4Packed, Int8_4PackedTy)
// HLSL Change - 'uint8_t4_packed'
UNSIGNED_TYPE(UInt8_4Packed, UInt8_4PackedTy)
// 'unsigned long long'
UNSIGNED_TYPE(ULongLong, UnsignedLongLongTy)
// '__uint128_t'
UNSIGNED_TYPE(UInt128, UnsignedInt128Ty)
//===- Signed Types -------------------------------------------------------===//
// 'char' for targets where it's signed
SHARED_SINGLETON_TYPE(SIGNED_TYPE(Char_S, CharTy))
// 'signed char', explicitly qualified
SIGNED_TYPE(SChar, SignedCharTy)
// 'wchar_t' for targets where it's signed
SHARED_SINGLETON_TYPE(SIGNED_TYPE(WChar_S, WCharTy))
// 'short' or 'signed short'
SIGNED_TYPE(Short, ShortTy)
// 'int' or 'signed int'
SIGNED_TYPE(Int, IntTy)
// 'long' or 'signed long'
SIGNED_TYPE(Long, LongTy)
// 'long long' or 'signed long long'
SIGNED_TYPE(LongLong, LongLongTy)
// '__int128_t'
SIGNED_TYPE(Int128, Int128Ty)
// HLSL Change - 'min12int' in HLSL
SIGNED_TYPE(Min12Int, Min12IntTy)
// HLSL Change - 'min16int' in HLSL
SIGNED_TYPE(Min16Int, Min16IntTy)
// HLSL Change - literal int in HLSL
SIGNED_TYPE(LitInt, LitIntTy)
//===- Floating point types -----------------------------------------------===//
// 'half' in OpenCL, '__fp16' in ARM NEON.
FLOATING_TYPE(Half, HalfTy)
// 'float'
FLOATING_TYPE(Float, FloatTy)
// 'double'
FLOATING_TYPE(Double, DoubleTy)
// 'long double'
FLOATING_TYPE(LongDouble, LongDoubleTy)
// HLSL Change - 'min10float' in HLSL
FLOATING_TYPE(Min10Float, Min10FloatTy)
// HLSL Change - 'min16float' in HLSL
FLOATING_TYPE(Min16Float, Min16FloatTy)
// HLSL Change - 'halffloat' in HLSL
FLOATING_TYPE(HalfFloat, HalfFloatTy)
// HLSL Change - literal float in HLSL
FLOATING_TYPE(LitFloat, LitFloatTy)
//===- Language-specific types --------------------------------------------===//
// This is the type of C++0x 'nullptr'.
BUILTIN_TYPE(NullPtr, NullPtrTy)
// The primitive Objective C 'id' type. The user-visible 'id'
// type is a typedef of an ObjCObjectPointerType to an
// ObjCObjectType with this as its base. In fact, this only ever
// shows up in an AST as the base type of an ObjCObjectType.
BUILTIN_TYPE(ObjCId, ObjCBuiltinIdTy)
// The primitive Objective C 'Class' type. The user-visible
// 'Class' type is a typedef of an ObjCObjectPointerType to an
// ObjCObjectType with this as its base. In fact, this only ever
// shows up in an AST as the base type of an ObjCObjectType.
BUILTIN_TYPE(ObjCClass, ObjCBuiltinClassTy)
// The primitive Objective C 'SEL' type. The user-visible 'SEL'
// type is a typedef of a PointerType to this.
BUILTIN_TYPE(ObjCSel, ObjCBuiltinSelTy)
// OpenCL image types.
BUILTIN_TYPE(OCLImage1d, OCLImage1dTy)
BUILTIN_TYPE(OCLImage1dArray, OCLImage1dArrayTy)
BUILTIN_TYPE(OCLImage1dBuffer, OCLImage1dBufferTy)
BUILTIN_TYPE(OCLImage2d, OCLImage2dTy)
BUILTIN_TYPE(OCLImage2dArray, OCLImage2dArrayTy)
BUILTIN_TYPE(OCLImage3d, OCLImage3dTy)
// OpenCL sampler_t.
BUILTIN_TYPE(OCLSampler, OCLSamplerTy)
// OpenCL event_t.
BUILTIN_TYPE(OCLEvent, OCLEventTy)
// This represents the type of an expression whose type is
// totally unknown, e.g. 'T::foo'. It is permitted for this to
// appear in situations where the structure of the type is
// theoretically deducible.
BUILTIN_TYPE(Dependent, DependentTy)
// The type of an unresolved overload set. A placeholder type.
// Expressions with this type have one of the following basic
// forms, with parentheses generally permitted:
// foo # possibly qualified, not if an implicit access
// foo # possibly qualified, not if an implicit access
// &foo # possibly qualified, not if an implicit access
// x->foo # only if might be a static member function
// &x->foo # only if might be a static member function
// &Class::foo # when a pointer-to-member; sub-expr also has this type
// OverloadExpr::find can be used to analyze the expression.
//
// Overload should be the first placeholder type, or else change
// BuiltinType::isNonOverloadPlaceholderType()
PLACEHOLDER_TYPE(Overload, OverloadTy)
// The type of a bound C++ non-static member function.
// A placeholder type. Expressions with this type have one of the
// following basic forms:
// foo # if an implicit access
// x->foo # if only contains non-static members
PLACEHOLDER_TYPE(BoundMember, BoundMemberTy)
// The type of an expression which refers to a pseudo-object,
// such as those introduced by Objective C's @property or
// VS.NET's __property declarations. A placeholder type. The
// pseudo-object is actually accessed by emitting a call to
// some sort of function or method; typically there is a pair
// of a setter and a getter, with the setter used if the
// pseudo-object reference is used syntactically as the
// left-hand-side of an assignment operator.
//
// A pseudo-object reference naming an Objective-C @property is
// always a dot access with a base of object-pointer type,
// e.g. 'x.foo'.
//
// In VS.NET, a __property declaration creates an implicit
// member with an associated name, which can then be named
// in any of the normal ways an ordinary member could be.
PLACEHOLDER_TYPE(PseudoObject, PseudoObjectTy)
// __builtin_any_type. A placeholder type. Useful for clients
// like debuggers that don't know what type to give something.
// Only a small number of operations are valid on expressions of
// unknown type, most notably explicit casts.
PLACEHOLDER_TYPE(UnknownAny, UnknownAnyTy)
PLACEHOLDER_TYPE(BuiltinFn, BuiltinFnTy)
// The type of a cast which, in ARC, would normally require a
// __bridge, but which might be okay depending on the immediate
// context.
PLACEHOLDER_TYPE(ARCUnbridgedCast, ARCUnbridgedCastTy)
#ifdef LAST_BUILTIN_TYPE
LAST_BUILTIN_TYPE(ARCUnbridgedCast)
#undef LAST_BUILTIN_TYPE
#endif
#undef SHARED_SINGLETON_TYPE
#undef PLACEHOLDER_TYPE
#undef FLOATING_TYPE
#undef SIGNED_TYPE
#undef UNSIGNED_TYPE
#undef BUILTIN_TYPE
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/NSAPI.h | //===--- NSAPI.h - NSFoundation APIs ----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_NSAPI_H
#define LLVM_CLANG_AST_NSAPI_H
#include "clang/Basic/IdentifierTable.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
namespace clang {
class ASTContext;
class ObjCInterfaceDecl;
class QualType;
class Expr;
// \brief Provides info and caches identifiers/selectors for NSFoundation API.
class NSAPI {
public:
explicit NSAPI(ASTContext &Ctx);
ASTContext &getASTContext() const { return Ctx; }
enum NSClassIdKindKind {
ClassId_NSObject,
ClassId_NSString,
ClassId_NSArray,
ClassId_NSMutableArray,
ClassId_NSDictionary,
ClassId_NSMutableDictionary,
ClassId_NSNumber,
ClassId_NSMutableSet,
ClassId_NSMutableOrderedSet,
ClassId_NSValue
};
static const unsigned NumClassIds = 10;
enum NSStringMethodKind {
NSStr_stringWithString,
NSStr_stringWithUTF8String,
NSStr_stringWithCStringEncoding,
NSStr_stringWithCString,
NSStr_initWithString,
NSStr_initWithUTF8String
};
static const unsigned NumNSStringMethods = 5;
IdentifierInfo *getNSClassId(NSClassIdKindKind K) const;
/// \brief The Objective-C NSString selectors.
Selector getNSStringSelector(NSStringMethodKind MK) const;
/// \brief Return NSStringMethodKind if \param Sel is such a selector.
Optional<NSStringMethodKind> getNSStringMethodKind(Selector Sel) const;
/// \brief Returns true if the expression \param E is a reference of
/// "NSUTF8StringEncoding" enum constant.
bool isNSUTF8StringEncodingConstant(const Expr *E) const {
return isObjCEnumerator(E, "NSUTF8StringEncoding", NSUTF8StringEncodingId);
}
/// \brief Returns true if the expression \param E is a reference of
/// "NSASCIIStringEncoding" enum constant.
bool isNSASCIIStringEncodingConstant(const Expr *E) const {
return isObjCEnumerator(E, "NSASCIIStringEncoding",NSASCIIStringEncodingId);
}
/// \brief Enumerates the NSArray/NSMutableArray methods used to generate
/// literals and to apply some checks.
enum NSArrayMethodKind {
NSArr_array,
NSArr_arrayWithArray,
NSArr_arrayWithObject,
NSArr_arrayWithObjects,
NSArr_arrayWithObjectsCount,
NSArr_initWithArray,
NSArr_initWithObjects,
NSArr_objectAtIndex,
NSMutableArr_replaceObjectAtIndex,
NSMutableArr_addObject,
NSMutableArr_insertObjectAtIndex,
NSMutableArr_setObjectAtIndexedSubscript
};
static const unsigned NumNSArrayMethods = 12;
/// \brief The Objective-C NSArray selectors.
Selector getNSArraySelector(NSArrayMethodKind MK) const;
/// \brief Return NSArrayMethodKind if \p Sel is such a selector.
Optional<NSArrayMethodKind> getNSArrayMethodKind(Selector Sel);
/// \brief Enumerates the NSDictionary/NSMutableDictionary methods used
/// to generate literals and to apply some checks.
enum NSDictionaryMethodKind {
NSDict_dictionary,
NSDict_dictionaryWithDictionary,
NSDict_dictionaryWithObjectForKey,
NSDict_dictionaryWithObjectsForKeys,
NSDict_dictionaryWithObjectsForKeysCount,
NSDict_dictionaryWithObjectsAndKeys,
NSDict_initWithDictionary,
NSDict_initWithObjectsAndKeys,
NSDict_initWithObjectsForKeys,
NSDict_objectForKey,
NSMutableDict_setObjectForKey,
NSMutableDict_setObjectForKeyedSubscript,
NSMutableDict_setValueForKey
};
static const unsigned NumNSDictionaryMethods = 14;
/// \brief The Objective-C NSDictionary selectors.
Selector getNSDictionarySelector(NSDictionaryMethodKind MK) const;
/// \brief Return NSDictionaryMethodKind if \p Sel is such a selector.
Optional<NSDictionaryMethodKind> getNSDictionaryMethodKind(Selector Sel);
/// \brief Enumerates the NSMutableSet/NSOrderedSet methods used
/// to apply some checks.
enum NSSetMethodKind {
NSMutableSet_addObject,
NSOrderedSet_insertObjectAtIndex,
NSOrderedSet_setObjectAtIndex,
NSOrderedSet_setObjectAtIndexedSubscript,
NSOrderedSet_replaceObjectAtIndexWithObject
};
static const unsigned NumNSSetMethods = 5;
/// \brief The Objective-C NSSet selectors.
Selector getNSSetSelector(NSSetMethodKind MK) const;
/// \brief Return NSSetMethodKind if \p Sel is such a selector.
Optional<NSSetMethodKind> getNSSetMethodKind(Selector Sel);
/// \brief Returns selector for "objectForKeyedSubscript:".
Selector getObjectForKeyedSubscriptSelector() const {
return getOrInitSelector(StringRef("objectForKeyedSubscript"),
objectForKeyedSubscriptSel);
}
/// \brief Returns selector for "objectAtIndexedSubscript:".
Selector getObjectAtIndexedSubscriptSelector() const {
return getOrInitSelector(StringRef("objectAtIndexedSubscript"),
objectAtIndexedSubscriptSel);
}
/// \brief Returns selector for "setObject:forKeyedSubscript".
Selector getSetObjectForKeyedSubscriptSelector() const {
StringRef Ids[] = { "setObject", "forKeyedSubscript" };
return getOrInitSelector(Ids, setObjectForKeyedSubscriptSel);
}
/// \brief Returns selector for "setObject:atIndexedSubscript".
Selector getSetObjectAtIndexedSubscriptSelector() const {
StringRef Ids[] = { "setObject", "atIndexedSubscript" };
return getOrInitSelector(Ids, setObjectAtIndexedSubscriptSel);
}
/// \brief Returns selector for "isEqual:".
Selector getIsEqualSelector() const {
return getOrInitSelector(StringRef("isEqual"), isEqualSel);
}
/// \brief Enumerates the NSNumber methods used to generate literals.
enum NSNumberLiteralMethodKind {
NSNumberWithChar,
NSNumberWithUnsignedChar,
NSNumberWithShort,
NSNumberWithUnsignedShort,
NSNumberWithInt,
NSNumberWithUnsignedInt,
NSNumberWithLong,
NSNumberWithUnsignedLong,
NSNumberWithLongLong,
NSNumberWithUnsignedLongLong,
NSNumberWithFloat,
NSNumberWithDouble,
NSNumberWithBool,
NSNumberWithInteger,
NSNumberWithUnsignedInteger
};
static const unsigned NumNSNumberLiteralMethods = 15;
/// \brief The Objective-C NSNumber selectors used to create NSNumber literals.
/// \param Instance if true it will return the selector for the init* method
/// otherwise it will return the selector for the number* method.
Selector getNSNumberLiteralSelector(NSNumberLiteralMethodKind MK,
bool Instance) const;
bool isNSNumberLiteralSelector(NSNumberLiteralMethodKind MK,
Selector Sel) const {
return Sel == getNSNumberLiteralSelector(MK, false) ||
Sel == getNSNumberLiteralSelector(MK, true);
}
/// \brief Return NSNumberLiteralMethodKind if \p Sel is such a selector.
Optional<NSNumberLiteralMethodKind>
getNSNumberLiteralMethodKind(Selector Sel) const;
/// \brief Determine the appropriate NSNumber factory method kind for a
/// literal of the given type.
Optional<NSNumberLiteralMethodKind>
getNSNumberFactoryMethodKind(QualType T) const;
/// \brief Returns true if \param T is a typedef of "BOOL" in objective-c.
bool isObjCBOOLType(QualType T) const;
/// \brief Returns true if \param T is a typedef of "NSInteger" in objective-c.
bool isObjCNSIntegerType(QualType T) const;
/// \brief Returns true if \param T is a typedef of "NSUInteger" in objective-c.
bool isObjCNSUIntegerType(QualType T) const;
/// \brief Returns one of NSIntegral typedef names if \param T is a typedef
/// of that name in objective-c.
StringRef GetNSIntegralKind(QualType T) const;
/// \brief Returns \c true if \p Id is currently defined as a macro.
bool isMacroDefined(StringRef Id) const;
/// \brief Returns \c true if \p InterfaceDecl is subclass of \p NSClassKind
bool isSubclassOfNSClass(ObjCInterfaceDecl *InterfaceDecl,
NSClassIdKindKind NSClassKind) const;
private:
bool isObjCTypedef(QualType T, StringRef name, IdentifierInfo *&II) const;
bool isObjCEnumerator(const Expr *E,
StringRef name, IdentifierInfo *&II) const;
Selector getOrInitSelector(ArrayRef<StringRef> Ids, Selector &Sel) const;
ASTContext &Ctx;
mutable IdentifierInfo *ClassIds[NumClassIds];
mutable Selector NSStringSelectors[NumNSStringMethods];
/// \brief The selectors for Objective-C NSArray methods.
mutable Selector NSArraySelectors[NumNSArrayMethods];
/// \brief The selectors for Objective-C NSDictionary methods.
mutable Selector NSDictionarySelectors[NumNSDictionaryMethods];
/// \brief The selectors for Objective-C NSSet methods.
mutable Selector NSSetSelectors[NumNSSetMethods];
/// \brief The Objective-C NSNumber selectors used to create NSNumber literals.
mutable Selector NSNumberClassSelectors[NumNSNumberLiteralMethods];
mutable Selector NSNumberInstanceSelectors[NumNSNumberLiteralMethods];
mutable Selector objectForKeyedSubscriptSel, objectAtIndexedSubscriptSel,
setObjectForKeyedSubscriptSel,setObjectAtIndexedSubscriptSel,
isEqualSel;
mutable IdentifierInfo *BOOLId, *NSIntegerId, *NSUIntegerId;
mutable IdentifierInfo *NSASCIIStringEncodingId, *NSUTF8StringEncodingId;
};
} // end namespace clang
#endif // LLVM_CLANG_AST_NSAPI_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/DeclCXX.h | //===-- DeclCXX.h - Classes for representing C++ declarations -*- C++ -*-=====//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Defines the C++ Decl subclasses, other than those for templates
/// (found in DeclTemplate.h) and friends (in DeclFriend.h).
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_DECLCXX_H
#define LLVM_CLANG_AST_DECLCXX_H
#include "clang/AST/ASTUnresolvedSet.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/LambdaCapture.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/Support/Compiler.h"
namespace clang {
class ClassTemplateDecl;
class ClassTemplateSpecializationDecl;
class CXXBasePath;
class CXXBasePaths;
class CXXConstructorDecl;
class CXXConversionDecl;
class CXXDestructorDecl;
class CXXMethodDecl;
class CXXRecordDecl;
class CXXMemberLookupCriteria;
class CXXFinalOverriderMap;
class CXXIndirectPrimaryBaseSet;
class FriendDecl;
class LambdaExpr;
class UsingDecl;
/// \brief Represents any kind of function declaration, whether it is a
/// concrete function or a function template.
class AnyFunctionDecl {
NamedDecl *Function;
AnyFunctionDecl(NamedDecl *ND) : Function(ND) { }
public:
AnyFunctionDecl(FunctionDecl *FD) : Function(FD) { }
AnyFunctionDecl(FunctionTemplateDecl *FTD);
/// \brief Implicily converts any function or function template into a
/// named declaration.
operator NamedDecl *() const { return Function; }
/// \brief Retrieve the underlying function or function template.
NamedDecl *get() const { return Function; }
static AnyFunctionDecl getFromNamedDecl(NamedDecl *ND) {
return AnyFunctionDecl(ND);
}
};
} // end namespace clang
namespace llvm {
// Provide PointerLikeTypeTraits for non-cvr pointers.
template<>
class PointerLikeTypeTraits< ::clang::AnyFunctionDecl> {
public:
static inline void *getAsVoidPointer(::clang::AnyFunctionDecl F) {
return F.get();
}
static inline ::clang::AnyFunctionDecl getFromVoidPointer(void *P) {
return ::clang::AnyFunctionDecl::getFromNamedDecl(
static_cast< ::clang::NamedDecl*>(P));
}
enum { NumLowBitsAvailable = 2 };
};
} // end namespace llvm
namespace clang {
/// \brief Represents an access specifier followed by colon ':'.
///
/// An objects of this class represents sugar for the syntactic occurrence
/// of an access specifier followed by a colon in the list of member
/// specifiers of a C++ class definition.
///
/// Note that they do not represent other uses of access specifiers,
/// such as those occurring in a list of base specifiers.
/// Also note that this class has nothing to do with so-called
/// "access declarations" (C++98 11.3 [class.access.dcl]).
class AccessSpecDecl : public Decl {
virtual void anchor();
/// \brief The location of the ':'.
SourceLocation ColonLoc;
AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
SourceLocation ASLoc, SourceLocation ColonLoc)
: Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
setAccess(AS);
}
AccessSpecDecl(EmptyShell Empty)
: Decl(AccessSpec, Empty) { }
public:
/// \brief The location of the access specifier.
SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
/// \brief Sets the location of the access specifier.
void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
/// \brief The location of the colon following the access specifier.
SourceLocation getColonLoc() const { return ColonLoc; }
/// \brief Sets the location of the colon.
void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
SourceRange getSourceRange() const override LLVM_READONLY {
return SourceRange(getAccessSpecifierLoc(), getColonLoc());
}
static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
DeclContext *DC, SourceLocation ASLoc,
SourceLocation ColonLoc) {
return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
}
static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == AccessSpec; }
};
/// \brief Represents a base class of a C++ class.
///
/// Each CXXBaseSpecifier represents a single, direct base class (or
/// struct) of a C++ class (or struct). It specifies the type of that
/// base class, whether it is a virtual or non-virtual base, and what
/// level of access (public, protected, private) is used for the
/// derivation. For example:
///
/// \code
/// class A { };
/// class B { };
/// class C : public virtual A, protected B { };
/// \endcode
///
/// In this code, C will have two CXXBaseSpecifiers, one for "public
/// virtual A" and the other for "protected B".
class CXXBaseSpecifier {
/// \brief The source code range that covers the full base
/// specifier, including the "virtual" (if present) and access
/// specifier (if present).
SourceRange Range;
/// \brief The source location of the ellipsis, if this is a pack
/// expansion.
SourceLocation EllipsisLoc;
/// \brief Whether this is a virtual base class or not.
bool Virtual : 1;
/// \brief Whether this is the base of a class (true) or of a struct (false).
///
/// This determines the mapping from the access specifier as written in the
/// source code to the access specifier used for semantic analysis.
bool BaseOfClass : 1;
/// \brief Access specifier as written in the source code (may be AS_none).
///
/// The actual type of data stored here is an AccessSpecifier, but we use
/// "unsigned" here to work around a VC++ bug.
unsigned Access : 2;
/// \brief Whether the class contains a using declaration
/// to inherit the named class's constructors.
bool InheritConstructors : 1;
/// \brief The type of the base class.
///
/// This will be a class or struct (or a typedef of such). The source code
/// range does not include the \c virtual or the access specifier.
TypeSourceInfo *BaseTypeInfo;
public:
CXXBaseSpecifier() { }
CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
: Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) { }
/// \brief Retrieves the source range that contains the entire base specifier.
SourceRange getSourceRange() const LLVM_READONLY { return Range; }
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
/// \brief Determines whether the base class is a virtual base class (or not).
bool isVirtual() const { return Virtual; }
/// \brief Determine whether this base class is a base of a class declared
/// with the 'class' keyword (vs. one declared with the 'struct' keyword).
bool isBaseOfClass() const { return BaseOfClass; }
/// \brief Determine whether this base specifier is a pack expansion.
bool isPackExpansion() const { return EllipsisLoc.isValid(); }
/// \brief Determine whether this base class's constructors get inherited.
bool getInheritConstructors() const { return InheritConstructors; }
/// \brief Set that this base class's constructors should be inherited.
void setInheritConstructors(bool Inherit = true) {
InheritConstructors = Inherit;
}
/// \brief For a pack expansion, determine the location of the ellipsis.
SourceLocation getEllipsisLoc() const {
return EllipsisLoc;
}
/// \brief Returns the access specifier for this base specifier.
///
/// This is the actual base specifier as used for semantic analysis, so
/// the result can never be AS_none. To retrieve the access specifier as
/// written in the source code, use getAccessSpecifierAsWritten().
AccessSpecifier getAccessSpecifier() const {
if ((AccessSpecifier)Access == AS_none)
return BaseOfClass? AS_private : AS_public;
else
return (AccessSpecifier)Access;
}
/// \brief Retrieves the access specifier as written in the source code
/// (which may mean that no access specifier was explicitly written).
///
/// Use getAccessSpecifier() to retrieve the access specifier for use in
/// semantic analysis.
AccessSpecifier getAccessSpecifierAsWritten() const {
return (AccessSpecifier)Access;
}
/// \brief Retrieves the type of the base class.
///
/// This type will always be an unqualified class type.
QualType getType() const {
return BaseTypeInfo->getType().getUnqualifiedType();
}
/// \brief Retrieves the type and source location of the base class.
TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
};
/// \brief A lazy pointer to the definition data for a declaration.
/// FIXME: This is a little CXXRecordDecl-specific that the moment.
template<typename Decl, typename T> class LazyDefinitionDataPtr {
llvm::PointerUnion<T *, Decl *> DataOrCanonicalDecl;
LazyDefinitionDataPtr update() {
if (Decl *Canon = DataOrCanonicalDecl.template dyn_cast<Decl*>()) {
if (Canon->isCanonicalDecl())
Canon->getMostRecentDecl();
else
// Declaration isn't canonical any more;
// update it and perform path compression.
*this = Canon->getPreviousDecl()->DefinitionData.update();
}
return *this;
}
public:
LazyDefinitionDataPtr(Decl *Canon) : DataOrCanonicalDecl(Canon) {}
LazyDefinitionDataPtr(T *Data) : DataOrCanonicalDecl(Data) {}
T *getNotUpdated() { return DataOrCanonicalDecl.template dyn_cast<T*>(); }
T *get() { return update().getNotUpdated(); }
};
/// \brief Represents a C++ struct/union/class.
class CXXRecordDecl : public RecordDecl {
friend void TagDecl::startDefinition();
/// Values used in DefinitionData fields to represent special members.
enum SpecialMemberFlags {
SMF_DefaultConstructor = 0x1,
SMF_CopyConstructor = 0x2,
SMF_MoveConstructor = 0x4,
SMF_CopyAssignment = 0x8,
SMF_MoveAssignment = 0x10,
SMF_Destructor = 0x20,
SMF_All = 0x3f
};
struct DefinitionData {
DefinitionData(CXXRecordDecl *D);
/// \brief True if this class has any user-declared constructors.
bool UserDeclaredConstructor : 1;
/// \brief The user-declared special members which this class has.
unsigned UserDeclaredSpecialMembers : 6;
/// \brief True when this class is an aggregate.
bool Aggregate : 1;
/// \brief True when this class is a POD-type.
bool PlainOldData : 1;
/// true when this class is empty for traits purposes,
/// i.e. has no data members other than 0-width bit-fields, has no
/// virtual function/base, and doesn't inherit from a non-empty
/// class. Doesn't take union-ness into account.
bool Empty : 1;
/// \brief True when this class is polymorphic, i.e., has at
/// least one virtual member or derives from a polymorphic class.
bool Polymorphic : 1;
/// \brief True when this class is abstract, i.e., has at least
/// one pure virtual function, (that can come from a base class).
bool Abstract : 1;
/// \brief True when this class has standard layout.
///
/// C++11 [class]p7. A standard-layout class is a class that:
/// * has no non-static data members of type non-standard-layout class (or
/// array of such types) or reference,
/// * has no virtual functions (10.3) and no virtual base classes (10.1),
/// * has the same access control (Clause 11) for all non-static data
/// members
/// * has no non-standard-layout base classes,
/// * either has no non-static data members in the most derived class and at
/// most one base class with non-static data members, or has no base
/// classes with non-static data members, and
/// * has no base classes of the same type as the first non-static data
/// member.
bool IsStandardLayout : 1;
/// \brief True when there are no non-empty base classes.
///
/// This is a helper bit of state used to implement IsStandardLayout more
/// efficiently.
bool HasNoNonEmptyBases : 1;
/// \brief True when there are private non-static data members.
bool HasPrivateFields : 1;
/// \brief True when there are protected non-static data members.
bool HasProtectedFields : 1;
/// \brief True when there are private non-static data members.
bool HasPublicFields : 1;
/// \brief True if this class (or any subobject) has mutable fields.
bool HasMutableFields : 1;
/// \brief True if this class (or any nested anonymous struct or union)
/// has variant members.
bool HasVariantMembers : 1;
/// \brief True if there no non-field members declared by the user.
bool HasOnlyCMembers : 1;
/// \brief True if any field has an in-class initializer, including those
/// within anonymous unions or structs.
bool HasInClassInitializer : 1;
/// \brief True if any field is of reference type, and does not have an
/// in-class initializer.
///
/// In this case, value-initialization of this class is illegal in C++98
/// even if the class has a trivial default constructor.
bool HasUninitializedReferenceMember : 1;
/// \brief These flags are \c true if a defaulted corresponding special
/// member can't be fully analyzed without performing overload resolution.
/// @{
bool NeedOverloadResolutionForMoveConstructor : 1;
bool NeedOverloadResolutionForMoveAssignment : 1;
bool NeedOverloadResolutionForDestructor : 1;
/// @}
/// \brief These flags are \c true if an implicit defaulted corresponding
/// special member would be defined as deleted.
/// @{
bool DefaultedMoveConstructorIsDeleted : 1;
bool DefaultedMoveAssignmentIsDeleted : 1;
bool DefaultedDestructorIsDeleted : 1;
/// @}
/// \brief The trivial special members which this class has, per
/// C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25,
/// C++11 [class.dtor]p5, or would have if the member were not suppressed.
///
/// This excludes any user-declared but not user-provided special members
/// which have been declared but not yet defined.
unsigned HasTrivialSpecialMembers : 6;
/// \brief The declared special members of this class which are known to be
/// non-trivial.
///
/// This excludes any user-declared but not user-provided special members
/// which have been declared but not yet defined, and any implicit special
/// members which have not yet been declared.
unsigned DeclaredNonTrivialSpecialMembers : 6;
/// \brief True when this class has a destructor with no semantic effect.
bool HasIrrelevantDestructor : 1;
/// \brief True when this class has at least one user-declared constexpr
/// constructor which is neither the copy nor move constructor.
bool HasConstexprNonCopyMoveConstructor : 1;
/// \brief True if a defaulted default constructor for this class would
/// be constexpr.
bool DefaultedDefaultConstructorIsConstexpr : 1;
/// \brief True if this class has a constexpr default constructor.
///
/// This is true for either a user-declared constexpr default constructor
/// or an implicitly declared constexpr default constructor.
bool HasConstexprDefaultConstructor : 1;
/// \brief True when this class contains at least one non-static data
/// member or base class of non-literal or volatile type.
bool HasNonLiteralTypeFieldsOrBases : 1;
/// \brief True when visible conversion functions are already computed
/// and are available.
bool ComputedVisibleConversions : 1;
/// \brief Whether we have a C++11 user-provided default constructor (not
/// explicitly deleted or defaulted).
bool UserProvidedDefaultConstructor : 1;
/// \brief The special members which have been declared for this class,
/// either by the user or implicitly.
unsigned DeclaredSpecialMembers : 6;
/// \brief Whether an implicit copy constructor would have a const-qualified
/// parameter.
bool ImplicitCopyConstructorHasConstParam : 1;
/// \brief Whether an implicit copy assignment operator would have a
/// const-qualified parameter.
bool ImplicitCopyAssignmentHasConstParam : 1;
/// \brief Whether any declared copy constructor has a const-qualified
/// parameter.
bool HasDeclaredCopyConstructorWithConstParam : 1;
/// \brief Whether any declared copy assignment operator has either a
/// const-qualified reference parameter or a non-reference parameter.
bool HasDeclaredCopyAssignmentWithConstParam : 1;
/// \brief Whether this class describes a C++ lambda.
bool IsLambda : 1;
/// \brief Whether we are currently parsing base specifiers.
bool IsParsingBaseSpecifiers : 1;
/// \brief The number of base class specifiers in Bases.
unsigned NumBases;
/// \brief The number of virtual base class specifiers in VBases.
unsigned NumVBases;
/// \brief Base classes of this class.
///
/// FIXME: This is wasted space for a union.
LazyCXXBaseSpecifiersPtr Bases;
/// \brief direct and indirect virtual base classes of this class.
LazyCXXBaseSpecifiersPtr VBases;
/// \brief The conversion functions of this C++ class (but not its
/// inherited conversion functions).
///
/// Each of the entries in this overload set is a CXXConversionDecl.
LazyASTUnresolvedSet Conversions;
/// \brief The conversion functions of this C++ class and all those
/// inherited conversion functions that are visible in this class.
///
/// Each of the entries in this overload set is a CXXConversionDecl or a
/// FunctionTemplateDecl.
LazyASTUnresolvedSet VisibleConversions;
/// \brief The declaration which defines this record.
CXXRecordDecl *Definition;
/// \brief The first friend declaration in this class, or null if there
/// aren't any.
///
/// This is actually currently stored in reverse order.
LazyDeclPtr FirstFriend;
/// \brief Retrieve the set of direct base classes.
CXXBaseSpecifier *getBases() const {
if (!Bases.isOffset())
return Bases.get(nullptr);
return getBasesSlowCase();
}
/// \brief Retrieve the set of virtual base classes.
CXXBaseSpecifier *getVBases() const {
if (!VBases.isOffset())
return VBases.get(nullptr);
return getVBasesSlowCase();
}
private:
CXXBaseSpecifier *getBasesSlowCase() const;
CXXBaseSpecifier *getVBasesSlowCase() const;
};
typedef LazyDefinitionDataPtr<CXXRecordDecl, struct DefinitionData>
DefinitionDataPtr;
friend class LazyDefinitionDataPtr<CXXRecordDecl, struct DefinitionData>;
mutable DefinitionDataPtr DefinitionData;
/// \brief Describes a C++ closure type (generated by a lambda expression).
struct LambdaDefinitionData : public DefinitionData {
typedef LambdaCapture Capture;
LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info,
bool Dependent, bool IsGeneric,
LambdaCaptureDefault CaptureDefault)
: DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
CaptureDefault(CaptureDefault), NumCaptures(0), NumExplicitCaptures(0),
ManglingNumber(0), ContextDecl(nullptr), Captures(nullptr),
MethodTyInfo(Info) {
IsLambda = true;
// C++11 [expr.prim.lambda]p3:
// This class type is neither an aggregate nor a literal type.
Aggregate = false;
PlainOldData = false;
HasNonLiteralTypeFieldsOrBases = true;
}
/// \brief Whether this lambda is known to be dependent, even if its
/// context isn't dependent.
///
/// A lambda with a non-dependent context can be dependent if it occurs
/// within the default argument of a function template, because the
/// lambda will have been created with the enclosing context as its
/// declaration context, rather than function. This is an unfortunate
/// artifact of having to parse the default arguments before.
unsigned Dependent : 1;
/// \brief Whether this lambda is a generic lambda.
unsigned IsGenericLambda : 1;
/// \brief The Default Capture.
unsigned CaptureDefault : 2;
/// \brief The number of captures in this lambda is limited 2^NumCaptures.
unsigned NumCaptures : 15;
/// \brief The number of explicit captures in this lambda.
unsigned NumExplicitCaptures : 13;
/// \brief The number used to indicate this lambda expression for name
/// mangling in the Itanium C++ ABI.
unsigned ManglingNumber;
/// \brief The declaration that provides context for this lambda, if the
/// actual DeclContext does not suffice. This is used for lambdas that
/// occur within default arguments of function parameters within the class
/// or within a data member initializer.
Decl *ContextDecl;
/// \brief The list of captures, both explicit and implicit, for this
/// lambda.
Capture *Captures;
/// \brief The type of the call method.
TypeSourceInfo *MethodTyInfo;
};
struct DefinitionData &data() const {
auto *DD = DefinitionData.get();
assert(DD && "queried property of class with no definition");
return *DD;
}
struct LambdaDefinitionData &getLambdaData() const {
// No update required: a merged definition cannot change any lambda
// properties.
auto *DD = DefinitionData.getNotUpdated();
assert(DD && DD->IsLambda && "queried lambda property of non-lambda class");
return static_cast<LambdaDefinitionData&>(*DD);
}
/// \brief The template or declaration that this declaration
/// describes or was instantiated from, respectively.
///
/// For non-templates, this value will be null. For record
/// declarations that describe a class template, this will be a
/// pointer to a ClassTemplateDecl. For member
/// classes of class template specializations, this will be the
/// MemberSpecializationInfo referring to the member class that was
/// instantiated or specialized.
llvm::PointerUnion<ClassTemplateDecl*, MemberSpecializationInfo*>
TemplateOrInstantiation;
friend class DeclContext;
friend class LambdaExpr;
/// \brief Called from setBases and addedMember to notify the class that a
/// direct or virtual base class or a member of class type has been added.
void addedClassSubobject(CXXRecordDecl *Base);
/// \brief Notify the class that member has been added.
///
/// This routine helps maintain information about the class based on which
/// members have been added. It will be invoked by DeclContext::addDecl()
/// whenever a member is added to this record.
void addedMember(Decl *D);
void markedVirtualFunctionPure();
friend void FunctionDecl::setPure(bool);
friend class ASTNodeImporter;
/// \brief Get the head of our list of friend declarations, possibly
/// deserializing the friends from an external AST source.
FriendDecl *getFirstFriend() const;
protected:
CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
public:
/// \brief Iterator that traverses the base classes of a class.
typedef CXXBaseSpecifier* base_class_iterator;
/// \brief Iterator that traverses the base classes of a class.
typedef const CXXBaseSpecifier* base_class_const_iterator;
CXXRecordDecl *getCanonicalDecl() override {
return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
}
const CXXRecordDecl *getCanonicalDecl() const {
return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
}
CXXRecordDecl *getPreviousDecl() {
return cast_or_null<CXXRecordDecl>(
static_cast<RecordDecl *>(this)->getPreviousDecl());
}
const CXXRecordDecl *getPreviousDecl() const {
return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
}
CXXRecordDecl *getMostRecentDecl() {
return cast<CXXRecordDecl>(
static_cast<RecordDecl *>(this)->getMostRecentDecl());
}
const CXXRecordDecl *getMostRecentDecl() const {
return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
}
CXXRecordDecl *getDefinition() const {
auto *DD = DefinitionData.get();
return DD ? DD->Definition : nullptr;
}
bool hasDefinition() const { return DefinitionData.get(); }
static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
SourceLocation StartLoc, SourceLocation IdLoc,
IdentifierInfo *Id,
CXXRecordDecl *PrevDecl = nullptr,
bool DelayTypeCreation = false);
static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
TypeSourceInfo *Info, SourceLocation Loc,
bool DependentLambda, bool IsGeneric,
LambdaCaptureDefault CaptureDefault);
static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
bool isDynamicClass() const {
return data().Polymorphic || data().NumVBases != 0;
}
void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
bool isParsingBaseSpecifiers() const {
return data().IsParsingBaseSpecifiers;
}
/// \brief Sets the base classes of this struct or class.
void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
/// \brief Retrieves the number of base classes of this class.
unsigned getNumBases() const { return data().NumBases; }
typedef llvm::iterator_range<base_class_iterator> base_class_range;
typedef llvm::iterator_range<base_class_const_iterator>
base_class_const_range;
base_class_range bases() {
return base_class_range(bases_begin(), bases_end());
}
base_class_const_range bases() const {
return base_class_const_range(bases_begin(), bases_end());
}
base_class_iterator bases_begin() { return data().getBases(); }
base_class_const_iterator bases_begin() const { return data().getBases(); }
base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
base_class_const_iterator bases_end() const {
return bases_begin() + data().NumBases;
}
/// \brief Retrieves the number of virtual base classes of this class.
unsigned getNumVBases() const { return data().NumVBases; }
base_class_range vbases() {
return base_class_range(vbases_begin(), vbases_end());
}
base_class_const_range vbases() const {
return base_class_const_range(vbases_begin(), vbases_end());
}
base_class_iterator vbases_begin() { return data().getVBases(); }
base_class_const_iterator vbases_begin() const { return data().getVBases(); }
base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
base_class_const_iterator vbases_end() const {
return vbases_begin() + data().NumVBases;
}
/// \brief Determine whether this class has any dependent base classes which
/// are not the current instantiation.
bool hasAnyDependentBases() const;
/// Iterator access to method members. The method iterator visits
/// all method members of the class, including non-instance methods,
/// special methods, etc.
typedef specific_decl_iterator<CXXMethodDecl> method_iterator;
typedef llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>
method_range;
method_range methods() const {
return method_range(method_begin(), method_end());
}
/// \brief Method begin iterator. Iterates in the order the methods
/// were declared.
method_iterator method_begin() const {
return method_iterator(decls_begin());
}
/// \brief Method past-the-end iterator.
method_iterator method_end() const {
return method_iterator(decls_end());
}
/// Iterator access to constructor members.
typedef specific_decl_iterator<CXXConstructorDecl> ctor_iterator;
typedef llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>
ctor_range;
ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
ctor_iterator ctor_begin() const {
return ctor_iterator(decls_begin());
}
ctor_iterator ctor_end() const {
return ctor_iterator(decls_end());
}
/// An iterator over friend declarations. All of these are defined
/// in DeclFriend.h.
class friend_iterator;
typedef llvm::iterator_range<friend_iterator> friend_range;
friend_range friends() const;
friend_iterator friend_begin() const;
friend_iterator friend_end() const;
void pushFriendDecl(FriendDecl *FD);
/// Determines whether this record has any friends.
bool hasFriends() const {
return data().FirstFriend.isValid();
}
/// \brief \c true if we know for sure that this class has a single,
/// accessible, unambiguous move constructor that is not deleted.
bool hasSimpleMoveConstructor() const {
return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
!data().DefaultedMoveConstructorIsDeleted;
}
/// \brief \c true if we know for sure that this class has a single,
/// accessible, unambiguous move assignment operator that is not deleted.
bool hasSimpleMoveAssignment() const {
return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
!data().DefaultedMoveAssignmentIsDeleted;
}
/// \brief \c true if we know for sure that this class has an accessible
/// destructor that is not deleted.
bool hasSimpleDestructor() const {
return !hasUserDeclaredDestructor() &&
!data().DefaultedDestructorIsDeleted;
}
/// \brief Determine whether this class has any default constructors.
bool hasDefaultConstructor() const {
return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
needsImplicitDefaultConstructor();
}
/// \brief Determine if we need to declare a default constructor for
/// this class.
///
/// This value is used for lazy creation of default constructors.
bool needsImplicitDefaultConstructor() const {
return !data().UserDeclaredConstructor &&
!(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
// C++14 [expr.prim.lambda]p20:
// The closure type associated with a lambda-expression has no
// default constructor.
!isLambda();
}
/// \brief Determine whether this class has any user-declared constructors.
///
/// When true, a default constructor will not be implicitly declared.
bool hasUserDeclaredConstructor() const {
return data().UserDeclaredConstructor;
}
/// \brief Whether this class has a user-provided default constructor
/// per C++11.
bool hasUserProvidedDefaultConstructor() const {
return data().UserProvidedDefaultConstructor;
}
/// \brief Determine whether this class has a user-declared copy constructor.
///
/// When false, a copy constructor will be implicitly declared.
bool hasUserDeclaredCopyConstructor() const {
return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
}
/// \brief Determine whether this class needs an implicit copy
/// constructor to be lazily declared.
bool needsImplicitCopyConstructor() const {
return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
}
/// \brief Determine whether we need to eagerly declare a defaulted copy
/// constructor for this class.
bool needsOverloadResolutionForCopyConstructor() const {
return data().HasMutableFields;
}
/// \brief Determine whether an implicit copy constructor for this type
/// would have a parameter with a const-qualified reference type.
bool implicitCopyConstructorHasConstParam() const {
return data().ImplicitCopyConstructorHasConstParam;
}
/// \brief Determine whether this class has a copy constructor with
/// a parameter type which is a reference to a const-qualified type.
bool hasCopyConstructorWithConstParam() const {
return data().HasDeclaredCopyConstructorWithConstParam ||
(needsImplicitCopyConstructor() &&
implicitCopyConstructorHasConstParam());
}
/// \brief Whether this class has a user-declared move constructor or
/// assignment operator.
///
/// When false, a move constructor and assignment operator may be
/// implicitly declared.
bool hasUserDeclaredMoveOperation() const {
return data().UserDeclaredSpecialMembers &
(SMF_MoveConstructor | SMF_MoveAssignment);
}
/// \brief Determine whether this class has had a move constructor
/// declared by the user.
bool hasUserDeclaredMoveConstructor() const {
return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
}
/// \brief Determine whether this class has a move constructor.
bool hasMoveConstructor() const {
return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
needsImplicitMoveConstructor();
}
/// \brief Set that we attempted to declare an implicitly move
/// constructor, but overload resolution failed so we deleted it.
void setImplicitMoveConstructorIsDeleted() {
assert((data().DefaultedMoveConstructorIsDeleted ||
needsOverloadResolutionForMoveConstructor()) &&
"move constructor should not be deleted");
data().DefaultedMoveConstructorIsDeleted = true;
}
/// \brief Determine whether this class should get an implicit move
/// constructor or if any existing special member function inhibits this.
bool needsImplicitMoveConstructor() const {
return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
!hasUserDeclaredCopyConstructor() &&
!hasUserDeclaredCopyAssignment() &&
!hasUserDeclaredMoveAssignment() &&
!hasUserDeclaredDestructor();
}
/// \brief Determine whether we need to eagerly declare a defaulted move
/// constructor for this class.
bool needsOverloadResolutionForMoveConstructor() const {
return data().NeedOverloadResolutionForMoveConstructor;
}
/// \brief Determine whether this class has a user-declared copy assignment
/// operator.
///
/// When false, a copy assigment operator will be implicitly declared.
bool hasUserDeclaredCopyAssignment() const {
return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
}
/// \brief Determine whether this class needs an implicit copy
/// assignment operator to be lazily declared.
bool needsImplicitCopyAssignment() const {
return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
}
/// \brief Determine whether we need to eagerly declare a defaulted copy
/// assignment operator for this class.
bool needsOverloadResolutionForCopyAssignment() const {
return data().HasMutableFields;
}
/// \brief Determine whether an implicit copy assignment operator for this
/// type would have a parameter with a const-qualified reference type.
bool implicitCopyAssignmentHasConstParam() const {
return data().ImplicitCopyAssignmentHasConstParam;
}
/// \brief Determine whether this class has a copy assignment operator with
/// a parameter type which is a reference to a const-qualified type or is not
/// a reference.
bool hasCopyAssignmentWithConstParam() const {
return data().HasDeclaredCopyAssignmentWithConstParam ||
(needsImplicitCopyAssignment() &&
implicitCopyAssignmentHasConstParam());
}
/// \brief Determine whether this class has had a move assignment
/// declared by the user.
bool hasUserDeclaredMoveAssignment() const {
return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
}
/// \brief Determine whether this class has a move assignment operator.
bool hasMoveAssignment() const {
return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
needsImplicitMoveAssignment();
}
/// \brief Set that we attempted to declare an implicit move assignment
/// operator, but overload resolution failed so we deleted it.
void setImplicitMoveAssignmentIsDeleted() {
assert((data().DefaultedMoveAssignmentIsDeleted ||
needsOverloadResolutionForMoveAssignment()) &&
"move assignment should not be deleted");
data().DefaultedMoveAssignmentIsDeleted = true;
}
/// \brief Determine whether this class should get an implicit move
/// assignment operator or if any existing special member function inhibits
/// this.
bool needsImplicitMoveAssignment() const {
return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
!hasUserDeclaredCopyConstructor() &&
!hasUserDeclaredCopyAssignment() &&
!hasUserDeclaredMoveConstructor() &&
!hasUserDeclaredDestructor();
}
/// \brief Determine whether we need to eagerly declare a move assignment
/// operator for this class.
bool needsOverloadResolutionForMoveAssignment() const {
return data().NeedOverloadResolutionForMoveAssignment;
}
/// \brief Determine whether this class has a user-declared destructor.
///
/// When false, a destructor will be implicitly declared.
bool hasUserDeclaredDestructor() const {
return data().UserDeclaredSpecialMembers & SMF_Destructor;
}
/// \brief Determine whether this class needs an implicit destructor to
/// be lazily declared.
bool needsImplicitDestructor() const {
return !(data().DeclaredSpecialMembers & SMF_Destructor);
}
/// \brief Determine whether we need to eagerly declare a destructor for this
/// class.
bool needsOverloadResolutionForDestructor() const {
return data().NeedOverloadResolutionForDestructor;
}
/// \brief Determine whether this class describes a lambda function object.
bool isLambda() const {
// An update record can't turn a non-lambda into a lambda.
auto *DD = DefinitionData.getNotUpdated();
return DD && DD->IsLambda;
}
/// \brief Determine whether this class describes a generic
/// lambda function object (i.e. function call operator is
/// a template).
bool isGenericLambda() const;
/// \brief Retrieve the lambda call operator of the closure type
/// if this is a closure type.
CXXMethodDecl *getLambdaCallOperator() const;
/// \brief Retrieve the lambda static invoker, the address of which
/// is returned by the conversion operator, and the body of which
/// is forwarded to the lambda call operator.
CXXMethodDecl *getLambdaStaticInvoker() const;
/// \brief Retrieve the generic lambda's template parameter list.
/// Returns null if the class does not represent a lambda or a generic
/// lambda.
TemplateParameterList *getGenericLambdaTemplateParameterList() const;
LambdaCaptureDefault getLambdaCaptureDefault() const {
assert(isLambda());
return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
}
/// \brief For a closure type, retrieve the mapping from captured
/// variables and \c this to the non-static data members that store the
/// values or references of the captures.
///
/// \param Captures Will be populated with the mapping from captured
/// variables to the corresponding fields.
///
/// \param ThisCapture Will be set to the field declaration for the
/// \c this capture.
///
/// \note No entries will be added for init-captures, as they do not capture
/// variables.
void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
FieldDecl *&ThisCapture) const;
typedef const LambdaCapture *capture_const_iterator;
typedef llvm::iterator_range<capture_const_iterator> capture_const_range;
capture_const_range captures() const {
return capture_const_range(captures_begin(), captures_end());
}
capture_const_iterator captures_begin() const {
return isLambda() ? getLambdaData().Captures : nullptr;
}
capture_const_iterator captures_end() const {
return isLambda() ? captures_begin() + getLambdaData().NumCaptures
: nullptr;
}
typedef UnresolvedSetIterator conversion_iterator;
conversion_iterator conversion_begin() const {
return data().Conversions.get(getASTContext()).begin();
}
conversion_iterator conversion_end() const {
return data().Conversions.get(getASTContext()).end();
}
/// Removes a conversion function from this class. The conversion
/// function must currently be a member of this class. Furthermore,
/// this class must currently be in the process of being defined.
void removeConversion(const NamedDecl *Old);
/// \brief Get all conversion functions visible in current class,
/// including conversion function templates.
llvm::iterator_range<conversion_iterator> getVisibleConversionFunctions();
/// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
/// which is a class with no user-declared constructors, no private
/// or protected non-static data members, no base classes, and no virtual
/// functions (C++ [dcl.init.aggr]p1).
bool isAggregate() const { return data().Aggregate; }
/// \brief Whether this class has any in-class initializers
/// for non-static data members (including those in anonymous unions or
/// structs).
bool hasInClassInitializer() const { return data().HasInClassInitializer; }
/// \brief Whether this class or any of its subobjects has any members of
/// reference type which would make value-initialization ill-formed.
///
/// Per C++03 [dcl.init]p5:
/// - if T is a non-union class type without a user-declared constructor,
/// then every non-static data member and base-class component of T is
/// value-initialized [...] A program that calls for [...]
/// value-initialization of an entity of reference type is ill-formed.
bool hasUninitializedReferenceMember() const {
return !isUnion() && !hasUserDeclaredConstructor() &&
data().HasUninitializedReferenceMember;
}
/// \brief Whether this class is a POD-type (C++ [class]p4)
///
/// For purposes of this function a class is POD if it is an aggregate
/// that has no non-static non-POD data members, no reference data
/// members, no user-defined copy assignment operator and no
/// user-defined destructor.
///
/// Note that this is the C++ TR1 definition of POD.
bool isPOD() const { return data().PlainOldData; }
/// \brief True if this class is C-like, without C++-specific features, e.g.
/// it contains only public fields, no bases, tag kind is not 'class', etc.
bool isCLike() const;
/// \brief Determine whether this is an empty class in the sense of
/// (C++11 [meta.unary.prop]).
///
/// A non-union class is empty iff it has a virtual function, virtual base,
/// data member (other than 0-width bit-field) or inherits from a non-empty
/// class.
///
/// \note This does NOT include a check for union-ness.
bool isEmpty() const { return data().Empty; }
/// Whether this class is polymorphic (C++ [class.virtual]),
/// which means that the class contains or inherits a virtual function.
bool isPolymorphic() const { return data().Polymorphic; }
/// \brief Determine whether this class has a pure virtual function.
///
/// The class is is abstract per (C++ [class.abstract]p2) if it declares
/// a pure virtual function or inherits a pure virtual function that is
/// not overridden.
bool isAbstract() const { return data().Abstract; }
/// \brief Determine whether this class has standard layout per
/// (C++ [class]p7)
bool isStandardLayout() const { return data().IsStandardLayout; }
/// \brief Determine whether this class, or any of its class subobjects,
/// contains a mutable field.
bool hasMutableFields() const { return data().HasMutableFields; }
/// \brief Determine whether this class has any variant members.
bool hasVariantMembers() const { return data().HasVariantMembers; }
/// \brief Determine whether this class has a trivial default constructor
/// (C++11 [class.ctor]p5).
bool hasTrivialDefaultConstructor() const {
return hasDefaultConstructor() &&
(data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
}
/// \brief Determine whether this class has a non-trivial default constructor
/// (C++11 [class.ctor]p5).
bool hasNonTrivialDefaultConstructor() const {
return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
(needsImplicitDefaultConstructor() &&
!(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
}
/// \brief Determine whether this class has at least one constexpr constructor
/// other than the copy or move constructors.
bool hasConstexprNonCopyMoveConstructor() const {
return data().HasConstexprNonCopyMoveConstructor ||
(needsImplicitDefaultConstructor() &&
defaultedDefaultConstructorIsConstexpr());
}
/// \brief Determine whether a defaulted default constructor for this class
/// would be constexpr.
bool defaultedDefaultConstructorIsConstexpr() const {
return data().DefaultedDefaultConstructorIsConstexpr &&
(!isUnion() || hasInClassInitializer() || !hasVariantMembers());
}
/// \brief Determine whether this class has a constexpr default constructor.
bool hasConstexprDefaultConstructor() const {
return data().HasConstexprDefaultConstructor ||
(needsImplicitDefaultConstructor() &&
defaultedDefaultConstructorIsConstexpr());
}
/// \brief Determine whether this class has a trivial copy constructor
/// (C++ [class.copy]p6, C++11 [class.copy]p12)
bool hasTrivialCopyConstructor() const {
return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
}
/// \brief Determine whether this class has a non-trivial copy constructor
/// (C++ [class.copy]p6, C++11 [class.copy]p12)
bool hasNonTrivialCopyConstructor() const {
return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
!hasTrivialCopyConstructor();
}
/// \brief Determine whether this class has a trivial move constructor
/// (C++11 [class.copy]p12)
bool hasTrivialMoveConstructor() const {
return hasMoveConstructor() &&
(data().HasTrivialSpecialMembers & SMF_MoveConstructor);
}
/// \brief Determine whether this class has a non-trivial move constructor
/// (C++11 [class.copy]p12)
bool hasNonTrivialMoveConstructor() const {
return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
(needsImplicitMoveConstructor() &&
!(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
}
/// \brief Determine whether this class has a trivial copy assignment operator
/// (C++ [class.copy]p11, C++11 [class.copy]p25)
bool hasTrivialCopyAssignment() const {
return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
}
/// \brief Determine whether this class has a non-trivial copy assignment
/// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
bool hasNonTrivialCopyAssignment() const {
return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
!hasTrivialCopyAssignment();
}
/// \brief Determine whether this class has a trivial move assignment operator
/// (C++11 [class.copy]p25)
bool hasTrivialMoveAssignment() const {
return hasMoveAssignment() &&
(data().HasTrivialSpecialMembers & SMF_MoveAssignment);
}
/// \brief Determine whether this class has a non-trivial move assignment
/// operator (C++11 [class.copy]p25)
bool hasNonTrivialMoveAssignment() const {
return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
(needsImplicitMoveAssignment() &&
!(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
}
/// \brief Determine whether this class has a trivial destructor
/// (C++ [class.dtor]p3)
bool hasTrivialDestructor() const {
return data().HasTrivialSpecialMembers & SMF_Destructor;
}
/// \brief Determine whether this class has a non-trivial destructor
/// (C++ [class.dtor]p3)
bool hasNonTrivialDestructor() const {
return !(data().HasTrivialSpecialMembers & SMF_Destructor);
}
/// \brief Determine whether this class has a destructor which has no
/// semantic effect.
///
/// Any such destructor will be trivial, public, defaulted and not deleted,
/// and will call only irrelevant destructors.
bool hasIrrelevantDestructor() const {
return data().HasIrrelevantDestructor;
}
/// \brief Determine whether this class has a non-literal or/ volatile type
/// non-static data member or base class.
bool hasNonLiteralTypeFieldsOrBases() const {
return data().HasNonLiteralTypeFieldsOrBases;
}
/// \brief Determine whether this class is considered trivially copyable per
/// (C++11 [class]p6).
bool isTriviallyCopyable() const;
/// \brief Determine whether this class is considered trivial.
///
/// C++11 [class]p6:
/// "A trivial class is a class that has a trivial default constructor and
/// is trivially copiable."
bool isTrivial() const {
return isTriviallyCopyable() && hasTrivialDefaultConstructor();
}
/// \brief Determine whether this class is a literal type.
///
/// C++11 [basic.types]p10:
/// A class type that has all the following properties:
/// - it has a trivial destructor
/// - every constructor call and full-expression in the
/// brace-or-equal-intializers for non-static data members (if any) is
/// a constant expression.
/// - it is an aggregate type or has at least one constexpr constructor
/// or constructor template that is not a copy or move constructor, and
/// - all of its non-static data members and base classes are of literal
/// types
///
/// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
/// treating types with trivial default constructors as literal types.
bool isLiteral() const {
return hasTrivialDestructor() &&
(isAggregate() || hasConstexprNonCopyMoveConstructor() ||
hasTrivialDefaultConstructor()) &&
!hasNonLiteralTypeFieldsOrBases();
}
/// \brief If this record is an instantiation of a member class,
/// retrieves the member class from which it was instantiated.
///
/// This routine will return non-null for (non-templated) member
/// classes of class templates. For example, given:
///
/// \code
/// template<typename T>
/// struct X {
/// struct A { };
/// };
/// \endcode
///
/// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
/// whose parent is the class template specialization X<int>. For
/// this declaration, getInstantiatedFromMemberClass() will return
/// the CXXRecordDecl X<T>::A. When a complete definition of
/// X<int>::A is required, it will be instantiated from the
/// declaration returned by getInstantiatedFromMemberClass().
CXXRecordDecl *getInstantiatedFromMemberClass() const;
/// \brief If this class is an instantiation of a member class of a
/// class template specialization, retrieves the member specialization
/// information.
MemberSpecializationInfo *getMemberSpecializationInfo() const {
return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();
}
/// \brief Specify that this record is an instantiation of the
/// member class \p RD.
void setInstantiationOfMemberClass(CXXRecordDecl *RD,
TemplateSpecializationKind TSK);
/// \brief Retrieves the class template that is described by this
/// class declaration.
///
/// Every class template is represented as a ClassTemplateDecl and a
/// CXXRecordDecl. The former contains template properties (such as
/// the template parameter lists) while the latter contains the
/// actual description of the template's
/// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
/// CXXRecordDecl that from a ClassTemplateDecl, while
/// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
/// a CXXRecordDecl.
ClassTemplateDecl *getDescribedClassTemplate() const {
return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl*>();
}
void setDescribedClassTemplate(ClassTemplateDecl *Template) {
TemplateOrInstantiation = Template;
}
/// \brief Determine whether this particular class is a specialization or
/// instantiation of a class template or member class of a class template,
/// and how it was instantiated or specialized.
TemplateSpecializationKind getTemplateSpecializationKind() const;
/// \brief Set the kind of specialization or template instantiation this is.
void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
/// \brief Retrieve the record declaration from which this record could be
/// instantiated. Returns null if this class is not a template instantiation.
const CXXRecordDecl *getTemplateInstantiationPattern() const;
CXXRecordDecl *getTemplateInstantiationPattern() {
return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
->getTemplateInstantiationPattern());
}
/// \brief Returns the destructor decl for this class.
CXXDestructorDecl *getDestructor() const;
/// \brief Returns true if the class destructor, or any implicitly invoked
/// destructors are marked noreturn.
bool isAnyDestructorNoReturn() const;
/// \brief If the class is a local class [class.local], returns
/// the enclosing function declaration.
const FunctionDecl *isLocalClass() const {
if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
return RD->isLocalClass();
return dyn_cast<FunctionDecl>(getDeclContext());
}
FunctionDecl *isLocalClass() {
return const_cast<FunctionDecl*>(
const_cast<const CXXRecordDecl*>(this)->isLocalClass());
}
/// \brief Determine whether this dependent class is a current instantiation,
/// when viewed from within the given context.
bool isCurrentInstantiation(const DeclContext *CurContext) const;
/// \brief Determine whether this class is derived from the class \p Base.
///
/// This routine only determines whether this class is derived from \p Base,
/// but does not account for factors that may make a Derived -> Base class
/// ill-formed, such as private/protected inheritance or multiple, ambiguous
/// base class subobjects.
///
/// \param Base the base class we are searching for.
///
/// \returns true if this class is derived from Base, false otherwise.
bool isDerivedFrom(const CXXRecordDecl *Base) const;
/// \brief Determine whether this class is derived from the type \p Base.
///
/// This routine only determines whether this class is derived from \p Base,
/// but does not account for factors that may make a Derived -> Base class
/// ill-formed, such as private/protected inheritance or multiple, ambiguous
/// base class subobjects.
///
/// \param Base the base class we are searching for.
///
/// \param Paths will contain the paths taken from the current class to the
/// given \p Base class.
///
/// \returns true if this class is derived from \p Base, false otherwise.
///
/// \todo add a separate parameter to configure IsDerivedFrom, rather than
/// tangling input and output in \p Paths
bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
/// \brief Determine whether this class is virtually derived from
/// the class \p Base.
///
/// This routine only determines whether this class is virtually
/// derived from \p Base, but does not account for factors that may
/// make a Derived -> Base class ill-formed, such as
/// private/protected inheritance or multiple, ambiguous base class
/// subobjects.
///
/// \param Base the base class we are searching for.
///
/// \returns true if this class is virtually derived from Base,
/// false otherwise.
bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
/// \brief Determine whether this class is provably not derived from
/// the type \p Base.
bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
/// \brief Function type used by forallBases() as a callback.
///
/// \param BaseDefinition the definition of the base class
///
/// \returns true if this base matched the search criteria
typedef bool ForallBasesCallback(const CXXRecordDecl *BaseDefinition,
void *UserData);
/// \brief Determines if the given callback holds for all the direct
/// or indirect base classes of this type.
///
/// The class itself does not count as a base class. This routine
/// returns false if the class has non-computable base classes.
///
/// \param BaseMatches Callback invoked for each (direct or indirect) base
/// class of this type, or if \p AllowShortCircuit is true then until a call
/// returns false.
///
/// \param UserData Passed as the second argument of every call to
/// \p BaseMatches.
///
/// \param AllowShortCircuit if false, forces the callback to be called
/// for every base class, even if a dependent or non-matching base was
/// found.
bool forallBases(ForallBasesCallback *BaseMatches, void *UserData,
bool AllowShortCircuit = true) const;
/// \brief Function type used by lookupInBases() to determine whether a
/// specific base class subobject matches the lookup criteria.
///
/// \param Specifier the base-class specifier that describes the inheritance
/// from the base class we are trying to match.
///
/// \param Path the current path, from the most-derived class down to the
/// base named by the \p Specifier.
///
/// \param UserData a single pointer to user-specified data, provided to
/// lookupInBases().
///
/// \returns true if this base matched the search criteria, false otherwise.
typedef bool BaseMatchesCallback(const CXXBaseSpecifier *Specifier,
CXXBasePath &Path,
void *UserData);
/// \brief Look for entities within the base classes of this C++ class,
/// transitively searching all base class subobjects.
///
/// This routine uses the callback function \p BaseMatches to find base
/// classes meeting some search criteria, walking all base class subobjects
/// and populating the given \p Paths structure with the paths through the
/// inheritance hierarchy that resulted in a match. On a successful search,
/// the \p Paths structure can be queried to retrieve the matching paths and
/// to determine if there were any ambiguities.
///
/// \param BaseMatches callback function used to determine whether a given
/// base matches the user-defined search criteria.
///
/// \param UserData user data pointer that will be provided to \p BaseMatches.
///
/// \param Paths used to record the paths from this class to its base class
/// subobjects that match the search criteria.
///
/// \returns true if there exists any path from this class to a base class
/// subobject that matches the search criteria.
bool lookupInBases(BaseMatchesCallback *BaseMatches, void *UserData,
CXXBasePaths &Paths) const;
/// \brief Base-class lookup callback that determines whether the given
/// base class specifier refers to a specific class declaration.
///
/// This callback can be used with \c lookupInBases() to determine whether
/// a given derived class has is a base class subobject of a particular type.
/// The user data pointer should refer to the canonical CXXRecordDecl of the
/// base class that we are searching for.
static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
CXXBasePath &Path, void *BaseRecord);
/// \brief Base-class lookup callback that determines whether the
/// given base class specifier refers to a specific class
/// declaration and describes virtual derivation.
///
/// This callback can be used with \c lookupInBases() to determine
/// whether a given derived class has is a virtual base class
/// subobject of a particular type. The user data pointer should
/// refer to the canonical CXXRecordDecl of the base class that we
/// are searching for.
static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
CXXBasePath &Path, void *BaseRecord);
/// \brief Base-class lookup callback that determines whether there exists
/// a tag with the given name.
///
/// This callback can be used with \c lookupInBases() to find tag members
/// of the given name within a C++ class hierarchy. The user data pointer
/// is an opaque \c DeclarationName pointer.
static bool FindTagMember(const CXXBaseSpecifier *Specifier,
CXXBasePath &Path, void *Name);
/// \brief Base-class lookup callback that determines whether there exists
/// a member with the given name.
///
/// This callback can be used with \c lookupInBases() to find members
/// of the given name within a C++ class hierarchy. The user data pointer
/// is an opaque \c DeclarationName pointer.
static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
CXXBasePath &Path, void *Name);
/// \brief Base-class lookup callback that determines whether there exists
/// a member with the given name that can be used in a nested-name-specifier.
///
/// This callback can be used with \c lookupInBases() to find membes of
/// the given name within a C++ class hierarchy that can occur within
/// nested-name-specifiers.
static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
CXXBasePath &Path,
void *UserData);
/// \brief Retrieve the final overriders for each virtual member
/// function in the class hierarchy where this class is the
/// most-derived class in the class hierarchy.
void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
/// \brief Get the indirect primary bases for this class.
void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
/// Renders and displays an inheritance diagram
/// for this C++ class and all of its base classes (transitively) using
/// GraphViz.
void viewInheritance(ASTContext& Context) const;
/// \brief Calculates the access of a decl that is reached
/// along a path.
static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
AccessSpecifier DeclAccess) {
assert(DeclAccess != AS_none);
if (DeclAccess == AS_private) return AS_none;
return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
}
/// \brief Indicates that the declaration of a defaulted or deleted special
/// member function is now complete.
void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
/// \brief Indicates that the definition of this class is now complete.
void completeDefinition() override;
/// \brief Indicates that the definition of this class is now complete,
/// and provides a final overrider map to help determine
///
/// \param FinalOverriders The final overrider map for this class, which can
/// be provided as an optimization for abstract-class checking. If NULL,
/// final overriders will be computed if they are needed to complete the
/// definition.
void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
/// \brief Determine whether this class may end up being abstract, even though
/// it is not yet known to be abstract.
///
/// \returns true if this class is not known to be abstract but has any
/// base classes that are abstract. In this case, \c completeDefinition()
/// will need to compute final overriders to determine whether the class is
/// actually abstract.
bool mayBeAbstract() const;
/// \brief If this is the closure type of a lambda expression, retrieve the
/// number to be used for name mangling in the Itanium C++ ABI.
///
/// Zero indicates that this closure type has internal linkage, so the
/// mangling number does not matter, while a non-zero value indicates which
/// lambda expression this is in this particular context.
unsigned getLambdaManglingNumber() const {
assert(isLambda() && "Not a lambda closure type!");
return getLambdaData().ManglingNumber;
}
/// \brief Retrieve the declaration that provides additional context for a
/// lambda, when the normal declaration context is not specific enough.
///
/// Certain contexts (default arguments of in-class function parameters and
/// the initializers of data members) have separate name mangling rules for
/// lambdas within the Itanium C++ ABI. For these cases, this routine provides
/// the declaration in which the lambda occurs, e.g., the function parameter
/// or the non-static data member. Otherwise, it returns NULL to imply that
/// the declaration context suffices.
Decl *getLambdaContextDecl() const {
assert(isLambda() && "Not a lambda closure type!");
return getLambdaData().ContextDecl;
}
/// \brief Set the mangling number and context declaration for a lambda
/// class.
void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl) {
getLambdaData().ManglingNumber = ManglingNumber;
getLambdaData().ContextDecl = ContextDecl;
}
/// \brief Returns the inheritance model used for this record.
MSInheritanceAttr::Spelling getMSInheritanceModel() const;
/// \brief Calculate what the inheritance model would be for this class.
MSInheritanceAttr::Spelling calculateInheritanceModel() const;
/// In the Microsoft C++ ABI, use zero for the field offset of a null data
/// member pointer if we can guarantee that zero is not a valid field offset,
/// or if the member pointer has multiple fields. Polymorphic classes have a
/// vfptr at offset zero, so we can use zero for null. If there are multiple
/// fields, we can use zero even if it is a valid field offset because
/// null-ness testing will check the other fields.
bool nullFieldOffsetIsZero() const {
return !MSInheritanceAttr::hasOnlyOneField(/*IsMemberFunction=*/false,
getMSInheritanceModel()) ||
(hasDefinition() && isPolymorphic());
}
/// \brief Controls when vtordisps will be emitted if this record is used as a
/// virtual base.
MSVtorDispAttr::Mode getMSVtorDispMode() const;
/// \brief Determine whether this lambda expression was known to be dependent
/// at the time it was created, even if its context does not appear to be
/// dependent.
///
/// This flag is a workaround for an issue with parsing, where default
/// arguments are parsed before their enclosing function declarations have
/// been created. This means that any lambda expressions within those
/// default arguments will have as their DeclContext the context enclosing
/// the function declaration, which may be non-dependent even when the
/// function declaration itself is dependent. This flag indicates when we
/// know that the lambda is dependent despite that.
bool isDependentLambda() const {
return isLambda() && getLambdaData().Dependent;
}
TypeSourceInfo *getLambdaTypeInfo() const {
return getLambdaData().MethodTyInfo;
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) {
return K >= firstCXXRecord && K <= lastCXXRecord;
}
friend class ASTDeclReader;
friend class ASTDeclWriter;
friend class ASTReader;
friend class ASTWriter;
};
/// \brief Represents a static or instance method of a struct/union/class.
///
/// In the terminology of the C++ Standard, these are the (static and
/// non-static) member functions, whether virtual or not.
class CXXMethodDecl : public FunctionDecl {
void anchor() override;
protected:
CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo *TInfo,
StorageClass SC, bool isInline,
bool isConstexpr, SourceLocation EndLocation)
: FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo,
SC, isInline, isConstexpr) {
if (EndLocation.isValid())
setRangeEnd(EndLocation);
}
public:
static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
SourceLocation StartLoc,
const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo *TInfo,
StorageClass SC,
bool isInline,
bool isConstexpr,
SourceLocation EndLocation);
static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
bool isStatic() const;
bool isInstance() const { return !isStatic(); }
/// Returns true if the given operator is implicitly static in a record
/// context.
static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
// [class.free]p1:
// Any allocation function for a class T is a static member
// (even if not explicitly declared static).
// [class.free]p6 Any deallocation function for a class X is a static member
// (even if not explicitly declared static).
return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
OOK == OO_Array_Delete;
}
bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
bool isVirtual() const {
CXXMethodDecl *CD =
cast<CXXMethodDecl>(const_cast<CXXMethodDecl*>(this)->getCanonicalDecl());
// Member function is virtual if it is marked explicitly so, or if it is
// declared in __interface -- then it is automatically pure virtual.
if (CD->isVirtualAsWritten() || CD->isPure())
return true;
return (CD->begin_overridden_methods() != CD->end_overridden_methods());
}
/// \brief Determine whether this is a usual deallocation function
/// (C++ [basic.stc.dynamic.deallocation]p2), which is an overloaded
/// delete or delete[] operator with a particular signature.
bool isUsualDeallocationFunction() const;
/// \brief Determine whether this is a copy-assignment operator, regardless
/// of whether it was declared implicitly or explicitly.
bool isCopyAssignmentOperator() const;
/// \brief Determine whether this is a move assignment operator.
bool isMoveAssignmentOperator() const;
CXXMethodDecl *getCanonicalDecl() override {
return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
}
const CXXMethodDecl *getCanonicalDecl() const {
return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
}
CXXMethodDecl *getMostRecentDecl() {
return cast<CXXMethodDecl>(
static_cast<FunctionDecl *>(this)->getMostRecentDecl());
}
const CXXMethodDecl *getMostRecentDecl() const {
return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
}
/// True if this method is user-declared and was not
/// deleted or defaulted on its first declaration.
bool isUserProvided() const {
return !(isDeleted() || getCanonicalDecl()->isDefaulted());
}
///
void addOverriddenMethod(const CXXMethodDecl *MD);
typedef const CXXMethodDecl *const* method_iterator;
method_iterator begin_overridden_methods() const;
method_iterator end_overridden_methods() const;
unsigned size_overridden_methods() const;
/// Returns the parent of this method declaration, which
/// is the class in which this method is defined.
const CXXRecordDecl *getParent() const {
return cast<CXXRecordDecl>(FunctionDecl::getParent());
}
/// Returns the parent of this method declaration, which
/// is the class in which this method is defined.
CXXRecordDecl *getParent() {
return const_cast<CXXRecordDecl *>(
cast<CXXRecordDecl>(FunctionDecl::getParent()));
}
/// \brief Returns the type of the \c this pointer.
///
/// Should only be called for instance (i.e., non-static) methods.
QualType getThisType(ASTContext &C) const;
// HLSL Change Begin - This is a reference.
/// \brief Returns the type of the \c this object looking through the pointer.
///
/// Should only be called for instance (i.e., non-static) methods.
QualType getThisObjectType(ASTContext &C) const;
// HLSL Change End - This is a reference.
unsigned getTypeQualifiers() const {
return getType()->getAs<FunctionProtoType>()->getTypeQuals();
}
/// \brief Retrieve the ref-qualifier associated with this method.
///
/// In the following example, \c f() has an lvalue ref-qualifier, \c g()
/// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
/// @code
/// struct X {
/// void f() &;
/// void g() &&;
/// void h();
/// };
/// @endcode
RefQualifierKind getRefQualifier() const {
return getType()->getAs<FunctionProtoType>()->getRefQualifier();
}
bool hasInlineBody() const;
/// \brief Determine whether this is a lambda closure type's static member
/// function that is used for the result of the lambda's conversion to
/// function pointer (for a lambda with no captures).
///
/// The function itself, if used, will have a placeholder body that will be
/// supplied by IR generation to either forward to the function call operator
/// or clone the function call operator.
bool isLambdaStaticInvoker() const;
/// \brief Find the method in \p RD that corresponds to this one.
///
/// Find if \p RD or one of the classes it inherits from override this method.
/// If so, return it. \p RD is assumed to be a subclass of the class defining
/// this method (or be the class itself), unless \p MayBeBase is set to true.
CXXMethodDecl *
getCorrespondingMethodInClass(const CXXRecordDecl *RD,
bool MayBeBase = false);
const CXXMethodDecl *
getCorrespondingMethodInClass(const CXXRecordDecl *RD,
bool MayBeBase = false) const {
return const_cast<CXXMethodDecl *>(this)
->getCorrespondingMethodInClass(RD, MayBeBase);
}
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) {
return K >= firstCXXMethod && K <= lastCXXMethod;
}
};
/// \brief Represents a C++ base or member initializer.
///
/// This is part of a constructor initializer that
/// initializes one non-static member variable or one base class. For
/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
/// initializers:
///
/// \code
/// class A { };
/// class B : public A {
/// float f;
/// public:
/// B(A& a) : A(a), f(3.14159) { }
/// };
/// \endcode
class CXXCtorInitializer {
/// \brief Either the base class name/delegating constructor type (stored as
/// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
/// (IndirectFieldDecl*) being initialized.
llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
Initializee;
/// \brief The source location for the field name or, for a base initializer
/// pack expansion, the location of the ellipsis.
///
/// In the case of a delegating
/// constructor, it will still include the type's source location as the
/// Initializee points to the CXXConstructorDecl (to allow loop detection).
SourceLocation MemberOrEllipsisLocation;
/// \brief The argument used to initialize the base or member, which may
/// end up constructing an object (when multiple arguments are involved).
Stmt *Init;
/// \brief Location of the left paren of the ctor-initializer.
SourceLocation LParenLoc;
/// \brief Location of the right paren of the ctor-initializer.
SourceLocation RParenLoc;
/// \brief If the initializee is a type, whether that type makes this
/// a delegating initialization.
bool IsDelegating : 1;
/// \brief If the initializer is a base initializer, this keeps track
/// of whether the base is virtual or not.
bool IsVirtual : 1;
/// \brief Whether or not the initializer is explicitly written
/// in the sources.
bool IsWritten : 1;
/// If IsWritten is true, then this number keeps track of the textual order
/// of this initializer in the original sources, counting from 0; otherwise,
/// it stores the number of array index variables stored after this object
/// in memory.
unsigned SourceOrderOrNumArrayIndices : 13;
CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
SourceLocation MemberLoc, SourceLocation L, Expr *Init,
SourceLocation R, VarDecl **Indices, unsigned NumIndices);
public:
/// \brief Creates a new base-class initializer.
explicit
CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
SourceLocation L, Expr *Init, SourceLocation R,
SourceLocation EllipsisLoc);
/// \brief Creates a new member initializer.
explicit
CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
SourceLocation MemberLoc, SourceLocation L, Expr *Init,
SourceLocation R);
/// \brief Creates a new anonymous field initializer.
explicit
CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
SourceLocation MemberLoc, SourceLocation L, Expr *Init,
SourceLocation R);
/// \brief Creates a new delegating initializer.
explicit
CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
SourceLocation L, Expr *Init, SourceLocation R);
/// \brief Creates a new member initializer that optionally contains
/// array indices used to describe an elementwise initialization.
static CXXCtorInitializer *Create(ASTContext &Context, FieldDecl *Member,
SourceLocation MemberLoc, SourceLocation L,
Expr *Init, SourceLocation R,
VarDecl **Indices, unsigned NumIndices);
/// \brief Determine whether this initializer is initializing a base class.
bool isBaseInitializer() const {
return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
}
/// \brief Determine whether this initializer is initializing a non-static
/// data member.
bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
bool isAnyMemberInitializer() const {
return isMemberInitializer() || isIndirectMemberInitializer();
}
bool isIndirectMemberInitializer() const {
return Initializee.is<IndirectFieldDecl*>();
}
/// \brief Determine whether this initializer is an implicit initializer
/// generated for a field with an initializer defined on the member
/// declaration.
///
/// In-class member initializers (also known as "non-static data member
/// initializations", NSDMIs) were introduced in C++11.
bool isInClassMemberInitializer() const {
return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
}
/// \brief Determine whether this initializer is creating a delegating
/// constructor.
bool isDelegatingInitializer() const {
return Initializee.is<TypeSourceInfo*>() && IsDelegating;
}
/// \brief Determine whether this initializer is a pack expansion.
bool isPackExpansion() const {
return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
}
// \brief For a pack expansion, returns the location of the ellipsis.
SourceLocation getEllipsisLoc() const {
assert(isPackExpansion() && "Initializer is not a pack expansion");
return MemberOrEllipsisLocation;
}
/// If this is a base class initializer, returns the type of the
/// base class with location information. Otherwise, returns an NULL
/// type location.
TypeLoc getBaseClassLoc() const;
/// If this is a base class initializer, returns the type of the base class.
/// Otherwise, returns null.
const Type *getBaseClass() const;
/// Returns whether the base is virtual or not.
bool isBaseVirtual() const {
assert(isBaseInitializer() && "Must call this on base initializer!");
return IsVirtual;
}
/// \brief Returns the declarator information for a base class or delegating
/// initializer.
TypeSourceInfo *getTypeSourceInfo() const {
return Initializee.dyn_cast<TypeSourceInfo *>();
}
/// \brief If this is a member initializer, returns the declaration of the
/// non-static data member being initialized. Otherwise, returns null.
FieldDecl *getMember() const {
if (isMemberInitializer())
return Initializee.get<FieldDecl*>();
return nullptr;
}
FieldDecl *getAnyMember() const {
if (isMemberInitializer())
return Initializee.get<FieldDecl*>();
if (isIndirectMemberInitializer())
return Initializee.get<IndirectFieldDecl*>()->getAnonField();
return nullptr;
}
IndirectFieldDecl *getIndirectMember() const {
if (isIndirectMemberInitializer())
return Initializee.get<IndirectFieldDecl*>();
return nullptr;
}
SourceLocation getMemberLocation() const {
return MemberOrEllipsisLocation;
}
/// \brief Determine the source location of the initializer.
SourceLocation getSourceLocation() const;
/// \brief Determine the source range covering the entire initializer.
SourceRange getSourceRange() const LLVM_READONLY;
/// \brief Determine whether this initializer is explicitly written
/// in the source code.
bool isWritten() const { return IsWritten; }
/// \brief Return the source position of the initializer, counting from 0.
/// If the initializer was implicit, -1 is returned.
int getSourceOrder() const {
return IsWritten ? static_cast<int>(SourceOrderOrNumArrayIndices) : -1;
}
/// \brief Set the source order of this initializer.
///
/// This can only be called once for each initializer; it cannot be called
/// on an initializer having a positive number of (implicit) array indices.
///
/// This assumes that the initializer was written in the source code, and
/// ensures that isWritten() returns true.
void setSourceOrder(int pos) {
assert(!IsWritten &&
"calling twice setSourceOrder() on the same initializer");
assert(SourceOrderOrNumArrayIndices == 0 &&
"setSourceOrder() used when there are implicit array indices");
assert(pos >= 0 &&
"setSourceOrder() used to make an initializer implicit");
IsWritten = true;
SourceOrderOrNumArrayIndices = static_cast<unsigned>(pos);
}
SourceLocation getLParenLoc() const { return LParenLoc; }
SourceLocation getRParenLoc() const { return RParenLoc; }
/// \brief Determine the number of implicit array indices used while
/// described an array member initialization.
unsigned getNumArrayIndices() const {
return IsWritten ? 0 : SourceOrderOrNumArrayIndices;
}
/// \brief Retrieve a particular array index variable used to
/// describe an array member initialization.
VarDecl *getArrayIndex(unsigned I) {
assert(I < getNumArrayIndices() && "Out of bounds member array index");
return reinterpret_cast<VarDecl **>(this + 1)[I];
}
const VarDecl *getArrayIndex(unsigned I) const {
assert(I < getNumArrayIndices() && "Out of bounds member array index");
return reinterpret_cast<const VarDecl * const *>(this + 1)[I];
}
void setArrayIndex(unsigned I, VarDecl *Index) {
assert(I < getNumArrayIndices() && "Out of bounds member array index");
reinterpret_cast<VarDecl **>(this + 1)[I] = Index;
}
ArrayRef<VarDecl *> getArrayIndexes() {
assert(getNumArrayIndices() != 0 && "Getting indexes for non-array init");
return llvm::makeArrayRef(reinterpret_cast<VarDecl **>(this + 1),
getNumArrayIndices());
}
/// \brief Get the initializer.
Expr *getInit() const { return static_cast<Expr*>(Init); }
};
/// \brief Represents a C++ constructor within a class.
///
/// For example:
///
/// \code
/// class X {
/// public:
/// explicit X(int); // represented by a CXXConstructorDecl.
/// };
/// \endcode
class CXXConstructorDecl : public CXXMethodDecl {
void anchor() override;
/// \brief Whether this constructor declaration has the \c explicit keyword
/// specified.
bool IsExplicitSpecified : 1;
/// \name Support for base and member initializers.
/// \{
/// \brief The arguments used to initialize the base or member.
LazyCXXCtorInitializersPtr CtorInitializers;
unsigned NumCtorInitializers;
/// \}
CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo *TInfo,
bool isExplicitSpecified, bool isInline,
bool isImplicitlyDeclared, bool isConstexpr)
: CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,
SC_None, isInline, isConstexpr, SourceLocation()),
IsExplicitSpecified(isExplicitSpecified), CtorInitializers(nullptr),
NumCtorInitializers(0) {
setImplicit(isImplicitlyDeclared);
}
public:
static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID);
static CXXConstructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
SourceLocation StartLoc,
const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo *TInfo,
bool isExplicit,
bool isInline, bool isImplicitlyDeclared,
bool isConstexpr);
/// \brief Determine whether this constructor declaration has the
/// \c explicit keyword specified.
bool isExplicitSpecified() const { return IsExplicitSpecified; }
/// \brief Determine whether this constructor was marked "explicit" or not.
bool isExplicit() const {
return cast<CXXConstructorDecl>(getFirstDecl())->isExplicitSpecified();
}
/// \brief Iterates through the member/base initializer list.
typedef CXXCtorInitializer **init_iterator;
/// \brief Iterates through the member/base initializer list.
typedef CXXCtorInitializer *const *init_const_iterator;
typedef llvm::iterator_range<init_iterator> init_range;
typedef llvm::iterator_range<init_const_iterator> init_const_range;
init_range inits() { return init_range(init_begin(), init_end()); }
init_const_range inits() const {
return init_const_range(init_begin(), init_end());
}
/// \brief Retrieve an iterator to the first initializer.
init_iterator init_begin() {
const auto *ConstThis = this;
return const_cast<init_iterator>(ConstThis->init_begin());
}
/// \brief Retrieve an iterator to the first initializer.
init_const_iterator init_begin() const;
/// \brief Retrieve an iterator past the last initializer.
init_iterator init_end() {
return init_begin() + NumCtorInitializers;
}
/// \brief Retrieve an iterator past the last initializer.
init_const_iterator init_end() const {
return init_begin() + NumCtorInitializers;
}
typedef std::reverse_iterator<init_iterator> init_reverse_iterator;
typedef std::reverse_iterator<init_const_iterator>
init_const_reverse_iterator;
init_reverse_iterator init_rbegin() {
return init_reverse_iterator(init_end());
}
init_const_reverse_iterator init_rbegin() const {
return init_const_reverse_iterator(init_end());
}
init_reverse_iterator init_rend() {
return init_reverse_iterator(init_begin());
}
init_const_reverse_iterator init_rend() const {
return init_const_reverse_iterator(init_begin());
}
/// \brief Determine the number of arguments used to initialize the member
/// or base.
unsigned getNumCtorInitializers() const {
return NumCtorInitializers;
}
void setNumCtorInitializers(unsigned numCtorInitializers) {
NumCtorInitializers = numCtorInitializers;
}
void setCtorInitializers(CXXCtorInitializer **Initializers) {
CtorInitializers = Initializers;
}
/// \brief Determine whether this constructor is a delegating constructor.
bool isDelegatingConstructor() const {
return (getNumCtorInitializers() == 1) &&
init_begin()[0]->isDelegatingInitializer();
}
/// \brief When this constructor delegates to another, retrieve the target.
CXXConstructorDecl *getTargetConstructor() const;
/// Whether this constructor is a default
/// constructor (C++ [class.ctor]p5), which can be used to
/// default-initialize a class of this type.
bool isDefaultConstructor() const;
/// \brief Whether this constructor is a copy constructor (C++ [class.copy]p2,
/// which can be used to copy the class.
///
/// \p TypeQuals will be set to the qualifiers on the
/// argument type. For example, \p TypeQuals would be set to \c
/// Qualifiers::Const for the following copy constructor:
///
/// \code
/// class X {
/// public:
/// X(const X&);
/// };
/// \endcode
bool isCopyConstructor(unsigned &TypeQuals) const;
/// Whether this constructor is a copy
/// constructor (C++ [class.copy]p2, which can be used to copy the
/// class.
bool isCopyConstructor() const {
unsigned TypeQuals = 0;
return isCopyConstructor(TypeQuals);
}
/// \brief Determine whether this constructor is a move constructor
/// (C++0x [class.copy]p3), which can be used to move values of the class.
///
/// \param TypeQuals If this constructor is a move constructor, will be set
/// to the type qualifiers on the referent of the first parameter's type.
bool isMoveConstructor(unsigned &TypeQuals) const;
/// \brief Determine whether this constructor is a move constructor
/// (C++0x [class.copy]p3), which can be used to move values of the class.
bool isMoveConstructor() const {
unsigned TypeQuals = 0;
return isMoveConstructor(TypeQuals);
}
/// \brief Determine whether this is a copy or move constructor.
///
/// \param TypeQuals Will be set to the type qualifiers on the reference
/// parameter, if in fact this is a copy or move constructor.
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
/// \brief Determine whether this a copy or move constructor.
bool isCopyOrMoveConstructor() const {
unsigned Quals;
return isCopyOrMoveConstructor(Quals);
}
/// Whether this constructor is a
/// converting constructor (C++ [class.conv.ctor]), which can be
/// used for user-defined conversions.
bool isConvertingConstructor(bool AllowExplicit) const;
/// \brief Determine whether this is a member template specialization that
/// would copy the object to itself. Such constructors are never used to copy
/// an object.
bool isSpecializationCopyingObject() const;
/// \brief Get the constructor that this inheriting constructor is based on.
const CXXConstructorDecl *getInheritedConstructor() const;
/// \brief Set the constructor that this inheriting constructor is based on.
void setInheritedConstructor(const CXXConstructorDecl *BaseCtor);
CXXConstructorDecl *getCanonicalDecl() override {
return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
}
const CXXConstructorDecl *getCanonicalDecl() const {
return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
}
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == CXXConstructor; }
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// \brief Represents a C++ destructor within a class.
///
/// For example:
///
/// \code
/// class X {
/// public:
/// ~X(); // represented by a CXXDestructorDecl.
/// };
/// \endcode
class CXXDestructorDecl : public CXXMethodDecl {
void anchor() override;
FunctionDecl *OperatorDelete;
CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo *TInfo,
bool isInline, bool isImplicitlyDeclared)
: CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
SC_None, isInline, /*isConstexpr=*/false, SourceLocation()),
OperatorDelete(nullptr) {
setImplicit(isImplicitlyDeclared);
}
public:
static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
SourceLocation StartLoc,
const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo* TInfo,
bool isInline,
bool isImplicitlyDeclared);
static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
void setOperatorDelete(FunctionDecl *OD);
const FunctionDecl *getOperatorDelete() const {
return cast<CXXDestructorDecl>(getFirstDecl())->OperatorDelete;
}
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == CXXDestructor; }
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// \brief Represents a C++ conversion function within a class.
///
/// For example:
///
/// \code
/// class X {
/// public:
/// operator bool();
/// };
/// \endcode
class CXXConversionDecl : public CXXMethodDecl {
void anchor() override;
/// Whether this conversion function declaration is marked
/// "explicit", meaning that it can only be applied when the user
/// explicitly wrote a cast. This is a C++0x feature.
bool IsExplicitSpecified : 1;
CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo *TInfo,
bool isInline, bool isExplicitSpecified,
bool isConstexpr, SourceLocation EndLocation)
: CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
SC_None, isInline, isConstexpr, EndLocation),
IsExplicitSpecified(isExplicitSpecified) { }
public:
static CXXConversionDecl *Create(ASTContext &C, CXXRecordDecl *RD,
SourceLocation StartLoc,
const DeclarationNameInfo &NameInfo,
QualType T, TypeSourceInfo *TInfo,
bool isInline, bool isExplicit,
bool isConstexpr,
SourceLocation EndLocation);
static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
/// Whether this conversion function declaration is marked
/// "explicit", meaning that it can only be used for direct initialization
/// (including explitly written casts). This is a C++11 feature.
bool isExplicitSpecified() const { return IsExplicitSpecified; }
/// \brief Whether this is an explicit conversion operator (C++11 and later).
///
/// Explicit conversion operators are only considered for direct
/// initialization, e.g., when the user has explicitly written a cast.
bool isExplicit() const {
return cast<CXXConversionDecl>(getFirstDecl())->isExplicitSpecified();
}
/// \brief Returns the type that this conversion function is converting to.
QualType getConversionType() const {
return getType()->getAs<FunctionType>()->getReturnType();
}
/// \brief Determine whether this conversion function is a conversion from
/// a lambda closure type to a block pointer.
bool isLambdaToBlockPointerConversion() const;
// Implement isa/cast/dyncast/etc.
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == CXXConversion; }
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// \brief Represents a linkage specification.
///
/// For example:
/// \code
/// extern "C" void foo();
/// \endcode
class LinkageSpecDecl : public Decl, public DeclContext {
virtual void anchor();
public:
/// \brief Represents the language in a linkage specification.
///
/// The values are part of the serialization ABI for
/// ASTs and cannot be changed without altering that ABI. To help
/// ensure a stable ABI for this, we choose the DW_LANG_ encodings
/// from the dwarf standard.
enum LanguageIDs {
lang_c = /* DW_LANG_C */ 0x0002,
lang_cxx = /* DW_LANG_C_plus_plus */ 0x0004
};
private:
/// \brief The language for this linkage specification.
unsigned Language : 3;
/// \brief True if this linkage spec has braces.
///
/// This is needed so that hasBraces() returns the correct result while the
/// linkage spec body is being parsed. Once RBraceLoc has been set this is
/// not used, so it doesn't need to be serialized.
unsigned HasBraces : 1;
/// \brief The source location for the extern keyword.
SourceLocation ExternLoc;
/// \brief The source location for the right brace (if valid).
SourceLocation RBraceLoc;
LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
SourceLocation LangLoc, LanguageIDs lang, bool HasBraces)
: Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),
Language(lang), HasBraces(HasBraces), ExternLoc(ExternLoc),
RBraceLoc(SourceLocation()) { }
public:
static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation ExternLoc,
SourceLocation LangLoc, LanguageIDs Lang,
bool HasBraces);
static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
/// \brief Return the language specified by this linkage specification.
LanguageIDs getLanguage() const { return LanguageIDs(Language); }
/// \brief Set the language specified by this linkage specification.
void setLanguage(LanguageIDs L) { Language = L; }
/// \brief Determines whether this linkage specification had braces in
/// its syntactic form.
bool hasBraces() const {
assert(!RBraceLoc.isValid() || HasBraces);
return HasBraces;
}
SourceLocation getExternLoc() const { return ExternLoc; }
SourceLocation getRBraceLoc() const { return RBraceLoc; }
void setExternLoc(SourceLocation L) { ExternLoc = L; }
void setRBraceLoc(SourceLocation L) {
RBraceLoc = L;
HasBraces = RBraceLoc.isValid();
}
SourceLocation getLocEnd() const LLVM_READONLY {
if (hasBraces())
return getRBraceLoc();
// No braces: get the end location of the (only) declaration in context
// (if present).
return decls_empty() ? getLocation() : decls_begin()->getLocEnd();
}
SourceRange getSourceRange() const override LLVM_READONLY {
return SourceRange(ExternLoc, getLocEnd());
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == LinkageSpec; }
static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
}
static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
}
};
/// \brief Represents C++ using-directive.
///
/// For example:
/// \code
/// using namespace std;
/// \endcode
///
/// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
/// artificial names for all using-directives in order to store
/// them in DeclContext effectively.
class UsingDirectiveDecl : public NamedDecl {
void anchor() override;
/// \brief The location of the \c using keyword.
SourceLocation UsingLoc;
/// \brief The location of the \c namespace keyword.
SourceLocation NamespaceLoc;
/// \brief The nested-name-specifier that precedes the namespace.
NestedNameSpecifierLoc QualifierLoc;
/// \brief The namespace nominated by this using-directive.
NamedDecl *NominatedNamespace;
/// Enclosing context containing both using-directive and nominated
/// namespace.
DeclContext *CommonAncestor;
/// \brief Returns special DeclarationName used by using-directives.
///
/// This is only used by DeclContext for storing UsingDirectiveDecls in
/// its lookup structure.
static DeclarationName getName() {
return DeclarationName::getUsingDirectiveName();
}
UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
SourceLocation NamespcLoc,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation IdentLoc,
NamedDecl *Nominated,
DeclContext *CommonAncestor)
: NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) { }
public:
/// \brief Retrieve the nested-name-specifier that qualifies the
/// name of the namespace, with source-location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the nested-name-specifier that qualifies the
/// name of the namespace.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
const NamedDecl *getNominatedNamespaceAsWritten() const {
return NominatedNamespace;
}
/// \brief Returns the namespace nominated by this using-directive.
NamespaceDecl *getNominatedNamespace();
const NamespaceDecl *getNominatedNamespace() const {
return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
}
/// \brief Returns the common ancestor context of this using-directive and
/// its nominated namespace.
DeclContext *getCommonAncestor() { return CommonAncestor; }
const DeclContext *getCommonAncestor() const { return CommonAncestor; }
/// \brief Return the location of the \c using keyword.
SourceLocation getUsingLoc() const { return UsingLoc; }
// FIXME: Could omit 'Key' in name.
/// \brief Returns the location of the \c namespace keyword.
SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
/// \brief Returns the location of this using declaration's identifier.
SourceLocation getIdentLocation() const { return getLocation(); }
static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation UsingLoc,
SourceLocation NamespaceLoc,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation IdentLoc,
NamedDecl *Nominated,
DeclContext *CommonAncestor);
static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
SourceRange getSourceRange() const override LLVM_READONLY {
return SourceRange(UsingLoc, getLocation());
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == UsingDirective; }
// Friend for getUsingDirectiveName.
friend class DeclContext;
friend class ASTDeclReader;
};
/// \brief Represents a C++ namespace alias.
///
/// For example:
///
/// \code
/// namespace Foo = Bar;
/// \endcode
class NamespaceAliasDecl : public NamedDecl,
public Redeclarable<NamespaceAliasDecl> {
void anchor() override;
/// \brief The location of the \c namespace keyword.
SourceLocation NamespaceLoc;
/// \brief The location of the namespace's identifier.
///
/// This is accessed by TargetNameLoc.
SourceLocation IdentLoc;
/// \brief The nested-name-specifier that precedes the namespace.
NestedNameSpecifierLoc QualifierLoc;
/// \brief The Decl that this alias points to, either a NamespaceDecl or
/// a NamespaceAliasDecl.
NamedDecl *Namespace;
NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
SourceLocation NamespaceLoc, SourceLocation AliasLoc,
IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
SourceLocation IdentLoc, NamedDecl *Namespace)
: NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
QualifierLoc(QualifierLoc), Namespace(Namespace) {}
typedef Redeclarable<NamespaceAliasDecl> redeclarable_base;
NamespaceAliasDecl *getNextRedeclarationImpl() override;
NamespaceAliasDecl *getPreviousDeclImpl() override;
NamespaceAliasDecl *getMostRecentDeclImpl() override;
friend class ASTDeclReader;
public:
static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation NamespaceLoc,
SourceLocation AliasLoc,
IdentifierInfo *Alias,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation IdentLoc,
NamedDecl *Namespace);
static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
typedef redeclarable_base::redecl_range redecl_range;
typedef redeclarable_base::redecl_iterator redecl_iterator;
using redeclarable_base::redecls_begin;
using redeclarable_base::redecls_end;
using redeclarable_base::redecls;
using redeclarable_base::getPreviousDecl;
using redeclarable_base::getMostRecentDecl;
NamespaceAliasDecl *getCanonicalDecl() override {
return getFirstDecl();
}
const NamespaceAliasDecl *getCanonicalDecl() const {
return getFirstDecl();
}
/// \brief Retrieve the nested-name-specifier that qualifies the
/// name of the namespace, with source-location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the nested-name-specifier that qualifies the
/// name of the namespace.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
/// \brief Retrieve the namespace declaration aliased by this directive.
NamespaceDecl *getNamespace() {
if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
return AD->getNamespace();
return cast<NamespaceDecl>(Namespace);
}
const NamespaceDecl *getNamespace() const {
return const_cast<NamespaceAliasDecl*>(this)->getNamespace();
}
/// Returns the location of the alias name, i.e. 'foo' in
/// "namespace foo = ns::bar;".
SourceLocation getAliasLoc() const { return getLocation(); }
/// Returns the location of the \c namespace keyword.
SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
/// Returns the location of the identifier in the named namespace.
SourceLocation getTargetNameLoc() const { return IdentLoc; }
/// \brief Retrieve the namespace that this alias refers to, which
/// may either be a NamespaceDecl or a NamespaceAliasDecl.
NamedDecl *getAliasedNamespace() const { return Namespace; }
SourceRange getSourceRange() const override LLVM_READONLY {
return SourceRange(NamespaceLoc, IdentLoc);
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == NamespaceAlias; }
};
/// \brief Represents a shadow declaration introduced into a scope by a
/// (resolved) using declaration.
///
/// For example,
/// \code
/// namespace A {
/// void foo();
/// }
/// namespace B {
/// using A::foo; // <- a UsingDecl
/// // Also creates a UsingShadowDecl for A::foo() in B
/// }
/// \endcode
class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
void anchor() override;
/// The referenced declaration.
NamedDecl *Underlying;
/// \brief The using declaration which introduced this decl or the next using
/// shadow declaration contained in the aforementioned using declaration.
NamedDecl *UsingOrNextShadow;
friend class UsingDecl;
UsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
UsingDecl *Using, NamedDecl *Target)
: NamedDecl(UsingShadow, DC, Loc, DeclarationName()),
redeclarable_base(C), Underlying(Target),
UsingOrNextShadow(reinterpret_cast<NamedDecl *>(Using)) {
if (Target) {
setDeclName(Target->getDeclName());
IdentifierNamespace = Target->getIdentifierNamespace();
}
setImplicit();
}
typedef Redeclarable<UsingShadowDecl> redeclarable_base;
UsingShadowDecl *getNextRedeclarationImpl() override {
return getNextRedeclaration();
}
UsingShadowDecl *getPreviousDeclImpl() override {
return getPreviousDecl();
}
UsingShadowDecl *getMostRecentDeclImpl() override {
return getMostRecentDecl();
}
public:
static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation Loc, UsingDecl *Using,
NamedDecl *Target) {
return new (C, DC) UsingShadowDecl(C, DC, Loc, Using, Target);
}
static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
typedef redeclarable_base::redecl_range redecl_range;
typedef redeclarable_base::redecl_iterator redecl_iterator;
using redeclarable_base::redecls_begin;
using redeclarable_base::redecls_end;
using redeclarable_base::redecls;
using redeclarable_base::getPreviousDecl;
using redeclarable_base::getMostRecentDecl;
UsingShadowDecl *getCanonicalDecl() override {
return getFirstDecl();
}
const UsingShadowDecl *getCanonicalDecl() const {
return getFirstDecl();
}
/// \brief Gets the underlying declaration which has been brought into the
/// local scope.
NamedDecl *getTargetDecl() const { return Underlying; }
/// \brief Sets the underlying declaration which has been brought into the
/// local scope.
void setTargetDecl(NamedDecl* ND) {
assert(ND && "Target decl is null!");
Underlying = ND;
IdentifierNamespace = ND->getIdentifierNamespace();
}
/// \brief Gets the using declaration to which this declaration is tied.
UsingDecl *getUsingDecl() const;
/// \brief The next using shadow declaration contained in the shadow decl
/// chain of the using declaration which introduced this decl.
UsingShadowDecl *getNextUsingShadowDecl() const {
return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Decl::UsingShadow; }
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// \brief Represents a C++ using-declaration.
///
/// For example:
/// \code
/// using someNameSpace::someIdentifier;
/// \endcode
class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> {
void anchor() override;
/// \brief The source location of the 'using' keyword itself.
SourceLocation UsingLocation;
/// \brief The nested-name-specifier that precedes the name.
NestedNameSpecifierLoc QualifierLoc;
/// \brief Provides source/type location info for the declaration name
/// embedded in the ValueDecl base class.
DeclarationNameLoc DNLoc;
/// \brief The first shadow declaration of the shadow decl chain associated
/// with this using declaration.
///
/// The bool member of the pair store whether this decl has the \c typename
/// keyword.
llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
UsingDecl(DeclContext *DC, SourceLocation UL,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
: NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
UsingLocation(UL), QualifierLoc(QualifierLoc),
DNLoc(NameInfo.getInfo()), FirstUsingShadow(nullptr, HasTypenameKeyword) {
}
public:
/// \brief Return the source location of the 'using' keyword.
SourceLocation getUsingLoc() const { return UsingLocation; }
/// \brief Set the source location of the 'using' keyword.
void setUsingLoc(SourceLocation L) { UsingLocation = L; }
/// \brief Retrieve the nested-name-specifier that qualifies the name,
/// with source-location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the nested-name-specifier that qualifies the name.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
DeclarationNameInfo getNameInfo() const {
return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
}
/// \brief Return true if it is a C++03 access declaration (no 'using').
bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
/// \brief Return true if the using declaration has 'typename'.
bool hasTypename() const { return FirstUsingShadow.getInt(); }
/// \brief Sets whether the using declaration has 'typename'.
void setTypename(bool TN) { FirstUsingShadow.setInt(TN); }
/// \brief Iterates through the using shadow declarations associated with
/// this using declaration.
class shadow_iterator {
/// \brief The current using shadow declaration.
UsingShadowDecl *Current;
public:
typedef UsingShadowDecl* value_type;
typedef UsingShadowDecl* reference;
typedef UsingShadowDecl* pointer;
typedef std::forward_iterator_tag iterator_category;
typedef std::ptrdiff_t difference_type;
shadow_iterator() : Current(nullptr) { }
explicit shadow_iterator(UsingShadowDecl *C) : Current(C) { }
reference operator*() const { return Current; }
pointer operator->() const { return Current; }
shadow_iterator& operator++() {
Current = Current->getNextUsingShadowDecl();
return *this;
}
shadow_iterator operator++(int) {
shadow_iterator tmp(*this);
++(*this);
return tmp;
}
friend bool operator==(shadow_iterator x, shadow_iterator y) {
return x.Current == y.Current;
}
friend bool operator!=(shadow_iterator x, shadow_iterator y) {
return x.Current != y.Current;
}
};
typedef llvm::iterator_range<shadow_iterator> shadow_range;
shadow_range shadows() const {
return shadow_range(shadow_begin(), shadow_end());
}
shadow_iterator shadow_begin() const {
return shadow_iterator(FirstUsingShadow.getPointer());
}
shadow_iterator shadow_end() const { return shadow_iterator(); }
/// \brief Return the number of shadowed declarations associated with this
/// using declaration.
unsigned shadow_size() const {
return std::distance(shadow_begin(), shadow_end());
}
void addShadowDecl(UsingShadowDecl *S);
void removeShadowDecl(UsingShadowDecl *S);
static UsingDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation UsingL,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo,
bool HasTypenameKeyword);
static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
SourceRange getSourceRange() const override LLVM_READONLY;
/// Retrieves the canonical declaration of this declaration.
UsingDecl *getCanonicalDecl() override { return getFirstDecl(); }
const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); }
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == Using; }
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// \brief Represents a dependent using declaration which was not marked with
/// \c typename.
///
/// Unlike non-dependent using declarations, these *only* bring through
/// non-types; otherwise they would break two-phase lookup.
///
/// \code
/// template \<class T> class A : public Base<T> {
/// using Base<T>::foo;
/// };
/// \endcode
class UnresolvedUsingValueDecl : public ValueDecl,
public Mergeable<UnresolvedUsingValueDecl> {
void anchor() override;
/// \brief The source location of the 'using' keyword
SourceLocation UsingLocation;
/// \brief The nested-name-specifier that precedes the name.
NestedNameSpecifierLoc QualifierLoc;
/// \brief Provides source/type location info for the declaration name
/// embedded in the ValueDecl base class.
DeclarationNameLoc DNLoc;
UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
SourceLocation UsingLoc,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo)
: ValueDecl(UnresolvedUsingValue, DC,
NameInfo.getLoc(), NameInfo.getName(), Ty),
UsingLocation(UsingLoc), QualifierLoc(QualifierLoc),
DNLoc(NameInfo.getInfo())
{ }
public:
/// \brief Returns the source location of the 'using' keyword.
SourceLocation getUsingLoc() const { return UsingLocation; }
/// \brief Set the source location of the 'using' keyword.
void setUsingLoc(SourceLocation L) { UsingLocation = L; }
/// \brief Return true if it is a C++03 access declaration (no 'using').
bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
/// \brief Retrieve the nested-name-specifier that qualifies the name,
/// with source-location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the nested-name-specifier that qualifies the name.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
DeclarationNameInfo getNameInfo() const {
return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
}
static UnresolvedUsingValueDecl *
Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo);
static UnresolvedUsingValueDecl *
CreateDeserialized(ASTContext &C, unsigned ID);
SourceRange getSourceRange() const override LLVM_READONLY;
/// Retrieves the canonical declaration of this declaration.
UnresolvedUsingValueDecl *getCanonicalDecl() override {
return getFirstDecl();
}
const UnresolvedUsingValueDecl *getCanonicalDecl() const {
return getFirstDecl();
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// \brief Represents a dependent using declaration which was marked with
/// \c typename.
///
/// \code
/// template \<class T> class A : public Base<T> {
/// using typename Base<T>::foo;
/// };
/// \endcode
///
/// The type associated with an unresolved using typename decl is
/// currently always a typename type.
class UnresolvedUsingTypenameDecl
: public TypeDecl,
public Mergeable<UnresolvedUsingTypenameDecl> {
void anchor() override;
/// \brief The source location of the 'typename' keyword
SourceLocation TypenameLocation;
/// \brief The nested-name-specifier that precedes the name.
NestedNameSpecifierLoc QualifierLoc;
UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
SourceLocation TypenameLoc,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TargetNameLoc,
IdentifierInfo *TargetName)
: TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
UsingLoc),
TypenameLocation(TypenameLoc), QualifierLoc(QualifierLoc) { }
friend class ASTDeclReader;
public:
/// \brief Returns the source location of the 'using' keyword.
SourceLocation getUsingLoc() const { return getLocStart(); }
/// \brief Returns the source location of the 'typename' keyword.
SourceLocation getTypenameLoc() const { return TypenameLocation; }
/// \brief Retrieve the nested-name-specifier that qualifies the name,
/// with source-location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the nested-name-specifier that qualifies the name.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
static UnresolvedUsingTypenameDecl *
Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
SourceLocation TargetNameLoc, DeclarationName TargetName);
static UnresolvedUsingTypenameDecl *
CreateDeserialized(ASTContext &C, unsigned ID);
/// Retrieves the canonical declaration of this declaration.
UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
return getFirstDecl();
}
const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
return getFirstDecl();
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
};
/// \brief Represents a C++11 static_assert declaration.
class StaticAssertDecl : public Decl {
virtual void anchor();
llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed;
StringLiteral *Message;
SourceLocation RParenLoc;
StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc,
Expr *AssertExpr, StringLiteral *Message,
SourceLocation RParenLoc, bool Failed)
: Decl(StaticAssert, DC, StaticAssertLoc),
AssertExprAndFailed(AssertExpr, Failed), Message(Message),
RParenLoc(RParenLoc) { }
public:
static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation StaticAssertLoc,
Expr *AssertExpr, StringLiteral *Message,
SourceLocation RParenLoc, bool Failed);
static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID);
Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); }
const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); }
StringLiteral *getMessage() { return Message; }
const StringLiteral *getMessage() const { return Message; }
bool isFailed() const { return AssertExprAndFailed.getInt(); }
SourceLocation getRParenLoc() const { return RParenLoc; }
SourceRange getSourceRange() const override LLVM_READONLY {
return SourceRange(getLocation(), getRParenLoc());
}
static bool classof(const Decl *D) { return classofKind(D->getKind()); }
static bool classofKind(Kind K) { return K == StaticAssert; }
friend class ASTDeclReader;
};
/// An instance of this class represents the declaration of a property
/// member. This is a Microsoft extension to C++, first introduced in
/// Visual Studio .NET 2003 as a parallel to similar features in C#
/// and Managed C++.
///
/// A property must always be a non-static class member.
///
/// A property member superficially resembles a non-static data
/// member, except preceded by a property attribute:
/// __declspec(property(get=GetX, put=PutX)) int x;
/// Either (but not both) of the 'get' and 'put' names may be omitted.
///
/// A reference to a property is always an lvalue. If the lvalue
/// undergoes lvalue-to-rvalue conversion, then a getter name is
/// required, and that member is called with no arguments.
/// If the lvalue is assigned into, then a setter name is required,
/// and that member is called with one argument, the value assigned.
/// Both operations are potentially overloaded. Compound assignments
/// are permitted, as are the increment and decrement operators.
///
/// The getter and putter methods are permitted to be overloaded,
/// although their return and parameter types are subject to certain
/// restrictions according to the type of the property.
///
/// A property declared using an incomplete array type may
/// additionally be subscripted, adding extra parameters to the getter
/// and putter methods.
class MSPropertyDecl : public DeclaratorDecl {
IdentifierInfo *GetterId, *SetterId;
MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N,
QualType T, TypeSourceInfo *TInfo, SourceLocation StartL,
IdentifierInfo *Getter, IdentifierInfo *Setter)
: DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL),
GetterId(Getter), SetterId(Setter) {}
public:
static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC,
SourceLocation L, DeclarationName N, QualType T,
TypeSourceInfo *TInfo, SourceLocation StartL,
IdentifierInfo *Getter, IdentifierInfo *Setter);
static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
static bool classof(const Decl *D) { return D->getKind() == MSProperty; }
bool hasGetter() const { return GetterId != nullptr; }
IdentifierInfo* getGetterId() const { return GetterId; }
bool hasSetter() const { return SetterId != nullptr; }
IdentifierInfo* getSetterId() const { return SetterId; }
friend class ASTDeclReader;
};
/// Insertion operator for diagnostics. This allows sending an AccessSpecifier
/// into a diagnostic with <<.
const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
AccessSpecifier AS);
const PartialDiagnostic &operator<<(const PartialDiagnostic &DB,
AccessSpecifier AS);
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/AST/Redeclarable.h | //===-- Redeclarable.h - Base for Decls that can be redeclared -*- 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 Redeclarable interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_REDECLARABLE_H
#define LLVM_CLANG_AST_REDECLARABLE_H
#include "clang/AST/ExternalASTSource.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/Support/Casting.h"
#include <iterator>
namespace clang {
/// \brief Provides common interface for the Decls that can be redeclared.
template<typename decl_type>
class Redeclarable {
protected:
class DeclLink {
/// A pointer to a known latest declaration, either statically known or
/// generationally updated as decls are added by an external source.
typedef LazyGenerationalUpdatePtr<const Decl*, Decl*,
&ExternalASTSource::CompleteRedeclChain>
KnownLatest;
typedef const ASTContext *UninitializedLatest;
typedef Decl *Previous;
/// A pointer to either an uninitialized latest declaration (where either
/// we've not yet set the previous decl or there isn't one), or to a known
/// previous declaration.
typedef llvm::PointerUnion<Previous, UninitializedLatest> NotKnownLatest;
mutable llvm::PointerUnion<NotKnownLatest, KnownLatest> Next;
public:
enum PreviousTag { PreviousLink };
enum LatestTag { LatestLink };
DeclLink(LatestTag, const ASTContext &Ctx)
: Next(NotKnownLatest(&Ctx)) {}
DeclLink(PreviousTag, decl_type *D)
: Next(NotKnownLatest(Previous(D))) {}
bool NextIsPrevious() const {
return Next.is<NotKnownLatest>() &&
// FIXME: 'template' is required on the next line due to an
// apparent clang bug.
Next.get<NotKnownLatest>().template is<Previous>();
}
bool NextIsLatest() const { return !NextIsPrevious(); }
decl_type *getNext(const decl_type *D) const {
if (Next.is<NotKnownLatest>()) {
NotKnownLatest NKL = Next.get<NotKnownLatest>();
if (NKL.is<Previous>())
return static_cast<decl_type*>(NKL.get<Previous>());
// Allocate the generational 'most recent' cache now, if needed.
Next = KnownLatest(*NKL.get<UninitializedLatest>(),
const_cast<decl_type *>(D));
}
return static_cast<decl_type*>(Next.get<KnownLatest>().get(D));
}
void setPrevious(decl_type *D) {
assert(NextIsPrevious() && "decl became non-canonical unexpectedly");
Next = Previous(D);
}
void setLatest(decl_type *D) {
assert(NextIsLatest() && "decl became canonical unexpectedly");
if (Next.is<NotKnownLatest>()) {
NotKnownLatest NKL = Next.get<NotKnownLatest>();
Next = KnownLatest(*NKL.get<UninitializedLatest>(), D);
} else {
auto Latest = Next.get<KnownLatest>();
Latest.set(D);
Next = Latest;
}
}
void markIncomplete() { Next.get<KnownLatest>().markIncomplete(); }
Decl *getLatestNotUpdated() const {
assert(NextIsLatest() && "expected a canonical decl");
if (Next.is<NotKnownLatest>())
return nullptr;
return Next.get<KnownLatest>().getNotUpdated();
}
};
static DeclLink PreviousDeclLink(decl_type *D) {
return DeclLink(DeclLink::PreviousLink, D);
}
static DeclLink LatestDeclLink(const ASTContext &Ctx) {
return DeclLink(DeclLink::LatestLink, Ctx);
}
/// \brief Points to the next redeclaration in the chain.
///
/// If NextIsPrevious() is true, this is a link to the previous declaration
/// of this same Decl. If NextIsLatest() is true, this is the first
/// declaration and Link points to the latest declaration. For example:
///
/// #1 int f(int x, int y = 1); // <pointer to #3, true>
/// #2 int f(int x = 0, int y); // <pointer to #1, false>
/// #3 int f(int x, int y) { return x + y; } // <pointer to #2, false>
///
/// If there is only one declaration, it is <pointer to self, true>
DeclLink RedeclLink;
decl_type *First;
decl_type *getNextRedeclaration() const {
return RedeclLink.getNext(static_cast<const decl_type *>(this));
}
public:
Redeclarable(const ASTContext &Ctx)
: RedeclLink(LatestDeclLink(Ctx)), First(static_cast<decl_type *>(this)) {}
/// \brief Return the previous declaration of this declaration or NULL if this
/// is the first declaration.
decl_type *getPreviousDecl() {
if (RedeclLink.NextIsPrevious())
return getNextRedeclaration();
return nullptr;
}
const decl_type *getPreviousDecl() const {
return const_cast<decl_type *>(
static_cast<const decl_type*>(this))->getPreviousDecl();
}
/// \brief Return the first declaration of this declaration or itself if this
/// is the only declaration.
decl_type *getFirstDecl() { return First; }
/// \brief Return the first declaration of this declaration or itself if this
/// is the only declaration.
const decl_type *getFirstDecl() const { return First; }
/// \brief True if this is the first declaration in its redeclaration chain.
bool isFirstDecl() const { return RedeclLink.NextIsLatest(); }
/// \brief Returns the most recent (re)declaration of this declaration.
decl_type *getMostRecentDecl() {
return getFirstDecl()->getNextRedeclaration();
}
/// \brief Returns the most recent (re)declaration of this declaration.
const decl_type *getMostRecentDecl() const {
return getFirstDecl()->getNextRedeclaration();
}
/// \brief Set the previous declaration. If PrevDecl is NULL, set this as the
/// first and only declaration.
void setPreviousDecl(decl_type *PrevDecl);
/// \brief Iterates through all the redeclarations of the same decl.
class redecl_iterator {
/// Current - The current declaration.
decl_type *Current;
decl_type *Starter;
bool PassedFirst;
public:
typedef decl_type* value_type;
typedef decl_type* reference;
typedef decl_type* pointer;
typedef std::forward_iterator_tag iterator_category;
typedef std::ptrdiff_t difference_type;
redecl_iterator() : Current(nullptr) { }
explicit redecl_iterator(decl_type *C)
: Current(C), Starter(C), PassedFirst(false) { }
reference operator*() const { return Current; }
pointer operator->() const { return Current; }
redecl_iterator& operator++() {
assert(Current && "Advancing while iterator has reached end");
// Sanity check to avoid infinite loop on invalid redecl chain.
if (Current->isFirstDecl()) {
if (PassedFirst) {
assert(0 && "Passed first decl twice, invalid redecl chain!");
Current = nullptr;
return *this;
}
PassedFirst = true;
}
// Get either previous decl or latest decl.
decl_type *Next = Current->getNextRedeclaration();
Current = (Next != Starter) ? Next : nullptr;
return *this;
}
redecl_iterator operator++(int) {
redecl_iterator tmp(*this);
++(*this);
return tmp;
}
friend bool operator==(redecl_iterator x, redecl_iterator y) {
return x.Current == y.Current;
}
friend bool operator!=(redecl_iterator x, redecl_iterator y) {
return x.Current != y.Current;
}
};
typedef llvm::iterator_range<redecl_iterator> redecl_range;
/// \brief Returns an iterator range for all the redeclarations of the same
/// decl. It will iterate at least once (when this decl is the only one).
redecl_range redecls() const {
return redecl_range(redecl_iterator(const_cast<decl_type *>(
static_cast<const decl_type *>(this))),
redecl_iterator());
}
redecl_iterator redecls_begin() const { return redecls().begin(); }
redecl_iterator redecls_end() const { return redecls().end(); }
friend class ASTDeclReader;
friend class ASTDeclWriter;
};
/// \brief Get the primary declaration for a declaration from an AST file. That
/// will be the first-loaded declaration.
Decl *getPrimaryMergedDecl(Decl *D);
/// \brief Provides common interface for the Decls that cannot be redeclared,
/// but can be merged if the same declaration is brought in from multiple
/// modules.
template<typename decl_type>
class Mergeable {
public:
Mergeable() {}
/// \brief Return the first declaration of this declaration or itself if this
/// is the only declaration.
decl_type *getFirstDecl() {
decl_type *D = static_cast<decl_type*>(this);
if (!D->isFromASTFile())
return D;
return cast<decl_type>(getPrimaryMergedDecl(const_cast<decl_type*>(D)));
}
/// \brief Return the first declaration of this declaration or itself if this
/// is the only declaration.
const decl_type *getFirstDecl() const {
const decl_type *D = static_cast<const decl_type*>(this);
if (!D->isFromASTFile())
return D;
return cast<decl_type>(getPrimaryMergedDecl(const_cast<decl_type*>(D)));
}
/// \brief Returns true if this is the first declaration.
bool isFirstDecl() const { return getFirstDecl() == this; }
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Index/USRGeneration.h | //===- USRGeneration.h - Routines for USR generation ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_INDEX_USRGENERATION_H
#define LLVM_CLANG_INDEX_USRGENERATION_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/StringRef.h"
namespace clang {
class Decl;
class MacroDefinitionRecord;
class SourceManager;
namespace index {
static inline StringRef getUSRSpacePrefix() {
return "c:";
}
/// \brief Generate a USR for a Decl, including the USR prefix.
/// \returns true if the results should be ignored, false otherwise.
bool generateUSRForDecl(const Decl *D, SmallVectorImpl<char> &Buf);
/// \brief Generate a USR fragment for an Objective-C class.
void generateUSRForObjCClass(StringRef Cls, raw_ostream &OS);
/// \brief Generate a USR fragment for an Objective-C class category.
void generateUSRForObjCCategory(StringRef Cls, StringRef Cat, raw_ostream &OS);
/// \brief 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 generateUSRForObjCIvar(StringRef Ivar, raw_ostream &OS);
/// \brief Generate a USR fragment for an Objective-C method.
void generateUSRForObjCMethod(StringRef Sel, bool IsInstanceMethod,
raw_ostream &OS);
/// \brief Generate a USR fragment for an Objective-C property.
void generateUSRForObjCProperty(StringRef Prop, raw_ostream &OS);
/// \brief Generate a USR fragment for an Objective-C protocol.
void generateUSRForObjCProtocol(StringRef Prot, raw_ostream &OS);
/// \brief Generate a USR for a macro, including the USR prefix.
///
/// \returns true on error, false on success.
bool generateUSRForMacro(const MacroDefinitionRecord *MD,
const SourceManager &SM, SmallVectorImpl<char> &Buf);
} // namespace index
} // namespace clang
#endif // LLVM_CLANG_IDE_USRGENERATION_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Index/CommentToXML.h | //===--- CommentToXML.h - Convert comments to XML representation ----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_INDEX_COMMENTTOXML_H
#define LLVM_CLANG_INDEX_COMMENTTOXML_H
#include "clang/Basic/LLVM.h"
#include <memory>
namespace clang {
class ASTContext;
namespace comments {
class FullComment;
class HTMLTagComment;
}
namespace index {
class SimpleFormatContext;
class CommentToXMLConverter {
std::unique_ptr<SimpleFormatContext> FormatContext;
unsigned FormatInMemoryUniqueId;
public:
CommentToXMLConverter();
~CommentToXMLConverter();
void convertCommentToHTML(const comments::FullComment *FC,
SmallVectorImpl<char> &HTML,
const ASTContext &Context);
void convertHTMLTagNodeToText(const comments::HTMLTagComment *HTC,
SmallVectorImpl<char> &Text,
const ASTContext &Context);
void convertCommentToXML(const comments::FullComment *FC,
SmallVectorImpl<char> &XML,
const ASTContext &Context);
};
} // namespace index
} // namespace clang
#endif // LLVM_CLANG_INDEX_COMMENTTOXML_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/CodeInjector.h | //===-- CodeInjector.h ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Defines the clang::CodeInjector interface which is responsible for
/// injecting AST of function definitions that may not be available in the
/// original source.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_CODEINJECTOR_H
#define LLVM_CLANG_ANALYSIS_CODEINJECTOR_H
namespace clang {
class Stmt;
class FunctionDecl;
class ObjCMethodDecl;
/// \brief CodeInjector is an interface which is responsible for injecting AST
/// of function definitions that may not be available in the original source.
///
/// The getBody function will be called each time the static analyzer examines a
/// function call that has no definition available in the current translation
/// unit. If the returned statement is not a null pointer, it is assumed to be
/// the body of a function which will be used for the analysis. The source of
/// the body can be arbitrary, but it is advised to use memoization to avoid
/// unnecessary reparsing of the external source that provides the body of the
/// functions.
class CodeInjector {
public:
CodeInjector();
virtual ~CodeInjector();
virtual Stmt *getBody(const FunctionDecl *D) = 0;
virtual Stmt *getBody(const ObjCMethodDecl *D) = 0;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/ProgramPoint.h | //==- ProgramPoint.h - Program Points for Path-Sensitive Analysis --*- 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 interface ProgramPoint, which identifies a
// distinct location in a function.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_PROGRAMPOINT_H
#define LLVM_CLANG_ANALYSIS_PROGRAMPOINT_H
#include "clang/Analysis/AnalysisContext.h"
#include "clang/Analysis/CFG.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/DataTypes.h"
#include <cassert>
#include <string>
#include <utility>
namespace clang {
class AnalysisDeclContext;
class FunctionDecl;
class LocationContext;
class ProgramPointTag;
class ProgramPoint {
public:
enum Kind { BlockEdgeKind,
BlockEntranceKind,
BlockExitKind,
PreStmtKind,
PreStmtPurgeDeadSymbolsKind,
PostStmtPurgeDeadSymbolsKind,
PostStmtKind,
PreLoadKind,
PostLoadKind,
PreStoreKind,
PostStoreKind,
PostConditionKind,
PostLValueKind,
MinPostStmtKind = PostStmtKind,
MaxPostStmtKind = PostLValueKind,
PostInitializerKind,
CallEnterKind,
CallExitBeginKind,
CallExitEndKind,
PreImplicitCallKind,
PostImplicitCallKind,
MinImplicitCallKind = PreImplicitCallKind,
MaxImplicitCallKind = PostImplicitCallKind,
EpsilonKind};
private:
const void *Data1;
llvm::PointerIntPair<const void *, 2, unsigned> Data2;
// The LocationContext could be NULL to allow ProgramPoint to be used in
// context insensitive analysis.
llvm::PointerIntPair<const LocationContext *, 2, unsigned> L;
llvm::PointerIntPair<const ProgramPointTag *, 2, unsigned> Tag;
protected:
ProgramPoint() {}
ProgramPoint(const void *P,
Kind k,
const LocationContext *l,
const ProgramPointTag *tag = nullptr)
: Data1(P),
Data2(nullptr, (((unsigned) k) >> 0) & 0x3),
L(l, (((unsigned) k) >> 2) & 0x3),
Tag(tag, (((unsigned) k) >> 4) & 0x3) {
assert(getKind() == k);
assert(getLocationContext() == l);
assert(getData1() == P);
}
ProgramPoint(const void *P1,
const void *P2,
Kind k,
const LocationContext *l,
const ProgramPointTag *tag = nullptr)
: Data1(P1),
Data2(P2, (((unsigned) k) >> 0) & 0x3),
L(l, (((unsigned) k) >> 2) & 0x3),
Tag(tag, (((unsigned) k) >> 4) & 0x3) {}
protected:
const void *getData1() const { return Data1; }
const void *getData2() const { return Data2.getPointer(); }
void setData2(const void *d) { Data2.setPointer(d); }
public:
/// Create a new ProgramPoint object that is the same as the original
/// except for using the specified tag value.
ProgramPoint withTag(const ProgramPointTag *tag) const {
return ProgramPoint(getData1(), getData2(), getKind(),
getLocationContext(), tag);
}
/// \brief Convert to the specified ProgramPoint type, asserting that this
/// ProgramPoint is of the desired type.
template<typename T>
T castAs() const {
assert(T::isKind(*this));
T t;
ProgramPoint& PP = t;
PP = *this;
return t;
}
/// \brief Convert to the specified ProgramPoint type, returning None if this
/// ProgramPoint is not of the desired type.
template<typename T>
Optional<T> getAs() const {
if (!T::isKind(*this))
return None;
T t;
ProgramPoint& PP = t;
PP = *this;
return t;
}
Kind getKind() const {
unsigned x = Tag.getInt();
x <<= 2;
x |= L.getInt();
x <<= 2;
x |= Data2.getInt();
return (Kind) x;
}
/// \brief Is this a program point corresponding to purge/removal of dead
/// symbols and bindings.
bool isPurgeKind() {
Kind K = getKind();
return (K == PostStmtPurgeDeadSymbolsKind ||
K == PreStmtPurgeDeadSymbolsKind);
}
const ProgramPointTag *getTag() const { return Tag.getPointer(); }
const LocationContext *getLocationContext() const {
return L.getPointer();
}
// For use with DenseMap. This hash is probably slow.
unsigned getHashValue() const {
llvm::FoldingSetNodeID ID;
Profile(ID);
return ID.ComputeHash();
}
bool operator==(const ProgramPoint & RHS) const {
return Data1 == RHS.Data1 &&
Data2 == RHS.Data2 &&
L == RHS.L &&
Tag == RHS.Tag;
}
bool operator!=(const ProgramPoint &RHS) const {
return Data1 != RHS.Data1 ||
Data2 != RHS.Data2 ||
L != RHS.L ||
Tag != RHS.Tag;
}
void Profile(llvm::FoldingSetNodeID& ID) const {
ID.AddInteger((unsigned) getKind());
ID.AddPointer(getData1());
ID.AddPointer(getData2());
ID.AddPointer(getLocationContext());
ID.AddPointer(getTag());
}
static ProgramPoint getProgramPoint(const Stmt *S, ProgramPoint::Kind K,
const LocationContext *LC,
const ProgramPointTag *tag);
};
class BlockEntrance : public ProgramPoint {
public:
BlockEntrance(const CFGBlock *B, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: ProgramPoint(B, BlockEntranceKind, L, tag) {
assert(B && "BlockEntrance requires non-null block");
}
const CFGBlock *getBlock() const {
return reinterpret_cast<const CFGBlock*>(getData1());
}
Optional<CFGElement> getFirstElement() const {
const CFGBlock *B = getBlock();
return B->empty() ? Optional<CFGElement>() : B->front();
}
private:
friend class ProgramPoint;
BlockEntrance() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == BlockEntranceKind;
}
};
class BlockExit : public ProgramPoint {
public:
BlockExit(const CFGBlock *B, const LocationContext *L)
: ProgramPoint(B, BlockExitKind, L) {}
const CFGBlock *getBlock() const {
return reinterpret_cast<const CFGBlock*>(getData1());
}
const Stmt *getTerminator() const {
return getBlock()->getTerminator();
}
private:
friend class ProgramPoint;
BlockExit() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == BlockExitKind;
}
};
class StmtPoint : public ProgramPoint {
public:
StmtPoint(const Stmt *S, const void *p2, Kind k, const LocationContext *L,
const ProgramPointTag *tag)
: ProgramPoint(S, p2, k, L, tag) {
assert(S);
}
const Stmt *getStmt() const { return (const Stmt*) getData1(); }
template <typename T>
const T* getStmtAs() const { return dyn_cast<T>(getStmt()); }
protected:
StmtPoint() {}
private:
friend class ProgramPoint;
static bool isKind(const ProgramPoint &Location) {
unsigned k = Location.getKind();
return k >= PreStmtKind && k <= MaxPostStmtKind;
}
};
class PreStmt : public StmtPoint {
public:
PreStmt(const Stmt *S, const LocationContext *L, const ProgramPointTag *tag,
const Stmt *SubStmt = nullptr)
: StmtPoint(S, SubStmt, PreStmtKind, L, tag) {}
const Stmt *getSubStmt() const { return (const Stmt*) getData2(); }
private:
friend class ProgramPoint;
PreStmt() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == PreStmtKind;
}
};
class PostStmt : public StmtPoint {
protected:
PostStmt() {}
PostStmt(const Stmt *S, const void *data, Kind k, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: StmtPoint(S, data, k, L, tag) {}
public:
explicit PostStmt(const Stmt *S, Kind k, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: StmtPoint(S, nullptr, k, L, tag) {}
explicit PostStmt(const Stmt *S, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: StmtPoint(S, nullptr, PostStmtKind, L, tag) {}
private:
friend class ProgramPoint;
static bool isKind(const ProgramPoint &Location) {
unsigned k = Location.getKind();
return k >= MinPostStmtKind && k <= MaxPostStmtKind;
}
};
// PostCondition represents the post program point of a branch condition.
class PostCondition : public PostStmt {
public:
PostCondition(const Stmt *S, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: PostStmt(S, PostConditionKind, L, tag) {}
private:
friend class ProgramPoint;
PostCondition() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == PostConditionKind;
}
};
class LocationCheck : public StmtPoint {
protected:
LocationCheck() {}
LocationCheck(const Stmt *S, const LocationContext *L,
ProgramPoint::Kind K, const ProgramPointTag *tag)
: StmtPoint(S, nullptr, K, L, tag) {}
private:
friend class ProgramPoint;
static bool isKind(const ProgramPoint &location) {
unsigned k = location.getKind();
return k == PreLoadKind || k == PreStoreKind;
}
};
class PreLoad : public LocationCheck {
public:
PreLoad(const Stmt *S, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: LocationCheck(S, L, PreLoadKind, tag) {}
private:
friend class ProgramPoint;
PreLoad() {}
static bool isKind(const ProgramPoint &location) {
return location.getKind() == PreLoadKind;
}
};
class PreStore : public LocationCheck {
public:
PreStore(const Stmt *S, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: LocationCheck(S, L, PreStoreKind, tag) {}
private:
friend class ProgramPoint;
PreStore() {}
static bool isKind(const ProgramPoint &location) {
return location.getKind() == PreStoreKind;
}
};
class PostLoad : public PostStmt {
public:
PostLoad(const Stmt *S, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: PostStmt(S, PostLoadKind, L, tag) {}
private:
friend class ProgramPoint;
PostLoad() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == PostLoadKind;
}
};
/// \brief Represents a program point after a store evaluation.
class PostStore : public PostStmt {
public:
/// Construct the post store point.
/// \param Loc can be used to store the information about the location
/// used in the form it was uttered in the code.
PostStore(const Stmt *S, const LocationContext *L, const void *Loc,
const ProgramPointTag *tag = nullptr)
: PostStmt(S, PostStoreKind, L, tag) {
assert(getData2() == nullptr);
setData2(Loc);
}
/// \brief Returns the information about the location used in the store,
/// how it was uttered in the code.
const void *getLocationValue() const {
return getData2();
}
private:
friend class ProgramPoint;
PostStore() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == PostStoreKind;
}
};
class PostLValue : public PostStmt {
public:
PostLValue(const Stmt *S, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: PostStmt(S, PostLValueKind, L, tag) {}
private:
friend class ProgramPoint;
PostLValue() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == PostLValueKind;
}
};
/// Represents a point after we ran remove dead bindings BEFORE
/// processing the given statement.
class PreStmtPurgeDeadSymbols : public StmtPoint {
public:
PreStmtPurgeDeadSymbols(const Stmt *S, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: StmtPoint(S, nullptr, PreStmtPurgeDeadSymbolsKind, L, tag) { }
private:
friend class ProgramPoint;
PreStmtPurgeDeadSymbols() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == PreStmtPurgeDeadSymbolsKind;
}
};
/// Represents a point after we ran remove dead bindings AFTER
/// processing the given statement.
class PostStmtPurgeDeadSymbols : public StmtPoint {
public:
PostStmtPurgeDeadSymbols(const Stmt *S, const LocationContext *L,
const ProgramPointTag *tag = nullptr)
: StmtPoint(S, nullptr, PostStmtPurgeDeadSymbolsKind, L, tag) { }
private:
friend class ProgramPoint;
PostStmtPurgeDeadSymbols() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == PostStmtPurgeDeadSymbolsKind;
}
};
class BlockEdge : public ProgramPoint {
public:
BlockEdge(const CFGBlock *B1, const CFGBlock *B2, const LocationContext *L)
: ProgramPoint(B1, B2, BlockEdgeKind, L) {
assert(B1 && "BlockEdge: source block must be non-null");
assert(B2 && "BlockEdge: destination block must be non-null");
}
const CFGBlock *getSrc() const {
return static_cast<const CFGBlock*>(getData1());
}
const CFGBlock *getDst() const {
return static_cast<const CFGBlock*>(getData2());
}
private:
friend class ProgramPoint;
BlockEdge() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == BlockEdgeKind;
}
};
class PostInitializer : public ProgramPoint {
public:
/// \brief Construct a PostInitializer point that represents a location after
/// CXXCtorInitializer expression evaluation.
///
/// \param I The initializer.
/// \param Loc The location of the field being initialized.
PostInitializer(const CXXCtorInitializer *I,
const void *Loc,
const LocationContext *L)
: ProgramPoint(I, Loc, PostInitializerKind, L) {}
const CXXCtorInitializer *getInitializer() const {
return static_cast<const CXXCtorInitializer *>(getData1());
}
/// \brief Returns the location of the field.
const void *getLocationValue() const {
return getData2();
}
private:
friend class ProgramPoint;
PostInitializer() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == PostInitializerKind;
}
};
/// Represents an implicit call event.
///
/// The nearest statement is provided for diagnostic purposes.
class ImplicitCallPoint : public ProgramPoint {
public:
ImplicitCallPoint(const Decl *D, SourceLocation Loc, Kind K,
const LocationContext *L, const ProgramPointTag *Tag)
: ProgramPoint(Loc.getPtrEncoding(), D, K, L, Tag) {}
const Decl *getDecl() const { return static_cast<const Decl *>(getData2()); }
SourceLocation getLocation() const {
return SourceLocation::getFromPtrEncoding(getData1());
}
protected:
ImplicitCallPoint() {}
private:
friend class ProgramPoint;
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() >= MinImplicitCallKind &&
Location.getKind() <= MaxImplicitCallKind;
}
};
/// Represents a program point just before an implicit call event.
///
/// Explicit calls will appear as PreStmt program points.
class PreImplicitCall : public ImplicitCallPoint {
public:
PreImplicitCall(const Decl *D, SourceLocation Loc, const LocationContext *L,
const ProgramPointTag *Tag = nullptr)
: ImplicitCallPoint(D, Loc, PreImplicitCallKind, L, Tag) {}
private:
friend class ProgramPoint;
PreImplicitCall() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == PreImplicitCallKind;
}
};
/// Represents a program point just after an implicit call event.
///
/// Explicit calls will appear as PostStmt program points.
class PostImplicitCall : public ImplicitCallPoint {
public:
PostImplicitCall(const Decl *D, SourceLocation Loc, const LocationContext *L,
const ProgramPointTag *Tag = nullptr)
: ImplicitCallPoint(D, Loc, PostImplicitCallKind, L, Tag) {}
private:
friend class ProgramPoint;
PostImplicitCall() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == PostImplicitCallKind;
}
};
/// Represents a point when we begin processing an inlined call.
/// CallEnter uses the caller's location context.
class CallEnter : public ProgramPoint {
public:
CallEnter(const Stmt *stmt, const StackFrameContext *calleeCtx,
const LocationContext *callerCtx)
: ProgramPoint(stmt, calleeCtx, CallEnterKind, callerCtx, nullptr) {}
const Stmt *getCallExpr() const {
return static_cast<const Stmt *>(getData1());
}
const StackFrameContext *getCalleeContext() const {
return static_cast<const StackFrameContext *>(getData2());
}
private:
friend class ProgramPoint;
CallEnter() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == CallEnterKind;
}
};
/// Represents a point when we start the call exit sequence (for inlined call).
///
/// The call exit is simulated with a sequence of nodes, which occur between
/// CallExitBegin and CallExitEnd. The following operations occur between the
/// two program points:
/// - CallExitBegin
/// - Bind the return value
/// - Run Remove dead bindings (to clean up the dead symbols from the callee).
/// - CallExitEnd
class CallExitBegin : public ProgramPoint {
public:
// CallExitBegin uses the callee's location context.
CallExitBegin(const StackFrameContext *L)
: ProgramPoint(nullptr, CallExitBeginKind, L, nullptr) {}
private:
friend class ProgramPoint;
CallExitBegin() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == CallExitBeginKind;
}
};
/// Represents a point when we finish the call exit sequence (for inlined call).
/// \sa CallExitBegin
class CallExitEnd : public ProgramPoint {
public:
// CallExitEnd uses the caller's location context.
CallExitEnd(const StackFrameContext *CalleeCtx,
const LocationContext *CallerCtx)
: ProgramPoint(CalleeCtx, CallExitEndKind, CallerCtx, nullptr) {}
const StackFrameContext *getCalleeContext() const {
return static_cast<const StackFrameContext *>(getData1());
}
private:
friend class ProgramPoint;
CallExitEnd() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == CallExitEndKind;
}
};
/// This is a meta program point, which should be skipped by all the diagnostic
/// reasoning etc.
class EpsilonPoint : public ProgramPoint {
public:
EpsilonPoint(const LocationContext *L, const void *Data1,
const void *Data2 = nullptr,
const ProgramPointTag *tag = nullptr)
: ProgramPoint(Data1, Data2, EpsilonKind, L, tag) {}
const void *getData() const { return getData1(); }
private:
friend class ProgramPoint;
EpsilonPoint() {}
static bool isKind(const ProgramPoint &Location) {
return Location.getKind() == EpsilonKind;
}
};
/// ProgramPoints can be "tagged" as representing points specific to a given
/// analysis entity. Tags are abstract annotations, with an associated
/// description and potentially other information.
class ProgramPointTag {
public:
ProgramPointTag(void *tagKind = nullptr) : TagKind(tagKind) {}
virtual ~ProgramPointTag();
virtual StringRef getTagDescription() const = 0;
protected:
/// Used to implement 'isKind' in subclasses.
const void *getTagKind() { return TagKind; }
private:
const void *TagKind;
};
class SimpleProgramPointTag : public ProgramPointTag {
std::string Desc;
public:
SimpleProgramPointTag(StringRef MsgProvider, StringRef Msg);
StringRef getTagDescription() const override;
};
} // end namespace clang
namespace llvm { // Traits specialization for DenseMap
template <> struct DenseMapInfo<clang::ProgramPoint> {
static inline clang::ProgramPoint getEmptyKey() {
uintptr_t x =
reinterpret_cast<uintptr_t>(DenseMapInfo<void*>::getEmptyKey()) & ~0x7;
return clang::BlockEntrance(reinterpret_cast<clang::CFGBlock*>(x), nullptr);
}
static inline clang::ProgramPoint getTombstoneKey() {
uintptr_t x =
reinterpret_cast<uintptr_t>(DenseMapInfo<void*>::getTombstoneKey()) & ~0x7;
return clang::BlockEntrance(reinterpret_cast<clang::CFGBlock*>(x), nullptr);
}
static unsigned getHashValue(const clang::ProgramPoint &Loc) {
return Loc.getHashValue();
}
static bool isEqual(const clang::ProgramPoint &L,
const clang::ProgramPoint &R) {
return L == R;
}
};
template <>
struct isPodLike<clang::ProgramPoint> { static const bool value = true; };
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/AnalysisDiagnostic.h | //===--- DiagnosticAnalysis.h - Diagnostics for libanalysis -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSISDIAGNOSTIC_H
#define LLVM_CLANG_ANALYSIS_ANALYSISDIAGNOSTIC_H
#include "clang/Basic/Diagnostic.h"
namespace clang {
namespace diag {
enum {
#define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
SFINAE,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
#define ANALYSISSTART
#include "clang/Basic/DiagnosticAnalysisKinds.inc"
#undef DIAG
NUM_BUILTIN_ANALYSIS_DIAGNOSTICS
};
} // end namespace diag
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/CFG.h | //===--- CFG.h - Classes for representing and building CFGs------*- 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 CFG and CFGBuilder classes for representing and
// building Control-Flow Graphs (CFGs) from ASTs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_CFG_H
#define LLVM_CLANG_ANALYSIS_CFG_H
#include "clang/AST/Stmt.h"
#include "clang/Analysis/Support/BumpVector.h"
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/GraphTraits.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/raw_ostream.h"
#include <bitset>
#include <cassert>
#include <iterator>
#include <memory>
namespace clang {
class CXXDestructorDecl;
class Decl;
class Stmt;
class Expr;
class FieldDecl;
class VarDecl;
class CXXCtorInitializer;
class CXXBaseSpecifier;
class CXXBindTemporaryExpr;
class CFG;
class PrinterHelper;
class LangOptions;
class ASTContext;
class CXXRecordDecl;
class CXXDeleteExpr;
class CXXNewExpr;
class BinaryOperator;
/// CFGElement - Represents a top-level expression in a basic block.
class CFGElement {
public:
enum Kind {
// main kind
Statement,
Initializer,
NewAllocator,
// dtor kind
AutomaticObjectDtor,
DeleteDtor,
BaseDtor,
MemberDtor,
TemporaryDtor,
DTOR_BEGIN = AutomaticObjectDtor,
DTOR_END = TemporaryDtor
};
protected:
// The int bits are used to mark the kind.
llvm::PointerIntPair<void *, 2> Data1;
llvm::PointerIntPair<void *, 2> Data2;
CFGElement(Kind kind, const void *Ptr1, const void *Ptr2 = nullptr)
: Data1(const_cast<void*>(Ptr1), ((unsigned) kind) & 0x3),
Data2(const_cast<void*>(Ptr2), (((unsigned) kind) >> 2) & 0x3) {
assert(getKind() == kind);
}
CFGElement() {}
public:
/// \brief Convert to the specified CFGElement type, asserting that this
/// CFGElement is of the desired type.
template<typename T>
T castAs() const {
assert(T::isKind(*this));
T t;
CFGElement& e = t;
e = *this;
return t;
}
/// \brief Convert to the specified CFGElement type, returning None if this
/// CFGElement is not of the desired type.
template<typename T>
Optional<T> getAs() const {
if (!T::isKind(*this))
return None;
T t;
CFGElement& e = t;
e = *this;
return t;
}
Kind getKind() const {
unsigned x = Data2.getInt();
x <<= 2;
x |= Data1.getInt();
return (Kind) x;
}
};
class CFGStmt : public CFGElement {
public:
CFGStmt(Stmt *S) : CFGElement(Statement, S) {}
const Stmt *getStmt() const {
return static_cast<const Stmt *>(Data1.getPointer());
}
private:
friend class CFGElement;
CFGStmt() {}
static bool isKind(const CFGElement &E) {
return E.getKind() == Statement;
}
};
/// CFGInitializer - Represents C++ base or member initializer from
/// constructor's initialization list.
class CFGInitializer : public CFGElement {
public:
CFGInitializer(CXXCtorInitializer *initializer)
: CFGElement(Initializer, initializer) {}
CXXCtorInitializer* getInitializer() const {
return static_cast<CXXCtorInitializer*>(Data1.getPointer());
}
private:
friend class CFGElement;
CFGInitializer() {}
static bool isKind(const CFGElement &E) {
return E.getKind() == Initializer;
}
};
/// CFGNewAllocator - Represents C++ allocator call.
class CFGNewAllocator : public CFGElement {
public:
explicit CFGNewAllocator(const CXXNewExpr *S)
: CFGElement(NewAllocator, S) {}
// Get the new expression.
const CXXNewExpr *getAllocatorExpr() const {
return static_cast<CXXNewExpr *>(Data1.getPointer());
}
private:
friend class CFGElement;
CFGNewAllocator() {}
static bool isKind(const CFGElement &elem) {
return elem.getKind() == NewAllocator;
}
};
/// CFGImplicitDtor - Represents C++ object destructor implicitly generated
/// by compiler on various occasions.
class CFGImplicitDtor : public CFGElement {
protected:
CFGImplicitDtor() {}
CFGImplicitDtor(Kind kind, const void *data1, const void *data2 = nullptr)
: CFGElement(kind, data1, data2) {
assert(kind >= DTOR_BEGIN && kind <= DTOR_END);
}
public:
const CXXDestructorDecl *getDestructorDecl(ASTContext &astContext) const;
bool isNoReturn(ASTContext &astContext) const;
private:
friend class CFGElement;
static bool isKind(const CFGElement &E) {
Kind kind = E.getKind();
return kind >= DTOR_BEGIN && kind <= DTOR_END;
}
};
/// CFGAutomaticObjDtor - Represents C++ object destructor implicitly generated
/// for automatic object or temporary bound to const reference at the point
/// of leaving its local scope.
class CFGAutomaticObjDtor: public CFGImplicitDtor {
public:
CFGAutomaticObjDtor(const VarDecl *var, const Stmt *stmt)
: CFGImplicitDtor(AutomaticObjectDtor, var, stmt) {}
const VarDecl *getVarDecl() const {
return static_cast<VarDecl*>(Data1.getPointer());
}
// Get statement end of which triggered the destructor call.
const Stmt *getTriggerStmt() const {
return static_cast<Stmt*>(Data2.getPointer());
}
private:
friend class CFGElement;
CFGAutomaticObjDtor() {}
static bool isKind(const CFGElement &elem) {
return elem.getKind() == AutomaticObjectDtor;
}
};
/// CFGDeleteDtor - Represents C++ object destructor generated
/// from a call to delete.
class CFGDeleteDtor : public CFGImplicitDtor {
public:
CFGDeleteDtor(const CXXRecordDecl *RD, const CXXDeleteExpr *DE)
: CFGImplicitDtor(DeleteDtor, RD, DE) {}
const CXXRecordDecl *getCXXRecordDecl() const {
return static_cast<CXXRecordDecl*>(Data1.getPointer());
}
// Get Delete expression which triggered the destructor call.
const CXXDeleteExpr *getDeleteExpr() const {
return static_cast<CXXDeleteExpr *>(Data2.getPointer());
}
private:
friend class CFGElement;
CFGDeleteDtor() {}
static bool isKind(const CFGElement &elem) {
return elem.getKind() == DeleteDtor;
}
};
/// CFGBaseDtor - Represents C++ object destructor implicitly generated for
/// base object in destructor.
class CFGBaseDtor : public CFGImplicitDtor {
public:
CFGBaseDtor(const CXXBaseSpecifier *base)
: CFGImplicitDtor(BaseDtor, base) {}
const CXXBaseSpecifier *getBaseSpecifier() const {
return static_cast<const CXXBaseSpecifier*>(Data1.getPointer());
}
private:
friend class CFGElement;
CFGBaseDtor() {}
static bool isKind(const CFGElement &E) {
return E.getKind() == BaseDtor;
}
};
/// CFGMemberDtor - Represents C++ object destructor implicitly generated for
/// member object in destructor.
class CFGMemberDtor : public CFGImplicitDtor {
public:
CFGMemberDtor(const FieldDecl *field)
: CFGImplicitDtor(MemberDtor, field, nullptr) {}
const FieldDecl *getFieldDecl() const {
return static_cast<const FieldDecl*>(Data1.getPointer());
}
private:
friend class CFGElement;
CFGMemberDtor() {}
static bool isKind(const CFGElement &E) {
return E.getKind() == MemberDtor;
}
};
/// CFGTemporaryDtor - Represents C++ object destructor implicitly generated
/// at the end of full expression for temporary object.
class CFGTemporaryDtor : public CFGImplicitDtor {
public:
CFGTemporaryDtor(CXXBindTemporaryExpr *expr)
: CFGImplicitDtor(TemporaryDtor, expr, nullptr) {}
const CXXBindTemporaryExpr *getBindTemporaryExpr() const {
return static_cast<const CXXBindTemporaryExpr *>(Data1.getPointer());
}
private:
friend class CFGElement;
CFGTemporaryDtor() {}
static bool isKind(const CFGElement &E) {
return E.getKind() == TemporaryDtor;
}
};
/// CFGTerminator - Represents CFGBlock terminator statement.
///
/// TemporaryDtorsBranch bit is set to true if the terminator marks a branch
/// in control flow of destructors of temporaries. In this case terminator
/// statement is the same statement that branches control flow in evaluation
/// of matching full expression.
class CFGTerminator {
llvm::PointerIntPair<Stmt *, 1> Data;
public:
CFGTerminator() {}
CFGTerminator(Stmt *S, bool TemporaryDtorsBranch = false)
: Data(S, TemporaryDtorsBranch) {}
Stmt *getStmt() { return Data.getPointer(); }
const Stmt *getStmt() const { return Data.getPointer(); }
bool isTemporaryDtorsBranch() const { return Data.getInt(); }
operator Stmt *() { return getStmt(); }
operator const Stmt *() const { return getStmt(); }
Stmt *operator->() { return getStmt(); }
const Stmt *operator->() const { return getStmt(); }
Stmt &operator*() { return *getStmt(); }
const Stmt &operator*() const { return *getStmt(); }
explicit operator bool() const { return getStmt(); }
};
/// CFGBlock - Represents a single basic block in a source-level CFG.
/// It consists of:
///
/// (1) A set of statements/expressions (which may contain subexpressions).
/// (2) A "terminator" statement (not in the set of statements).
/// (3) A list of successors and predecessors.
///
/// Terminator: The terminator represents the type of control-flow that occurs
/// at the end of the basic block. The terminator is a Stmt* referring to an
/// AST node that has control-flow: if-statements, breaks, loops, etc.
/// If the control-flow is conditional, the condition expression will appear
/// within the set of statements in the block (usually the last statement).
///
/// Predecessors: the order in the set of predecessors is arbitrary.
///
/// Successors: the order in the set of successors is NOT arbitrary. We
/// currently have the following orderings based on the terminator:
///
/// Terminator Successor Ordering
/// -----------------------------------------------------
/// if Then Block; Else Block
/// ? operator LHS expression; RHS expression
/// &&, || expression that uses result of && or ||, RHS
///
/// But note that any of that may be NULL in case of optimized-out edges.
///
class CFGBlock {
class ElementList {
typedef BumpVector<CFGElement> ImplTy;
ImplTy Impl;
public:
ElementList(BumpVectorContext &C) : Impl(C, 4) {}
typedef std::reverse_iterator<ImplTy::iterator> iterator;
typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
typedef ImplTy::iterator reverse_iterator;
typedef ImplTy::const_iterator const_reverse_iterator;
typedef ImplTy::const_reference const_reference;
void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
reverse_iterator insert(reverse_iterator I, size_t Cnt, CFGElement E,
BumpVectorContext &C) {
return Impl.insert(I, Cnt, E, C);
}
const_reference front() const { return Impl.back(); }
const_reference back() const { return Impl.front(); }
iterator begin() { return Impl.rbegin(); }
iterator end() { return Impl.rend(); }
const_iterator begin() const { return Impl.rbegin(); }
const_iterator end() const { return Impl.rend(); }
reverse_iterator rbegin() { return Impl.begin(); }
reverse_iterator rend() { return Impl.end(); }
const_reverse_iterator rbegin() const { return Impl.begin(); }
const_reverse_iterator rend() const { return Impl.end(); }
CFGElement operator[](size_t i) const {
assert(i < Impl.size());
return Impl[Impl.size() - 1 - i];
}
size_t size() const { return Impl.size(); }
bool empty() const { return Impl.empty(); }
};
/// Stmts - The set of statements in the basic block.
ElementList Elements;
/// Label - An (optional) label that prefixes the executable
/// statements in the block. When this variable is non-NULL, it is
/// either an instance of LabelStmt, SwitchCase or CXXCatchStmt.
Stmt *Label;
/// Terminator - The terminator for a basic block that
/// indicates the type of control-flow that occurs between a block
/// and its successors.
CFGTerminator Terminator;
/// LoopTarget - Some blocks are used to represent the "loop edge" to
/// the start of a loop from within the loop body. This Stmt* will be
/// refer to the loop statement for such blocks (and be null otherwise).
const Stmt *LoopTarget;
/// BlockID - A numerical ID assigned to a CFGBlock during construction
/// of the CFG.
unsigned BlockID;
public:
/// This class represents a potential adjacent block in the CFG. It encodes
/// whether or not the block is actually reachable, or can be proved to be
/// trivially unreachable. For some cases it allows one to encode scenarios
/// where a block was substituted because the original (now alternate) block
/// is unreachable.
class AdjacentBlock {
enum Kind {
AB_Normal,
AB_Unreachable,
AB_Alternate
};
CFGBlock *ReachableBlock;
llvm::PointerIntPair<CFGBlock*, 2> UnreachableBlock;
public:
/// Construct an AdjacentBlock with a possibly unreachable block.
AdjacentBlock(CFGBlock *B, bool IsReachable);
/// Construct an AdjacentBlock with a reachable block and an alternate
/// unreachable block.
AdjacentBlock(CFGBlock *B, CFGBlock *AlternateBlock);
/// Get the reachable block, if one exists.
CFGBlock *getReachableBlock() const {
return ReachableBlock;
}
/// Get the potentially unreachable block.
CFGBlock *getPossiblyUnreachableBlock() const {
return UnreachableBlock.getPointer();
}
/// Provide an implicit conversion to CFGBlock* so that
/// AdjacentBlock can be substituted for CFGBlock*.
operator CFGBlock*() const {
return getReachableBlock();
}
CFGBlock& operator *() const {
return *getReachableBlock();
}
CFGBlock* operator ->() const {
return getReachableBlock();
}
bool isReachable() const {
Kind K = (Kind) UnreachableBlock.getInt();
return K == AB_Normal || K == AB_Alternate;
}
};
private:
/// Predecessors/Successors - Keep track of the predecessor / successor
/// CFG blocks.
typedef BumpVector<AdjacentBlock> AdjacentBlocks;
AdjacentBlocks Preds;
AdjacentBlocks Succs;
/// NoReturn - This bit is set when the basic block contains a function call
/// or implicit destructor that is attributed as 'noreturn'. In that case,
/// control cannot technically ever proceed past this block. All such blocks
/// will have a single immediate successor: the exit block. This allows them
/// to be easily reached from the exit block and using this bit quickly
/// recognized without scanning the contents of the block.
///
/// Optimization Note: This bit could be profitably folded with Terminator's
/// storage if the memory usage of CFGBlock becomes an issue.
unsigned HasNoReturnElement : 1;
/// Parent - The parent CFG that owns this CFGBlock.
CFG *Parent;
public:
explicit CFGBlock(unsigned blockid, BumpVectorContext &C, CFG *parent)
: Elements(C), Label(nullptr), Terminator(nullptr), LoopTarget(nullptr),
BlockID(blockid), Preds(C, 1), Succs(C, 1), HasNoReturnElement(false),
Parent(parent) {}
// Statement iterators
typedef ElementList::iterator iterator;
typedef ElementList::const_iterator const_iterator;
typedef ElementList::reverse_iterator reverse_iterator;
typedef ElementList::const_reverse_iterator const_reverse_iterator;
CFGElement front() const { return Elements.front(); }
CFGElement back() const { return Elements.back(); }
iterator begin() { return Elements.begin(); }
iterator end() { return Elements.end(); }
const_iterator begin() const { return Elements.begin(); }
const_iterator end() const { return Elements.end(); }
reverse_iterator rbegin() { return Elements.rbegin(); }
reverse_iterator rend() { return Elements.rend(); }
const_reverse_iterator rbegin() const { return Elements.rbegin(); }
const_reverse_iterator rend() const { return Elements.rend(); }
unsigned size() const { return Elements.size(); }
bool empty() const { return Elements.empty(); }
CFGElement operator[](size_t i) const { return Elements[i]; }
// CFG iterators
typedef AdjacentBlocks::iterator pred_iterator;
typedef AdjacentBlocks::const_iterator const_pred_iterator;
typedef AdjacentBlocks::reverse_iterator pred_reverse_iterator;
typedef AdjacentBlocks::const_reverse_iterator const_pred_reverse_iterator;
typedef AdjacentBlocks::iterator succ_iterator;
typedef AdjacentBlocks::const_iterator const_succ_iterator;
typedef AdjacentBlocks::reverse_iterator succ_reverse_iterator;
typedef AdjacentBlocks::const_reverse_iterator const_succ_reverse_iterator;
pred_iterator pred_begin() { return Preds.begin(); }
pred_iterator pred_end() { return Preds.end(); }
const_pred_iterator pred_begin() const { return Preds.begin(); }
const_pred_iterator pred_end() const { return Preds.end(); }
pred_reverse_iterator pred_rbegin() { return Preds.rbegin(); }
pred_reverse_iterator pred_rend() { return Preds.rend(); }
const_pred_reverse_iterator pred_rbegin() const { return Preds.rbegin(); }
const_pred_reverse_iterator pred_rend() const { return Preds.rend(); }
succ_iterator succ_begin() { return Succs.begin(); }
succ_iterator succ_end() { return Succs.end(); }
const_succ_iterator succ_begin() const { return Succs.begin(); }
const_succ_iterator succ_end() const { return Succs.end(); }
succ_reverse_iterator succ_rbegin() { return Succs.rbegin(); }
succ_reverse_iterator succ_rend() { return Succs.rend(); }
const_succ_reverse_iterator succ_rbegin() const { return Succs.rbegin(); }
const_succ_reverse_iterator succ_rend() const { return Succs.rend(); }
unsigned succ_size() const { return Succs.size(); }
bool succ_empty() const { return Succs.empty(); }
unsigned pred_size() const { return Preds.size(); }
bool pred_empty() const { return Preds.empty(); }
class FilterOptions {
public:
FilterOptions() {
IgnoreNullPredecessors = 1;
IgnoreDefaultsWithCoveredEnums = 0;
}
unsigned IgnoreNullPredecessors : 1;
unsigned IgnoreDefaultsWithCoveredEnums : 1;
};
static bool FilterEdge(const FilterOptions &F, const CFGBlock *Src,
const CFGBlock *Dst);
template <typename IMPL, bool IsPred>
class FilteredCFGBlockIterator {
private:
IMPL I, E;
const FilterOptions F;
const CFGBlock *From;
public:
explicit FilteredCFGBlockIterator(const IMPL &i, const IMPL &e,
const CFGBlock *from,
const FilterOptions &f)
: I(i), E(e), F(f), From(from) {
while (hasMore() && Filter(*I))
++I;
}
bool hasMore() const { return I != E; }
FilteredCFGBlockIterator &operator++() {
do { ++I; } while (hasMore() && Filter(*I));
return *this;
}
const CFGBlock *operator*() const { return *I; }
private:
bool Filter(const CFGBlock *To) {
return IsPred ? FilterEdge(F, To, From) : FilterEdge(F, From, To);
}
};
typedef FilteredCFGBlockIterator<const_pred_iterator, true>
filtered_pred_iterator;
typedef FilteredCFGBlockIterator<const_succ_iterator, false>
filtered_succ_iterator;
filtered_pred_iterator filtered_pred_start_end(const FilterOptions &f) const {
return filtered_pred_iterator(pred_begin(), pred_end(), this, f);
}
filtered_succ_iterator filtered_succ_start_end(const FilterOptions &f) const {
return filtered_succ_iterator(succ_begin(), succ_end(), this, f);
}
// Manipulation of block contents
void setTerminator(CFGTerminator Term) { Terminator = Term; }
void setLabel(Stmt *Statement) { Label = Statement; }
void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
void setHasNoReturnElement() { HasNoReturnElement = true; }
CFGTerminator getTerminator() { return Terminator; }
const CFGTerminator getTerminator() const { return Terminator; }
Stmt *getTerminatorCondition(bool StripParens = true);
const Stmt *getTerminatorCondition(bool StripParens = true) const {
return const_cast<CFGBlock*>(this)->getTerminatorCondition(StripParens);
}
const Stmt *getLoopTarget() const { return LoopTarget; }
Stmt *getLabel() { return Label; }
const Stmt *getLabel() const { return Label; }
bool hasNoReturnElement() const { return HasNoReturnElement; }
unsigned getBlockID() const { return BlockID; }
CFG *getParent() const { return Parent; }
void dump() const;
void dump(const CFG *cfg, const LangOptions &LO, bool ShowColors = false) const;
void print(raw_ostream &OS, const CFG* cfg, const LangOptions &LO,
bool ShowColors) const;
void printTerminator(raw_ostream &OS, const LangOptions &LO) const;
void printAsOperand(raw_ostream &OS, bool /*PrintType*/) {
OS << "BB#" << getBlockID();
}
/// Adds a (potentially unreachable) successor block to the current block.
void addSuccessor(AdjacentBlock Succ, BumpVectorContext &C);
void appendStmt(Stmt *statement, BumpVectorContext &C) {
Elements.push_back(CFGStmt(statement), C);
}
void appendInitializer(CXXCtorInitializer *initializer,
BumpVectorContext &C) {
Elements.push_back(CFGInitializer(initializer), C);
}
void appendNewAllocator(CXXNewExpr *NE,
BumpVectorContext &C) {
Elements.push_back(CFGNewAllocator(NE), C);
}
void appendBaseDtor(const CXXBaseSpecifier *BS, BumpVectorContext &C) {
Elements.push_back(CFGBaseDtor(BS), C);
}
void appendMemberDtor(FieldDecl *FD, BumpVectorContext &C) {
Elements.push_back(CFGMemberDtor(FD), C);
}
void appendTemporaryDtor(CXXBindTemporaryExpr *E, BumpVectorContext &C) {
Elements.push_back(CFGTemporaryDtor(E), C);
}
void appendAutomaticObjDtor(VarDecl *VD, Stmt *S, BumpVectorContext &C) {
Elements.push_back(CFGAutomaticObjDtor(VD, S), C);
}
void appendDeleteDtor(CXXRecordDecl *RD, CXXDeleteExpr *DE, BumpVectorContext &C) {
Elements.push_back(CFGDeleteDtor(RD, DE), C);
}
// Destructors must be inserted in reversed order. So insertion is in two
// steps. First we prepare space for some number of elements, then we insert
// the elements beginning at the last position in prepared space.
iterator beginAutomaticObjDtorsInsert(iterator I, size_t Cnt,
BumpVectorContext &C) {
return iterator(Elements.insert(I.base(), Cnt,
CFGAutomaticObjDtor(nullptr, 0), C));
}
iterator insertAutomaticObjDtor(iterator I, VarDecl *VD, Stmt *S) {
*I = CFGAutomaticObjDtor(VD, S);
return ++I;
}
};
/// \brief CFGCallback defines methods that should be called when a logical
/// operator error is found when building the CFG.
class CFGCallback {
public:
CFGCallback() {}
virtual void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {}
virtual void compareBitwiseEquality(const BinaryOperator *B,
bool isAlwaysTrue) {}
virtual ~CFGCallback() {}
};
/// CFG - Represents a source-level, intra-procedural CFG that represents the
/// control-flow of a Stmt. The Stmt can represent an entire function body,
/// or a single expression. A CFG will always contain one empty block that
/// represents the Exit point of the CFG. A CFG will also contain a designated
/// Entry block. The CFG solely represents control-flow; it consists of
/// CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
/// was constructed from.
class CFG {
public:
//===--------------------------------------------------------------------===//
// CFG Construction & Manipulation.
//===--------------------------------------------------------------------===//
class BuildOptions {
std::bitset<Stmt::lastStmtConstant> alwaysAddMask;
public:
typedef llvm::DenseMap<const Stmt *, const CFGBlock*> ForcedBlkExprs;
ForcedBlkExprs **forcedBlkExprs;
CFGCallback *Observer;
bool PruneTriviallyFalseEdges;
bool AddEHEdges;
bool AddInitializers;
bool AddImplicitDtors;
bool AddTemporaryDtors;
bool AddStaticInitBranches;
bool AddCXXNewAllocator;
bool AddCXXDefaultInitExprInCtors;
bool alwaysAdd(const Stmt *stmt) const {
return alwaysAddMask[stmt->getStmtClass()];
}
BuildOptions &setAlwaysAdd(Stmt::StmtClass stmtClass, bool val = true) {
alwaysAddMask[stmtClass] = val;
return *this;
}
BuildOptions &setAllAlwaysAdd() {
alwaysAddMask.set();
return *this;
}
BuildOptions()
: forcedBlkExprs(nullptr), Observer(nullptr),
PruneTriviallyFalseEdges(true), AddEHEdges(false),
AddInitializers(false), AddImplicitDtors(false),
AddTemporaryDtors(false), AddStaticInitBranches(false),
AddCXXNewAllocator(false), AddCXXDefaultInitExprInCtors(false) {}
};
/// \brief Provides a custom implementation of the iterator class to have the
/// same interface as Function::iterator - iterator returns CFGBlock
/// (not a pointer to CFGBlock).
class graph_iterator {
public:
typedef const CFGBlock value_type;
typedef value_type& reference;
typedef value_type* pointer;
typedef BumpVector<CFGBlock*>::iterator ImplTy;
graph_iterator(const ImplTy &i) : I(i) {}
bool operator==(const graph_iterator &X) const { return I == X.I; }
bool operator!=(const graph_iterator &X) const { return I != X.I; }
reference operator*() const { return **I; }
pointer operator->() const { return *I; }
operator CFGBlock* () { return *I; }
graph_iterator &operator++() { ++I; return *this; }
graph_iterator &operator--() { --I; return *this; }
private:
ImplTy I;
};
class const_graph_iterator {
public:
typedef const CFGBlock value_type;
typedef value_type& reference;
typedef value_type* pointer;
typedef BumpVector<CFGBlock*>::const_iterator ImplTy;
const_graph_iterator(const ImplTy &i) : I(i) {}
bool operator==(const const_graph_iterator &X) const { return I == X.I; }
bool operator!=(const const_graph_iterator &X) const { return I != X.I; }
reference operator*() const { return **I; }
pointer operator->() const { return *I; }
operator CFGBlock* () const { return *I; }
const_graph_iterator &operator++() { ++I; return *this; }
const_graph_iterator &operator--() { --I; return *this; }
private:
ImplTy I;
};
/// buildCFG - Builds a CFG from an AST.
static std::unique_ptr<CFG> buildCFG(const Decl *D, Stmt *AST, ASTContext *C,
const BuildOptions &BO);
/// createBlock - Create a new block in the CFG. The CFG owns the block;
/// the caller should not directly free it.
CFGBlock *createBlock();
/// setEntry - Set the entry block of the CFG. This is typically used
/// only during CFG construction. Most CFG clients expect that the
/// entry block has no predecessors and contains no statements.
void setEntry(CFGBlock *B) { Entry = B; }
/// setIndirectGotoBlock - Set the block used for indirect goto jumps.
/// This is typically used only during CFG construction.
void setIndirectGotoBlock(CFGBlock *B) { IndirectGotoBlock = B; }
//===--------------------------------------------------------------------===//
// Block Iterators
//===--------------------------------------------------------------------===//
typedef BumpVector<CFGBlock*> CFGBlockListTy;
typedef CFGBlockListTy::iterator iterator;
typedef CFGBlockListTy::const_iterator const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
CFGBlock & front() { return *Blocks.front(); }
CFGBlock & back() { return *Blocks.back(); }
iterator begin() { return Blocks.begin(); }
iterator end() { return Blocks.end(); }
const_iterator begin() const { return Blocks.begin(); }
const_iterator end() const { return Blocks.end(); }
graph_iterator nodes_begin() { return graph_iterator(Blocks.begin()); }
graph_iterator nodes_end() { return graph_iterator(Blocks.end()); }
const_graph_iterator nodes_begin() const {
return const_graph_iterator(Blocks.begin());
}
const_graph_iterator nodes_end() const {
return const_graph_iterator(Blocks.end());
}
reverse_iterator rbegin() { return Blocks.rbegin(); }
reverse_iterator rend() { return Blocks.rend(); }
const_reverse_iterator rbegin() const { return Blocks.rbegin(); }
const_reverse_iterator rend() const { return Blocks.rend(); }
CFGBlock & getEntry() { return *Entry; }
const CFGBlock & getEntry() const { return *Entry; }
CFGBlock & getExit() { return *Exit; }
const CFGBlock & getExit() const { return *Exit; }
CFGBlock * getIndirectGotoBlock() { return IndirectGotoBlock; }
const CFGBlock * getIndirectGotoBlock() const { return IndirectGotoBlock; }
typedef std::vector<const CFGBlock*>::const_iterator try_block_iterator;
try_block_iterator try_blocks_begin() const {
return TryDispatchBlocks.begin();
}
try_block_iterator try_blocks_end() const {
return TryDispatchBlocks.end();
}
void addTryDispatchBlock(const CFGBlock *block) {
TryDispatchBlocks.push_back(block);
}
/// Records a synthetic DeclStmt and the DeclStmt it was constructed from.
///
/// The CFG uses synthetic DeclStmts when a single AST DeclStmt contains
/// multiple decls.
void addSyntheticDeclStmt(const DeclStmt *Synthetic,
const DeclStmt *Source) {
assert(Synthetic->isSingleDecl() && "Can handle single declarations only");
assert(Synthetic != Source && "Don't include original DeclStmts in map");
assert(!SyntheticDeclStmts.count(Synthetic) && "Already in map");
SyntheticDeclStmts[Synthetic] = Source;
}
typedef llvm::DenseMap<const DeclStmt *, const DeclStmt *>::const_iterator
synthetic_stmt_iterator;
/// Iterates over synthetic DeclStmts in the CFG.
///
/// Each element is a (synthetic statement, source statement) pair.
///
/// \sa addSyntheticDeclStmt
synthetic_stmt_iterator synthetic_stmt_begin() const {
return SyntheticDeclStmts.begin();
}
/// \sa synthetic_stmt_begin
synthetic_stmt_iterator synthetic_stmt_end() const {
return SyntheticDeclStmts.end();
}
//===--------------------------------------------------------------------===//
// Member templates useful for various batch operations over CFGs.
//===--------------------------------------------------------------------===//
template <typename Callback> void VisitBlockStmts(Callback &O) const {
for (const_iterator I=begin(), E=end(); I != E; ++I)
for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
BI != BE; ++BI) {
if (Optional<CFGStmt> stmt = BI->getAs<CFGStmt>())
O(const_cast<Stmt*>(stmt->getStmt()));
}
}
//===--------------------------------------------------------------------===//
// CFG Introspection.
//===--------------------------------------------------------------------===//
/// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
/// start at 0).
unsigned getNumBlockIDs() const { return NumBlockIDs; }
/// size - Return the total number of CFGBlocks within the CFG
/// This is simply a renaming of the getNumBlockIDs(). This is necessary
/// because the dominator implementation needs such an interface.
unsigned size() const { return NumBlockIDs; }
//===--------------------------------------------------------------------===//
// CFG Debugging: Pretty-Printing and Visualization.
//===--------------------------------------------------------------------===//
void viewCFG(const LangOptions &LO) const;
void print(raw_ostream &OS, const LangOptions &LO, bool ShowColors) const;
void dump(const LangOptions &LO, bool ShowColors) const;
//===--------------------------------------------------------------------===//
// Internal: constructors and data.
//===--------------------------------------------------------------------===//
CFG()
: Entry(nullptr), Exit(nullptr), IndirectGotoBlock(nullptr), NumBlockIDs(0),
Blocks(BlkBVC, 10) {}
llvm::BumpPtrAllocator& getAllocator() {
return BlkBVC.getAllocator();
}
BumpVectorContext &getBumpVectorContext() {
return BlkBVC;
}
private:
CFGBlock *Entry;
CFGBlock *Exit;
CFGBlock* IndirectGotoBlock; // Special block to contain collective dispatch
// for indirect gotos
unsigned NumBlockIDs;
BumpVectorContext BlkBVC;
CFGBlockListTy Blocks;
/// C++ 'try' statements are modeled with an indirect dispatch block.
/// This is the collection of such blocks present in the CFG.
std::vector<const CFGBlock *> TryDispatchBlocks;
/// Collects DeclStmts synthesized for this CFG and maps each one back to its
/// source DeclStmt.
llvm::DenseMap<const DeclStmt *, const DeclStmt *> SyntheticDeclStmts;
};
} // end namespace clang
//===----------------------------------------------------------------------===//
// GraphTraits specializations for CFG basic block graphs (source-level CFGs)
// //
///////////////////////////////////////////////////////////////////////////////
namespace llvm {
/// Implement simplify_type for CFGTerminator, so that we can dyn_cast from
/// CFGTerminator to a specific Stmt class.
template <> struct simplify_type< ::clang::CFGTerminator> {
typedef ::clang::Stmt *SimpleType;
static SimpleType getSimplifiedValue(::clang::CFGTerminator Val) {
return Val.getStmt();
}
};
// Traits for: CFGBlock
template <> struct GraphTraits< ::clang::CFGBlock *> {
typedef ::clang::CFGBlock NodeType;
typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
static NodeType* getEntryNode(::clang::CFGBlock *BB)
{ return BB; }
static inline ChildIteratorType child_begin(NodeType* N)
{ return N->succ_begin(); }
static inline ChildIteratorType child_end(NodeType* N)
{ return N->succ_end(); }
};
template <> struct GraphTraits< const ::clang::CFGBlock *> {
typedef const ::clang::CFGBlock NodeType;
typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
static NodeType* getEntryNode(const clang::CFGBlock *BB)
{ return BB; }
static inline ChildIteratorType child_begin(NodeType* N)
{ return N->succ_begin(); }
static inline ChildIteratorType child_end(NodeType* N)
{ return N->succ_end(); }
};
template <> struct GraphTraits<Inverse< ::clang::CFGBlock*> > {
typedef ::clang::CFGBlock NodeType;
typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
static NodeType *getEntryNode(Inverse< ::clang::CFGBlock*> G)
{ return G.Graph; }
static inline ChildIteratorType child_begin(NodeType* N)
{ return N->pred_begin(); }
static inline ChildIteratorType child_end(NodeType* N)
{ return N->pred_end(); }
};
template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
typedef const ::clang::CFGBlock NodeType;
typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
{ return G.Graph; }
static inline ChildIteratorType child_begin(NodeType* N)
{ return N->pred_begin(); }
static inline ChildIteratorType child_end(NodeType* N)
{ return N->pred_end(); }
};
// Traits for: CFG
template <> struct GraphTraits< ::clang::CFG* >
: public GraphTraits< ::clang::CFGBlock *> {
typedef ::clang::CFG::graph_iterator nodes_iterator;
static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
static nodes_iterator nodes_begin(::clang::CFG* F) { return F->nodes_begin();}
static nodes_iterator nodes_end(::clang::CFG* F) { return F->nodes_end(); }
static unsigned size(::clang::CFG* F) { return F->size(); }
};
template <> struct GraphTraits<const ::clang::CFG* >
: public GraphTraits<const ::clang::CFGBlock *> {
typedef ::clang::CFG::const_graph_iterator nodes_iterator;
static NodeType *getEntryNode( const ::clang::CFG* F) {
return &F->getEntry();
}
static nodes_iterator nodes_begin( const ::clang::CFG* F) {
return F->nodes_begin();
}
static nodes_iterator nodes_end( const ::clang::CFG* F) {
return F->nodes_end();
}
static unsigned size(const ::clang::CFG* F) {
return F->size();
}
};
template <> struct GraphTraits<Inverse< ::clang::CFG*> >
: public GraphTraits<Inverse< ::clang::CFGBlock*> > {
typedef ::clang::CFG::graph_iterator nodes_iterator;
static NodeType *getEntryNode( ::clang::CFG* F) { return &F->getExit(); }
static nodes_iterator nodes_begin( ::clang::CFG* F) {return F->nodes_begin();}
static nodes_iterator nodes_end( ::clang::CFG* F) { return F->nodes_end(); }
};
template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
: public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
typedef ::clang::CFG::const_graph_iterator nodes_iterator;
static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
static nodes_iterator nodes_begin(const ::clang::CFG* F) {
return F->nodes_begin();
}
static nodes_iterator nodes_end(const ::clang::CFG* F) {
return F->nodes_end();
}
};
} // end llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/CFGStmtMap.h | //===--- CFGStmtMap.h - Map from Stmt* to CFGBlock* -----------*- 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 CFGStmtMap class, which defines a mapping from
// Stmt* to CFGBlock*
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_CFGSTMTMAP_H
#define LLVM_CLANG_ANALYSIS_CFGSTMTMAP_H
#include "clang/Analysis/CFG.h"
namespace clang {
class CFG;
class CFGBlock;
class ParentMap;
class Stmt;
class CFGStmtMap {
ParentMap *PM;
void *M;
CFGStmtMap(ParentMap *pm, void *m) : PM(pm), M(m) {}
public:
~CFGStmtMap();
/// Returns a new CFGMap for the given CFG. It is the caller's
/// responsibility to 'delete' this object when done using it.
static CFGStmtMap *Build(CFG* C, ParentMap *PM);
/// Returns the CFGBlock the specified Stmt* appears in. For Stmt* that
/// are terminators, the CFGBlock is the block they appear as a terminator,
/// and not the block they appear as a block-level expression (e.g, '&&').
/// CaseStmts and LabelStmts map to the CFGBlock they label.
CFGBlock *getBlock(Stmt * S);
const CFGBlock *getBlock(const Stmt * S) const {
return const_cast<CFGStmtMap*>(this)->getBlock(const_cast<Stmt*>(S));
}
};
} // end clang namespace
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/AnalysisContext.h | //=== AnalysisContext.h - Analysis context for Path Sens analysis --*- 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 AnalysisDeclContext, a class that manages the analysis
// context data for path sensitive analysis.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSISCONTEXT_H
#define LLVM_CLANG_ANALYSIS_ANALYSISCONTEXT_H
#include "clang/AST/Decl.h"
#include "clang/Analysis/CFG.h"
#include "clang/Analysis/CodeInjector.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/Support/Allocator.h"
#include <memory>
namespace clang {
class Stmt;
class CFGReverseBlockReachabilityAnalysis;
class CFGStmtMap;
class LiveVariables;
class ManagedAnalysis;
class ParentMap;
class PseudoConstantAnalysis;
class LocationContextManager;
class StackFrameContext;
class BlockInvocationContext;
class AnalysisDeclContextManager;
class LocationContext;
namespace idx { class TranslationUnit; }
/// The base class of a hierarchy of objects representing analyses tied
/// to AnalysisDeclContext.
class ManagedAnalysis {
protected:
ManagedAnalysis() {}
public:
virtual ~ManagedAnalysis();
// Subclasses need to implement:
//
// static const void *getTag();
//
// Which returns a fixed pointer address to distinguish classes of
// analysis objects. They also need to implement:
//
// static [Derived*] create(AnalysisDeclContext &Ctx);
//
// which creates the analysis object given an AnalysisDeclContext.
};
/// AnalysisDeclContext contains the context data for the function or method
/// under analysis.
class AnalysisDeclContext {
/// Backpoint to the AnalysisManager object that created this
/// AnalysisDeclContext. This may be null.
AnalysisDeclContextManager *Manager;
const Decl * const D;
std::unique_ptr<CFG> cfg, completeCFG;
std::unique_ptr<CFGStmtMap> cfgStmtMap;
CFG::BuildOptions cfgBuildOptions;
CFG::BuildOptions::ForcedBlkExprs *forcedBlkExprs;
bool builtCFG, builtCompleteCFG;
std::unique_ptr<ParentMap> PM;
std::unique_ptr<PseudoConstantAnalysis> PCA;
std::unique_ptr<CFGReverseBlockReachabilityAnalysis> CFA;
llvm::BumpPtrAllocator A;
llvm::DenseMap<const BlockDecl*,void*> *ReferencedBlockVars;
void *ManagedAnalyses;
public:
AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
const Decl *D);
AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
const Decl *D,
const CFG::BuildOptions &BuildOptions);
~AnalysisDeclContext();
ASTContext &getASTContext() const { return D->getASTContext(); }
const Decl *getDecl() const { return D; }
/// Return the AnalysisDeclContextManager (if any) that created
/// this AnalysisDeclContext.
AnalysisDeclContextManager *getManager() const {
return Manager;
}
/// Return the build options used to construct the CFG.
CFG::BuildOptions &getCFGBuildOptions() {
return cfgBuildOptions;
}
const CFG::BuildOptions &getCFGBuildOptions() const {
return cfgBuildOptions;
}
/// getAddEHEdges - Return true iff we are adding exceptional edges from
/// callExprs. If this is false, then try/catch statements and blocks
/// reachable from them can appear to be dead in the CFG, analysis passes must
/// cope with that.
bool getAddEHEdges() const { return cfgBuildOptions.AddEHEdges; }
bool getUseUnoptimizedCFG() const {
return !cfgBuildOptions.PruneTriviallyFalseEdges;
}
bool getAddImplicitDtors() const { return cfgBuildOptions.AddImplicitDtors; }
bool getAddInitializers() const { return cfgBuildOptions.AddInitializers; }
void registerForcedBlockExpression(const Stmt *stmt);
const CFGBlock *getBlockForRegisteredExpression(const Stmt *stmt);
/// \brief Get the body of the Declaration.
Stmt *getBody() const;
/// \brief Get the body of the Declaration.
/// \param[out] IsAutosynthesized Specifies if the body is auto-generated
/// by the BodyFarm.
Stmt *getBody(bool &IsAutosynthesized) const;
/// \brief Checks if the body of the Decl is generated by the BodyFarm.
///
/// Note, the lookup is not free. We are going to call getBody behind
/// the scenes.
/// \sa getBody
bool isBodyAutosynthesized() const;
/// \brief Checks if the body of the Decl is generated by the BodyFarm from a
/// model file.
///
/// Note, the lookup is not free. We are going to call getBody behind
/// the scenes.
/// \sa getBody
bool isBodyAutosynthesizedFromModelFile() const;
CFG *getCFG();
CFGStmtMap *getCFGStmtMap();
CFGReverseBlockReachabilityAnalysis *getCFGReachablityAnalysis();
/// Return a version of the CFG without any edges pruned.
CFG *getUnoptimizedCFG();
void dumpCFG(bool ShowColors);
/// \brief Returns true if we have built a CFG for this analysis context.
/// Note that this doesn't correspond to whether or not a valid CFG exists, it
/// corresponds to whether we *attempted* to build one.
bool isCFGBuilt() const { return builtCFG; }
ParentMap &getParentMap();
PseudoConstantAnalysis *getPseudoConstantAnalysis();
typedef const VarDecl * const * referenced_decls_iterator;
llvm::iterator_range<referenced_decls_iterator>
getReferencedBlockVars(const BlockDecl *BD);
/// Return the ImplicitParamDecl* associated with 'self' if this
/// AnalysisDeclContext wraps an ObjCMethodDecl. Returns NULL otherwise.
const ImplicitParamDecl *getSelfDecl() const;
const StackFrameContext *getStackFrame(LocationContext const *Parent,
const Stmt *S,
const CFGBlock *Blk,
unsigned Idx);
const BlockInvocationContext *
getBlockInvocationContext(const LocationContext *parent,
const BlockDecl *BD,
const void *ContextData);
/// Return the specified analysis object, lazily running the analysis if
/// necessary. Return NULL if the analysis could not run.
template <typename T>
T *getAnalysis() {
const void *tag = T::getTag();
ManagedAnalysis *&data = getAnalysisImpl(tag);
if (!data) {
data = T::create(*this);
}
return static_cast<T*>(data);
}
private:
ManagedAnalysis *&getAnalysisImpl(const void* tag);
LocationContextManager &getLocationContextManager();
};
class LocationContext : public llvm::FoldingSetNode {
public:
enum ContextKind { StackFrame, Scope, Block };
private:
ContextKind Kind;
// AnalysisDeclContext can't be const since some methods may modify its
// member.
AnalysisDeclContext *Ctx;
const LocationContext *Parent;
protected:
LocationContext(ContextKind k, AnalysisDeclContext *ctx,
const LocationContext *parent)
: Kind(k), Ctx(ctx), Parent(parent) {}
public:
virtual ~LocationContext();
ContextKind getKind() const { return Kind; }
AnalysisDeclContext *getAnalysisDeclContext() const { return Ctx; }
const LocationContext *getParent() const { return Parent; }
bool isParentOf(const LocationContext *LC) const;
const Decl *getDecl() const { return getAnalysisDeclContext()->getDecl(); }
CFG *getCFG() const { return getAnalysisDeclContext()->getCFG(); }
template <typename T>
T *getAnalysis() const {
return getAnalysisDeclContext()->getAnalysis<T>();
}
ParentMap &getParentMap() const {
return getAnalysisDeclContext()->getParentMap();
}
const ImplicitParamDecl *getSelfDecl() const {
return Ctx->getSelfDecl();
}
const StackFrameContext *getCurrentStackFrame() const;
/// Return true if the current LocationContext has no caller context.
virtual bool inTopFrame() const;
virtual void Profile(llvm::FoldingSetNodeID &ID) = 0;
void dumpStack(raw_ostream &OS, StringRef Indent = "") const;
void dumpStack() const;
public:
static void ProfileCommon(llvm::FoldingSetNodeID &ID,
ContextKind ck,
AnalysisDeclContext *ctx,
const LocationContext *parent,
const void *data);
};
class StackFrameContext : public LocationContext {
// The callsite where this stack frame is established.
const Stmt *CallSite;
// The parent block of the callsite.
const CFGBlock *Block;
// The index of the callsite in the CFGBlock.
unsigned Index;
friend class LocationContextManager;
StackFrameContext(AnalysisDeclContext *ctx, const LocationContext *parent,
const Stmt *s, const CFGBlock *blk,
unsigned idx)
: LocationContext(StackFrame, ctx, parent), CallSite(s),
Block(blk), Index(idx) {}
public:
~StackFrameContext() override {}
const Stmt *getCallSite() const { return CallSite; }
const CFGBlock *getCallSiteBlock() const { return Block; }
/// Return true if the current LocationContext has no caller context.
bool inTopFrame() const override { return getParent() == nullptr; }
unsigned getIndex() const { return Index; }
void Profile(llvm::FoldingSetNodeID &ID) override;
static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ctx,
const LocationContext *parent, const Stmt *s,
const CFGBlock *blk, unsigned idx) {
ProfileCommon(ID, StackFrame, ctx, parent, s);
ID.AddPointer(blk);
ID.AddInteger(idx);
}
static bool classof(const LocationContext *Ctx) {
return Ctx->getKind() == StackFrame;
}
};
class ScopeContext : public LocationContext {
const Stmt *Enter;
friend class LocationContextManager;
ScopeContext(AnalysisDeclContext *ctx, const LocationContext *parent,
const Stmt *s)
: LocationContext(Scope, ctx, parent), Enter(s) {}
public:
~ScopeContext() override {}
void Profile(llvm::FoldingSetNodeID &ID) override;
static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ctx,
const LocationContext *parent, const Stmt *s) {
ProfileCommon(ID, Scope, ctx, parent, s);
}
static bool classof(const LocationContext *Ctx) {
return Ctx->getKind() == Scope;
}
};
class BlockInvocationContext : public LocationContext {
const BlockDecl *BD;
// FIXME: Come up with a more type-safe way to model context-sensitivity.
const void *ContextData;
friend class LocationContextManager;
BlockInvocationContext(AnalysisDeclContext *ctx,
const LocationContext *parent,
const BlockDecl *bd, const void *contextData)
: LocationContext(Block, ctx, parent), BD(bd), ContextData(contextData) {}
public:
~BlockInvocationContext() override {}
const BlockDecl *getBlockDecl() const { return BD; }
const void *getContextData() const { return ContextData; }
void Profile(llvm::FoldingSetNodeID &ID) override;
static void Profile(llvm::FoldingSetNodeID &ID, AnalysisDeclContext *ctx,
const LocationContext *parent, const BlockDecl *bd,
const void *contextData) {
ProfileCommon(ID, Block, ctx, parent, bd);
ID.AddPointer(contextData);
}
static bool classof(const LocationContext *Ctx) {
return Ctx->getKind() == Block;
}
};
class LocationContextManager {
llvm::FoldingSet<LocationContext> Contexts;
public:
~LocationContextManager();
const StackFrameContext *getStackFrame(AnalysisDeclContext *ctx,
const LocationContext *parent,
const Stmt *s,
const CFGBlock *blk, unsigned idx);
const ScopeContext *getScope(AnalysisDeclContext *ctx,
const LocationContext *parent,
const Stmt *s);
const BlockInvocationContext *
getBlockInvocationContext(AnalysisDeclContext *ctx,
const LocationContext *parent,
const BlockDecl *BD,
const void *ContextData);
/// Discard all previously created LocationContext objects.
void clear();
private:
template <typename LOC, typename DATA>
const LOC *getLocationContext(AnalysisDeclContext *ctx,
const LocationContext *parent,
const DATA *d);
};
class AnalysisDeclContextManager {
typedef llvm::DenseMap<const Decl*, AnalysisDeclContext*> ContextMap;
ContextMap Contexts;
LocationContextManager LocContexts;
CFG::BuildOptions cfgBuildOptions;
/// Pointer to an interface that can provide function bodies for
/// declarations from external source.
std::unique_ptr<CodeInjector> Injector;
/// Flag to indicate whether or not bodies should be synthesized
/// for well-known functions.
bool SynthesizeBodies;
public:
AnalysisDeclContextManager(bool useUnoptimizedCFG = false,
bool addImplicitDtors = false,
bool addInitializers = false,
bool addTemporaryDtors = false,
bool synthesizeBodies = false,
bool addStaticInitBranches = false,
bool addCXXNewAllocator = true,
CodeInjector* injector = nullptr);
~AnalysisDeclContextManager();
AnalysisDeclContext *getContext(const Decl *D);
bool getUseUnoptimizedCFG() const {
return !cfgBuildOptions.PruneTriviallyFalseEdges;
}
CFG::BuildOptions &getCFGBuildOptions() {
return cfgBuildOptions;
}
/// Return true if faux bodies should be synthesized for well-known
/// functions.
bool synthesizeBodies() const { return SynthesizeBodies; }
const StackFrameContext *getStackFrame(AnalysisDeclContext *Ctx,
LocationContext const *Parent,
const Stmt *S,
const CFGBlock *Blk,
unsigned Idx) {
return LocContexts.getStackFrame(Ctx, Parent, S, Blk, Idx);
}
// Get the top level stack frame.
const StackFrameContext *getStackFrame(const Decl *D) {
return LocContexts.getStackFrame(getContext(D), nullptr, nullptr, nullptr,
0);
}
// Get a stack frame with parent.
StackFrameContext const *getStackFrame(const Decl *D,
LocationContext const *Parent,
const Stmt *S,
const CFGBlock *Blk,
unsigned Idx) {
return LocContexts.getStackFrame(getContext(D), Parent, S, Blk, Idx);
}
/// Discard all previously created AnalysisDeclContexts.
void clear();
private:
friend class AnalysisDeclContext;
LocationContextManager &getLocationContextManager() {
return LocContexts;
}
};
} // end clang namespace
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/CallGraph.h | //== CallGraph.h - AST-based Call graph ------------------------*- C++ -*--==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares the AST-based CallGraph.
//
// A call graph for functions whose definitions/bodies are available in the
// current translation unit. The graph has a "virtual" root node that contains
// edges to all externally available functions.
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_CALLGRAPH_H
#define LLVM_CLANG_ANALYSIS_CALLGRAPH_H
#include "clang/AST/DeclBase.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/GraphTraits.h"
#include "llvm/ADT/SetVector.h"
namespace clang {
class CallGraphNode;
/// \brief The AST-based call graph.
///
/// The call graph extends itself with the given declarations by implementing
/// the recursive AST visitor, which constructs the graph by visiting the given
/// declarations.
class CallGraph : public RecursiveASTVisitor<CallGraph> {
friend class CallGraphNode;
typedef llvm::DenseMap<const Decl *, CallGraphNode *> FunctionMapTy;
/// FunctionMap owns all CallGraphNodes.
FunctionMapTy FunctionMap;
/// This is a virtual root node that has edges to all the functions.
CallGraphNode *Root;
public:
CallGraph();
~CallGraph();
/// \brief Populate the call graph with the functions in the given
/// declaration.
///
/// Recursively walks the declaration to find all the dependent Decls as well.
void addToCallGraph(Decl *D) {
TraverseDecl(D);
}
/// \brief Determine if a declaration should be included in the graph.
static bool includeInGraph(const Decl *D);
/// \brief Lookup the node for the given declaration.
CallGraphNode *getNode(const Decl *) const;
/// \brief Lookup the node for the given declaration. If none found, insert
/// one into the graph.
CallGraphNode *getOrInsertNode(Decl *);
/// Iterators through all the elements in the graph. Note, this gives
/// non-deterministic order.
typedef FunctionMapTy::iterator iterator;
typedef FunctionMapTy::const_iterator const_iterator;
iterator begin() { return FunctionMap.begin(); }
iterator end() { return FunctionMap.end(); }
const_iterator begin() const { return FunctionMap.begin(); }
const_iterator end() const { return FunctionMap.end(); }
/// \brief Get the number of nodes in the graph.
unsigned size() const { return FunctionMap.size(); }
/// \ brief Get the virtual root of the graph, all the functions available
/// externally are represented as callees of the node.
CallGraphNode *getRoot() const { return Root; }
/// Iterators through all the nodes of the graph that have no parent. These
/// are the unreachable nodes, which are either unused or are due to us
/// failing to add a call edge due to the analysis imprecision.
typedef llvm::SetVector<CallGraphNode *>::iterator nodes_iterator;
typedef llvm::SetVector<CallGraphNode *>::const_iterator const_nodes_iterator;
void print(raw_ostream &os) const;
void dump() const;
void viewGraph() const;
void addNodesForBlocks(DeclContext *D);
/// Part of recursive declaration visitation. We recursively visit all the
/// declarations to collect the root functions.
bool VisitFunctionDecl(FunctionDecl *FD) {
// We skip function template definitions, as their semantics is
// only determined when they are instantiated.
if (includeInGraph(FD)) {
// Add all blocks declared inside this function to the graph.
addNodesForBlocks(FD);
// If this function has external linkage, anything could call it.
// Note, we are not precise here. For example, the function could have
// its address taken.
addNodeForDecl(FD, FD->isGlobal());
}
return true;
}
/// Part of recursive declaration visitation.
bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
if (includeInGraph(MD)) {
addNodesForBlocks(MD);
addNodeForDecl(MD, true);
}
return true;
}
// We are only collecting the declarations, so do not step into the bodies.
bool TraverseStmt(Stmt *S) { return true; }
bool shouldWalkTypesOfTypeLocs() const { return false; }
private:
/// \brief Add the given declaration to the call graph.
void addNodeForDecl(Decl *D, bool IsGlobal);
/// \brief Allocate a new node in the graph.
CallGraphNode *allocateNewNode(Decl *);
};
class CallGraphNode {
public:
typedef CallGraphNode* CallRecord;
private:
/// \brief The function/method declaration.
Decl *FD;
/// \brief The list of functions called from this node.
SmallVector<CallRecord, 5> CalledFunctions;
public:
CallGraphNode(Decl *D) : FD(D) {}
typedef SmallVectorImpl<CallRecord>::iterator iterator;
typedef SmallVectorImpl<CallRecord>::const_iterator const_iterator;
/// Iterators through all the callees/children of the node.
inline iterator begin() { return CalledFunctions.begin(); }
inline iterator end() { return CalledFunctions.end(); }
inline const_iterator begin() const { return CalledFunctions.begin(); }
inline const_iterator end() const { return CalledFunctions.end(); }
inline bool empty() const {return CalledFunctions.empty(); }
inline unsigned size() const {return CalledFunctions.size(); }
void addCallee(CallGraphNode *N, CallGraph *CG) {
CalledFunctions.push_back(N);
}
Decl *getDecl() const { return FD; }
void print(raw_ostream &os) const;
void dump() const;
};
} // end clang namespace
// Graph traits for iteration, viewing.
namespace llvm {
template <> struct GraphTraits<clang::CallGraphNode*> {
typedef clang::CallGraphNode NodeType;
typedef clang::CallGraphNode::CallRecord CallRecordTy;
static clang::CallGraphNode *CGNDeref(CallRecordTy P) {
return P;
}
static NodeType *getEntryNode(clang::CallGraphNode *CGN) { return CGN; }
typedef mapped_iterator<NodeType::iterator, decltype(&CGNDeref)> ChildIteratorType;
static inline ChildIteratorType child_begin(NodeType *N) {
return ChildIteratorType(N->begin(), &CGNDeref);
}
static inline ChildIteratorType child_end (NodeType *N) {
return ChildIteratorType(N->end(), &CGNDeref);
}
};
template <> struct GraphTraits<const clang::CallGraphNode*> {
typedef const clang::CallGraphNode NodeType;
typedef NodeType::const_iterator ChildIteratorType;
static NodeType *getEntryNode(const clang::CallGraphNode *CGN) { return CGN; }
static inline ChildIteratorType child_begin(NodeType *N) { return N->begin();}
static inline ChildIteratorType child_end(NodeType *N) { return N->end(); }
};
template <> struct GraphTraits<clang::CallGraph*>
: public GraphTraits<clang::CallGraphNode*> {
static NodeType *getEntryNode(clang::CallGraph *CGN) {
return CGN->getRoot(); // Start at the external node!
}
typedef std::pair<const clang::Decl*, clang::CallGraphNode*> PairTy;
static clang::CallGraphNode &CGdereference(PairTy P) {
return *(P.second);
}
// nodes_iterator/begin/end - Allow iteration over all nodes in the graph
typedef mapped_iterator<clang::CallGraph::iterator, decltype(&CGdereference)> nodes_iterator;
static nodes_iterator nodes_begin(clang::CallGraph *CG) {
return nodes_iterator(CG->begin(), &CGdereference);
}
static nodes_iterator nodes_end (clang::CallGraph *CG) {
return nodes_iterator(CG->end(), &CGdereference);
}
static unsigned size(clang::CallGraph *CG) {
return CG->size();
}
};
template <> struct GraphTraits<const clang::CallGraph*> :
public GraphTraits<const clang::CallGraphNode*> {
static NodeType *getEntryNode(const clang::CallGraph *CGN) {
return CGN->getRoot();
}
typedef std::pair<const clang::Decl*, clang::CallGraphNode*> PairTy;
static clang::CallGraphNode &CGdereference(PairTy P) {
return *(P.second);
}
// nodes_iterator/begin/end - Allow iteration over all nodes in the graph
typedef mapped_iterator<clang::CallGraph::const_iterator,
decltype(&CGdereference)> nodes_iterator;
static nodes_iterator nodes_begin(const clang::CallGraph *CG) {
return nodes_iterator(CG->begin(), &CGdereference);
}
static nodes_iterator nodes_end(const clang::CallGraph *CG) {
return nodes_iterator(CG->end(), &CGdereference);
}
static unsigned size(const clang::CallGraph *CG) {
return CG->size();
}
};
} // end llvm namespace
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/FlowSensitive/DataflowValues.h | //===--- DataflowValues.h - Data structure for dataflow values --*- 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 a skeleton data structure for encapsulating the dataflow
// values for a CFG. Typically this is subclassed to provide methods for
// computing these values from a CFG.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSES_DATAFLOW_VALUES
#define LLVM_CLANG_ANALYSES_DATAFLOW_VALUES
#include "clang/Analysis/CFG.h"
#include "clang/Analysis/ProgramPoint.h"
#include "llvm/ADT/DenseMap.h"
//===----------------------------------------------------------------------===//
/// Dataflow Directional Tag Classes. These are used for tag dispatching
/// within the dataflow solver/transfer functions to determine what direction
/// a dataflow analysis flows.
//===----------------------------------------------------------------------===//
namespace clang {
namespace dataflow {
struct forward_analysis_tag {};
struct backward_analysis_tag {};
} // end namespace dataflow
//===----------------------------------------------------------------------===//
/// DataflowValues. Container class to store dataflow values for a CFG.
// //
///////////////////////////////////////////////////////////////////////////////
template <typename ValueTypes,
typename _AnalysisDirTag = dataflow::forward_analysis_tag >
class DataflowValues {
//===--------------------------------------------------------------------===//
// Type declarations.
//===--------------------------------------------------------------------===//
public:
typedef typename ValueTypes::ValTy ValTy;
typedef typename ValueTypes::AnalysisDataTy AnalysisDataTy;
typedef _AnalysisDirTag AnalysisDirTag;
typedef llvm::DenseMap<ProgramPoint, ValTy> EdgeDataMapTy;
typedef llvm::DenseMap<const CFGBlock*, ValTy> BlockDataMapTy;
typedef llvm::DenseMap<const Stmt*, ValTy> StmtDataMapTy;
//===--------------------------------------------------------------------===//
// Predicates.
//===--------------------------------------------------------------------===//
public:
/// isForwardAnalysis - Returns true if the dataflow values are computed
/// from a forward analysis.
bool isForwardAnalysis() { return isForwardAnalysis(AnalysisDirTag()); }
/// isBackwardAnalysis - Returns true if the dataflow values are computed
/// from a backward analysis.
bool isBackwardAnalysis() { return !isForwardAnalysis(); }
private:
bool isForwardAnalysis(dataflow::forward_analysis_tag) { return true; }
bool isForwardAnalysis(dataflow::backward_analysis_tag) { return false; }
//===--------------------------------------------------------------------===//
// Initialization and accessors methods.
//===--------------------------------------------------------------------===//
public:
DataflowValues() : StmtDataMap(NULL) {}
~DataflowValues() { delete StmtDataMap; }
/// InitializeValues - Invoked by the solver to initialize state needed for
/// dataflow analysis. This method is usually specialized by subclasses.
void InitializeValues(const CFG& cfg) {}
/// getEdgeData - Retrieves the dataflow values associated with a
/// CFG edge.
ValTy& getEdgeData(const BlockEdge &E) {
typename EdgeDataMapTy::iterator I = EdgeDataMap.find(E);
assert (I != EdgeDataMap.end() && "No data associated with Edge.");
return I->second;
}
const ValTy& getEdgeData(const BlockEdge &E) const {
return reinterpret_cast<DataflowValues*>(this)->getEdgeData(E);
}
/// getBlockData - Retrieves the dataflow values associated with a
/// specified CFGBlock. If the dataflow analysis is a forward analysis,
/// this data is associated with the END of the block. If the analysis
/// is a backwards analysis, it is associated with the ENTRY of the block.
ValTy& getBlockData(const CFGBlock *B) {
typename BlockDataMapTy::iterator I = BlockDataMap.find(B);
assert (I != BlockDataMap.end() && "No data associated with block.");
return I->second;
}
const ValTy& getBlockData(const CFGBlock *B) const {
return const_cast<DataflowValues*>(this)->getBlockData(B);
}
/// getStmtData - Retrieves the dataflow values associated with a
/// specified Stmt. If the dataflow analysis is a forward analysis,
/// this data corresponds to the point immediately before a Stmt.
/// If the analysis is a backwards analysis, it is associated with
/// the point after a Stmt. This data is only computed for block-level
/// expressions, and only when requested when the analysis is executed.
ValTy& getStmtData(const Stmt *S) {
assert (StmtDataMap && "Dataflow values were not computed for statements.");
typename StmtDataMapTy::iterator I = StmtDataMap->find(S);
assert (I != StmtDataMap->end() && "No data associated with statement.");
return I->second;
}
const ValTy& getStmtData(const Stmt *S) const {
return const_cast<DataflowValues*>(this)->getStmtData(S);
}
/// getEdgeDataMap - Retrieves the internal map between CFG edges and
/// dataflow values. Usually used by a dataflow solver to compute
/// values for blocks.
EdgeDataMapTy& getEdgeDataMap() { return EdgeDataMap; }
const EdgeDataMapTy& getEdgeDataMap() const { return EdgeDataMap; }
/// getBlockDataMap - Retrieves the internal map between CFGBlocks and
/// dataflow values. If the dataflow analysis operates in the forward
/// direction, the values correspond to the dataflow values at the start
/// of the block. Otherwise, for a backward analysis, the values correpsond
/// to the dataflow values at the end of the block.
BlockDataMapTy& getBlockDataMap() { return BlockDataMap; }
const BlockDataMapTy& getBlockDataMap() const { return BlockDataMap; }
/// getStmtDataMap - Retrieves the internal map between Stmts and
/// dataflow values.
StmtDataMapTy& getStmtDataMap() {
if (!StmtDataMap) StmtDataMap = new StmtDataMapTy();
return *StmtDataMap;
}
const StmtDataMapTy& getStmtDataMap() const {
return const_cast<DataflowValues*>(this)->getStmtDataMap();
}
/// getAnalysisData - Retrieves the meta data associated with a
/// dataflow analysis for analyzing a particular CFG.
/// This is typically consumed by transfer function code (via the solver).
/// This can also be used by subclasses to interpret the dataflow values.
AnalysisDataTy& getAnalysisData() { return AnalysisData; }
const AnalysisDataTy& getAnalysisData() const { return AnalysisData; }
//===--------------------------------------------------------------------===//
// Internal data.
//===--------------------------------------------------------------------===//
protected:
EdgeDataMapTy EdgeDataMap;
BlockDataMapTy BlockDataMap;
StmtDataMapTy* StmtDataMap;
AnalysisDataTy AnalysisData;
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/DomainSpecific/CocoaConventions.h | //===- CocoaConventions.h - Special handling of Cocoa conventions -*- C++ -*--//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements cocoa naming convention analysis.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_DOMAINSPECIFIC_COCOACONVENTIONS_H
#define LLVM_CLANG_ANALYSIS_DOMAINSPECIFIC_COCOACONVENTIONS_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/StringRef.h"
namespace clang {
class FunctionDecl;
class QualType;
namespace ento {
namespace cocoa {
bool isRefType(QualType RetTy, StringRef Prefix,
StringRef Name = StringRef());
bool isCocoaObjectRef(QualType T);
}
namespace coreFoundation {
bool isCFObjectRef(QualType T);
bool followsCreateRule(const FunctionDecl *FD);
}
}} // end: "clang:ento"
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/DomainSpecific/ObjCNoReturn.h | //= ObjCNoReturn.h - Handling of Cocoa APIs known not to return --*- C++ -*---//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements special handling of recognizing ObjC API hooks that
// do not return but aren't marked as such in API headers.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_DOMAINSPECIFIC_OBJCNORETURN_H
#define LLVM_CLANG_ANALYSIS_DOMAINSPECIFIC_OBJCNORETURN_H
#include "clang/Basic/IdentifierTable.h"
namespace clang {
class ASTContext;
class ObjCMessageExpr;
class ObjCNoReturn {
/// Cached "raise" selector.
Selector RaiseSel;
/// Cached identifier for "NSException".
IdentifierInfo *NSExceptionII;
enum { NUM_RAISE_SELECTORS = 2 };
/// Cached set of selectors in NSException that are 'noreturn'.
Selector NSExceptionInstanceRaiseSelectors[NUM_RAISE_SELECTORS];
public:
ObjCNoReturn(ASTContext &C);
/// Return true if the given message expression is known to never
/// return.
bool isImplicitNoReturn(const ObjCMessageExpr *ME);
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyOps.def | //===- ThreadSafetyTIL.h ---------------------------------------*- 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 list of core opcodes for the Thread Safety
// Typed Intermediate language. Please see ThreadSafetyTIL.h for more
// information.
//
//===----------------------------------------------------------------------===//
TIL_OPCODE_DEF(Future)
TIL_OPCODE_DEF(Undefined)
TIL_OPCODE_DEF(Wildcard)
TIL_OPCODE_DEF(Literal)
TIL_OPCODE_DEF(LiteralPtr)
TIL_OPCODE_DEF(Variable)
TIL_OPCODE_DEF(Function)
TIL_OPCODE_DEF(SFunction)
TIL_OPCODE_DEF(Code)
TIL_OPCODE_DEF(Field)
TIL_OPCODE_DEF(Apply)
TIL_OPCODE_DEF(SApply)
TIL_OPCODE_DEF(Project)
TIL_OPCODE_DEF(Call)
TIL_OPCODE_DEF(Alloc)
TIL_OPCODE_DEF(Load)
TIL_OPCODE_DEF(Store)
TIL_OPCODE_DEF(ArrayIndex)
TIL_OPCODE_DEF(ArrayAdd)
TIL_OPCODE_DEF(UnaryOp)
TIL_OPCODE_DEF(BinaryOp)
TIL_OPCODE_DEF(Cast)
TIL_OPCODE_DEF(SCFG)
TIL_OPCODE_DEF(BasicBlock)
TIL_OPCODE_DEF(Phi)
// Terminator instructions
TIL_OPCODE_DEF(Goto)
TIL_OPCODE_DEF(Branch)
TIL_OPCODE_DEF(Return)
// pseudo-terms
TIL_OPCODE_DEF(Identifier)
TIL_OPCODE_DEF(IfThenElse)
TIL_OPCODE_DEF(Let)
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTIL.h | //===- ThreadSafetyTIL.h ---------------------------------------*- C++ --*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT in the llvm repository for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines a simple Typed Intermediate Language, or TIL, that is used
// by the thread safety analysis (See ThreadSafety.cpp). The TIL is intended
// to be largely independent of clang, in the hope that the analysis can be
// reused for other non-C++ languages. All dependencies on clang/llvm should
// go in ThreadSafetyUtil.h.
//
// Thread safety analysis works by comparing mutex expressions, e.g.
//
// class A { Mutex mu; int dat GUARDED_BY(this->mu); }
// class B { A a; }
//
// void foo(B* b) {
// (*b).a.mu.lock(); // locks (*b).a.mu
// b->a.dat = 0; // substitute &b->a for 'this';
// // requires lock on (&b->a)->mu
// (b->a.mu).unlock(); // unlocks (b->a.mu)
// }
//
// As illustrated by the above example, clang Exprs are not well-suited to
// represent mutex expressions directly, since there is no easy way to compare
// Exprs for equivalence. The thread safety analysis thus lowers clang Exprs
// into a simple intermediate language (IL). The IL supports:
//
// (1) comparisons for semantic equality of expressions
// (2) SSA renaming of variables
// (3) wildcards and pattern matching over expressions
// (4) hash-based expression lookup
//
// The TIL is currently very experimental, is intended only for use within
// the thread safety analysis, and is subject to change without notice.
// After the API stabilizes and matures, it may be appropriate to make this
// more generally available to other analyses.
//
// UNDER CONSTRUCTION. USE AT YOUR OWN RISK.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTIL_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTIL_H
// All clang include dependencies for this file must be put in
// ThreadSafetyUtil.h.
#include "ThreadSafetyUtil.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <stdint.h>
#include <utility>
namespace clang {
namespace threadSafety {
namespace til {
/// Enum for the different distinct classes of SExpr
enum TIL_Opcode {
#define TIL_OPCODE_DEF(X) COP_##X,
#include "ThreadSafetyOps.def"
#undef TIL_OPCODE_DEF
};
/// Opcode for unary arithmetic operations.
enum TIL_UnaryOpcode : unsigned char {
UOP_Minus, // -
UOP_BitNot, // ~
UOP_LogicNot // !
};
/// Opcode for binary arithmetic operations.
enum TIL_BinaryOpcode : unsigned char {
BOP_Add, // +
BOP_Sub, // -
BOP_Mul, // *
BOP_Div, // /
BOP_Rem, // %
BOP_Shl, // <<
BOP_Shr, // >>
BOP_BitAnd, // &
BOP_BitXor, // ^
BOP_BitOr, // |
BOP_Eq, // ==
BOP_Neq, // !=
BOP_Lt, // <
BOP_Leq, // <=
BOP_LogicAnd, // && (no short-circuit)
BOP_LogicOr // || (no short-circuit)
};
/// Opcode for cast operations.
enum TIL_CastOpcode : unsigned char {
CAST_none = 0,
CAST_extendNum, // extend precision of numeric type
CAST_truncNum, // truncate precision of numeric type
CAST_toFloat, // convert to floating point type
CAST_toInt, // convert to integer type
CAST_objToPtr // convert smart pointer to pointer (C++ only)
};
const TIL_Opcode COP_Min = COP_Future;
const TIL_Opcode COP_Max = COP_Branch;
const TIL_UnaryOpcode UOP_Min = UOP_Minus;
const TIL_UnaryOpcode UOP_Max = UOP_LogicNot;
const TIL_BinaryOpcode BOP_Min = BOP_Add;
const TIL_BinaryOpcode BOP_Max = BOP_LogicOr;
const TIL_CastOpcode CAST_Min = CAST_none;
const TIL_CastOpcode CAST_Max = CAST_toInt;
/// Return the name of a unary opcode.
StringRef getUnaryOpcodeString(TIL_UnaryOpcode Op);
/// Return the name of a binary opcode.
StringRef getBinaryOpcodeString(TIL_BinaryOpcode Op);
/// ValueTypes are data types that can actually be held in registers.
/// All variables and expressions must have a value type.
/// Pointer types are further subdivided into the various heap-allocated
/// types, such as functions, records, etc.
/// Structured types that are passed by value (e.g. complex numbers)
/// require special handling; they use BT_ValueRef, and size ST_0.
struct ValueType {
enum BaseType : unsigned char {
BT_Void = 0,
BT_Bool,
BT_Int,
BT_Float,
BT_String, // String literals
BT_Pointer,
BT_ValueRef
};
enum SizeType : unsigned char {
ST_0 = 0,
ST_1,
ST_8,
ST_16,
ST_32,
ST_64,
ST_128
};
inline static SizeType getSizeType(unsigned nbytes);
template <class T>
inline static ValueType getValueType();
ValueType(BaseType B, SizeType Sz, bool S, unsigned char VS)
: Base(B), Size(Sz), Signed(S), VectSize(VS)
{ }
BaseType Base;
SizeType Size;
bool Signed;
unsigned char VectSize; // 0 for scalar, otherwise num elements in vector
};
inline ValueType::SizeType ValueType::getSizeType(unsigned nbytes) {
switch (nbytes) {
case 1: return ST_8;
case 2: return ST_16;
case 4: return ST_32;
case 8: return ST_64;
case 16: return ST_128;
default: return ST_0;
}
}
template<>
inline ValueType ValueType::getValueType<void>() {
return ValueType(BT_Void, ST_0, false, 0);
}
template<>
inline ValueType ValueType::getValueType<bool>() {
return ValueType(BT_Bool, ST_1, false, 0);
}
template<>
inline ValueType ValueType::getValueType<int8_t>() {
return ValueType(BT_Int, ST_8, true, 0);
}
template<>
inline ValueType ValueType::getValueType<uint8_t>() {
return ValueType(BT_Int, ST_8, false, 0);
}
template<>
inline ValueType ValueType::getValueType<int16_t>() {
return ValueType(BT_Int, ST_16, true, 0);
}
template<>
inline ValueType ValueType::getValueType<uint16_t>() {
return ValueType(BT_Int, ST_16, false, 0);
}
template<>
inline ValueType ValueType::getValueType<int32_t>() {
return ValueType(BT_Int, ST_32, true, 0);
}
template<>
inline ValueType ValueType::getValueType<uint32_t>() {
return ValueType(BT_Int, ST_32, false, 0);
}
template<>
inline ValueType ValueType::getValueType<int64_t>() {
return ValueType(BT_Int, ST_64, true, 0);
}
template<>
inline ValueType ValueType::getValueType<uint64_t>() {
return ValueType(BT_Int, ST_64, false, 0);
}
template<>
inline ValueType ValueType::getValueType<float>() {
return ValueType(BT_Float, ST_32, true, 0);
}
template<>
inline ValueType ValueType::getValueType<double>() {
return ValueType(BT_Float, ST_64, true, 0);
}
template<>
inline ValueType ValueType::getValueType<long double>() {
return ValueType(BT_Float, ST_128, true, 0);
}
template<>
inline ValueType ValueType::getValueType<StringRef>() {
return ValueType(BT_String, getSizeType(sizeof(StringRef)), false, 0);
}
template<>
inline ValueType ValueType::getValueType<void*>() {
return ValueType(BT_Pointer, getSizeType(sizeof(void*)), false, 0);
}
class BasicBlock;
/// Base class for AST nodes in the typed intermediate language.
class SExpr {
public:
TIL_Opcode opcode() const { return static_cast<TIL_Opcode>(Opcode); }
// Subclasses of SExpr must define the following:
//
// This(const This& E, ...) {
// copy constructor: construct copy of E, with some additional arguments.
// }
//
// template <class V>
// typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
// traverse all subexpressions, following the traversal/rewriter interface.
// }
//
// template <class C> typename C::CType compare(CType* E, C& Cmp) {
// compare all subexpressions, following the comparator interface
// }
void *operator new(size_t S, MemRegionRef &R) {
return ::operator new(S, R);
}
/// SExpr objects cannot be deleted.
// This declaration is public to workaround a gcc bug that breaks building
// with REQUIRES_EH=1.
void operator delete(void *) = delete;
/// Returns the instruction ID for this expression.
/// All basic block instructions have a unique ID (i.e. virtual register).
unsigned id() const { return SExprID; }
/// Returns the block, if this is an instruction in a basic block,
/// otherwise returns null.
BasicBlock* block() const { return Block; }
/// Set the basic block and instruction ID for this expression.
void setID(BasicBlock *B, unsigned id) { Block = B; SExprID = id; }
protected:
SExpr(TIL_Opcode Op)
: Opcode(Op), Reserved(0), Flags(0), SExprID(0), Block(nullptr) {}
SExpr(const SExpr &E)
: Opcode(E.Opcode), Reserved(0), Flags(E.Flags), SExprID(0),
Block(nullptr) {}
const unsigned char Opcode;
unsigned char Reserved;
unsigned short Flags;
unsigned SExprID;
BasicBlock* Block;
private:
SExpr() = delete;
/// SExpr objects must be created in an arena.
void *operator new(size_t) = delete;
};
// Contains various helper functions for SExprs.
namespace ThreadSafetyTIL {
inline bool isTrivial(const SExpr *E) {
unsigned Op = E->opcode();
return Op == COP_Variable || Op == COP_Literal || Op == COP_LiteralPtr;
}
}
// Nodes which declare variables
class Function;
class SFunction;
class Let;
/// A named variable, e.g. "x".
///
/// There are two distinct places in which a Variable can appear in the AST.
/// A variable declaration introduces a new variable, and can occur in 3 places:
/// Let-expressions: (Let (x = t) u)
/// Functions: (Function (x : t) u)
/// Self-applicable functions (SFunction (x) t)
///
/// If a variable occurs in any other location, it is a reference to an existing
/// variable declaration -- e.g. 'x' in (x * y + z). To save space, we don't
/// allocate a separate AST node for variable references; a reference is just a
/// pointer to the original declaration.
class Variable : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Variable; }
enum VariableKind {
VK_Let, ///< Let-variable
VK_Fun, ///< Function parameter
VK_SFun ///< SFunction (self) parameter
};
Variable(StringRef s, SExpr *D = nullptr)
: SExpr(COP_Variable), Name(s), Definition(D), Cvdecl(nullptr) {
Flags = VK_Let;
}
Variable(SExpr *D, const clang::ValueDecl *Cvd = nullptr)
: SExpr(COP_Variable), Name(Cvd ? Cvd->getName() : "_x"),
Definition(D), Cvdecl(Cvd) {
Flags = VK_Let;
}
Variable(const Variable &Vd, SExpr *D) // rewrite constructor
: SExpr(Vd), Name(Vd.Name), Definition(D), Cvdecl(Vd.Cvdecl) {
Flags = Vd.kind();
}
/// Return the kind of variable (let, function param, or self)
VariableKind kind() const { return static_cast<VariableKind>(Flags); }
/// Return the name of the variable, if any.
StringRef name() const { return Name; }
/// Return the clang declaration for this variable, if any.
const clang::ValueDecl *clangDecl() const { return Cvdecl; }
/// Return the definition of the variable.
/// For let-vars, this is the setting expression.
/// For function and self parameters, it is the type of the variable.
SExpr *definition() { return Definition; }
const SExpr *definition() const { return Definition; }
void setName(StringRef S) { Name = S; }
void setKind(VariableKind K) { Flags = K; }
void setDefinition(SExpr *E) { Definition = E; }
void setClangDecl(const clang::ValueDecl *VD) { Cvdecl = VD; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
// This routine is only called for variable references.
return Vs.reduceVariableRef(this);
}
template <class C>
typename C::CType compare(const Variable* E, C& Cmp) const {
return Cmp.compareVariableRefs(this, E);
}
private:
friend class Function;
friend class SFunction;
friend class BasicBlock;
friend class Let;
StringRef Name; // The name of the variable.
SExpr* Definition; // The TIL type or definition
const clang::ValueDecl *Cvdecl; // The clang declaration for this variable.
};
/// Placeholder for an expression that has not yet been created.
/// Used to implement lazy copy and rewriting strategies.
class Future : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Future; }
enum FutureStatus {
FS_pending,
FS_evaluating,
FS_done
};
Future() : SExpr(COP_Future), Status(FS_pending), Result(nullptr) {}
private:
virtual ~Future() = delete;
public:
// A lazy rewriting strategy should subclass Future and override this method.
virtual SExpr *compute() { return nullptr; }
// Return the result of this future if it exists, otherwise return null.
SExpr *maybeGetResult() const {
return Result;
}
// Return the result of this future; forcing it if necessary.
SExpr *result() {
switch (Status) {
case FS_pending:
return force();
case FS_evaluating:
return nullptr; // infinite loop; illegal recursion.
case FS_done:
return Result;
}
}
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
assert(Result && "Cannot traverse Future that has not been forced.");
return Vs.traverse(Result, Ctx);
}
template <class C>
typename C::CType compare(const Future* E, C& Cmp) const {
if (!Result || !E->Result)
return Cmp.comparePointers(this, E);
return Cmp.compare(Result, E->Result);
}
private:
SExpr* force();
FutureStatus Status;
SExpr *Result;
};
/// Placeholder for expressions that cannot be represented in the TIL.
class Undefined : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Undefined; }
Undefined(const clang::Stmt *S = nullptr) : SExpr(COP_Undefined), Cstmt(S) {}
Undefined(const Undefined &U) : SExpr(U), Cstmt(U.Cstmt) {}
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
return Vs.reduceUndefined(*this);
}
template <class C>
typename C::CType compare(const Undefined* E, C& Cmp) const {
return Cmp.trueResult();
}
private:
const clang::Stmt *Cstmt;
};
/// Placeholder for a wildcard that matches any other expression.
class Wildcard : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Wildcard; }
Wildcard() : SExpr(COP_Wildcard) {}
Wildcard(const Wildcard &W) : SExpr(W) {}
template <class V> typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
return Vs.reduceWildcard(*this);
}
template <class C>
typename C::CType compare(const Wildcard* E, C& Cmp) const {
return Cmp.trueResult();
}
};
template <class T> class LiteralT;
// Base class for literal values.
class Literal : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Literal; }
Literal(const clang::Expr *C)
: SExpr(COP_Literal), ValType(ValueType::getValueType<void>()), Cexpr(C)
{ }
Literal(ValueType VT) : SExpr(COP_Literal), ValType(VT), Cexpr(nullptr) {}
Literal(const Literal &L) : SExpr(L), ValType(L.ValType), Cexpr(L.Cexpr) {}
// The clang expression for this literal.
const clang::Expr *clangExpr() const { return Cexpr; }
ValueType valueType() const { return ValType; }
template<class T> const LiteralT<T>& as() const {
return *static_cast<const LiteralT<T>*>(this);
}
template<class T> LiteralT<T>& as() {
return *static_cast<LiteralT<T>*>(this);
}
template <class V> typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx);
template <class C>
typename C::CType compare(const Literal* E, C& Cmp) const {
// TODO: defer actual comparison to LiteralT
return Cmp.trueResult();
}
private:
const ValueType ValType;
const clang::Expr *Cexpr;
};
// Derived class for literal values, which stores the actual value.
template<class T>
class LiteralT : public Literal {
public:
LiteralT(T Dat) : Literal(ValueType::getValueType<T>()), Val(Dat) { }
LiteralT(const LiteralT<T> &L) : Literal(L), Val(L.Val) { }
T value() const { return Val;}
T& value() { return Val; }
private:
T Val;
};
template <class V>
typename V::R_SExpr Literal::traverse(V &Vs, typename V::R_Ctx Ctx) {
if (Cexpr)
return Vs.reduceLiteral(*this);
switch (ValType.Base) {
case ValueType::BT_Void:
break;
case ValueType::BT_Bool:
return Vs.reduceLiteralT(as<bool>());
case ValueType::BT_Int: {
switch (ValType.Size) {
case ValueType::ST_8:
if (ValType.Signed)
return Vs.reduceLiteralT(as<int8_t>());
else
return Vs.reduceLiteralT(as<uint8_t>());
case ValueType::ST_16:
if (ValType.Signed)
return Vs.reduceLiteralT(as<int16_t>());
else
return Vs.reduceLiteralT(as<uint16_t>());
case ValueType::ST_32:
if (ValType.Signed)
return Vs.reduceLiteralT(as<int32_t>());
else
return Vs.reduceLiteralT(as<uint32_t>());
case ValueType::ST_64:
if (ValType.Signed)
return Vs.reduceLiteralT(as<int64_t>());
else
return Vs.reduceLiteralT(as<uint64_t>());
default:
break;
}
}
case ValueType::BT_Float: {
switch (ValType.Size) {
case ValueType::ST_32:
return Vs.reduceLiteralT(as<float>());
case ValueType::ST_64:
return Vs.reduceLiteralT(as<double>());
default:
break;
}
}
case ValueType::BT_String:
return Vs.reduceLiteralT(as<StringRef>());
case ValueType::BT_Pointer:
return Vs.reduceLiteralT(as<void*>());
case ValueType::BT_ValueRef:
break;
}
return Vs.reduceLiteral(*this);
}
/// A Literal pointer to an object allocated in memory.
/// At compile time, pointer literals are represented by symbolic names.
class LiteralPtr : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_LiteralPtr; }
LiteralPtr(const clang::ValueDecl *D) : SExpr(COP_LiteralPtr), Cvdecl(D) {}
LiteralPtr(const LiteralPtr &R) : SExpr(R), Cvdecl(R.Cvdecl) {}
// The clang declaration for the value that this pointer points to.
const clang::ValueDecl *clangDecl() const { return Cvdecl; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
return Vs.reduceLiteralPtr(*this);
}
template <class C>
typename C::CType compare(const LiteralPtr* E, C& Cmp) const {
return Cmp.comparePointers(Cvdecl, E->Cvdecl);
}
private:
const clang::ValueDecl *Cvdecl;
};
/// A function -- a.k.a. lambda abstraction.
/// Functions with multiple arguments are created by currying,
/// e.g. (Function (x: Int) (Function (y: Int) (Code { return x + y })))
class Function : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Function; }
Function(Variable *Vd, SExpr *Bd)
: SExpr(COP_Function), VarDecl(Vd), Body(Bd) {
Vd->setKind(Variable::VK_Fun);
}
Function(const Function &F, Variable *Vd, SExpr *Bd) // rewrite constructor
: SExpr(F), VarDecl(Vd), Body(Bd) {
Vd->setKind(Variable::VK_Fun);
}
Variable *variableDecl() { return VarDecl; }
const Variable *variableDecl() const { return VarDecl; }
SExpr *body() { return Body; }
const SExpr *body() const { return Body; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
// This is a variable declaration, so traverse the definition.
auto E0 = Vs.traverse(VarDecl->Definition, Vs.typeCtx(Ctx));
// Tell the rewriter to enter the scope of the function.
Variable *Nvd = Vs.enterScope(*VarDecl, E0);
auto E1 = Vs.traverse(Body, Vs.declCtx(Ctx));
Vs.exitScope(*VarDecl);
return Vs.reduceFunction(*this, Nvd, E1);
}
template <class C>
typename C::CType compare(const Function* E, C& Cmp) const {
typename C::CType Ct =
Cmp.compare(VarDecl->definition(), E->VarDecl->definition());
if (Cmp.notTrue(Ct))
return Ct;
Cmp.enterScope(variableDecl(), E->variableDecl());
Ct = Cmp.compare(body(), E->body());
Cmp.leaveScope();
return Ct;
}
private:
Variable *VarDecl;
SExpr* Body;
};
/// A self-applicable function.
/// A self-applicable function can be applied to itself. It's useful for
/// implementing objects and late binding.
class SFunction : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_SFunction; }
SFunction(Variable *Vd, SExpr *B)
: SExpr(COP_SFunction), VarDecl(Vd), Body(B) {
assert(Vd->Definition == nullptr);
Vd->setKind(Variable::VK_SFun);
Vd->Definition = this;
}
SFunction(const SFunction &F, Variable *Vd, SExpr *B) // rewrite constructor
: SExpr(F), VarDecl(Vd), Body(B) {
assert(Vd->Definition == nullptr);
Vd->setKind(Variable::VK_SFun);
Vd->Definition = this;
}
Variable *variableDecl() { return VarDecl; }
const Variable *variableDecl() const { return VarDecl; }
SExpr *body() { return Body; }
const SExpr *body() const { return Body; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
// A self-variable points to the SFunction itself.
// A rewrite must introduce the variable with a null definition, and update
// it after 'this' has been rewritten.
Variable *Nvd = Vs.enterScope(*VarDecl, nullptr);
auto E1 = Vs.traverse(Body, Vs.declCtx(Ctx));
Vs.exitScope(*VarDecl);
// A rewrite operation will call SFun constructor to set Vvd->Definition.
return Vs.reduceSFunction(*this, Nvd, E1);
}
template <class C>
typename C::CType compare(const SFunction* E, C& Cmp) const {
Cmp.enterScope(variableDecl(), E->variableDecl());
typename C::CType Ct = Cmp.compare(body(), E->body());
Cmp.leaveScope();
return Ct;
}
private:
Variable *VarDecl;
SExpr* Body;
};
/// A block of code -- e.g. the body of a function.
class Code : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Code; }
Code(SExpr *T, SExpr *B) : SExpr(COP_Code), ReturnType(T), Body(B) {}
Code(const Code &C, SExpr *T, SExpr *B) // rewrite constructor
: SExpr(C), ReturnType(T), Body(B) {}
SExpr *returnType() { return ReturnType; }
const SExpr *returnType() const { return ReturnType; }
SExpr *body() { return Body; }
const SExpr *body() const { return Body; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Nt = Vs.traverse(ReturnType, Vs.typeCtx(Ctx));
auto Nb = Vs.traverse(Body, Vs.lazyCtx(Ctx));
return Vs.reduceCode(*this, Nt, Nb);
}
template <class C>
typename C::CType compare(const Code* E, C& Cmp) const {
typename C::CType Ct = Cmp.compare(returnType(), E->returnType());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(body(), E->body());
}
private:
SExpr* ReturnType;
SExpr* Body;
};
/// A typed, writable location in memory
class Field : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Field; }
Field(SExpr *R, SExpr *B) : SExpr(COP_Field), Range(R), Body(B) {}
Field(const Field &C, SExpr *R, SExpr *B) // rewrite constructor
: SExpr(C), Range(R), Body(B) {}
SExpr *range() { return Range; }
const SExpr *range() const { return Range; }
SExpr *body() { return Body; }
const SExpr *body() const { return Body; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Nr = Vs.traverse(Range, Vs.typeCtx(Ctx));
auto Nb = Vs.traverse(Body, Vs.lazyCtx(Ctx));
return Vs.reduceField(*this, Nr, Nb);
}
template <class C>
typename C::CType compare(const Field* E, C& Cmp) const {
typename C::CType Ct = Cmp.compare(range(), E->range());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(body(), E->body());
}
private:
SExpr* Range;
SExpr* Body;
};
/// Apply an argument to a function.
/// Note that this does not actually call the function. Functions are curried,
/// so this returns a closure in which the first parameter has been applied.
/// Once all parameters have been applied, Call can be used to invoke the
/// function.
class Apply : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Apply; }
Apply(SExpr *F, SExpr *A) : SExpr(COP_Apply), Fun(F), Arg(A) {}
Apply(const Apply &A, SExpr *F, SExpr *Ar) // rewrite constructor
: SExpr(A), Fun(F), Arg(Ar)
{}
SExpr *fun() { return Fun; }
const SExpr *fun() const { return Fun; }
SExpr *arg() { return Arg; }
const SExpr *arg() const { return Arg; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Nf = Vs.traverse(Fun, Vs.subExprCtx(Ctx));
auto Na = Vs.traverse(Arg, Vs.subExprCtx(Ctx));
return Vs.reduceApply(*this, Nf, Na);
}
template <class C>
typename C::CType compare(const Apply* E, C& Cmp) const {
typename C::CType Ct = Cmp.compare(fun(), E->fun());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(arg(), E->arg());
}
private:
SExpr* Fun;
SExpr* Arg;
};
/// Apply a self-argument to a self-applicable function.
class SApply : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_SApply; }
SApply(SExpr *Sf, SExpr *A = nullptr) : SExpr(COP_SApply), Sfun(Sf), Arg(A) {}
SApply(SApply &A, SExpr *Sf, SExpr *Ar = nullptr) // rewrite constructor
: SExpr(A), Sfun(Sf), Arg(Ar) {}
SExpr *sfun() { return Sfun; }
const SExpr *sfun() const { return Sfun; }
SExpr *arg() { return Arg ? Arg : Sfun; }
const SExpr *arg() const { return Arg ? Arg : Sfun; }
bool isDelegation() const { return Arg != nullptr; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Nf = Vs.traverse(Sfun, Vs.subExprCtx(Ctx));
typename V::R_SExpr Na = Arg ? Vs.traverse(Arg, Vs.subExprCtx(Ctx))
: nullptr;
return Vs.reduceSApply(*this, Nf, Na);
}
template <class C>
typename C::CType compare(const SApply* E, C& Cmp) const {
typename C::CType Ct = Cmp.compare(sfun(), E->sfun());
if (Cmp.notTrue(Ct) || (!arg() && !E->arg()))
return Ct;
return Cmp.compare(arg(), E->arg());
}
private:
SExpr* Sfun;
SExpr* Arg;
};
/// Project a named slot from a C++ struct or class.
class Project : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Project; }
Project(SExpr *R, StringRef SName)
: SExpr(COP_Project), Rec(R), SlotName(SName), Cvdecl(nullptr)
{ }
Project(SExpr *R, const clang::ValueDecl *Cvd)
: SExpr(COP_Project), Rec(R), SlotName(Cvd->getName()), Cvdecl(Cvd)
{ }
Project(const Project &P, SExpr *R)
: SExpr(P), Rec(R), SlotName(P.SlotName), Cvdecl(P.Cvdecl)
{ }
SExpr *record() { return Rec; }
const SExpr *record() const { return Rec; }
const clang::ValueDecl *clangDecl() const { return Cvdecl; }
bool isArrow() const { return (Flags & 0x01) != 0; }
void setArrow(bool b) {
if (b) Flags |= 0x01;
else Flags &= 0xFFFE;
}
StringRef slotName() const {
if (Cvdecl)
return Cvdecl->getName();
else
return SlotName;
}
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Nr = Vs.traverse(Rec, Vs.subExprCtx(Ctx));
return Vs.reduceProject(*this, Nr);
}
template <class C>
typename C::CType compare(const Project* E, C& Cmp) const {
typename C::CType Ct = Cmp.compare(record(), E->record());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.comparePointers(Cvdecl, E->Cvdecl);
}
private:
SExpr* Rec;
StringRef SlotName;
const clang::ValueDecl *Cvdecl;
};
/// Call a function (after all arguments have been applied).
class Call : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Call; }
Call(SExpr *T, const clang::CallExpr *Ce = nullptr)
: SExpr(COP_Call), Target(T), Cexpr(Ce) {}
Call(const Call &C, SExpr *T) : SExpr(C), Target(T), Cexpr(C.Cexpr) {}
SExpr *target() { return Target; }
const SExpr *target() const { return Target; }
const clang::CallExpr *clangCallExpr() const { return Cexpr; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Nt = Vs.traverse(Target, Vs.subExprCtx(Ctx));
return Vs.reduceCall(*this, Nt);
}
template <class C>
typename C::CType compare(const Call* E, C& Cmp) const {
return Cmp.compare(target(), E->target());
}
private:
SExpr* Target;
const clang::CallExpr *Cexpr;
};
/// Allocate memory for a new value on the heap or stack.
class Alloc : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Call; }
enum AllocKind {
AK_Stack,
AK_Heap
};
Alloc(SExpr *D, AllocKind K) : SExpr(COP_Alloc), Dtype(D) { Flags = K; }
Alloc(const Alloc &A, SExpr *Dt) : SExpr(A), Dtype(Dt) { Flags = A.kind(); }
AllocKind kind() const { return static_cast<AllocKind>(Flags); }
SExpr *dataType() { return Dtype; }
const SExpr *dataType() const { return Dtype; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Nd = Vs.traverse(Dtype, Vs.declCtx(Ctx));
return Vs.reduceAlloc(*this, Nd);
}
template <class C>
typename C::CType compare(const Alloc* E, C& Cmp) const {
typename C::CType Ct = Cmp.compareIntegers(kind(), E->kind());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(dataType(), E->dataType());
}
private:
SExpr* Dtype;
};
/// Load a value from memory.
class Load : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Load; }
Load(SExpr *P) : SExpr(COP_Load), Ptr(P) {}
Load(const Load &L, SExpr *P) : SExpr(L), Ptr(P) {}
SExpr *pointer() { return Ptr; }
const SExpr *pointer() const { return Ptr; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Np = Vs.traverse(Ptr, Vs.subExprCtx(Ctx));
return Vs.reduceLoad(*this, Np);
}
template <class C>
typename C::CType compare(const Load* E, C& Cmp) const {
return Cmp.compare(pointer(), E->pointer());
}
private:
SExpr* Ptr;
};
/// Store a value to memory.
/// The destination is a pointer to a field, the source is the value to store.
class Store : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Store; }
Store(SExpr *P, SExpr *V) : SExpr(COP_Store), Dest(P), Source(V) {}
Store(const Store &S, SExpr *P, SExpr *V) : SExpr(S), Dest(P), Source(V) {}
SExpr *destination() { return Dest; } // Address to store to
const SExpr *destination() const { return Dest; }
SExpr *source() { return Source; } // Value to store
const SExpr *source() const { return Source; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Np = Vs.traverse(Dest, Vs.subExprCtx(Ctx));
auto Nv = Vs.traverse(Source, Vs.subExprCtx(Ctx));
return Vs.reduceStore(*this, Np, Nv);
}
template <class C>
typename C::CType compare(const Store* E, C& Cmp) const {
typename C::CType Ct = Cmp.compare(destination(), E->destination());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(source(), E->source());
}
private:
SExpr* Dest;
SExpr* Source;
};
/// If p is a reference to an array, then p[i] is a reference to the i'th
/// element of the array.
class ArrayIndex : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_ArrayIndex; }
ArrayIndex(SExpr *A, SExpr *N) : SExpr(COP_ArrayIndex), Array(A), Index(N) {}
ArrayIndex(const ArrayIndex &E, SExpr *A, SExpr *N)
: SExpr(E), Array(A), Index(N) {}
SExpr *array() { return Array; }
const SExpr *array() const { return Array; }
SExpr *index() { return Index; }
const SExpr *index() const { return Index; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Na = Vs.traverse(Array, Vs.subExprCtx(Ctx));
auto Ni = Vs.traverse(Index, Vs.subExprCtx(Ctx));
return Vs.reduceArrayIndex(*this, Na, Ni);
}
template <class C>
typename C::CType compare(const ArrayIndex* E, C& Cmp) const {
typename C::CType Ct = Cmp.compare(array(), E->array());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(index(), E->index());
}
private:
SExpr* Array;
SExpr* Index;
};
/// Pointer arithmetic, restricted to arrays only.
/// If p is a reference to an array, then p + n, where n is an integer, is
/// a reference to a subarray.
class ArrayAdd : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_ArrayAdd; }
ArrayAdd(SExpr *A, SExpr *N) : SExpr(COP_ArrayAdd), Array(A), Index(N) {}
ArrayAdd(const ArrayAdd &E, SExpr *A, SExpr *N)
: SExpr(E), Array(A), Index(N) {}
SExpr *array() { return Array; }
const SExpr *array() const { return Array; }
SExpr *index() { return Index; }
const SExpr *index() const { return Index; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Na = Vs.traverse(Array, Vs.subExprCtx(Ctx));
auto Ni = Vs.traverse(Index, Vs.subExprCtx(Ctx));
return Vs.reduceArrayAdd(*this, Na, Ni);
}
template <class C>
typename C::CType compare(const ArrayAdd* E, C& Cmp) const {
typename C::CType Ct = Cmp.compare(array(), E->array());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(index(), E->index());
}
private:
SExpr* Array;
SExpr* Index;
};
/// Simple arithmetic unary operations, e.g. negate and not.
/// These operations have no side-effects.
class UnaryOp : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_UnaryOp; }
UnaryOp(TIL_UnaryOpcode Op, SExpr *E) : SExpr(COP_UnaryOp), Expr0(E) {
Flags = Op;
}
UnaryOp(const UnaryOp &U, SExpr *E) : SExpr(U), Expr0(E) { Flags = U.Flags; }
TIL_UnaryOpcode unaryOpcode() const {
return static_cast<TIL_UnaryOpcode>(Flags);
}
SExpr *expr() { return Expr0; }
const SExpr *expr() const { return Expr0; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Ne = Vs.traverse(Expr0, Vs.subExprCtx(Ctx));
return Vs.reduceUnaryOp(*this, Ne);
}
template <class C>
typename C::CType compare(const UnaryOp* E, C& Cmp) const {
typename C::CType Ct =
Cmp.compareIntegers(unaryOpcode(), E->unaryOpcode());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(expr(), E->expr());
}
private:
SExpr* Expr0;
};
/// Simple arithmetic binary operations, e.g. +, -, etc.
/// These operations have no side effects.
class BinaryOp : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_BinaryOp; }
BinaryOp(TIL_BinaryOpcode Op, SExpr *E0, SExpr *E1)
: SExpr(COP_BinaryOp), Expr0(E0), Expr1(E1) {
Flags = Op;
}
BinaryOp(const BinaryOp &B, SExpr *E0, SExpr *E1)
: SExpr(B), Expr0(E0), Expr1(E1) {
Flags = B.Flags;
}
TIL_BinaryOpcode binaryOpcode() const {
return static_cast<TIL_BinaryOpcode>(Flags);
}
SExpr *expr0() { return Expr0; }
const SExpr *expr0() const { return Expr0; }
SExpr *expr1() { return Expr1; }
const SExpr *expr1() const { return Expr1; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Ne0 = Vs.traverse(Expr0, Vs.subExprCtx(Ctx));
auto Ne1 = Vs.traverse(Expr1, Vs.subExprCtx(Ctx));
return Vs.reduceBinaryOp(*this, Ne0, Ne1);
}
template <class C>
typename C::CType compare(const BinaryOp* E, C& Cmp) const {
typename C::CType Ct =
Cmp.compareIntegers(binaryOpcode(), E->binaryOpcode());
if (Cmp.notTrue(Ct))
return Ct;
Ct = Cmp.compare(expr0(), E->expr0());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(expr1(), E->expr1());
}
private:
SExpr* Expr0;
SExpr* Expr1;
};
/// Cast expressions.
/// Cast expressions are essentially unary operations, but we treat them
/// as a distinct AST node because they only change the type of the result.
class Cast : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Cast; }
Cast(TIL_CastOpcode Op, SExpr *E) : SExpr(COP_Cast), Expr0(E) { Flags = Op; }
Cast(const Cast &C, SExpr *E) : SExpr(C), Expr0(E) { Flags = C.Flags; }
TIL_CastOpcode castOpcode() const {
return static_cast<TIL_CastOpcode>(Flags);
}
SExpr *expr() { return Expr0; }
const SExpr *expr() const { return Expr0; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Ne = Vs.traverse(Expr0, Vs.subExprCtx(Ctx));
return Vs.reduceCast(*this, Ne);
}
template <class C>
typename C::CType compare(const Cast* E, C& Cmp) const {
typename C::CType Ct =
Cmp.compareIntegers(castOpcode(), E->castOpcode());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(expr(), E->expr());
}
private:
SExpr* Expr0;
};
class SCFG;
/// Phi Node, for code in SSA form.
/// Each Phi node has an array of possible values that it can take,
/// depending on where control flow comes from.
class Phi : public SExpr {
public:
typedef SimpleArray<SExpr *> ValArray;
// In minimal SSA form, all Phi nodes are MultiVal.
// During conversion to SSA, incomplete Phi nodes may be introduced, which
// are later determined to be SingleVal, and are thus redundant.
enum Status {
PH_MultiVal = 0, // Phi node has multiple distinct values. (Normal)
PH_SingleVal, // Phi node has one distinct value, and can be eliminated
PH_Incomplete // Phi node is incomplete
};
static bool classof(const SExpr *E) { return E->opcode() == COP_Phi; }
Phi()
: SExpr(COP_Phi), Cvdecl(nullptr) {}
Phi(MemRegionRef A, unsigned Nvals)
: SExpr(COP_Phi), Values(A, Nvals), Cvdecl(nullptr) {}
Phi(const Phi &P, ValArray &&Vs)
: SExpr(P), Values(std::move(Vs)), Cvdecl(nullptr) {}
const ValArray &values() const { return Values; }
ValArray &values() { return Values; }
Status status() const { return static_cast<Status>(Flags); }
void setStatus(Status s) { Flags = s; }
/// Return the clang declaration of the variable for this Phi node, if any.
const clang::ValueDecl *clangDecl() const { return Cvdecl; }
/// Set the clang variable associated with this Phi node.
void setClangDecl(const clang::ValueDecl *Cvd) { Cvdecl = Cvd; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
typename V::template Container<typename V::R_SExpr>
Nvs(Vs, Values.size());
for (auto *Val : Values) {
Nvs.push_back( Vs.traverse(Val, Vs.subExprCtx(Ctx)) );
}
return Vs.reducePhi(*this, Nvs);
}
template <class C>
typename C::CType compare(const Phi *E, C &Cmp) const {
// TODO: implement CFG comparisons
return Cmp.comparePointers(this, E);
}
private:
ValArray Values;
const clang::ValueDecl* Cvdecl;
};
/// Base class for basic block terminators: Branch, Goto, and Return.
class Terminator : public SExpr {
public:
static bool classof(const SExpr *E) {
return E->opcode() >= COP_Goto && E->opcode() <= COP_Return;
}
protected:
Terminator(TIL_Opcode Op) : SExpr(Op) {}
Terminator(const SExpr &E) : SExpr(E) {}
public:
/// Return the list of basic blocks that this terminator can branch to.
ArrayRef<BasicBlock*> successors();
ArrayRef<BasicBlock*> successors() const {
return const_cast<Terminator*>(this)->successors();
}
};
/// Jump to another basic block.
/// A goto instruction is essentially a tail-recursive call into another
/// block. In addition to the block pointer, it specifies an index into the
/// phi nodes of that block. The index can be used to retrieve the "arguments"
/// of the call.
class Goto : public Terminator {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Goto; }
Goto(BasicBlock *B, unsigned I)
: Terminator(COP_Goto), TargetBlock(B), Index(I) {}
Goto(const Goto &G, BasicBlock *B, unsigned I)
: Terminator(COP_Goto), TargetBlock(B), Index(I) {}
const BasicBlock *targetBlock() const { return TargetBlock; }
BasicBlock *targetBlock() { return TargetBlock; }
/// Returns the index into the
unsigned index() const { return Index; }
/// Return the list of basic blocks that this terminator can branch to.
ArrayRef<BasicBlock*> successors() {
return ArrayRef<BasicBlock*>(&TargetBlock, 1);
}
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
BasicBlock *Ntb = Vs.reduceBasicBlockRef(TargetBlock);
return Vs.reduceGoto(*this, Ntb);
}
template <class C>
typename C::CType compare(const Goto *E, C &Cmp) const {
// TODO: implement CFG comparisons
return Cmp.comparePointers(this, E);
}
private:
BasicBlock *TargetBlock;
unsigned Index;
};
/// A conditional branch to two other blocks.
/// Note that unlike Goto, Branch does not have an index. The target blocks
/// must be child-blocks, and cannot have Phi nodes.
class Branch : public Terminator {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Branch; }
Branch(SExpr *C, BasicBlock *T, BasicBlock *E)
: Terminator(COP_Branch), Condition(C) {
Branches[0] = T;
Branches[1] = E;
}
Branch(const Branch &Br, SExpr *C, BasicBlock *T, BasicBlock *E)
: Terminator(Br), Condition(C) {
Branches[0] = T;
Branches[1] = E;
}
const SExpr *condition() const { return Condition; }
SExpr *condition() { return Condition; }
const BasicBlock *thenBlock() const { return Branches[0]; }
BasicBlock *thenBlock() { return Branches[0]; }
const BasicBlock *elseBlock() const { return Branches[1]; }
BasicBlock *elseBlock() { return Branches[1]; }
/// Return the list of basic blocks that this terminator can branch to.
ArrayRef<BasicBlock*> successors() {
return ArrayRef<BasicBlock*>(Branches, 2);
}
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Nc = Vs.traverse(Condition, Vs.subExprCtx(Ctx));
BasicBlock *Ntb = Vs.reduceBasicBlockRef(Branches[0]);
BasicBlock *Nte = Vs.reduceBasicBlockRef(Branches[1]);
return Vs.reduceBranch(*this, Nc, Ntb, Nte);
}
template <class C>
typename C::CType compare(const Branch *E, C &Cmp) const {
// TODO: implement CFG comparisons
return Cmp.comparePointers(this, E);
}
private:
SExpr* Condition;
BasicBlock *Branches[2];
};
/// Return from the enclosing function, passing the return value to the caller.
/// Only the exit block should end with a return statement.
class Return : public Terminator {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Return; }
Return(SExpr* Rval) : Terminator(COP_Return), Retval(Rval) {}
Return(const Return &R, SExpr* Rval) : Terminator(R), Retval(Rval) {}
/// Return an empty list.
ArrayRef<BasicBlock*> successors() {
return ArrayRef<BasicBlock*>();
}
SExpr *returnValue() { return Retval; }
const SExpr *returnValue() const { return Retval; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Ne = Vs.traverse(Retval, Vs.subExprCtx(Ctx));
return Vs.reduceReturn(*this, Ne);
}
template <class C>
typename C::CType compare(const Return *E, C &Cmp) const {
return Cmp.compare(Retval, E->Retval);
}
private:
SExpr* Retval;
};
inline ArrayRef<BasicBlock*> Terminator::successors() {
switch (opcode()) {
case COP_Goto: return cast<Goto>(this)->successors();
case COP_Branch: return cast<Branch>(this)->successors();
case COP_Return: return cast<Return>(this)->successors();
default:
return ArrayRef<BasicBlock*>();
}
}
/// A basic block is part of an SCFG. It can be treated as a function in
/// continuation passing style. A block consists of a sequence of phi nodes,
/// which are "arguments" to the function, followed by a sequence of
/// instructions. It ends with a Terminator, which is a Branch or Goto to
/// another basic block in the same SCFG.
class BasicBlock : public SExpr {
public:
typedef SimpleArray<SExpr*> InstrArray;
typedef SimpleArray<BasicBlock*> BlockArray;
// TopologyNodes are used to overlay tree structures on top of the CFG,
// such as dominator and postdominator trees. Each block is assigned an
// ID in the tree according to a depth-first search. Tree traversals are
// always up, towards the parents.
struct TopologyNode {
TopologyNode() : NodeID(0), SizeOfSubTree(0), Parent(nullptr) {}
bool isParentOf(const TopologyNode& OtherNode) {
return OtherNode.NodeID > NodeID &&
OtherNode.NodeID < NodeID + SizeOfSubTree;
}
bool isParentOfOrEqual(const TopologyNode& OtherNode) {
return OtherNode.NodeID >= NodeID &&
OtherNode.NodeID < NodeID + SizeOfSubTree;
}
int NodeID;
int SizeOfSubTree; // Includes this node, so must be > 1.
BasicBlock *Parent; // Pointer to parent.
};
static bool classof(const SExpr *E) { return E->opcode() == COP_BasicBlock; }
explicit BasicBlock(MemRegionRef A)
: SExpr(COP_BasicBlock), Arena(A), CFGPtr(nullptr), BlockID(0),
Visited(0), TermInstr(nullptr) {}
BasicBlock(BasicBlock &B, MemRegionRef A, InstrArray &&As, InstrArray &&Is,
Terminator *T)
: SExpr(COP_BasicBlock), Arena(A), CFGPtr(nullptr), BlockID(0),Visited(0),
Args(std::move(As)), Instrs(std::move(Is)), TermInstr(T) {}
/// Returns the block ID. Every block has a unique ID in the CFG.
int blockID() const { return BlockID; }
/// Returns the number of predecessors.
size_t numPredecessors() const { return Predecessors.size(); }
size_t numSuccessors() const { return successors().size(); }
const SCFG* cfg() const { return CFGPtr; }
SCFG* cfg() { return CFGPtr; }
const BasicBlock *parent() const { return DominatorNode.Parent; }
BasicBlock *parent() { return DominatorNode.Parent; }
const InstrArray &arguments() const { return Args; }
InstrArray &arguments() { return Args; }
InstrArray &instructions() { return Instrs; }
const InstrArray &instructions() const { return Instrs; }
/// Returns a list of predecessors.
/// The order of predecessors in the list is important; each phi node has
/// exactly one argument for each precessor, in the same order.
BlockArray &predecessors() { return Predecessors; }
const BlockArray &predecessors() const { return Predecessors; }
ArrayRef<BasicBlock*> successors() { return TermInstr->successors(); }
ArrayRef<BasicBlock*> successors() const { return TermInstr->successors(); }
const Terminator *terminator() const { return TermInstr; }
Terminator *terminator() { return TermInstr; }
void setTerminator(Terminator *E) { TermInstr = E; }
bool Dominates(const BasicBlock &Other) {
return DominatorNode.isParentOfOrEqual(Other.DominatorNode);
}
bool PostDominates(const BasicBlock &Other) {
return PostDominatorNode.isParentOfOrEqual(Other.PostDominatorNode);
}
/// Add a new argument.
void addArgument(Phi *V) {
Args.reserveCheck(1, Arena);
Args.push_back(V);
}
/// Add a new instruction.
void addInstruction(SExpr *V) {
Instrs.reserveCheck(1, Arena);
Instrs.push_back(V);
}
// Add a new predecessor, and return the phi-node index for it.
// Will add an argument to all phi-nodes, initialized to nullptr.
unsigned addPredecessor(BasicBlock *Pred);
// Reserve space for Nargs arguments.
void reserveArguments(unsigned Nargs) { Args.reserve(Nargs, Arena); }
// Reserve space for Nins instructions.
void reserveInstructions(unsigned Nins) { Instrs.reserve(Nins, Arena); }
// Reserve space for NumPreds predecessors, including space in phi nodes.
void reservePredecessors(unsigned NumPreds);
/// Return the index of BB, or Predecessors.size if BB is not a predecessor.
unsigned findPredecessorIndex(const BasicBlock *BB) const {
auto I = std::find(Predecessors.cbegin(), Predecessors.cend(), BB);
return std::distance(Predecessors.cbegin(), I);
}
template <class V>
typename V::R_BasicBlock traverse(V &Vs, typename V::R_Ctx Ctx) {
typename V::template Container<SExpr*> Nas(Vs, Args.size());
typename V::template Container<SExpr*> Nis(Vs, Instrs.size());
// Entering the basic block should do any scope initialization.
Vs.enterBasicBlock(*this);
for (auto *E : Args) {
auto Ne = Vs.traverse(E, Vs.subExprCtx(Ctx));
Nas.push_back(Ne);
}
for (auto *E : Instrs) {
auto Ne = Vs.traverse(E, Vs.subExprCtx(Ctx));
Nis.push_back(Ne);
}
auto Nt = Vs.traverse(TermInstr, Ctx);
// Exiting the basic block should handle any scope cleanup.
Vs.exitBasicBlock(*this);
return Vs.reduceBasicBlock(*this, Nas, Nis, Nt);
}
template <class C>
typename C::CType compare(const BasicBlock *E, C &Cmp) const {
// TODO: implement CFG comparisons
return Cmp.comparePointers(this, E);
}
private:
friend class SCFG;
int renumberInstrs(int id); // assign unique ids to all instructions
int topologicalSort(SimpleArray<BasicBlock*>& Blocks, int ID);
int topologicalFinalSort(SimpleArray<BasicBlock*>& Blocks, int ID);
void computeDominator();
void computePostDominator();
private:
MemRegionRef Arena; // The arena used to allocate this block.
SCFG *CFGPtr; // The CFG that contains this block.
int BlockID : 31; // unique id for this BB in the containing CFG.
// IDs are in topological order.
bool Visited : 1; // Bit to determine if a block has been visited
// during a traversal.
BlockArray Predecessors; // Predecessor blocks in the CFG.
InstrArray Args; // Phi nodes. One argument per predecessor.
InstrArray Instrs; // Instructions.
Terminator* TermInstr; // Terminating instruction
TopologyNode DominatorNode; // The dominator tree
TopologyNode PostDominatorNode; // The post-dominator tree
};
/// An SCFG is a control-flow graph. It consists of a set of basic blocks,
/// each of which terminates in a branch to another basic block. There is one
/// entry point, and one exit point.
class SCFG : public SExpr {
public:
typedef SimpleArray<BasicBlock *> BlockArray;
typedef BlockArray::iterator iterator;
typedef BlockArray::const_iterator const_iterator;
static bool classof(const SExpr *E) { return E->opcode() == COP_SCFG; }
SCFG(MemRegionRef A, unsigned Nblocks)
: SExpr(COP_SCFG), Arena(A), Blocks(A, Nblocks),
Entry(nullptr), Exit(nullptr), NumInstructions(0), Normal(false) {
Entry = new (A) BasicBlock(A);
Exit = new (A) BasicBlock(A);
auto *V = new (A) Phi();
Exit->addArgument(V);
Exit->setTerminator(new (A) Return(V));
add(Entry);
add(Exit);
}
SCFG(const SCFG &Cfg, BlockArray &&Ba) // steals memory from Ba
: SExpr(COP_SCFG), Arena(Cfg.Arena), Blocks(std::move(Ba)),
Entry(nullptr), Exit(nullptr), NumInstructions(0), Normal(false) {
// TODO: set entry and exit!
}
/// Return true if this CFG is valid.
bool valid() const { return Entry && Exit && Blocks.size() > 0; }
/// Return true if this CFG has been normalized.
/// After normalization, blocks are in topological order, and block and
/// instruction IDs have been assigned.
bool normal() const { return Normal; }
iterator begin() { return Blocks.begin(); }
iterator end() { return Blocks.end(); }
const_iterator begin() const { return cbegin(); }
const_iterator end() const { return cend(); }
const_iterator cbegin() const { return Blocks.cbegin(); }
const_iterator cend() const { return Blocks.cend(); }
const BasicBlock *entry() const { return Entry; }
BasicBlock *entry() { return Entry; }
const BasicBlock *exit() const { return Exit; }
BasicBlock *exit() { return Exit; }
/// Return the number of blocks in the CFG.
/// Block::blockID() will return a number less than numBlocks();
size_t numBlocks() const { return Blocks.size(); }
/// Return the total number of instructions in the CFG.
/// This is useful for building instruction side-tables;
/// A call to SExpr::id() will return a number less than numInstructions().
unsigned numInstructions() { return NumInstructions; }
inline void add(BasicBlock *BB) {
assert(BB->CFGPtr == nullptr);
BB->CFGPtr = this;
Blocks.reserveCheck(1, Arena);
Blocks.push_back(BB);
}
void setEntry(BasicBlock *BB) { Entry = BB; }
void setExit(BasicBlock *BB) { Exit = BB; }
void computeNormalForm();
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
Vs.enterCFG(*this);
typename V::template Container<BasicBlock *> Bbs(Vs, Blocks.size());
for (auto *B : Blocks) {
Bbs.push_back( B->traverse(Vs, Vs.subExprCtx(Ctx)) );
}
Vs.exitCFG(*this);
return Vs.reduceSCFG(*this, Bbs);
}
template <class C>
typename C::CType compare(const SCFG *E, C &Cmp) const {
// TODO: implement CFG comparisons
return Cmp.comparePointers(this, E);
}
private:
void renumberInstrs(); // assign unique ids to all instructions
private:
MemRegionRef Arena;
BlockArray Blocks;
BasicBlock *Entry;
BasicBlock *Exit;
unsigned NumInstructions;
bool Normal;
};
/// An identifier, e.g. 'foo' or 'x'.
/// This is a pseduo-term; it will be lowered to a variable or projection.
class Identifier : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Identifier; }
Identifier(StringRef Id): SExpr(COP_Identifier), Name(Id) { }
Identifier(const Identifier& I) : SExpr(I), Name(I.Name) { }
StringRef name() const { return Name; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
return Vs.reduceIdentifier(*this);
}
template <class C>
typename C::CType compare(const Identifier* E, C& Cmp) const {
return Cmp.compareStrings(name(), E->name());
}
private:
StringRef Name;
};
/// An if-then-else expression.
/// This is a pseduo-term; it will be lowered to a branch in a CFG.
class IfThenElse : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_IfThenElse; }
IfThenElse(SExpr *C, SExpr *T, SExpr *E)
: SExpr(COP_IfThenElse), Condition(C), ThenExpr(T), ElseExpr(E)
{ }
IfThenElse(const IfThenElse &I, SExpr *C, SExpr *T, SExpr *E)
: SExpr(I), Condition(C), ThenExpr(T), ElseExpr(E)
{ }
SExpr *condition() { return Condition; } // Address to store to
const SExpr *condition() const { return Condition; }
SExpr *thenExpr() { return ThenExpr; } // Value to store
const SExpr *thenExpr() const { return ThenExpr; }
SExpr *elseExpr() { return ElseExpr; } // Value to store
const SExpr *elseExpr() const { return ElseExpr; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
auto Nc = Vs.traverse(Condition, Vs.subExprCtx(Ctx));
auto Nt = Vs.traverse(ThenExpr, Vs.subExprCtx(Ctx));
auto Ne = Vs.traverse(ElseExpr, Vs.subExprCtx(Ctx));
return Vs.reduceIfThenElse(*this, Nc, Nt, Ne);
}
template <class C>
typename C::CType compare(const IfThenElse* E, C& Cmp) const {
typename C::CType Ct = Cmp.compare(condition(), E->condition());
if (Cmp.notTrue(Ct))
return Ct;
Ct = Cmp.compare(thenExpr(), E->thenExpr());
if (Cmp.notTrue(Ct))
return Ct;
return Cmp.compare(elseExpr(), E->elseExpr());
}
private:
SExpr* Condition;
SExpr* ThenExpr;
SExpr* ElseExpr;
};
/// A let-expression, e.g. let x=t; u.
/// This is a pseduo-term; it will be lowered to instructions in a CFG.
class Let : public SExpr {
public:
static bool classof(const SExpr *E) { return E->opcode() == COP_Let; }
Let(Variable *Vd, SExpr *Bd) : SExpr(COP_Let), VarDecl(Vd), Body(Bd) {
Vd->setKind(Variable::VK_Let);
}
Let(const Let &L, Variable *Vd, SExpr *Bd) : SExpr(L), VarDecl(Vd), Body(Bd) {
Vd->setKind(Variable::VK_Let);
}
Variable *variableDecl() { return VarDecl; }
const Variable *variableDecl() const { return VarDecl; }
SExpr *body() { return Body; }
const SExpr *body() const { return Body; }
template <class V>
typename V::R_SExpr traverse(V &Vs, typename V::R_Ctx Ctx) {
// This is a variable declaration, so traverse the definition.
auto E0 = Vs.traverse(VarDecl->Definition, Vs.subExprCtx(Ctx));
// Tell the rewriter to enter the scope of the let variable.
Variable *Nvd = Vs.enterScope(*VarDecl, E0);
auto E1 = Vs.traverse(Body, Ctx);
Vs.exitScope(*VarDecl);
return Vs.reduceLet(*this, Nvd, E1);
}
template <class C>
typename C::CType compare(const Let* E, C& Cmp) const {
typename C::CType Ct =
Cmp.compare(VarDecl->definition(), E->VarDecl->definition());
if (Cmp.notTrue(Ct))
return Ct;
Cmp.enterScope(variableDecl(), E->variableDecl());
Ct = Cmp.compare(body(), E->body());
Cmp.leaveScope();
return Ct;
}
private:
Variable *VarDecl;
SExpr* Body;
};
const SExpr *getCanonicalVal(const SExpr *E);
SExpr* simplifyToCanonicalVal(SExpr *E);
void simplifyIncompleteArg(til::Phi *Ph);
} // end namespace til
} // end namespace threadSafety
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyTraverse.h | //===- ThreadSafetyTraverse.h ----------------------------------*- 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 a framework for doing generic traversals and rewriting
// operations over the Thread Safety TIL.
//
// UNDER CONSTRUCTION. USE AT YOUR OWN RISK.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTRAVERSE_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYTRAVERSE_H
#include "ThreadSafetyTIL.h"
#include <ostream>
namespace clang {
namespace threadSafety {
namespace til {
// Defines an interface used to traverse SExprs. Traversals have been made as
// generic as possible, and are intended to handle any kind of pass over the
// AST, e.g. visiters, copying, non-destructive rewriting, destructive
// (in-place) rewriting, hashing, typing, etc.
//
// Traversals implement the functional notion of a "fold" operation on SExprs.
// Each SExpr class provides a traverse method, which does the following:
// * e->traverse(v):
// // compute a result r_i for each subexpression e_i
// for (i = 1..n) r_i = v.traverse(e_i);
// // combine results into a result for e, where X is the class of e
// return v.reduceX(*e, r_1, .. r_n).
//
// A visitor can control the traversal by overriding the following methods:
// * v.traverse(e):
// return v.traverseByCase(e), which returns v.traverseX(e)
// * v.traverseX(e): (X is the class of e)
// return e->traverse(v).
// * v.reduceX(*e, r_1, .. r_n):
// compute a result for a node of type X
//
// The reduceX methods control the kind of traversal (visitor, copy, etc.).
// They are defined in derived classes.
//
// Class R defines the basic interface types (R_SExpr).
template <class Self, class R>
class Traversal {
public:
Self *self() { return static_cast<Self *>(this); }
// Traverse an expression -- returning a result of type R_SExpr.
// Override this method to do something for every expression, regardless
// of which kind it is.
// E is a reference, so this can be use for in-place updates.
// The type T must be a subclass of SExpr.
template <class T>
typename R::R_SExpr traverse(T* &E, typename R::R_Ctx Ctx) {
return traverseSExpr(E, Ctx);
}
// Override this method to do something for every expression.
// Does not allow in-place updates.
typename R::R_SExpr traverseSExpr(SExpr *E, typename R::R_Ctx Ctx) {
return traverseByCase(E, Ctx);
}
// Helper method to call traverseX(e) on the appropriate type.
typename R::R_SExpr traverseByCase(SExpr *E, typename R::R_Ctx Ctx) {
switch (E->opcode()) {
#define TIL_OPCODE_DEF(X) \
case COP_##X: \
return self()->traverse##X(cast<X>(E), Ctx);
#include "ThreadSafetyOps.def"
#undef TIL_OPCODE_DEF
}
return self()->reduceNull();
}
// Traverse e, by static dispatch on the type "X" of e.
// Override these methods to do something for a particular kind of term.
#define TIL_OPCODE_DEF(X) \
typename R::R_SExpr traverse##X(X *e, typename R::R_Ctx Ctx) { \
return e->traverse(*self(), Ctx); \
}
#include "ThreadSafetyOps.def"
#undef TIL_OPCODE_DEF
};
// Base class for simple reducers that don't much care about the context.
class SimpleReducerBase {
public:
enum TraversalKind {
TRV_Normal, // ordinary subexpressions
TRV_Decl, // declarations (e.g. function bodies)
TRV_Lazy, // expressions that require lazy evaluation
TRV_Type // type expressions
};
// R_Ctx defines a "context" for the traversal, which encodes information
// about where a term appears. This can be used to encoding the
// "current continuation" for CPS transforms, or other information.
typedef TraversalKind R_Ctx;
// Create context for an ordinary subexpression.
R_Ctx subExprCtx(R_Ctx Ctx) { return TRV_Normal; }
// Create context for a subexpression that occurs in a declaration position
// (e.g. function body).
R_Ctx declCtx(R_Ctx Ctx) { return TRV_Decl; }
// Create context for a subexpression that occurs in a position that
// should be reduced lazily. (e.g. code body).
R_Ctx lazyCtx(R_Ctx Ctx) { return TRV_Lazy; }
// Create context for a subexpression that occurs in a type position.
R_Ctx typeCtx(R_Ctx Ctx) { return TRV_Type; }
};
// Base class for traversals that rewrite an SExpr to another SExpr.
class CopyReducerBase : public SimpleReducerBase {
public:
// R_SExpr is the result type for a traversal.
// A copy or non-destructive rewrite returns a newly allocated term.
typedef SExpr *R_SExpr;
typedef BasicBlock *R_BasicBlock;
// Container is a minimal interface used to store results when traversing
// SExprs of variable arity, such as Phi, Goto, and SCFG.
template <class T> class Container {
public:
// Allocate a new container with a capacity for n elements.
Container(CopyReducerBase &S, unsigned N) : Elems(S.Arena, N) {}
// Push a new element onto the container.
void push_back(T E) { Elems.push_back(E); }
SimpleArray<T> Elems;
};
CopyReducerBase(MemRegionRef A) : Arena(A) {}
protected:
MemRegionRef Arena;
};
// Base class for visit traversals.
class VisitReducerBase : public SimpleReducerBase {
public:
// A visitor returns a bool, representing success or failure.
typedef bool R_SExpr;
typedef bool R_BasicBlock;
// A visitor "container" is a single bool, which accumulates success.
template <class T> class Container {
public:
Container(VisitReducerBase &S, unsigned N) : Success(true) {}
void push_back(bool E) { Success = Success && E; }
bool Success;
};
};
// Implements a traversal that visits each subexpression, and returns either
// true or false.
template <class Self>
class VisitReducer : public Traversal<Self, VisitReducerBase>,
public VisitReducerBase {
public:
VisitReducer() {}
public:
R_SExpr reduceNull() { return true; }
R_SExpr reduceUndefined(Undefined &Orig) { return true; }
R_SExpr reduceWildcard(Wildcard &Orig) { return true; }
R_SExpr reduceLiteral(Literal &Orig) { return true; }
template<class T>
R_SExpr reduceLiteralT(LiteralT<T> &Orig) { return true; }
R_SExpr reduceLiteralPtr(Literal &Orig) { return true; }
R_SExpr reduceFunction(Function &Orig, Variable *Nvd, R_SExpr E0) {
return Nvd && E0;
}
R_SExpr reduceSFunction(SFunction &Orig, Variable *Nvd, R_SExpr E0) {
return Nvd && E0;
}
R_SExpr reduceCode(Code &Orig, R_SExpr E0, R_SExpr E1) {
return E0 && E1;
}
R_SExpr reduceField(Field &Orig, R_SExpr E0, R_SExpr E1) {
return E0 && E1;
}
R_SExpr reduceApply(Apply &Orig, R_SExpr E0, R_SExpr E1) {
return E0 && E1;
}
R_SExpr reduceSApply(SApply &Orig, R_SExpr E0, R_SExpr E1) {
return E0 && E1;
}
R_SExpr reduceProject(Project &Orig, R_SExpr E0) { return E0; }
R_SExpr reduceCall(Call &Orig, R_SExpr E0) { return E0; }
R_SExpr reduceAlloc(Alloc &Orig, R_SExpr E0) { return E0; }
R_SExpr reduceLoad(Load &Orig, R_SExpr E0) { return E0; }
R_SExpr reduceStore(Store &Orig, R_SExpr E0, R_SExpr E1) { return E0 && E1; }
R_SExpr reduceArrayIndex(Store &Orig, R_SExpr E0, R_SExpr E1) {
return E0 && E1;
}
R_SExpr reduceArrayAdd(Store &Orig, R_SExpr E0, R_SExpr E1) {
return E0 && E1;
}
R_SExpr reduceUnaryOp(UnaryOp &Orig, R_SExpr E0) { return E0; }
R_SExpr reduceBinaryOp(BinaryOp &Orig, R_SExpr E0, R_SExpr E1) {
return E0 && E1;
}
R_SExpr reduceCast(Cast &Orig, R_SExpr E0) { return E0; }
R_SExpr reduceSCFG(SCFG &Orig, Container<BasicBlock *> Bbs) {
return Bbs.Success;
}
R_BasicBlock reduceBasicBlock(BasicBlock &Orig, Container<R_SExpr> &As,
Container<R_SExpr> &Is, R_SExpr T) {
return (As.Success && Is.Success && T);
}
R_SExpr reducePhi(Phi &Orig, Container<R_SExpr> &As) {
return As.Success;
}
R_SExpr reduceGoto(Goto &Orig, BasicBlock *B) {
return true;
}
R_SExpr reduceBranch(Branch &O, R_SExpr C, BasicBlock *B0, BasicBlock *B1) {
return C;
}
R_SExpr reduceReturn(Return &O, R_SExpr E) {
return E;
}
R_SExpr reduceIdentifier(Identifier &Orig) {
return true;
}
R_SExpr reduceIfThenElse(IfThenElse &Orig, R_SExpr C, R_SExpr T, R_SExpr E) {
return C && T && E;
}
R_SExpr reduceLet(Let &Orig, Variable *Nvd, R_SExpr B) {
return Nvd && B;
}
Variable *enterScope(Variable &Orig, R_SExpr E0) { return &Orig; }
void exitScope(const Variable &Orig) {}
void enterCFG(SCFG &Cfg) {}
void exitCFG(SCFG &Cfg) {}
void enterBasicBlock(BasicBlock &BB) {}
void exitBasicBlock(BasicBlock &BB) {}
Variable *reduceVariableRef (Variable *Ovd) { return Ovd; }
BasicBlock *reduceBasicBlockRef(BasicBlock *Obb) { return Obb; }
public:
bool traverse(SExpr *E, TraversalKind K = TRV_Normal) {
Success = Success && this->traverseByCase(E);
return Success;
}
static bool visit(SExpr *E) {
Self Visitor;
return Visitor.traverse(E, TRV_Normal);
}
private:
bool Success;
};
// Basic class for comparison operations over expressions.
template <typename Self>
class Comparator {
protected:
Self *self() { return reinterpret_cast<Self *>(this); }
public:
bool compareByCase(const SExpr *E1, const SExpr* E2) {
switch (E1->opcode()) {
#define TIL_OPCODE_DEF(X) \
case COP_##X: \
return cast<X>(E1)->compare(cast<X>(E2), *self());
#include "ThreadSafetyOps.def"
#undef TIL_OPCODE_DEF
}
return false;
}
};
class EqualsComparator : public Comparator<EqualsComparator> {
public:
// Result type for the comparison, e.g. bool for simple equality,
// or int for lexigraphic comparison (-1, 0, 1). Must have one value which
// denotes "true".
typedef bool CType;
CType trueResult() { return true; }
bool notTrue(CType ct) { return !ct; }
bool compareIntegers(unsigned i, unsigned j) { return i == j; }
bool compareStrings (StringRef s, StringRef r) { return s == r; }
bool comparePointers(const void* P, const void* Q) { return P == Q; }
bool compare(const SExpr *E1, const SExpr* E2) {
if (E1->opcode() != E2->opcode())
return false;
return compareByCase(E1, E2);
}
// TODO -- handle alpha-renaming of variables
void enterScope(const Variable* V1, const Variable* V2) { }
void leaveScope() { }
bool compareVariableRefs(const Variable* V1, const Variable* V2) {
return V1 == V2;
}
static bool compareExprs(const SExpr *E1, const SExpr* E2) {
EqualsComparator Eq;
return Eq.compare(E1, E2);
}
};
class MatchComparator : public Comparator<MatchComparator> {
public:
// Result type for the comparison, e.g. bool for simple equality,
// or int for lexigraphic comparison (-1, 0, 1). Must have one value which
// denotes "true".
typedef bool CType;
CType trueResult() { return true; }
bool notTrue(CType ct) { return !ct; }
bool compareIntegers(unsigned i, unsigned j) { return i == j; }
bool compareStrings (StringRef s, StringRef r) { return s == r; }
bool comparePointers(const void* P, const void* Q) { return P == Q; }
bool compare(const SExpr *E1, const SExpr* E2) {
// Wildcards match anything.
if (E1->opcode() == COP_Wildcard || E2->opcode() == COP_Wildcard)
return true;
// otherwise normal equality.
if (E1->opcode() != E2->opcode())
return false;
return compareByCase(E1, E2);
}
// TODO -- handle alpha-renaming of variables
void enterScope(const Variable* V1, const Variable* V2) { }
void leaveScope() { }
bool compareVariableRefs(const Variable* V1, const Variable* V2) {
return V1 == V2;
}
static bool compareExprs(const SExpr *E1, const SExpr* E2) {
MatchComparator Matcher;
return Matcher.compare(E1, E2);
}
};
// inline std::ostream& operator<<(std::ostream& SS, StringRef R) {
// return SS.write(R.data(), R.size());
// }
// Pretty printer for TIL expressions
template <typename Self, typename StreamType>
class PrettyPrinter {
private:
bool Verbose; // Print out additional information
bool Cleanup; // Omit redundant decls.
bool CStyle; // Print exprs in C-like syntax.
public:
PrettyPrinter(bool V = false, bool C = true, bool CS = true)
: Verbose(V), Cleanup(C), CStyle(CS)
{}
static void print(const SExpr *E, StreamType &SS) {
Self printer;
printer.printSExpr(E, SS, Prec_MAX);
}
protected:
Self *self() { return reinterpret_cast<Self *>(this); }
void newline(StreamType &SS) {
SS << "\n";
}
// TODO: further distinguish between binary operations.
static const unsigned Prec_Atom = 0;
static const unsigned Prec_Postfix = 1;
static const unsigned Prec_Unary = 2;
static const unsigned Prec_Binary = 3;
static const unsigned Prec_Other = 4;
static const unsigned Prec_Decl = 5;
static const unsigned Prec_MAX = 6;
// Return the precedence of a given node, for use in pretty printing.
unsigned precedence(const SExpr *E) {
switch (E->opcode()) {
case COP_Future: return Prec_Atom;
case COP_Undefined: return Prec_Atom;
case COP_Wildcard: return Prec_Atom;
case COP_Literal: return Prec_Atom;
case COP_LiteralPtr: return Prec_Atom;
case COP_Variable: return Prec_Atom;
case COP_Function: return Prec_Decl;
case COP_SFunction: return Prec_Decl;
case COP_Code: return Prec_Decl;
case COP_Field: return Prec_Decl;
case COP_Apply: return Prec_Postfix;
case COP_SApply: return Prec_Postfix;
case COP_Project: return Prec_Postfix;
case COP_Call: return Prec_Postfix;
case COP_Alloc: return Prec_Other;
case COP_Load: return Prec_Postfix;
case COP_Store: return Prec_Other;
case COP_ArrayIndex: return Prec_Postfix;
case COP_ArrayAdd: return Prec_Postfix;
case COP_UnaryOp: return Prec_Unary;
case COP_BinaryOp: return Prec_Binary;
case COP_Cast: return Prec_Atom;
case COP_SCFG: return Prec_Decl;
case COP_BasicBlock: return Prec_MAX;
case COP_Phi: return Prec_Atom;
case COP_Goto: return Prec_Atom;
case COP_Branch: return Prec_Atom;
case COP_Return: return Prec_Other;
case COP_Identifier: return Prec_Atom;
case COP_IfThenElse: return Prec_Other;
case COP_Let: return Prec_Decl;
}
return Prec_MAX;
}
void printBlockLabel(StreamType & SS, const BasicBlock *BB, int index) {
if (!BB) {
SS << "BB_null";
return;
}
SS << "BB_";
SS << BB->blockID();
if (index >= 0) {
SS << ":";
SS << index;
}
}
void printSExpr(const SExpr *E, StreamType &SS, unsigned P, bool Sub=true) {
if (!E) {
self()->printNull(SS);
return;
}
if (Sub && E->block() && E->opcode() != COP_Variable) {
SS << "_x" << E->id();
return;
}
if (self()->precedence(E) > P) {
// Wrap expr in () if necessary.
SS << "(";
self()->printSExpr(E, SS, Prec_MAX);
SS << ")";
return;
}
switch (E->opcode()) {
#define TIL_OPCODE_DEF(X) \
case COP_##X: \
self()->print##X(cast<X>(E), SS); \
return;
#include "ThreadSafetyOps.def"
#undef TIL_OPCODE_DEF
}
}
void printNull(StreamType &SS) {
SS << "#null";
}
void printFuture(const Future *E, StreamType &SS) {
self()->printSExpr(E->maybeGetResult(), SS, Prec_Atom);
}
void printUndefined(const Undefined *E, StreamType &SS) {
SS << "#undefined";
}
void printWildcard(const Wildcard *E, StreamType &SS) {
SS << "*";
}
template<class T>
void printLiteralT(const LiteralT<T> *E, StreamType &SS) {
SS << E->value();
}
void printLiteralT(const LiteralT<uint8_t> *E, StreamType &SS) {
SS << "'" << E->value() << "'";
}
void printLiteral(const Literal *E, StreamType &SS) {
if (E->clangExpr()) {
SS << getSourceLiteralString(E->clangExpr());
return;
}
else {
ValueType VT = E->valueType();
switch (VT.Base) {
case ValueType::BT_Void: {
SS << "void";
return;
}
case ValueType::BT_Bool: {
if (E->as<bool>().value())
SS << "true";
else
SS << "false";
return;
}
case ValueType::BT_Int: {
switch (VT.Size) {
case ValueType::ST_8:
if (VT.Signed)
printLiteralT(&E->as<int8_t>(), SS);
else
printLiteralT(&E->as<uint8_t>(), SS);
return;
case ValueType::ST_16:
if (VT.Signed)
printLiteralT(&E->as<int16_t>(), SS);
else
printLiteralT(&E->as<uint16_t>(), SS);
return;
case ValueType::ST_32:
if (VT.Signed)
printLiteralT(&E->as<int32_t>(), SS);
else
printLiteralT(&E->as<uint32_t>(), SS);
return;
case ValueType::ST_64:
if (VT.Signed)
printLiteralT(&E->as<int64_t>(), SS);
else
printLiteralT(&E->as<uint64_t>(), SS);
return;
default:
break;
}
break;
}
case ValueType::BT_Float: {
switch (VT.Size) {
case ValueType::ST_32:
printLiteralT(&E->as<float>(), SS);
return;
case ValueType::ST_64:
printLiteralT(&E->as<double>(), SS);
return;
default:
break;
}
break;
}
case ValueType::BT_String: {
SS << "\"";
printLiteralT(&E->as<StringRef>(), SS);
SS << "\"";
return;
}
case ValueType::BT_Pointer: {
SS << "#ptr";
return;
}
case ValueType::BT_ValueRef: {
SS << "#vref";
return;
}
}
}
SS << "#lit";
}
void printLiteralPtr(const LiteralPtr *E, StreamType &SS) {
SS << E->clangDecl()->getNameAsString();
}
void printVariable(const Variable *V, StreamType &SS, bool IsVarDecl=false) {
if (CStyle && V->kind() == Variable::VK_SFun)
SS << "this";
else
SS << V->name() << V->id();
}
void printFunction(const Function *E, StreamType &SS, unsigned sugared = 0) {
switch (sugared) {
default:
SS << "\\("; // Lambda
break;
case 1:
SS << "("; // Slot declarations
break;
case 2:
SS << ", "; // Curried functions
break;
}
self()->printVariable(E->variableDecl(), SS, true);
SS << ": ";
self()->printSExpr(E->variableDecl()->definition(), SS, Prec_MAX);
const SExpr *B = E->body();
if (B && B->opcode() == COP_Function)
self()->printFunction(cast<Function>(B), SS, 2);
else {
SS << ")";
self()->printSExpr(B, SS, Prec_Decl);
}
}
void printSFunction(const SFunction *E, StreamType &SS) {
SS << "@";
self()->printVariable(E->variableDecl(), SS, true);
SS << " ";
self()->printSExpr(E->body(), SS, Prec_Decl);
}
void printCode(const Code *E, StreamType &SS) {
SS << ": ";
self()->printSExpr(E->returnType(), SS, Prec_Decl-1);
SS << " -> ";
self()->printSExpr(E->body(), SS, Prec_Decl);
}
void printField(const Field *E, StreamType &SS) {
SS << ": ";
self()->printSExpr(E->range(), SS, Prec_Decl-1);
SS << " = ";
self()->printSExpr(E->body(), SS, Prec_Decl);
}
void printApply(const Apply *E, StreamType &SS, bool sugared = false) {
const SExpr *F = E->fun();
if (F->opcode() == COP_Apply) {
printApply(cast<Apply>(F), SS, true);
SS << ", ";
} else {
self()->printSExpr(F, SS, Prec_Postfix);
SS << "(";
}
self()->printSExpr(E->arg(), SS, Prec_MAX);
if (!sugared)
SS << ")$";
}
void printSApply(const SApply *E, StreamType &SS) {
self()->printSExpr(E->sfun(), SS, Prec_Postfix);
if (E->isDelegation()) {
SS << "@(";
self()->printSExpr(E->arg(), SS, Prec_MAX);
SS << ")";
}
}
void printProject(const Project *E, StreamType &SS) {
if (CStyle) {
// Omit the this->
if (const SApply *SAP = dyn_cast<SApply>(E->record())) {
if (const Variable *V = dyn_cast<Variable>(SAP->sfun())) {
if (!SAP->isDelegation() && V->kind() == Variable::VK_SFun) {
SS << E->slotName();
return;
}
}
}
if (isa<Wildcard>(E->record())) {
// handle existentials
SS << "&";
SS << E->clangDecl()->getQualifiedNameAsString();
return;
}
}
self()->printSExpr(E->record(), SS, Prec_Postfix);
if (CStyle && E->isArrow()) {
SS << "->";
}
else {
SS << ".";
}
SS << E->slotName();
}
void printCall(const Call *E, StreamType &SS) {
const SExpr *T = E->target();
if (T->opcode() == COP_Apply) {
self()->printApply(cast<Apply>(T), SS, true);
SS << ")";
}
else {
self()->printSExpr(T, SS, Prec_Postfix);
SS << "()";
}
}
void printAlloc(const Alloc *E, StreamType &SS) {
SS << "new ";
self()->printSExpr(E->dataType(), SS, Prec_Other-1);
}
void printLoad(const Load *E, StreamType &SS) {
self()->printSExpr(E->pointer(), SS, Prec_Postfix);
if (!CStyle)
SS << "^";
}
void printStore(const Store *E, StreamType &SS) {
self()->printSExpr(E->destination(), SS, Prec_Other-1);
SS << " := ";
self()->printSExpr(E->source(), SS, Prec_Other-1);
}
void printArrayIndex(const ArrayIndex *E, StreamType &SS) {
self()->printSExpr(E->array(), SS, Prec_Postfix);
SS << "[";
self()->printSExpr(E->index(), SS, Prec_MAX);
SS << "]";
}
void printArrayAdd(const ArrayAdd *E, StreamType &SS) {
self()->printSExpr(E->array(), SS, Prec_Postfix);
SS << " + ";
self()->printSExpr(E->index(), SS, Prec_Atom);
}
void printUnaryOp(const UnaryOp *E, StreamType &SS) {
SS << getUnaryOpcodeString(E->unaryOpcode());
self()->printSExpr(E->expr(), SS, Prec_Unary);
}
void printBinaryOp(const BinaryOp *E, StreamType &SS) {
self()->printSExpr(E->expr0(), SS, Prec_Binary-1);
SS << " " << getBinaryOpcodeString(E->binaryOpcode()) << " ";
self()->printSExpr(E->expr1(), SS, Prec_Binary-1);
}
void printCast(const Cast *E, StreamType &SS) {
if (!CStyle) {
SS << "cast[";
SS << E->castOpcode();
SS << "](";
self()->printSExpr(E->expr(), SS, Prec_Unary);
SS << ")";
return;
}
self()->printSExpr(E->expr(), SS, Prec_Unary);
}
void printSCFG(const SCFG *E, StreamType &SS) {
SS << "CFG {\n";
for (auto BBI : *E) {
printBasicBlock(BBI, SS);
}
SS << "}";
newline(SS);
}
void printBBInstr(const SExpr *E, StreamType &SS) {
bool Sub = false;
if (E->opcode() == COP_Variable) {
auto *V = cast<Variable>(E);
SS << "let " << V->name() << V->id() << " = ";
E = V->definition();
Sub = true;
}
else if (E->opcode() != COP_Store) {
SS << "let _x" << E->id() << " = ";
}
self()->printSExpr(E, SS, Prec_MAX, Sub);
SS << ";";
newline(SS);
}
void printBasicBlock(const BasicBlock *E, StreamType &SS) {
SS << "BB_" << E->blockID() << ":";
if (E->parent())
SS << " BB_" << E->parent()->blockID();
newline(SS);
for (auto *A : E->arguments())
printBBInstr(A, SS);
for (auto *I : E->instructions())
printBBInstr(I, SS);
const SExpr *T = E->terminator();
if (T) {
self()->printSExpr(T, SS, Prec_MAX, false);
SS << ";";
newline(SS);
}
newline(SS);
}
void printPhi(const Phi *E, StreamType &SS) {
SS << "phi(";
if (E->status() == Phi::PH_SingleVal)
self()->printSExpr(E->values()[0], SS, Prec_MAX);
else {
unsigned i = 0;
for (auto V : E->values()) {
if (i++ > 0)
SS << ", ";
self()->printSExpr(V, SS, Prec_MAX);
}
}
SS << ")";
}
void printGoto(const Goto *E, StreamType &SS) {
SS << "goto ";
printBlockLabel(SS, E->targetBlock(), E->index());
}
void printBranch(const Branch *E, StreamType &SS) {
SS << "branch (";
self()->printSExpr(E->condition(), SS, Prec_MAX);
SS << ") ";
printBlockLabel(SS, E->thenBlock(), -1);
SS << " ";
printBlockLabel(SS, E->elseBlock(), -1);
}
void printReturn(const Return *E, StreamType &SS) {
SS << "return ";
self()->printSExpr(E->returnValue(), SS, Prec_Other);
}
void printIdentifier(const Identifier *E, StreamType &SS) {
SS << E->name();
}
void printIfThenElse(const IfThenElse *E, StreamType &SS) {
if (CStyle) {
printSExpr(E->condition(), SS, Prec_Unary);
SS << " ? ";
printSExpr(E->thenExpr(), SS, Prec_Unary);
SS << " : ";
printSExpr(E->elseExpr(), SS, Prec_Unary);
return;
}
SS << "if (";
printSExpr(E->condition(), SS, Prec_MAX);
SS << ") then ";
printSExpr(E->thenExpr(), SS, Prec_Other);
SS << " else ";
printSExpr(E->elseExpr(), SS, Prec_Other);
}
void printLet(const Let *E, StreamType &SS) {
SS << "let ";
printVariable(E->variableDecl(), SS, true);
SS << " = ";
printSExpr(E->variableDecl()->definition(), SS, Prec_Decl-1);
SS << "; ";
printSExpr(E->body(), SS, Prec_Decl-1);
}
};
class StdPrinter : public PrettyPrinter<StdPrinter, std::ostream> { };
} // end namespace til
} // end namespace threadSafety
} // end namespace clang
#endif // LLVM_CLANG_THREAD_SAFETY_TRAVERSE_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/Dominators.h | //==- Dominators.h - Implementation of dominators tree for Clang CFG C++ -*-==//
//
// 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 dominators tree functionality for Clang CFGs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_DOMINATORS_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_DOMINATORS_H
#include "clang/Analysis/AnalysisContext.h"
#include "clang/Analysis/CFG.h"
#include "llvm/ADT/GraphTraits.h"
#include "llvm/Support/GenericDomTree.h"
#include "llvm/Support/GenericDomTreeConstruction.h"
// FIXME: There is no good reason for the domtree to require a print method
// which accepts an LLVM Module, so remove this (and the method's argument that
// needs it) when that is fixed.
namespace llvm {
class Module;
}
namespace clang {
class CFGBlock;
typedef llvm::DomTreeNodeBase<CFGBlock> DomTreeNode;
/// \brief Concrete subclass of DominatorTreeBase for Clang
/// This class implements the dominators tree functionality given a Clang CFG.
///
class DominatorTree : public ManagedAnalysis {
virtual void anchor();
public:
llvm::DominatorTreeBase<CFGBlock>* DT;
DominatorTree() {
DT = new llvm::DominatorTreeBase<CFGBlock>(false);
}
~DominatorTree() override { delete DT; }
llvm::DominatorTreeBase<CFGBlock>& getBase() { return *DT; }
/// \brief This method returns the root CFGBlock of the dominators tree.
///
inline CFGBlock *getRoot() const {
return DT->getRoot();
}
/// \brief This method returns the root DomTreeNode, which is the wrapper
/// for CFGBlock.
inline DomTreeNode *getRootNode() const {
return DT->getRootNode();
}
/// \brief This method compares two dominator trees.
/// The method returns false if the other dominator tree matches this
/// dominator tree, otherwise returns true.
///
inline bool compare(DominatorTree &Other) const {
DomTreeNode *R = getRootNode();
DomTreeNode *OtherR = Other.getRootNode();
if (!R || !OtherR || R->getBlock() != OtherR->getBlock())
return true;
if (DT->compare(Other.getBase()))
return true;
return false;
}
/// \brief This method builds the dominator tree for a given CFG
/// The CFG information is passed via AnalysisDeclContext
///
void buildDominatorTree(AnalysisDeclContext &AC) {
cfg = AC.getCFG();
DT->recalculate(*cfg);
}
/// \brief This method dumps immediate dominators for each block,
/// mainly used for debug purposes.
///
void dump() {
llvm::errs() << "Immediate dominance tree (Node#,IDom#):\n";
for (CFG::const_iterator I = cfg->begin(),
E = cfg->end(); I != E; ++I) {
if(DT->getNode(*I)->getIDom())
llvm::errs() << "(" << (*I)->getBlockID()
<< ","
<< DT->getNode(*I)->getIDom()->getBlock()->getBlockID()
<< ")\n";
else llvm::errs() << "(" << (*I)->getBlockID()
<< "," << (*I)->getBlockID() << ")\n";
}
}
/// \brief This method tests if one CFGBlock dominates the other.
/// The method return true if A dominates B, false otherwise.
/// Note a block always dominates itself.
///
inline bool dominates(const CFGBlock* A, const CFGBlock* B) const {
return DT->dominates(A, B);
}
/// \brief This method tests if one CFGBlock properly dominates the other.
/// The method return true if A properly dominates B, false otherwise.
///
bool properlyDominates(const CFGBlock*A, const CFGBlock*B) const {
return DT->properlyDominates(A, B);
}
/// \brief This method finds the nearest common dominator CFG block
/// for CFG block A and B. If there is no such block then return NULL.
///
inline CFGBlock *findNearestCommonDominator(CFGBlock *A, CFGBlock *B) {
return DT->findNearestCommonDominator(A, B);
}
inline const CFGBlock *findNearestCommonDominator(const CFGBlock *A,
const CFGBlock *B) {
return DT->findNearestCommonDominator(A, B);
}
/// \brief This method is used to update the dominator
/// tree information when a node's immediate dominator changes.
///
inline void changeImmediateDominator(CFGBlock *N, CFGBlock *NewIDom) {
DT->changeImmediateDominator(N, NewIDom);
}
/// \brief This method tests if the given CFGBlock can be reachable from root.
/// Returns true if reachable, false otherwise.
///
bool isReachableFromEntry(const CFGBlock *A) {
return DT->isReachableFromEntry(A);
}
/// \brief This method releases the memory held by the dominator tree.
///
virtual void releaseMemory() {
DT->releaseMemory();
}
/// \brief This method converts the dominator tree to human readable form.
///
virtual void print(raw_ostream &OS, const llvm::Module* M= nullptr) const {
DT->print(OS);
}
private:
CFG *cfg;
};
} // end namespace clang
//===-------------------------------------
/// DominatorTree GraphTraits specialization so the DominatorTree can be
/// iterable by generic graph iterators.
///
namespace llvm {
template <> struct GraphTraits< ::clang::DomTreeNode* > {
typedef ::clang::DomTreeNode NodeType;
typedef NodeType::iterator ChildIteratorType;
static NodeType *getEntryNode(NodeType *N) {
return N;
}
static inline ChildIteratorType child_begin(NodeType *N) {
return N->begin();
}
static inline ChildIteratorType child_end(NodeType *N) {
return N->end();
}
typedef df_iterator< ::clang::DomTreeNode* > nodes_iterator;
static nodes_iterator nodes_begin(::clang::DomTreeNode *N) {
return df_begin(getEntryNode(N));
}
static nodes_iterator nodes_end(::clang::DomTreeNode *N) {
return df_end(getEntryNode(N));
}
};
template <> struct GraphTraits< ::clang::DominatorTree* >
: public GraphTraits< ::clang::DomTreeNode* > {
static NodeType *getEntryNode(::clang::DominatorTree *DT) {
return DT->getRootNode();
}
static nodes_iterator nodes_begin(::clang::DominatorTree *N) {
return df_begin(getEntryNode(N));
}
static nodes_iterator nodes_end(::clang::DominatorTree *N) {
return df_end(getEntryNode(N));
}
};
} // end namespace llvm
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/Consumed.h | //===- Consumed.h ----------------------------------------------*- C++ --*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// A intra-procedural analysis for checking consumed properties. This is based,
// in part, on research on linear types.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_CONSUMED_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_CONSUMED_H
#include "clang/AST/DeclCXX.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/StmtCXX.h"
#include "clang/Analysis/Analyses/PostOrderCFGView.h"
#include "clang/Analysis/AnalysisContext.h"
#include "clang/Basic/SourceLocation.h"
namespace clang {
namespace consumed {
enum ConsumedState {
// No state information for the given variable.
CS_None,
CS_Unknown,
CS_Unconsumed,
CS_Consumed
};
class ConsumedStmtVisitor;
typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
typedef std::list<DelayedDiag> DiagList;
class ConsumedWarningsHandlerBase {
public:
virtual ~ConsumedWarningsHandlerBase();
/// \brief Emit the warnings and notes left by the analysis.
virtual void emitDiagnostics() {}
/// \brief Warn that a variable's state doesn't match at the entry and exit
/// of a loop.
///
/// \param Loc -- The location of the end of the loop.
///
/// \param VariableName -- The name of the variable that has a mismatched
/// state.
virtual void warnLoopStateMismatch(SourceLocation Loc,
StringRef VariableName) {}
/// \brief Warn about parameter typestate mismatches upon return.
///
/// \param Loc -- The SourceLocation of the return statement.
///
/// \param ExpectedState -- The state the return value was expected to be
/// in.
///
/// \param ObservedState -- The state the return value was observed to be
/// in.
virtual void warnParamReturnTypestateMismatch(SourceLocation Loc,
StringRef VariableName,
StringRef ExpectedState,
StringRef ObservedState) {};
// FIXME: Add documentation.
virtual void warnParamTypestateMismatch(SourceLocation LOC,
StringRef ExpectedState,
StringRef ObservedState) {}
// FIXME: This can be removed when the attr propagation fix for templated
// classes lands.
/// \brief Warn about return typestates set for unconsumable types.
///
/// \param Loc -- The location of the attributes.
///
/// \param TypeName -- The name of the unconsumable type.
virtual void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
StringRef TypeName) {}
/// \brief Warn about return typestate mismatches.
///
/// \param Loc -- The SourceLocation of the return statement.
///
/// \param ExpectedState -- The state the return value was expected to be
/// in.
///
/// \param ObservedState -- The state the return value was observed to be
/// in.
virtual void warnReturnTypestateMismatch(SourceLocation Loc,
StringRef ExpectedState,
StringRef ObservedState) {}
/// \brief Warn about use-while-consumed errors.
/// \param MethodName -- The name of the method that was incorrectly
/// invoked.
///
/// \param State -- The state the object was used in.
///
/// \param Loc -- The SourceLocation of the method invocation.
virtual void warnUseOfTempInInvalidState(StringRef MethodName,
StringRef State,
SourceLocation Loc) {}
/// \brief Warn about use-while-consumed errors.
/// \param MethodName -- The name of the method that was incorrectly
/// invoked.
///
/// \param State -- The state the object was used in.
///
/// \param VariableName -- The name of the variable that holds the unique
/// value.
///
/// \param Loc -- The SourceLocation of the method invocation.
virtual void warnUseInInvalidState(StringRef MethodName,
StringRef VariableName,
StringRef State,
SourceLocation Loc) {}
};
class ConsumedStateMap {
typedef llvm::DenseMap<const VarDecl *, ConsumedState> VarMapType;
typedef llvm::DenseMap<const CXXBindTemporaryExpr *, ConsumedState>
TmpMapType;
protected:
bool Reachable;
const Stmt *From;
VarMapType VarMap;
TmpMapType TmpMap;
public:
ConsumedStateMap() : Reachable(true), From(nullptr) {}
ConsumedStateMap(const ConsumedStateMap &Other)
: Reachable(Other.Reachable), From(Other.From), VarMap(Other.VarMap),
TmpMap() {}
/// \brief Warn if any of the parameters being tracked are not in the state
/// they were declared to be in upon return from a function.
void checkParamsForReturnTypestate(SourceLocation BlameLoc,
ConsumedWarningsHandlerBase &WarningsHandler) const;
/// \brief Clear the TmpMap.
void clearTemporaries();
/// \brief Get the consumed state of a given variable.
ConsumedState getState(const VarDecl *Var) const;
/// \brief Get the consumed state of a given temporary value.
ConsumedState getState(const CXXBindTemporaryExpr *Tmp) const;
/// \brief Merge this state map with another map.
void intersect(const ConsumedStateMap *Other);
void intersectAtLoopHead(const CFGBlock *LoopHead, const CFGBlock *LoopBack,
const ConsumedStateMap *LoopBackStates,
ConsumedWarningsHandlerBase &WarningsHandler);
/// \brief Return true if this block is reachable.
bool isReachable() const { return Reachable; }
/// \brief Mark the block as unreachable.
void markUnreachable();
/// \brief Set the source for a decision about the branching of states.
/// \param Source -- The statement that was the origin of a branching
/// decision.
void setSource(const Stmt *Source) { this->From = Source; }
/// \brief Set the consumed state of a given variable.
void setState(const VarDecl *Var, ConsumedState State);
/// \brief Set the consumed state of a given temporary value.
void setState(const CXXBindTemporaryExpr *Tmp, ConsumedState State);
/// \brief Remove the temporary value from our state map.
void remove(const CXXBindTemporaryExpr *Tmp);
/// \brief Tests to see if there is a mismatch in the states stored in two
/// maps.
///
/// \param Other -- The second map to compare against.
bool operator!=(const ConsumedStateMap *Other) const;
};
class ConsumedBlockInfo {
std::vector<ConsumedStateMap*> StateMapsArray;
std::vector<unsigned int> VisitOrder;
public:
ConsumedBlockInfo() { }
~ConsumedBlockInfo() { llvm::DeleteContainerPointers(StateMapsArray); }
ConsumedBlockInfo(unsigned int NumBlocks, PostOrderCFGView *SortedGraph)
: StateMapsArray(NumBlocks, nullptr), VisitOrder(NumBlocks, 0) {
unsigned int VisitOrderCounter = 0;
for (PostOrderCFGView::iterator BI = SortedGraph->begin(),
BE = SortedGraph->end(); BI != BE; ++BI) {
VisitOrder[(*BI)->getBlockID()] = VisitOrderCounter++;
}
}
bool allBackEdgesVisited(const CFGBlock *CurrBlock,
const CFGBlock *TargetBlock);
void addInfo(const CFGBlock *Block, ConsumedStateMap *StateMap,
bool &AlreadyOwned);
void addInfo(const CFGBlock *Block, ConsumedStateMap *StateMap);
ConsumedStateMap* borrowInfo(const CFGBlock *Block);
void discardInfo(const CFGBlock *Block);
ConsumedStateMap* getInfo(const CFGBlock *Block);
bool isBackEdge(const CFGBlock *From, const CFGBlock *To);
bool isBackEdgeTarget(const CFGBlock *Block);
};
/// A class that handles the analysis of uniqueness violations.
class ConsumedAnalyzer {
ConsumedBlockInfo BlockInfo;
ConsumedStateMap *CurrStates;
ConsumedState ExpectedReturnState;
void determineExpectedReturnState(AnalysisDeclContext &AC,
const FunctionDecl *D);
bool hasConsumableAttributes(const CXXRecordDecl *RD);
bool splitState(const CFGBlock *CurrBlock,
const ConsumedStmtVisitor &Visitor);
public:
ConsumedWarningsHandlerBase &WarningsHandler;
ConsumedAnalyzer(ConsumedWarningsHandlerBase &WarningsHandler)
: WarningsHandler(WarningsHandler) {}
ConsumedState getExpectedReturnState() const { return ExpectedReturnState; }
/// \brief Check a function's CFG for consumed violations.
///
/// We traverse the blocks in the CFG, keeping track of the state of each
/// value who's type has uniquness annotations. If methods are invoked in
/// the wrong state a warning is issued. Each block in the CFG is traversed
/// exactly once.
void run(AnalysisDeclContext &AC);
};
}} // end namespace clang::consumed
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyUtil.h | //===- ThreadSafetyUtil.h --------------------------------------*- 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 some basic utility classes for use by ThreadSafetyTIL.h
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYUTIL_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYUTIL_H
#include "clang/AST/ExprCXX.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/AlignOf.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Compiler.h"
#include <cassert>
#include <cstddef>
#include <ostream>
#include <utility>
#include <vector>
namespace clang {
namespace threadSafety {
namespace til {
// Simple wrapper class to abstract away from the details of memory management.
// SExprs are allocated in pools, and deallocated all at once.
class MemRegionRef {
private:
union AlignmentType {
double d;
void *p;
long double dd;
long long ii;
};
public:
MemRegionRef() : Allocator(nullptr) {}
MemRegionRef(llvm::BumpPtrAllocator *A) : Allocator(A) {}
void *allocate(size_t Sz) {
return Allocator->Allocate(Sz, llvm::AlignOf<AlignmentType>::Alignment);
}
template <typename T> T *allocateT() { return Allocator->Allocate<T>(); }
template <typename T> T *allocateT(size_t NumElems) {
return Allocator->Allocate<T>(NumElems);
}
private:
llvm::BumpPtrAllocator *Allocator;
};
} // end namespace til
} // end namespace threadSafety
} // end namespace clang
inline void *operator new(size_t Sz,
clang::threadSafety::til::MemRegionRef &R) {
return R.allocate(Sz);
}
namespace clang {
namespace threadSafety {
std::string getSourceLiteralString(const clang::Expr *CE);
using llvm::StringRef;
using clang::SourceLocation;
namespace til {
// A simple fixed size array class that does not manage its own memory,
// suitable for use with bump pointer allocation.
template <class T> class SimpleArray {
public:
SimpleArray() : Data(nullptr), Size(0), Capacity(0) {}
SimpleArray(T *Dat, size_t Cp, size_t Sz = 0)
: Data(Dat), Size(Sz), Capacity(Cp) {}
SimpleArray(MemRegionRef A, size_t Cp)
: Data(Cp == 0 ? nullptr : A.allocateT<T>(Cp)), Size(0), Capacity(Cp) {}
SimpleArray(SimpleArray<T> &&A)
: Data(A.Data), Size(A.Size), Capacity(A.Capacity) {
A.Data = nullptr;
A.Size = 0;
A.Capacity = 0;
}
SimpleArray &operator=(SimpleArray &&RHS) {
if (this != &RHS) {
Data = RHS.Data;
Size = RHS.Size;
Capacity = RHS.Capacity;
RHS.Data = nullptr;
RHS.Size = RHS.Capacity = 0;
}
return *this;
}
// Reserve space for at least Ncp items, reallocating if necessary.
void reserve(size_t Ncp, MemRegionRef A) {
if (Ncp <= Capacity)
return;
T *Odata = Data;
Data = A.allocateT<T>(Ncp);
Capacity = Ncp;
memcpy(Data, Odata, sizeof(T) * Size);
return;
}
// Reserve space for at least N more items.
void reserveCheck(size_t N, MemRegionRef A) {
if (Capacity == 0)
reserve(u_max(InitialCapacity, N), A);
else if (Size + N < Capacity)
reserve(u_max(Size + N, Capacity * 2), A);
}
typedef T *iterator;
typedef const T *const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
size_t size() const { return Size; }
size_t capacity() const { return Capacity; }
T &operator[](unsigned i) {
assert(i < Size && "Array index out of bounds.");
return Data[i];
}
const T &operator[](unsigned i) const {
assert(i < Size && "Array index out of bounds.");
return Data[i];
}
T &back() {
assert(Size && "No elements in the array.");
return Data[Size - 1];
}
const T &back() const {
assert(Size && "No elements in the array.");
return Data[Size - 1];
}
iterator begin() { return Data; }
iterator end() { return Data + Size; }
const_iterator begin() const { return Data; }
const_iterator end() const { return Data + Size; }
const_iterator cbegin() const { return Data; }
const_iterator cend() const { return Data + Size; }
reverse_iterator rbegin() { return reverse_iterator(end()); }
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rbegin() const {
return const_reverse_iterator(end());
}
const_reverse_iterator rend() const {
return const_reverse_iterator(begin());
}
void push_back(const T &Elem) {
assert(Size < Capacity);
Data[Size++] = Elem;
}
// drop last n elements from array
void drop(unsigned n = 0) {
assert(Size > n);
Size -= n;
}
void setValues(unsigned Sz, const T& C) {
assert(Sz <= Capacity);
Size = Sz;
for (unsigned i = 0; i < Sz; ++i) {
Data[i] = C;
}
}
template <class Iter> unsigned append(Iter I, Iter E) {
size_t Osz = Size;
size_t J = Osz;
for (; J < Capacity && I != E; ++J, ++I)
Data[J] = *I;
Size = J;
return J - Osz;
}
llvm::iterator_range<reverse_iterator> reverse() {
return llvm::make_range(rbegin(), rend());
}
llvm::iterator_range<const_reverse_iterator> reverse() const {
return llvm::make_range(rbegin(), rend());
}
private:
// std::max is annoying here, because it requires a reference,
// thus forcing InitialCapacity to be initialized outside the .h file.
size_t u_max(size_t i, size_t j) { return (i < j) ? j : i; }
static const size_t InitialCapacity = 4;
SimpleArray(const SimpleArray<T> &A) = delete;
T *Data;
size_t Size;
size_t Capacity;
};
} // end namespace til
// A copy on write vector.
// The vector can be in one of three states:
// * invalid -- no operations are permitted.
// * read-only -- read operations are permitted.
// * writable -- read and write operations are permitted.
// The init(), destroy(), and makeWritable() methods will change state.
template<typename T>
class CopyOnWriteVector {
class VectorData {
public:
VectorData() : NumRefs(1) { }
VectorData(const VectorData &VD) : NumRefs(1), Vect(VD.Vect) { }
unsigned NumRefs;
std::vector<T> Vect;
};
// No copy constructor or copy assignment. Use clone() with move assignment.
CopyOnWriteVector(const CopyOnWriteVector &V) = delete;
void operator=(const CopyOnWriteVector &V) = delete;
public:
CopyOnWriteVector() : Data(nullptr) {}
CopyOnWriteVector(CopyOnWriteVector &&V) : Data(V.Data) { V.Data = nullptr; }
~CopyOnWriteVector() { destroy(); }
// Returns true if this holds a valid vector.
bool valid() const { return Data; }
// Returns true if this vector is writable.
bool writable() const { return Data && Data->NumRefs == 1; }
// If this vector is not valid, initialize it to a valid vector.
void init() {
if (!Data) {
Data = new VectorData();
}
}
// Destroy this vector; thus making it invalid.
void destroy() {
if (!Data)
return;
if (Data->NumRefs <= 1)
delete Data;
else
--Data->NumRefs;
Data = nullptr;
}
// Make this vector writable, creating a copy if needed.
void makeWritable() {
if (!Data) {
Data = new VectorData();
return;
}
if (Data->NumRefs == 1)
return; // already writeable.
--Data->NumRefs;
Data = new VectorData(*Data);
}
// Create a lazy copy of this vector.
CopyOnWriteVector clone() { return CopyOnWriteVector(Data); }
CopyOnWriteVector &operator=(CopyOnWriteVector &&V) {
destroy();
Data = V.Data;
V.Data = nullptr;
return *this;
}
typedef typename std::vector<T>::const_iterator const_iterator;
const std::vector<T> &elements() const { return Data->Vect; }
const_iterator begin() const { return elements().cbegin(); }
const_iterator end() const { return elements().cend(); }
const T& operator[](unsigned i) const { return elements()[i]; }
unsigned size() const { return Data ? elements().size() : 0; }
// Return true if V and this vector refer to the same data.
bool sameAs(const CopyOnWriteVector &V) const { return Data == V.Data; }
// Clear vector. The vector must be writable.
void clear() {
assert(writable() && "Vector is not writable!");
Data->Vect.clear();
}
// Push a new element onto the end. The vector must be writable.
void push_back(const T &Elem) {
assert(writable() && "Vector is not writable!");
Data->Vect.push_back(Elem);
}
// Gets a mutable reference to the element at index(i).
// The vector must be writable.
T& elem(unsigned i) {
assert(writable() && "Vector is not writable!");
return Data->Vect[i];
}
// Drops elements from the back until the vector has size i.
void downsize(unsigned i) {
assert(writable() && "Vector is not writable!");
Data->Vect.erase(Data->Vect.begin() + i, Data->Vect.end());
}
private:
CopyOnWriteVector(VectorData *D) : Data(D) {
if (!Data)
return;
++Data->NumRefs;
}
VectorData *Data;
};
inline std::ostream& operator<<(std::ostream& ss, const StringRef str) {
return ss.write(str.data(), str.size());
}
} // end namespace threadSafety
} // end namespace clang
#endif // LLVM_CLANG_THREAD_SAFETY_UTIL_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/ThreadSafety.h | //===- ThreadSafety.h ------------------------------------------*- C++ --*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//
// A intra-procedural analysis for thread safety (e.g. deadlocks and race
// conditions), based off of an annotation system.
//
// See http://clang.llvm.org/docs/LanguageExtensions.html#thread-safety-annotation-checking
// for more information.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETY_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETY_H
#include "clang/Analysis/AnalysisContext.h"
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/StringRef.h"
namespace clang {
namespace threadSafety {
class BeforeSet;
/// This enum distinguishes between different kinds of operations that may
/// need to be protected by locks. We use this enum in error handling.
enum ProtectedOperationKind {
POK_VarDereference, ///< Dereferencing a variable (e.g. p in *p = 5;)
POK_VarAccess, ///< Reading or writing a variable (e.g. x in x = 5;)
POK_FunctionCall, ///< Making a function call (e.g. fool())
POK_PassByRef, ///< Passing a guarded variable by reference.
POK_PtPassByRef, ///< Passing a pt-guarded variable by reference.
};
/// This enum distinguishes between different kinds of lock actions. For
/// example, it is an error to write a variable protected by shared version of a
/// mutex.
enum LockKind {
LK_Shared, ///< Shared/reader lock of a mutex.
LK_Exclusive, ///< Exclusive/writer lock of a mutex.
LK_Generic ///< Can be either Shared or Exclusive
};
/// This enum distinguishes between different ways to access (read or write) a
/// variable.
enum AccessKind {
AK_Read, ///< Reading a variable.
AK_Written ///< Writing a variable.
};
/// This enum distinguishes between different situations where we warn due to
/// inconsistent locking.
/// \enum SK_LockedSomeLoopIterations -- a mutex is locked for some but not all
/// loop iterations.
/// \enum SK_LockedSomePredecessors -- a mutex is locked in some but not all
/// predecessors of a CFGBlock.
/// \enum SK_LockedAtEndOfFunction -- a mutex is still locked at the end of a
/// function.
enum LockErrorKind {
LEK_LockedSomeLoopIterations,
LEK_LockedSomePredecessors,
LEK_LockedAtEndOfFunction,
LEK_NotLockedAtEndOfFunction
};
/// Handler class for thread safety warnings.
class ThreadSafetyHandler {
public:
typedef StringRef Name;
ThreadSafetyHandler() : IssueBetaWarnings(false) { }
virtual ~ThreadSafetyHandler();
/// Warn about lock expressions which fail to resolve to lockable objects.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
/// \param Loc -- the SourceLocation of the unresolved expression.
virtual void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) {}
/// Warn about unlock function calls that do not have a prior matching lock
/// expression.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
/// \param LockName -- A StringRef name for the lock expression, to be printed
/// in the error message.
/// \param Loc -- The SourceLocation of the Unlock
virtual void handleUnmatchedUnlock(StringRef Kind, Name LockName,
SourceLocation Loc) {}
/// Warn about an unlock function call that attempts to unlock a lock with
/// the incorrect lock kind. For instance, a shared lock being unlocked
/// exclusively, or vice versa.
/// \param LockName -- A StringRef name for the lock expression, to be printed
/// in the error message.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
/// \param Expected -- the kind of lock expected.
/// \param Received -- the kind of lock received.
/// \param Loc -- The SourceLocation of the Unlock.
virtual void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
LockKind Expected, LockKind Received,
SourceLocation Loc) {}
/// Warn about lock function calls for locks which are already held.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
/// \param LockName -- A StringRef name for the lock expression, to be printed
/// in the error message.
/// \param Loc -- The location of the second lock expression.
virtual void handleDoubleLock(StringRef Kind, Name LockName,
SourceLocation Loc) {}
/// Warn about situations where a mutex is sometimes held and sometimes not.
/// The three situations are:
/// 1. a mutex is locked on an "if" branch but not the "else" branch,
/// 2, or a mutex is only held at the start of some loop iterations,
/// 3. or when a mutex is locked but not unlocked inside a function.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
/// \param LockName -- A StringRef name for the lock expression, to be printed
/// in the error message.
/// \param LocLocked -- The location of the lock expression where the mutex is
/// locked
/// \param LocEndOfScope -- The location of the end of the scope where the
/// mutex is no longer held
/// \param LEK -- which of the three above cases we should warn for
virtual void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
SourceLocation LocLocked,
SourceLocation LocEndOfScope,
LockErrorKind LEK) {}
/// Warn when a mutex is held exclusively and shared at the same point. For
/// example, if a mutex is locked exclusively during an if branch and shared
/// during the else branch.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
/// \param LockName -- A StringRef name for the lock expression, to be printed
/// in the error message.
/// \param Loc1 -- The location of the first lock expression.
/// \param Loc2 -- The location of the second lock expression.
virtual void handleExclusiveAndShared(StringRef Kind, Name LockName,
SourceLocation Loc1,
SourceLocation Loc2) {}
/// Warn when a protected operation occurs while no locks are held.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
/// \param D -- The decl for the protected variable or function
/// \param POK -- The kind of protected operation (e.g. variable access)
/// \param AK -- The kind of access (i.e. read or write) that occurred
/// \param Loc -- The location of the protected operation.
virtual void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
ProtectedOperationKind POK, AccessKind AK,
SourceLocation Loc) {}
/// Warn when a protected operation occurs while the specific mutex protecting
/// the operation is not locked.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
/// \param D -- The decl for the protected variable or function
/// \param POK -- The kind of protected operation (e.g. variable access)
/// \param LockName -- A StringRef name for the lock expression, to be printed
/// in the error message.
/// \param LK -- The kind of access (i.e. read or write) that occurred
/// \param Loc -- The location of the protected operation.
virtual void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
ProtectedOperationKind POK, Name LockName,
LockKind LK, SourceLocation Loc,
Name *PossibleMatch = nullptr) {}
/// Warn when acquiring a lock that the negative capability is not held.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
/// \param LockName -- The name for the lock expression, to be printed in the
/// diagnostic.
/// \param Neg -- The name of the negative capability to be printed in the
/// diagnostic.
/// \param Loc -- The location of the protected operation.
virtual void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
SourceLocation Loc) {}
/// Warn when a function is called while an excluded mutex is locked. For
/// example, the mutex may be locked inside the function.
/// \param Kind -- the capability's name parameter (role, mutex, etc).
/// \param FunName -- The name of the function
/// \param LockName -- A StringRef name for the lock expression, to be printed
/// in the error message.
/// \param Loc -- The location of the function call.
virtual void handleFunExcludesLock(StringRef Kind, Name FunName,
Name LockName, SourceLocation Loc) {}
/// Warn that L1 cannot be acquired before L2.
virtual void handleLockAcquiredBefore(StringRef Kind, Name L1Name,
Name L2Name, SourceLocation Loc) {}
/// Warn that there is a cycle in acquired_before/after dependencies.
virtual void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) {}
/// Called by the analysis when starting analysis of a function.
/// Used to issue suggestions for changes to annotations.
virtual void enterFunction(const FunctionDecl *FD) {}
/// Called by the analysis when finishing analysis of a function.
virtual void leaveFunction(const FunctionDecl *FD) {}
bool issueBetaWarnings() { return IssueBetaWarnings; }
void setIssueBetaWarnings(bool b) { IssueBetaWarnings = b; }
private:
bool IssueBetaWarnings;
};
/// \brief Check a function's CFG for thread-safety violations.
///
/// We traverse the blocks in the CFG, compute the set of mutexes that are held
/// at the end of each block, and issue warnings for thread safety violations.
/// Each block in the CFG is traversed exactly once.
void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
ThreadSafetyHandler &Handler,
BeforeSet **Bset);
void threadSafetyCleanup(BeforeSet *Cache);
/// \brief Helper function that returns a LockKind required for the given level
/// of access.
LockKind getLockKindFromAccessKind(AccessKind AK);
}} // end namespace clang::threadSafety
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/UninitializedValues.h | //= UninitializedValues.h - Finding uses of uninitialized values -*- 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 APIs for invoking and reported uninitialized values
// warnings.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_UNINITIALIZEDVALUES_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_UNINITIALIZEDVALUES_H
#include "clang/AST/Stmt.h"
#include "llvm/ADT/SmallVector.h"
namespace clang {
class AnalysisDeclContext;
class CFG;
class DeclContext;
class Expr;
class VarDecl;
/// A use of a variable, which might be uninitialized.
class UninitUse {
public:
struct Branch {
const Stmt *Terminator;
unsigned Output;
};
private:
/// The expression which uses this variable.
const Expr *User;
/// Is this use uninitialized whenever the function is called?
bool UninitAfterCall;
/// Is this use uninitialized whenever the variable declaration is reached?
bool UninitAfterDecl;
/// Does this use always see an uninitialized value?
bool AlwaysUninit;
/// This use is always uninitialized if it occurs after any of these branches
/// is taken.
SmallVector<Branch, 2> UninitBranches;
public:
UninitUse(const Expr *User, bool AlwaysUninit)
: User(User), UninitAfterCall(false), UninitAfterDecl(false),
AlwaysUninit(AlwaysUninit) {}
void addUninitBranch(Branch B) {
UninitBranches.push_back(B);
}
void setUninitAfterCall() { UninitAfterCall = true; }
void setUninitAfterDecl() { UninitAfterDecl = true; }
/// Get the expression containing the uninitialized use.
const Expr *getUser() const { return User; }
/// The kind of uninitialized use.
enum Kind {
/// The use might be uninitialized.
Maybe,
/// The use is uninitialized whenever a certain branch is taken.
Sometimes,
/// The use is uninitialized the first time it is reached after we reach
/// the variable's declaration.
AfterDecl,
/// The use is uninitialized the first time it is reached after the function
/// is called.
AfterCall,
/// The use is always uninitialized.
Always
};
/// Get the kind of uninitialized use.
Kind getKind() const {
return AlwaysUninit ? Always :
UninitAfterCall ? AfterCall :
UninitAfterDecl ? AfterDecl :
!branch_empty() ? Sometimes : Maybe;
}
typedef SmallVectorImpl<Branch>::const_iterator branch_iterator;
/// Branches which inevitably result in the variable being used uninitialized.
branch_iterator branch_begin() const { return UninitBranches.begin(); }
branch_iterator branch_end() const { return UninitBranches.end(); }
bool branch_empty() const { return UninitBranches.empty(); }
};
class UninitVariablesHandler {
public:
UninitVariablesHandler() {}
virtual ~UninitVariablesHandler();
/// Called when the uninitialized variable is used at the given expression.
virtual void handleUseOfUninitVariable(const VarDecl *vd,
const UninitUse &use) {}
/// Called when the uninitialized variable analysis detects the
/// idiom 'int x = x'. All other uses of 'x' within the initializer
/// are handled by handleUseOfUninitVariable.
virtual void handleSelfInit(const VarDecl *vd) {}
};
struct UninitVariablesAnalysisStats {
unsigned NumVariablesAnalyzed;
unsigned NumBlockVisits;
};
void runUninitializedVariablesAnalysis(const DeclContext &dc, const CFG &cfg,
AnalysisDeclContext &ac,
UninitVariablesHandler &handler,
UninitVariablesAnalysisStats &stats);
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/LiveVariables.h | //===- LiveVariables.h - Live Variable Analysis for Source CFGs -*- C++ --*-//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements Live Variables analysis for source-level CFGs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_LIVEVARIABLES_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_LIVEVARIABLES_H
#include "clang/AST/Decl.h"
#include "clang/Analysis/AnalysisContext.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/ImmutableSet.h"
namespace clang {
class CFG;
class CFGBlock;
class Stmt;
class DeclRefExpr;
class SourceManager;
class LiveVariables : public ManagedAnalysis {
public:
class LivenessValues {
public:
llvm::ImmutableSet<const Stmt *> liveStmts;
llvm::ImmutableSet<const VarDecl *> liveDecls;
bool equals(const LivenessValues &V) const;
LivenessValues()
: liveStmts(nullptr), liveDecls(nullptr) {}
LivenessValues(llvm::ImmutableSet<const Stmt *> LiveStmts,
llvm::ImmutableSet<const VarDecl *> LiveDecls)
: liveStmts(LiveStmts), liveDecls(LiveDecls) {}
bool isLive(const Stmt *S) const;
bool isLive(const VarDecl *D) const;
friend class LiveVariables;
};
class Observer {
virtual void anchor();
public:
virtual ~Observer() {}
/// A callback invoked right before invoking the
/// liveness transfer function on the given statement.
virtual void observeStmt(const Stmt *S,
const CFGBlock *currentBlock,
const LivenessValues& V) {}
/// Called when the live variables analysis registers
/// that a variable is killed.
virtual void observerKill(const DeclRefExpr *DR) {}
};
~LiveVariables() override;
/// Compute the liveness information for a given CFG.
static LiveVariables *computeLiveness(AnalysisDeclContext &analysisContext,
bool killAtAssign);
/// Return true if a variable is live at the end of a
/// specified block.
bool isLive(const CFGBlock *B, const VarDecl *D);
/// Returns true if a variable is live at the beginning of the
/// the statement. This query only works if liveness information
/// has been recorded at the statement level (see runOnAllBlocks), and
/// only returns liveness information for block-level expressions.
bool isLive(const Stmt *S, const VarDecl *D);
/// Returns true the block-level expression "value" is live
/// before the given block-level expression (see runOnAllBlocks).
bool isLive(const Stmt *Loc, const Stmt *StmtVal);
/// Print to stderr the liveness information associated with
/// each basic block.
void dumpBlockLiveness(const SourceManager& M);
void runOnAllBlocks(Observer &obs);
static LiveVariables *create(AnalysisDeclContext &analysisContext) {
return computeLiveness(analysisContext, true);
}
static const void *getTag();
private:
LiveVariables(void *impl);
void *impl;
};
class RelaxedLiveVariables : public LiveVariables {
public:
static LiveVariables *create(AnalysisDeclContext &analysisContext) {
return computeLiveness(analysisContext, false);
}
static const void *getTag();
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/PostOrderCFGView.h | //===- PostOrderCFGView.h - Post order view of CFG blocks ---------*- C++ --*-//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements post order view of the blocks in a CFG.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_POSTORDERCFGVIEW_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_POSTORDERCFGVIEW_H
#include <vector>
//#include <algorithm>
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/BitVector.h"
#include "clang/Analysis/AnalysisContext.h"
#include "clang/Analysis/CFG.h"
namespace clang {
class PostOrderCFGView : public ManagedAnalysis {
virtual void anchor();
public:
/// \brief Implements a set of CFGBlocks using a BitVector.
///
/// This class contains a minimal interface, primarily dictated by the SetType
/// template parameter of the llvm::po_iterator template, as used with
/// external storage. We also use this set to keep track of which CFGBlocks we
/// visit during the analysis.
class CFGBlockSet {
llvm::BitVector VisitedBlockIDs;
public:
// po_iterator requires this iterator, but the only interface needed is the
// value_type typedef.
struct iterator { typedef const CFGBlock *value_type; };
CFGBlockSet() {}
CFGBlockSet(const CFG *G) : VisitedBlockIDs(G->getNumBlockIDs(), false) {}
/// \brief Set the bit associated with a particular CFGBlock.
/// This is the important method for the SetType template parameter.
std::pair<llvm::NoneType, bool> insert(const CFGBlock *Block) {
// Note that insert() is called by po_iterator, which doesn't check to
// make sure that Block is non-null. Moreover, the CFGBlock iterator will
// occasionally hand out null pointers for pruned edges, so we catch those
// here.
if (!Block)
return std::make_pair(None, false); // if an edge is trivially false.
if (VisitedBlockIDs.test(Block->getBlockID()))
return std::make_pair(None, false);
VisitedBlockIDs.set(Block->getBlockID());
return std::make_pair(None, true);
}
/// \brief Check if the bit for a CFGBlock has been already set.
/// This method is for tracking visited blocks in the main threadsafety
/// loop. Block must not be null.
bool alreadySet(const CFGBlock *Block) {
return VisitedBlockIDs.test(Block->getBlockID());
}
};
private:
typedef llvm::po_iterator<const CFG*, CFGBlockSet, true> po_iterator;
std::vector<const CFGBlock*> Blocks;
typedef llvm::DenseMap<const CFGBlock *, unsigned> BlockOrderTy;
BlockOrderTy BlockOrder;
public:
typedef std::vector<const CFGBlock *>::reverse_iterator iterator;
typedef std::vector<const CFGBlock *>::const_reverse_iterator const_iterator;
PostOrderCFGView(const CFG *cfg);
iterator begin() { return Blocks.rbegin(); }
iterator end() { return Blocks.rend(); }
const_iterator begin() const { return Blocks.rbegin(); }
const_iterator end() const { return Blocks.rend(); }
bool empty() const { return begin() == end(); }
struct BlockOrderCompare;
friend struct BlockOrderCompare;
struct BlockOrderCompare {
const PostOrderCFGView &POV;
public:
BlockOrderCompare(const PostOrderCFGView &pov) : POV(pov) {}
bool operator()(const CFGBlock *b1, const CFGBlock *b2) const;
};
BlockOrderCompare getComparator() const {
return BlockOrderCompare(*this);
}
// Used by AnalyisContext to construct this object.
static const void *getTag();
static PostOrderCFGView *create(AnalysisDeclContext &analysisContext);
};
} // end clang namespace
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/PseudoConstantAnalysis.h | //== PseudoConstantAnalysis.h - Find Pseudo-constants in the AST -*- C++ -*-==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file tracks the usage of variables in a Decl body to see if they are
// never written to, implying that they constant. This is useful in static
// analysis to see if a developer might have intended a variable to be const.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_PSEUDOCONSTANTANALYSIS_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_PSEUDOCONSTANTANALYSIS_H
#include "clang/AST/Stmt.h"
namespace clang {
class PseudoConstantAnalysis {
public:
PseudoConstantAnalysis(const Stmt *DeclBody);
~PseudoConstantAnalysis();
bool isPseudoConstant(const VarDecl *VD);
bool wasReferenced(const VarDecl *VD);
private:
void RunAnalysis();
inline static const Decl *getDecl(const Expr *E);
// for storing the result of analyzed ValueDecls
void *NonConstantsImpl;
void *UsedVarsImpl;
const Stmt *DeclBody;
bool Analyzed;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/ReachableCode.h | //===- ReachableCode.h -----------------------------------------*- C++ --*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// A flow-sensitive, path-insensitive analysis of unreachable code.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_REACHABLECODE_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_REACHABLECODE_H
#include "clang/Basic/SourceLocation.h"
//===----------------------------------------------------------------------===//
// Forward declarations.
//===----------------------------------------------------------------------===//
namespace llvm {
class BitVector;
}
namespace clang {
class AnalysisDeclContext;
class CFGBlock;
class Preprocessor;
}
//===----------------------------------------------------------------------===//
// API.
// //
///////////////////////////////////////////////////////////////////////////////
namespace clang {
namespace reachable_code {
/// Classifications of unreachable code.
enum UnreachableKind {
UK_Return,
UK_Break,
UK_Loop_Increment,
UK_Other
};
class Callback {
virtual void anchor();
public:
virtual ~Callback() {}
virtual void HandleUnreachable(UnreachableKind UK,
SourceLocation L,
SourceRange ConditionVal,
SourceRange R1,
SourceRange R2) = 0;
};
/// ScanReachableFromBlock - Mark all blocks reachable from Start.
/// Returns the total number of blocks that were marked reachable.
unsigned ScanReachableFromBlock(const CFGBlock *Start,
llvm::BitVector &Reachable);
void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP,
Callback &CB);
}} // end namespace clang::reachable_code
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyLogical.h | //===- ThreadSafetyLogical.h -----------------------------------*- 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 a representation for logical expressions with SExpr leaves
// that are used as part of fact-checking capability expressions.
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYLOGICAL_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYLOGICAL_H
#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
namespace clang {
namespace threadSafety {
namespace lexpr {
class LExpr {
public:
enum Opcode {
Terminal,
And,
Or,
Not
};
Opcode kind() const { return Kind; }
/// \brief Logical implication. Returns true if the LExpr implies RHS, i.e. if
/// the LExpr holds, then RHS must hold. For example, (A & B) implies A.
inline bool implies(const LExpr *RHS) const;
protected:
LExpr(Opcode Kind) : Kind(Kind) {}
private:
Opcode Kind;
};
class Terminal : public LExpr {
til::SExpr *Expr;
public:
Terminal(til::SExpr *Expr) : LExpr(LExpr::Terminal), Expr(Expr) {}
const til::SExpr *expr() const { return Expr; }
til::SExpr *expr() { return Expr; }
static bool classof(const LExpr *E) { return E->kind() == LExpr::Terminal; }
};
class BinOp : public LExpr {
LExpr *LHS, *RHS;
protected:
BinOp(LExpr *LHS, LExpr *RHS, Opcode Code) : LExpr(Code), LHS(LHS), RHS(RHS) {}
public:
const LExpr *left() const { return LHS; }
LExpr *left() { return LHS; }
const LExpr *right() const { return RHS; }
LExpr *right() { return RHS; }
};
class And : public BinOp {
public:
And(LExpr *LHS, LExpr *RHS) : BinOp(LHS, RHS, LExpr::And) {}
static bool classof(const LExpr *E) { return E->kind() == LExpr::And; }
};
class Or : public BinOp {
public:
Or(LExpr *LHS, LExpr *RHS) : BinOp(LHS, RHS, LExpr::Or) {}
static bool classof(const LExpr *E) { return E->kind() == LExpr::Or; }
};
class Not : public LExpr {
LExpr *Exp;
public:
Not(LExpr *Exp) : LExpr(LExpr::Not), Exp(Exp) {}
const LExpr *exp() const { return Exp; }
LExpr *exp() { return Exp; }
static bool classof(const LExpr *E) { return E->kind() == LExpr::Not; }
};
/// \brief Logical implication. Returns true if LHS implies RHS, i.e. if LHS
/// holds, then RHS must hold. For example, (A & B) implies A.
bool implies(const LExpr *LHS, const LExpr *RHS);
bool LExpr::implies(const LExpr *RHS) const {
return lexpr::implies(this, RHS);
}
}
}
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/CFGReachabilityAnalysis.h | //==- CFGReachabilityAnalysis.h - Basic reachability analysis ----*- 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 a flow-sensitive, (mostly) path-insensitive reachability
// analysis based on Clang's CFGs. Clients can query if a given basic block
// is reachable within the CFG.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_CFGREACHABILITYANALYSIS_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_CFGREACHABILITYANALYSIS_H
#include "llvm/ADT/BitVector.h"
#include "llvm/ADT/DenseMap.h"
namespace clang {
class CFG;
class CFGBlock;
// A class that performs reachability queries for CFGBlocks. Several internal
// checks in this checker require reachability information. The requests all
// tend to have a common destination, so we lazily do a predecessor search
// from the destination node and cache the results to prevent work
// duplication.
class CFGReverseBlockReachabilityAnalysis {
typedef llvm::BitVector ReachableSet;
typedef llvm::DenseMap<unsigned, ReachableSet> ReachableMap;
ReachableSet analyzed;
ReachableMap reachable;
public:
CFGReverseBlockReachabilityAnalysis(const CFG &cfg);
/// Returns true if the block 'Dst' can be reached from block 'Src'.
bool isReachable(const CFGBlock *Src, const CFGBlock *Dst);
private:
void mapReachability(const CFGBlock *Dst);
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/FormatString.h | //= FormatString.h - Analysis of printf/fprintf format strings --*- 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 APIs for analyzing the format strings of printf, fscanf,
// and friends.
//
// The structure of format strings for fprintf are described in C99 7.19.6.1.
//
// The structure of format strings for fscanf are described in C99 7.19.6.2.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_FORMATSTRING_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_FORMATSTRING_H
#include "clang/AST/CanonicalType.h"
namespace clang {
class TargetInfo;
//===----------------------------------------------------------------------===//
/// Common components of both fprintf and fscanf format strings.
namespace analyze_format_string {
/// Class representing optional flags with location and representation
/// information.
class OptionalFlag {
public:
OptionalFlag(const char *Representation)
: representation(Representation), flag(false) {}
bool isSet() { return flag; }
void set() { flag = true; }
void clear() { flag = false; }
void setPosition(const char *position) {
assert(position);
flag = true;
this->position = position;
}
const char *getPosition() const {
assert(position);
return position;
}
const char *toString() const { return representation; }
// Overloaded operators for bool like qualities
explicit operator bool() const { return flag; }
OptionalFlag& operator=(const bool &rhs) {
flag = rhs;
return *this; // Return a reference to myself.
}
private:
const char *representation;
const char *position;
bool flag;
};
/// Represents the length modifier in a format string in scanf/printf.
class LengthModifier {
public:
enum Kind {
None,
AsChar, // 'hh'
AsShort, // 'h'
AsLong, // 'l'
AsLongLong, // 'll'
AsQuad, // 'q' (BSD, deprecated, for 64-bit integer types)
AsIntMax, // 'j'
AsSizeT, // 'z'
AsPtrDiff, // 't'
AsInt32, // 'I32' (MSVCRT, like __int32)
AsInt3264, // 'I' (MSVCRT, like __int3264 from MIDL)
AsInt64, // 'I64' (MSVCRT, like __int64)
AsLongDouble, // 'L'
AsAllocate, // for '%as', GNU extension to C90 scanf
AsMAllocate, // for '%ms', GNU extension to scanf
AsWide, // 'w' (MSVCRT, like l but only for c, C, s, S, or Z
AsWideChar = AsLong // for '%ls', only makes sense for printf
};
LengthModifier()
: Position(nullptr), kind(None) {}
LengthModifier(const char *pos, Kind k)
: Position(pos), kind(k) {}
const char *getStart() const {
return Position;
}
unsigned getLength() const {
switch (kind) {
default:
return 1;
case AsLongLong:
case AsChar:
return 2;
case AsInt32:
case AsInt64:
return 3;
case None:
return 0;
}
}
Kind getKind() const { return kind; }
void setKind(Kind k) { kind = k; }
const char *toString() const;
private:
const char *Position;
Kind kind;
};
class ConversionSpecifier {
public:
enum Kind {
InvalidSpecifier = 0,
// C99 conversion specifiers.
cArg,
dArg,
DArg, // Apple extension
iArg,
IntArgBeg = dArg, IntArgEnd = iArg,
oArg,
OArg, // Apple extension
uArg,
UArg, // Apple extension
xArg,
XArg,
UIntArgBeg = oArg, UIntArgEnd = XArg,
fArg,
FArg,
eArg,
EArg,
gArg,
GArg,
aArg,
AArg,
DoubleArgBeg = fArg, DoubleArgEnd = AArg,
sArg,
pArg,
nArg,
PercentArg,
CArg,
SArg,
// ** Printf-specific **
ZArg, // MS extension
// Objective-C specific specifiers.
ObjCObjArg, // '@'
ObjCBeg = ObjCObjArg, ObjCEnd = ObjCObjArg,
// FreeBSD kernel specific specifiers.
FreeBSDbArg,
FreeBSDDArg,
FreeBSDrArg,
FreeBSDyArg,
// GlibC specific specifiers.
PrintErrno, // 'm'
PrintfConvBeg = ObjCObjArg, PrintfConvEnd = PrintErrno,
// ** Scanf-specific **
ScanListArg, // '['
ScanfConvBeg = ScanListArg, ScanfConvEnd = ScanListArg
};
ConversionSpecifier(bool isPrintf = true)
: IsPrintf(isPrintf), Position(nullptr), EndScanList(nullptr),
kind(InvalidSpecifier) {}
ConversionSpecifier(bool isPrintf, const char *pos, Kind k)
: IsPrintf(isPrintf), Position(pos), EndScanList(nullptr), kind(k) {}
const char *getStart() const {
return Position;
}
StringRef getCharacters() const {
return StringRef(getStart(), getLength());
}
bool consumesDataArgument() const {
switch (kind) {
case PrintErrno:
assert(IsPrintf);
return false;
case PercentArg:
return false;
default:
return true;
}
}
Kind getKind() const { return kind; }
void setKind(Kind k) { kind = k; }
unsigned getLength() const {
return EndScanList ? EndScanList - Position : 1;
}
bool isIntArg() const { return (kind >= IntArgBeg && kind <= IntArgEnd) ||
kind == FreeBSDrArg || kind == FreeBSDyArg; }
bool isUIntArg() const { return kind >= UIntArgBeg && kind <= UIntArgEnd; }
bool isAnyIntArg() const { return kind >= IntArgBeg && kind <= UIntArgEnd; }
const char *toString() const;
bool isPrintfKind() const { return IsPrintf; }
Optional<ConversionSpecifier> getStandardSpecifier() const;
protected:
bool IsPrintf;
const char *Position;
const char *EndScanList;
Kind kind;
};
class ArgType {
public:
enum Kind { UnknownTy, InvalidTy, SpecificTy, ObjCPointerTy, CPointerTy,
AnyCharTy, CStrTy, WCStrTy, WIntTy };
enum MatchKind { NoMatch = 0, Match = 1, NoMatchPedantic };
private:
const Kind K;
QualType T;
const char *Name;
bool Ptr;
public:
ArgType(Kind k = UnknownTy, const char *n = nullptr)
: K(k), Name(n), Ptr(false) {}
ArgType(QualType t, const char *n = nullptr)
: K(SpecificTy), T(t), Name(n), Ptr(false) {}
ArgType(CanQualType t) : K(SpecificTy), T(t), Name(nullptr), Ptr(false) {}
static ArgType Invalid() { return ArgType(InvalidTy); }
bool isValid() const { return K != InvalidTy; }
/// Create an ArgType which corresponds to the type pointer to A.
static ArgType PtrTo(const ArgType& A) {
assert(A.K >= InvalidTy && "ArgType cannot be pointer to invalid/unknown");
ArgType Res = A;
Res.Ptr = true;
return Res;
}
MatchKind matchesType(ASTContext &C, QualType argTy) const;
QualType getRepresentativeType(ASTContext &C) const;
std::string getRepresentativeTypeName(ASTContext &C) const;
};
class OptionalAmount {
public:
enum HowSpecified { NotSpecified, Constant, Arg, Invalid };
OptionalAmount(HowSpecified howSpecified,
unsigned amount,
const char *amountStart,
unsigned amountLength,
bool usesPositionalArg)
: start(amountStart), length(amountLength), hs(howSpecified), amt(amount),
UsesPositionalArg(usesPositionalArg), UsesDotPrefix(0) {}
OptionalAmount(bool valid = true)
: start(nullptr),length(0), hs(valid ? NotSpecified : Invalid), amt(0),
UsesPositionalArg(0), UsesDotPrefix(0) {}
bool isInvalid() const {
return hs == Invalid;
}
HowSpecified getHowSpecified() const { return hs; }
void setHowSpecified(HowSpecified h) { hs = h; }
bool hasDataArgument() const { return hs == Arg; }
unsigned getArgIndex() const {
assert(hasDataArgument());
return amt;
}
unsigned getConstantAmount() const {
assert(hs == Constant);
return amt;
}
const char *getStart() const {
// We include the . character if it is given.
return start - UsesDotPrefix;
}
unsigned getConstantLength() const {
assert(hs == Constant);
return length + UsesDotPrefix;
}
ArgType getArgType(ASTContext &Ctx) const;
void toString(raw_ostream &os) const;
bool usesPositionalArg() const { return (bool) UsesPositionalArg; }
unsigned getPositionalArgIndex() const {
assert(hasDataArgument());
return amt + 1;
}
bool usesDotPrefix() const { return UsesDotPrefix; }
void setUsesDotPrefix() { UsesDotPrefix = true; }
private:
const char *start;
unsigned length;
HowSpecified hs;
unsigned amt;
bool UsesPositionalArg : 1;
bool UsesDotPrefix;
};
class FormatSpecifier {
protected:
LengthModifier LM;
OptionalAmount FieldWidth;
ConversionSpecifier CS;
/// Positional arguments, an IEEE extension:
/// IEEE Std 1003.1, 2004 Edition
/// http://www.opengroup.org/onlinepubs/009695399/functions/printf.html
bool UsesPositionalArg;
unsigned argIndex;
public:
FormatSpecifier(bool isPrintf)
: CS(isPrintf), UsesPositionalArg(false), argIndex(0) {}
void setLengthModifier(LengthModifier lm) {
LM = lm;
}
void setUsesPositionalArg() { UsesPositionalArg = true; }
void setArgIndex(unsigned i) {
argIndex = i;
}
unsigned getArgIndex() const {
return argIndex;
}
unsigned getPositionalArgIndex() const {
return argIndex + 1;
}
const LengthModifier &getLengthModifier() const {
return LM;
}
const OptionalAmount &getFieldWidth() const {
return FieldWidth;
}
void setFieldWidth(const OptionalAmount &Amt) {
FieldWidth = Amt;
}
bool usesPositionalArg() const { return UsesPositionalArg; }
bool hasValidLengthModifier(const TargetInfo &Target) const;
bool hasStandardLengthModifier() const;
Optional<LengthModifier> getCorrectedLengthModifier() const;
bool hasStandardConversionSpecifier(const LangOptions &LangOpt) const;
bool hasStandardLengthConversionCombination() const;
/// For a TypedefType QT, if it is a named integer type such as size_t,
/// assign the appropriate value to LM and return true.
static bool namedTypeToLengthModifier(QualType QT, LengthModifier &LM);
};
} // end analyze_format_string namespace
//===----------------------------------------------------------------------===//
/// Pieces specific to fprintf format strings.
namespace analyze_printf {
class PrintfConversionSpecifier :
public analyze_format_string::ConversionSpecifier {
public:
PrintfConversionSpecifier()
: ConversionSpecifier(true, nullptr, InvalidSpecifier) {}
PrintfConversionSpecifier(const char *pos, Kind k)
: ConversionSpecifier(true, pos, k) {}
bool isObjCArg() const { return kind >= ObjCBeg && kind <= ObjCEnd; }
bool isDoubleArg() const { return kind >= DoubleArgBeg &&
kind <= DoubleArgEnd; }
unsigned getLength() const {
// Conversion specifiers currently only are represented by
// single characters, but we be flexible.
return 1;
}
static bool classof(const analyze_format_string::ConversionSpecifier *CS) {
return CS->isPrintfKind();
}
};
using analyze_format_string::ArgType;
using analyze_format_string::LengthModifier;
using analyze_format_string::OptionalAmount;
using analyze_format_string::OptionalFlag;
class PrintfSpecifier : public analyze_format_string::FormatSpecifier {
OptionalFlag HasThousandsGrouping; // ''', POSIX extension.
OptionalFlag IsLeftJustified; // '-'
OptionalFlag HasPlusPrefix; // '+'
OptionalFlag HasSpacePrefix; // ' '
OptionalFlag HasAlternativeForm; // '#'
OptionalFlag HasLeadingZeroes; // '0'
OptionalFlag HasObjCTechnicalTerm; // '[tt]'
OptionalAmount Precision;
public:
PrintfSpecifier() :
FormatSpecifier(/* isPrintf = */ true),
HasThousandsGrouping("'"), IsLeftJustified("-"), HasPlusPrefix("+"),
HasSpacePrefix(" "), HasAlternativeForm("#"), HasLeadingZeroes("0"),
HasObjCTechnicalTerm("tt") {}
static PrintfSpecifier Parse(const char *beg, const char *end);
// Methods for incrementally constructing the PrintfSpecifier.
void setConversionSpecifier(const PrintfConversionSpecifier &cs) {
CS = cs;
}
void setHasThousandsGrouping(const char *position) {
HasThousandsGrouping.setPosition(position);
}
void setIsLeftJustified(const char *position) {
IsLeftJustified.setPosition(position);
}
void setHasPlusPrefix(const char *position) {
HasPlusPrefix.setPosition(position);
}
void setHasSpacePrefix(const char *position) {
HasSpacePrefix.setPosition(position);
}
void setHasAlternativeForm(const char *position) {
HasAlternativeForm.setPosition(position);
}
void setHasLeadingZeros(const char *position) {
HasLeadingZeroes.setPosition(position);
}
void setHasObjCTechnicalTerm(const char *position) {
HasObjCTechnicalTerm.setPosition(position);
}
void setUsesPositionalArg() { UsesPositionalArg = true; }
// Methods for querying the format specifier.
const PrintfConversionSpecifier &getConversionSpecifier() const {
return cast<PrintfConversionSpecifier>(CS);
}
void setPrecision(const OptionalAmount &Amt) {
Precision = Amt;
Precision.setUsesDotPrefix();
}
const OptionalAmount &getPrecision() const {
return Precision;
}
bool consumesDataArgument() const {
return getConversionSpecifier().consumesDataArgument();
}
/// \brief Returns the builtin type that a data argument
/// paired with this format specifier should have. This method
/// will return null if the format specifier does not have
/// a matching data argument or the matching argument matches
/// more than one type.
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const;
const OptionalFlag &hasThousandsGrouping() const {
return HasThousandsGrouping;
}
const OptionalFlag &isLeftJustified() const { return IsLeftJustified; }
const OptionalFlag &hasPlusPrefix() const { return HasPlusPrefix; }
const OptionalFlag &hasAlternativeForm() const { return HasAlternativeForm; }
const OptionalFlag &hasLeadingZeros() const { return HasLeadingZeroes; }
const OptionalFlag &hasSpacePrefix() const { return HasSpacePrefix; }
const OptionalFlag &hasObjCTechnicalTerm() const { return HasObjCTechnicalTerm; }
bool usesPositionalArg() const { return UsesPositionalArg; }
/// Changes the specifier and length according to a QualType, retaining any
/// flags or options. Returns true on success, or false when a conversion
/// was not successful.
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx,
bool IsObjCLiteral);
void toString(raw_ostream &os) const;
// Validation methods - to check if any element results in undefined behavior
bool hasValidPlusPrefix() const;
bool hasValidAlternativeForm() const;
bool hasValidLeadingZeros() const;
bool hasValidSpacePrefix() const;
bool hasValidLeftJustified() const;
bool hasValidThousandsGroupingPrefix() const;
bool hasValidPrecision() const;
bool hasValidFieldWidth() const;
};
} // end analyze_printf namespace
//===----------------------------------------------------------------------===//
/// Pieces specific to fscanf format strings.
namespace analyze_scanf {
class ScanfConversionSpecifier :
public analyze_format_string::ConversionSpecifier {
public:
ScanfConversionSpecifier()
: ConversionSpecifier(false, nullptr, InvalidSpecifier) {}
ScanfConversionSpecifier(const char *pos, Kind k)
: ConversionSpecifier(false, pos, k) {}
void setEndScanList(const char *pos) { EndScanList = pos; }
static bool classof(const analyze_format_string::ConversionSpecifier *CS) {
return !CS->isPrintfKind();
}
};
using analyze_format_string::ArgType;
using analyze_format_string::LengthModifier;
using analyze_format_string::OptionalAmount;
using analyze_format_string::OptionalFlag;
class ScanfSpecifier : public analyze_format_string::FormatSpecifier {
OptionalFlag SuppressAssignment; // '*'
public:
ScanfSpecifier() :
FormatSpecifier(/* isPrintf = */ false),
SuppressAssignment("*") {}
void setSuppressAssignment(const char *position) {
SuppressAssignment.setPosition(position);
}
const OptionalFlag &getSuppressAssignment() const {
return SuppressAssignment;
}
void setConversionSpecifier(const ScanfConversionSpecifier &cs) {
CS = cs;
}
const ScanfConversionSpecifier &getConversionSpecifier() const {
return cast<ScanfConversionSpecifier>(CS);
}
bool consumesDataArgument() const {
return CS.consumesDataArgument() && !SuppressAssignment;
}
ArgType getArgType(ASTContext &Ctx) const;
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt,
ASTContext &Ctx);
void toString(raw_ostream &os) const;
static ScanfSpecifier Parse(const char *beg, const char *end);
};
} // end analyze_scanf namespace
// //
///////////////////////////////////////////////////////////////////////////////
// Parsing and processing of format strings (both fprintf and fscanf).
namespace analyze_format_string {
enum PositionContext { FieldWidthPos = 0, PrecisionPos = 1 };
class FormatStringHandler {
public:
FormatStringHandler() {}
virtual ~FormatStringHandler();
virtual void HandleNullChar(const char *nullCharacter) {}
virtual void HandlePosition(const char *startPos, unsigned posLen) {}
virtual void HandleInvalidPosition(const char *startPos, unsigned posLen,
PositionContext p) {}
virtual void HandleZeroPosition(const char *startPos, unsigned posLen) {}
virtual void HandleIncompleteSpecifier(const char *startSpecifier,
unsigned specifierLen) {}
virtual void HandleEmptyObjCModifierFlag(const char *startFlags,
unsigned flagsLen) {}
virtual void HandleInvalidObjCModifierFlag(const char *startFlag,
unsigned flagLen) {}
virtual void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
const char *flagsEnd,
const char *conversionPosition) {}
// Printf-specific handlers.
virtual bool HandleInvalidPrintfConversionSpecifier(
const analyze_printf::PrintfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) {
return true;
}
virtual bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) {
return true;
}
// Scanf-specific handlers.
virtual bool HandleInvalidScanfConversionSpecifier(
const analyze_scanf::ScanfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) {
return true;
}
virtual bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen) {
return true;
}
virtual void HandleIncompleteScanList(const char *start, const char *end) {}
};
bool ParsePrintfString(FormatStringHandler &H,
const char *beg, const char *end, const LangOptions &LO,
const TargetInfo &Target, bool isFreeBSDKPrintf);
bool ParseFormatStringHasSArg(const char *beg, const char *end,
const LangOptions &LO, const TargetInfo &Target);
bool ParseScanfString(FormatStringHandler &H,
const char *beg, const char *end, const LangOptions &LO,
const TargetInfo &Target);
} // end analyze_format_string namespace
} // end clang namespace
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Analyses/ThreadSafetyCommon.h | //===- ThreadSafetyCommon.h ------------------------------------*- C++ --*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Parts of thread safety analysis that are not specific to thread safety
// itself have been factored into classes here, where they can be potentially
// used by other analyses. Currently these include:
//
// * Generalize clang CFG visitors.
// * Conversion of the clang CFG to SSA form.
// * Translation of clang Exprs to TIL SExprs
//
// UNDER CONSTRUCTION. USE AT YOUR OWN RISK.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
#define LLVM_CLANG_ANALYSIS_ANALYSES_THREADSAFETYCOMMON_H
#include "clang/Analysis/Analyses/PostOrderCFGView.h"
#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
#include "clang/Analysis/AnalysisContext.h"
#include "clang/Basic/OperatorKinds.h"
#include <memory>
#include <ostream>
#include <sstream>
#include <vector>
namespace clang {
namespace threadSafety {
// Various helper functions on til::SExpr
namespace sx {
inline bool equals(const til::SExpr *E1, const til::SExpr *E2) {
return til::EqualsComparator::compareExprs(E1, E2);
}
inline bool matches(const til::SExpr *E1, const til::SExpr *E2) {
// We treat a top-level wildcard as the "univsersal" lock.
// It matches everything for the purpose of checking locks, but not
// for unlocking them.
if (isa<til::Wildcard>(E1))
return isa<til::Wildcard>(E2);
if (isa<til::Wildcard>(E2))
return isa<til::Wildcard>(E1);
return til::MatchComparator::compareExprs(E1, E2);
}
inline bool partiallyMatches(const til::SExpr *E1, const til::SExpr *E2) {
const auto *PE1 = dyn_cast_or_null<til::Project>(E1);
if (!PE1)
return false;
const auto *PE2 = dyn_cast_or_null<til::Project>(E2);
if (!PE2)
return false;
return PE1->clangDecl() == PE2->clangDecl();
}
inline std::string toString(const til::SExpr *E) {
std::stringstream ss;
til::StdPrinter::print(E, ss);
return ss.str();
}
} // end namespace sx
// This class defines the interface of a clang CFG Visitor.
// CFGWalker will invoke the following methods.
// Note that methods are not virtual; the visitor is templatized.
class CFGVisitor {
// Enter the CFG for Decl D, and perform any initial setup operations.
void enterCFG(CFG *Cfg, const NamedDecl *D, const CFGBlock *First) {}
// Enter a CFGBlock.
void enterCFGBlock(const CFGBlock *B) {}
// Returns true if this visitor implements handlePredecessor
bool visitPredecessors() { return true; }
// Process a predecessor edge.
void handlePredecessor(const CFGBlock *Pred) {}
// Process a successor back edge to a previously visited block.
void handlePredecessorBackEdge(const CFGBlock *Pred) {}
// Called just before processing statements.
void enterCFGBlockBody(const CFGBlock *B) {}
// Process an ordinary statement.
void handleStatement(const Stmt *S) {}
// Process a destructor call
void handleDestructorCall(const VarDecl *VD, const CXXDestructorDecl *DD) {}
// Called after all statements have been handled.
void exitCFGBlockBody(const CFGBlock *B) {}
// Return true
bool visitSuccessors() { return true; }
// Process a successor edge.
void handleSuccessor(const CFGBlock *Succ) {}
// Process a successor back edge to a previously visited block.
void handleSuccessorBackEdge(const CFGBlock *Succ) {}
// Leave a CFGBlock.
void exitCFGBlock(const CFGBlock *B) {}
// Leave the CFG, and perform any final cleanup operations.
void exitCFG(const CFGBlock *Last) {}
};
// Walks the clang CFG, and invokes methods on a given CFGVisitor.
class CFGWalker {
public:
CFGWalker() : CFGraph(nullptr), ACtx(nullptr), SortedGraph(nullptr) {}
// Initialize the CFGWalker. This setup only needs to be done once, even
// if there are multiple passes over the CFG.
bool init(AnalysisDeclContext &AC) {
ACtx = &AC;
CFGraph = AC.getCFG();
if (!CFGraph)
return false;
// Ignore anonymous functions.
if (!dyn_cast_or_null<NamedDecl>(AC.getDecl()))
return false;
SortedGraph = AC.getAnalysis<PostOrderCFGView>();
if (!SortedGraph)
return false;
return true;
}
// Traverse the CFG, calling methods on V as appropriate.
template <class Visitor>
void walk(Visitor &V) {
PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
V.enterCFG(CFGraph, getDecl(), &CFGraph->getEntry());
for (const auto *CurrBlock : *SortedGraph) {
VisitedBlocks.insert(CurrBlock);
V.enterCFGBlock(CurrBlock);
// Process predecessors, handling back edges last
if (V.visitPredecessors()) {
SmallVector<CFGBlock*, 4> BackEdges;
// Process successors
for (CFGBlock::const_pred_iterator SI = CurrBlock->pred_begin(),
SE = CurrBlock->pred_end();
SI != SE; ++SI) {
if (*SI == nullptr)
continue;
if (!VisitedBlocks.alreadySet(*SI)) {
BackEdges.push_back(*SI);
continue;
}
V.handlePredecessor(*SI);
}
for (auto *Blk : BackEdges)
V.handlePredecessorBackEdge(Blk);
}
V.enterCFGBlockBody(CurrBlock);
// Process statements
for (const auto &BI : *CurrBlock) {
switch (BI.getKind()) {
case CFGElement::Statement: {
V.handleStatement(BI.castAs<CFGStmt>().getStmt());
break;
}
case CFGElement::AutomaticObjectDtor: {
CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
AD.getDestructorDecl(ACtx->getASTContext()));
VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
V.handleDestructorCall(VD, DD);
break;
}
default:
break;
}
}
V.exitCFGBlockBody(CurrBlock);
// Process successors, handling back edges first.
if (V.visitSuccessors()) {
SmallVector<CFGBlock*, 8> ForwardEdges;
// Process successors
for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
SE = CurrBlock->succ_end();
SI != SE; ++SI) {
if (*SI == nullptr)
continue;
if (!VisitedBlocks.alreadySet(*SI)) {
ForwardEdges.push_back(*SI);
continue;
}
V.handleSuccessorBackEdge(*SI);
}
for (auto *Blk : ForwardEdges)
V.handleSuccessor(Blk);
}
V.exitCFGBlock(CurrBlock);
}
V.exitCFG(&CFGraph->getExit());
}
const CFG *getGraph() const { return CFGraph; }
CFG *getGraph() { return CFGraph; }
const NamedDecl *getDecl() const {
return dyn_cast<NamedDecl>(ACtx->getDecl());
}
const PostOrderCFGView *getSortedGraph() const { return SortedGraph; }
private:
CFG *CFGraph;
AnalysisDeclContext *ACtx;
PostOrderCFGView *SortedGraph;
};
class CapabilityExpr {
// TODO: move this back into ThreadSafety.cpp
// This is specific to thread safety. It is here because
// translateAttrExpr needs it, but that should be moved too.
private:
const til::SExpr* CapExpr; ///< The capability expression.
bool Negated; ///< True if this is a negative capability
public:
CapabilityExpr(const til::SExpr *E, bool Neg) : CapExpr(E), Negated(Neg) {}
const til::SExpr* sexpr() const { return CapExpr; }
bool negative() const { return Negated; }
CapabilityExpr operator!() const {
return CapabilityExpr(CapExpr, !Negated);
}
bool equals(const CapabilityExpr &other) const {
return (Negated == other.Negated) && sx::equals(CapExpr, other.CapExpr);
}
bool matches(const CapabilityExpr &other) const {
return (Negated == other.Negated) && sx::matches(CapExpr, other.CapExpr);
}
bool matchesUniv(const CapabilityExpr &CapE) const {
return isUniversal() || matches(CapE);
}
bool partiallyMatches(const CapabilityExpr &other) const {
return (Negated == other.Negated) &&
sx::partiallyMatches(CapExpr, other.CapExpr);
}
const ValueDecl* valueDecl() const {
if (Negated)
return nullptr;
if (auto *P = dyn_cast<til::Project>(CapExpr))
return P->clangDecl();
return nullptr;
}
std::string toString() const {
if (Negated)
return "!" + sx::toString(CapExpr);
return sx::toString(CapExpr);
}
bool shouldIgnore() const { return CapExpr == nullptr; }
bool isInvalid() const { return sexpr() && isa<til::Undefined>(sexpr()); }
bool isUniversal() const { return sexpr() && isa<til::Wildcard>(sexpr()); }
};
// Translate clang::Expr to til::SExpr.
class SExprBuilder {
public:
/// \brief Encapsulates the lexical context of a function call. The lexical
/// context includes the arguments to the call, including the implicit object
/// argument. When an attribute containing a mutex expression is attached to
/// a method, the expression may refer to formal parameters of the method.
/// Actual arguments must be substituted for formal parameters to derive
/// the appropriate mutex expression in the lexical context where the function
/// is called. PrevCtx holds the context in which the arguments themselves
/// should be evaluated; multiple calling contexts can be chained together
/// by the lock_returned attribute.
struct CallingContext {
CallingContext *Prev; // The previous context; or 0 if none.
const NamedDecl *AttrDecl; // The decl to which the attr is attached.
const Expr *SelfArg; // Implicit object argument -- e.g. 'this'
unsigned NumArgs; // Number of funArgs
const Expr *const *FunArgs; // Function arguments
bool SelfArrow; // is Self referred to with -> or .?
CallingContext(CallingContext *P, const NamedDecl *D = nullptr)
: Prev(P), AttrDecl(D), SelfArg(nullptr),
NumArgs(0), FunArgs(nullptr), SelfArrow(false)
{}
};
SExprBuilder(til::MemRegionRef A)
: Arena(A), SelfVar(nullptr), Scfg(nullptr), CurrentBB(nullptr),
CurrentBlockInfo(nullptr) {
// FIXME: we don't always have a self-variable.
SelfVar = new (Arena) til::Variable(nullptr);
SelfVar->setKind(til::Variable::VK_SFun);
}
// Translate a clang expression in an attribute to a til::SExpr.
// Constructs the context from D, DeclExp, and SelfDecl.
CapabilityExpr translateAttrExpr(const Expr *AttrExp, const NamedDecl *D,
const Expr *DeclExp, VarDecl *SelfD=nullptr);
CapabilityExpr translateAttrExpr(const Expr *AttrExp, CallingContext *Ctx);
// Translate a clang statement or expression to a TIL expression.
// Also performs substitution of variables; Ctx provides the context.
// Dispatches on the type of S.
til::SExpr *translate(const Stmt *S, CallingContext *Ctx);
til::SCFG *buildCFG(CFGWalker &Walker);
til::SExpr *lookupStmt(const Stmt *S);
til::BasicBlock *lookupBlock(const CFGBlock *B) {
return BlockMap[B->getBlockID()];
}
const til::SCFG *getCFG() const { return Scfg; }
til::SCFG *getCFG() { return Scfg; }
private:
til::SExpr *translateDeclRefExpr(const DeclRefExpr *DRE,
CallingContext *Ctx) ;
til::SExpr *translateCXXThisExpr(const CXXThisExpr *TE, CallingContext *Ctx);
til::SExpr *translateMemberExpr(const MemberExpr *ME, CallingContext *Ctx);
til::SExpr *translateCallExpr(const CallExpr *CE, CallingContext *Ctx,
const Expr *SelfE = nullptr);
til::SExpr *translateCXXMemberCallExpr(const CXXMemberCallExpr *ME,
CallingContext *Ctx);
til::SExpr *translateCXXOperatorCallExpr(const CXXOperatorCallExpr *OCE,
CallingContext *Ctx);
til::SExpr *translateUnaryOperator(const UnaryOperator *UO,
CallingContext *Ctx);
til::SExpr *translateBinOp(til::TIL_BinaryOpcode Op,
const BinaryOperator *BO,
CallingContext *Ctx, bool Reverse = false);
til::SExpr *translateBinAssign(til::TIL_BinaryOpcode Op,
const BinaryOperator *BO,
CallingContext *Ctx, bool Assign = false);
til::SExpr *translateBinaryOperator(const BinaryOperator *BO,
CallingContext *Ctx);
til::SExpr *translateCastExpr(const CastExpr *CE, CallingContext *Ctx);
til::SExpr *translateArraySubscriptExpr(const ArraySubscriptExpr *E,
CallingContext *Ctx);
til::SExpr *translateAbstractConditionalOperator(
const AbstractConditionalOperator *C, CallingContext *Ctx);
til::SExpr *translateDeclStmt(const DeclStmt *S, CallingContext *Ctx);
// Map from statements in the clang CFG to SExprs in the til::SCFG.
typedef llvm::DenseMap<const Stmt*, til::SExpr*> StatementMap;
// Map from clang local variables to indices in a LVarDefinitionMap.
typedef llvm::DenseMap<const ValueDecl *, unsigned> LVarIndexMap;
// Map from local variable indices to SSA variables (or constants).
typedef std::pair<const ValueDecl *, til::SExpr *> NameVarPair;
typedef CopyOnWriteVector<NameVarPair> LVarDefinitionMap;
struct BlockInfo {
LVarDefinitionMap ExitMap;
bool HasBackEdges;
unsigned UnprocessedSuccessors; // Successors yet to be processed
unsigned ProcessedPredecessors; // Predecessors already processed
BlockInfo()
: HasBackEdges(false), UnprocessedSuccessors(0),
ProcessedPredecessors(0) {}
BlockInfo(BlockInfo &&RHS)
: ExitMap(std::move(RHS.ExitMap)),
HasBackEdges(RHS.HasBackEdges),
UnprocessedSuccessors(RHS.UnprocessedSuccessors),
ProcessedPredecessors(RHS.ProcessedPredecessors) {}
BlockInfo &operator=(BlockInfo &&RHS) {
if (this != &RHS) {
ExitMap = std::move(RHS.ExitMap);
HasBackEdges = RHS.HasBackEdges;
UnprocessedSuccessors = RHS.UnprocessedSuccessors;
ProcessedPredecessors = RHS.ProcessedPredecessors;
}
return *this;
}
private:
BlockInfo(const BlockInfo &) = delete;
void operator=(const BlockInfo &) = delete;
};
// We implement the CFGVisitor API
friend class CFGWalker;
void enterCFG(CFG *Cfg, const NamedDecl *D, const CFGBlock *First);
void enterCFGBlock(const CFGBlock *B);
bool visitPredecessors() { return true; }
void handlePredecessor(const CFGBlock *Pred);
void handlePredecessorBackEdge(const CFGBlock *Pred);
void enterCFGBlockBody(const CFGBlock *B);
void handleStatement(const Stmt *S);
void handleDestructorCall(const VarDecl *VD, const CXXDestructorDecl *DD);
void exitCFGBlockBody(const CFGBlock *B);
bool visitSuccessors() { return true; }
void handleSuccessor(const CFGBlock *Succ);
void handleSuccessorBackEdge(const CFGBlock *Succ);
void exitCFGBlock(const CFGBlock *B);
void exitCFG(const CFGBlock *Last);
void insertStmt(const Stmt *S, til::SExpr *E) {
SMap.insert(std::make_pair(S, E));
}
til::SExpr *getCurrentLVarDefinition(const ValueDecl *VD);
til::SExpr *addStatement(til::SExpr *E, const Stmt *S,
const ValueDecl *VD = nullptr);
til::SExpr *lookupVarDecl(const ValueDecl *VD);
til::SExpr *addVarDecl(const ValueDecl *VD, til::SExpr *E);
til::SExpr *updateVarDecl(const ValueDecl *VD, til::SExpr *E);
void makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E);
void mergeEntryMap(LVarDefinitionMap Map);
void mergeEntryMapBackEdge();
void mergePhiNodesBackEdge(const CFGBlock *Blk);
private:
// Set to true when parsing capability expressions, which get translated
// inaccurately in order to hack around smart pointers etc.
static const bool CapabilityExprMode = true;
til::MemRegionRef Arena;
til::Variable *SelfVar; // Variable to use for 'this'. May be null.
til::SCFG *Scfg;
StatementMap SMap; // Map from Stmt to TIL Variables
LVarIndexMap LVarIdxMap; // Indices of clang local vars.
std::vector<til::BasicBlock *> BlockMap; // Map from clang to til BBs.
std::vector<BlockInfo> BBInfo; // Extra information per BB.
// Indexed by clang BlockID.
LVarDefinitionMap CurrentLVarMap;
std::vector<til::Phi*> CurrentArguments;
std::vector<til::SExpr*> CurrentInstructions;
std::vector<til::Phi*> IncompleteArgs;
til::BasicBlock *CurrentBB;
BlockInfo *CurrentBlockInfo;
};
// Dump an SCFG to llvm::errs().
void printSCFG(CFGWalker &Walker);
} // end namespace threadSafety
} // end namespace clang
#endif // LLVM_CLANG_THREAD_SAFETY_COMMON_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis | repos/DirectXShaderCompiler/tools/clang/include/clang/Analysis/Support/BumpVector.h | //===-- BumpVector.h - Vector-like ADT that uses bump allocation --*- C++ -*-=//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides BumpVector, a vector-like ADT whose contents are
// allocated from a BumpPtrAllocator.
//
//===----------------------------------------------------------------------===//
// FIXME: Most of this is copy-and-paste from SmallVector.h. We can
// refactor this core logic into something common that is shared between
// the two. The main thing that is different is the allocation strategy.
#ifndef LLVM_CLANG_ANALYSIS_SUPPORT_BUMPVECTOR_H
#define LLVM_CLANG_ANALYSIS_SUPPORT_BUMPVECTOR_H
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/type_traits.h"
#include <algorithm>
#include <cstring>
#include <iterator>
#include <memory>
namespace clang {
class BumpVectorContext {
llvm::PointerIntPair<llvm::BumpPtrAllocator*, 1> Alloc;
public:
/// Construct a new BumpVectorContext that creates a new BumpPtrAllocator
/// and destroys it when the BumpVectorContext object is destroyed.
BumpVectorContext() : Alloc(new llvm::BumpPtrAllocator(), 1) {}
/// Construct a new BumpVectorContext that reuses an existing
/// BumpPtrAllocator. This BumpPtrAllocator is not destroyed when the
/// BumpVectorContext object is destroyed.
BumpVectorContext(llvm::BumpPtrAllocator &A) : Alloc(&A, 0) {}
~BumpVectorContext() {
if (Alloc.getInt())
delete Alloc.getPointer();
}
llvm::BumpPtrAllocator &getAllocator() { return *Alloc.getPointer(); }
};
template<typename T>
class BumpVector {
T *Begin, *End, *Capacity;
public:
// Default ctor - Initialize to empty.
explicit BumpVector(BumpVectorContext &C, unsigned N)
: Begin(nullptr), End(nullptr), Capacity(nullptr) {
reserve(C, N);
}
~BumpVector() {
if (std::is_class<T>::value) {
// Destroy the constructed elements in the vector.
destroy_range(Begin, End);
}
}
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T value_type;
typedef T* iterator;
typedef const T* const_iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef T& reference;
typedef const T& const_reference;
typedef T* pointer;
typedef const T* const_pointer;
// forward iterator creation methods.
iterator begin() { return Begin; }
const_iterator begin() const { return Begin; }
iterator end() { return End; }
const_iterator end() const { return End; }
// reverse iterator creation methods.
reverse_iterator rbegin() { return reverse_iterator(end()); }
const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
reverse_iterator rend() { return reverse_iterator(begin()); }
const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
bool empty() const { return Begin == End; }
size_type size() const { return End-Begin; }
reference operator[](unsigned idx) {
assert(Begin + idx < End);
return Begin[idx];
}
const_reference operator[](unsigned idx) const {
assert(Begin + idx < End);
return Begin[idx];
}
reference front() {
return begin()[0];
}
const_reference front() const {
return begin()[0];
}
reference back() {
return end()[-1];
}
const_reference back() const {
return end()[-1];
}
void pop_back() {
--End;
End->~T();
}
T pop_back_val() {
T Result = back();
pop_back();
return Result;
}
void clear() {
if (std::is_class<T>::value) {
destroy_range(Begin, End);
}
End = Begin;
}
/// data - Return a pointer to the vector's buffer, even if empty().
pointer data() {
return pointer(Begin);
}
/// data - Return a pointer to the vector's buffer, even if empty().
const_pointer data() const {
return const_pointer(Begin);
}
void push_back(const_reference Elt, BumpVectorContext &C) {
if (End < Capacity) {
Retry:
new (End) T(Elt);
++End;
return;
}
grow(C);
goto Retry;
}
/// insert - Insert some number of copies of element into a position. Return
/// iterator to position after last inserted copy.
iterator insert(iterator I, size_t Cnt, const_reference E,
BumpVectorContext &C) {
assert (I >= Begin && I <= End && "Iterator out of bounds.");
if (End + Cnt <= Capacity) {
Retry:
move_range_right(I, End, Cnt);
construct_range(I, I + Cnt, E);
End += Cnt;
return I + Cnt;
}
ptrdiff_t D = I - Begin;
grow(C, size() + Cnt);
I = Begin + D;
goto Retry;
}
void reserve(BumpVectorContext &C, unsigned N) {
if (unsigned(Capacity-Begin) < N)
grow(C, N);
}
/// capacity - Return the total number of elements in the currently allocated
/// buffer.
size_t capacity() const { return Capacity - Begin; }
private:
/// grow - double the size of the allocated memory, guaranteeing space for at
/// least one more element or MinSize if specified.
void grow(BumpVectorContext &C, size_type MinSize = 1);
void construct_range(T *S, T *E, const T &Elt) {
for (; S != E; ++S)
new (S) T(Elt);
}
void destroy_range(T *S, T *E) {
while (S != E) {
--E;
E->~T();
}
}
void move_range_right(T *S, T *E, size_t D) {
for (T *I = E + D - 1, *IL = S + D - 1; I != IL; --I) {
--E;
new (I) T(*E);
E->~T();
}
}
};
// Define this out-of-line to dissuade the C++ compiler from inlining it.
template <typename T>
void BumpVector<T>::grow(BumpVectorContext &C, size_t MinSize) {
size_t CurCapacity = Capacity-Begin;
size_t CurSize = size();
size_t NewCapacity = 2*CurCapacity;
if (NewCapacity < MinSize)
NewCapacity = MinSize;
// Allocate the memory from the BumpPtrAllocator.
T *NewElts = C.getAllocator().template Allocate<T>(NewCapacity);
// Copy the elements over.
if (Begin != End) {
if (std::is_class<T>::value) {
std::uninitialized_copy(Begin, End, NewElts);
// Destroy the original elements.
destroy_range(Begin, End);
} else {
// Use memcpy for PODs (std::uninitialized_copy optimizes to memmove).
memcpy(NewElts, Begin, CurSize * sizeof(T));
}
}
// For now, leak 'Begin'. We can add it back to a freelist in
// BumpVectorContext.
Begin = NewElts;
End = NewElts+CurSize;
Capacity = Begin+NewCapacity;
}
} // end: clang namespace
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Format/Format.h | //===--- Format.h - Format C++ code -----------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Various functions to configurably format source code.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_FORMAT_FORMAT_H
#define LLVM_CLANG_FORMAT_FORMAT_H
#include "clang/Basic/LangOptions.h"
#include "clang/Tooling/Core/Replacement.h"
#include "llvm/ADT/ArrayRef.h"
#include <system_error>
namespace clang {
class Lexer;
class SourceManager;
class DiagnosticConsumer;
namespace format {
enum class ParseError { Success = 0, Error, Unsuitable };
class ParseErrorCategory final : public std::error_category {
public:
const char *name() const LLVM_NOEXCEPT override;
std::string message(int EV) const override;
};
const std::error_category &getParseCategory();
std::error_code make_error_code(ParseError e);
/// \brief The \c FormatStyle is used to configure the formatting to follow
/// specific guidelines.
struct FormatStyle {
/// \brief The extra indent or outdent of access modifiers, e.g. \c public:.
int AccessModifierOffset;
/// \brief If \c true, horizontally aligns arguments after an open bracket.
///
/// This applies to round brackets (parentheses), angle brackets and square
/// brackets. This will result in formattings like
/// \code
/// someLongFunction(argument1,
/// argument2);
/// \endcode
bool AlignAfterOpenBracket;
/// \brief If \c true, aligns consecutive assignments.
///
/// This will align the assignment operators of consecutive lines. This
/// will result in formattings like
/// \code
/// int aaaa = 12;
/// int b = 23;
/// int ccc = 23;
/// \endcode
bool AlignConsecutiveAssignments;
/// \brief If \c true, aligns escaped newlines as far left as possible.
/// Otherwise puts them into the right-most column.
bool AlignEscapedNewlinesLeft;
/// \brief If \c true, horizontally align operands of binary and ternary
/// expressions.
bool AlignOperands;
/// \brief If \c true, aligns trailing comments.
bool AlignTrailingComments;
/// \brief Allow putting all parameters of a function declaration onto
/// the next line even if \c BinPackParameters is \c false.
bool AllowAllParametersOfDeclarationOnNextLine;
/// \brief Allows contracting simple braced statements to a single line.
///
/// E.g., this allows <tt>if (a) { return; }</tt> to be put on a single line.
bool AllowShortBlocksOnASingleLine;
/// \brief If \c true, short case labels will be contracted to a single line.
bool AllowShortCaseLabelsOnASingleLine;
/// \brief Different styles for merging short functions containing at most one
/// statement.
enum ShortFunctionStyle {
/// \brief Never merge functions into a single line.
SFS_None,
/// \brief Only merge empty functions.
SFS_Empty,
/// \brief Only merge functions defined inside a class. Implies "empty".
SFS_Inline,
/// \brief Merge all functions fitting on a single line.
SFS_All,
};
/// \brief Dependent on the value, <tt>int f() { return 0; }</tt> can be put
/// on a single line.
ShortFunctionStyle AllowShortFunctionsOnASingleLine;
/// \brief If \c true, <tt>if (a) return;</tt> can be put on a single
/// line.
bool AllowShortIfStatementsOnASingleLine;
/// \brief If \c true, <tt>while (true) continue;</tt> can be put on a
/// single line.
bool AllowShortLoopsOnASingleLine;
/// \brief Different ways to break after the function definition return type.
enum DefinitionReturnTypeBreakingStyle {
/// Break after return type automatically.
/// \c PenaltyReturnTypeOnItsOwnLine is taken into account.
DRTBS_None,
/// Always break after the return type.
DRTBS_All,
/// Always break after the return types of top level functions.
DRTBS_TopLevel,
};
/// \brief The function definition return type breaking style to use.
DefinitionReturnTypeBreakingStyle AlwaysBreakAfterDefinitionReturnType;
/// \brief If \c true, always break before multiline string literals.
///
/// This flag is mean to make cases where there are multiple multiline strings
/// in a file look more consistent. Thus, it will only take effect if wrapping
/// the string at that point leads to it being indented
/// \c ContinuationIndentWidth spaces from the start of the line.
bool AlwaysBreakBeforeMultilineStrings;
/// \brief If \c true, always break after the <tt>template<...></tt> of a
/// template declaration.
bool AlwaysBreakTemplateDeclarations;
/// \brief If \c false, a function call's arguments will either be all on the
/// same line or will have one line each.
bool BinPackArguments;
/// \brief If \c false, a function declaration's or function definition's
/// parameters will either all be on the same line or will have one line each.
bool BinPackParameters;
/// \brief The style of breaking before or after binary operators.
enum BinaryOperatorStyle {
/// Break after operators.
BOS_None,
/// Break before operators that aren't assignments.
BOS_NonAssignment,
/// Break before operators.
BOS_All,
};
/// \brief The way to wrap binary operators.
BinaryOperatorStyle BreakBeforeBinaryOperators;
/// \brief Different ways to attach braces to their surrounding context.
enum BraceBreakingStyle {
/// Always attach braces to surrounding context.
BS_Attach,
/// Like \c Attach, but break before braces on function, namespace and
/// class definitions.
BS_Linux,
/// Like ``Attach``, but break before braces on enum, function, and record
/// definitions.
BS_Mozilla,
/// Like \c Attach, but break before function definitions, and 'else'.
BS_Stroustrup,
/// Always break before braces.
BS_Allman,
/// Always break before braces and add an extra level of indentation to
/// braces of control statements, not to those of class, function
/// or other definitions.
BS_GNU
};
/// \brief The brace breaking style to use.
BraceBreakingStyle BreakBeforeBraces;
/// \brief If \c true, ternary operators will be placed after line breaks.
bool BreakBeforeTernaryOperators;
/// \brief Always break constructor initializers before commas and align
/// the commas with the colon.
bool BreakConstructorInitializersBeforeComma;
/// \brief The column limit.
///
/// A column limit of \c 0 means that there is no column limit. In this case,
/// clang-format will respect the input's line breaking decisions within
/// statements unless they contradict other rules.
unsigned ColumnLimit;
/// \brief A regular expression that describes comments with special meaning,
/// which should not be split into lines or otherwise changed.
std::string CommentPragmas;
/// \brief If the constructor initializers don't fit on a line, put each
/// initializer on its own line.
bool ConstructorInitializerAllOnOneLineOrOnePerLine;
/// \brief The number of characters to use for indentation of constructor
/// initializer lists.
unsigned ConstructorInitializerIndentWidth;
/// \brief Indent width for line continuations.
unsigned ContinuationIndentWidth;
/// \brief If \c true, format braced lists as best suited for C++11 braced
/// lists.
///
/// Important differences:
/// - No spaces inside the braced list.
/// - No line break before the closing brace.
/// - Indentation with the continuation indent, not with the block indent.
///
/// Fundamentally, C++11 braced lists are formatted exactly like function
/// calls would be formatted in their place. If the braced list follows a name
/// (e.g. a type or variable name), clang-format formats as if the \c {} were
/// the parentheses of a function call with that name. If there is no name,
/// a zero-length name is assumed.
bool Cpp11BracedListStyle;
/// \brief If \c true, analyze the formatted file for the most common
/// alignment of & and *. \c PointerAlignment is then used only as fallback.
bool DerivePointerAlignment;
/// \brief Disables formatting completely.
bool DisableFormat;
/// \brief If \c true, clang-format detects whether function calls and
/// definitions are formatted with one parameter per line.
///
/// Each call can be bin-packed, one-per-line or inconclusive. If it is
/// inconclusive, e.g. completely on one line, but a decision needs to be
/// made, clang-format analyzes whether there are other bin-packed cases in
/// the input file and act accordingly.
///
/// NOTE: This is an experimental flag, that might go away or be renamed. Do
/// not use this in config files, etc. Use at your own risk.
bool ExperimentalAutoDetectBinPacking;
/// \brief A vector of macros that should be interpreted as foreach loops
/// instead of as function calls.
///
/// These are expected to be macros of the form:
/// \code
/// FOREACH(<variable-declaration>, ...)
/// <loop-body>
/// \endcode
///
/// For example: BOOST_FOREACH.
std::vector<std::string> ForEachMacros;
/// \brief Indent case labels one level from the switch statement.
///
/// When \c false, use the same indentation level as for the switch statement.
/// Switch statement body is always indented one level more than case labels.
bool IndentCaseLabels;
/// \brief The number of columns to use for indentation.
unsigned IndentWidth;
/// \brief Indent if a function definition or declaration is wrapped after the
/// type.
bool IndentWrappedFunctionNames;
/// \brief If true, empty lines at the start of blocks are kept.
bool KeepEmptyLinesAtTheStartOfBlocks;
/// \brief Supported languages. When stored in a configuration file, specifies
/// the language, that the configuration targets. When passed to the
/// reformat() function, enables syntax features specific to the language.
enum LanguageKind {
/// Do not use.
LK_None,
/// Should be used for C, C++, ObjectiveC, ObjectiveC++.
LK_Cpp,
/// Should be used for Java.
LK_Java,
/// Should be used for JavaScript.
LK_JavaScript,
/// Should be used for Protocol Buffers
/// (https://developers.google.com/protocol-buffers/).
LK_Proto
};
/// \brief Language, this format style is targeted at.
LanguageKind Language;
/// \brief A regular expression matching macros that start a block.
std::string MacroBlockBegin;
/// \brief A regular expression matching macros that end a block.
std::string MacroBlockEnd;
/// \brief The maximum number of consecutive empty lines to keep.
unsigned MaxEmptyLinesToKeep;
/// \brief Different ways to indent namespace contents.
enum NamespaceIndentationKind {
/// Don't indent in namespaces.
NI_None,
/// Indent only in inner namespaces (nested in other namespaces).
NI_Inner,
/// Indent in all namespaces.
NI_All
};
/// \brief The indentation used for namespaces.
NamespaceIndentationKind NamespaceIndentation;
/// \brief The number of characters to use for indentation of ObjC blocks.
unsigned ObjCBlockIndentWidth;
/// \brief Add a space after \c @property in Objective-C, i.e. use
/// <tt>\@property (readonly)</tt> instead of <tt>\@property(readonly)</tt>.
bool ObjCSpaceAfterProperty;
/// \brief Add a space in front of an Objective-C protocol list, i.e. use
/// <tt>Foo <Protocol></tt> instead of \c Foo<Protocol>.
bool ObjCSpaceBeforeProtocolList;
/// \brief The penalty for breaking a function call after "call(".
unsigned PenaltyBreakBeforeFirstCallParameter;
/// \brief The penalty for each line break introduced inside a comment.
unsigned PenaltyBreakComment;
/// \brief The penalty for breaking before the first \c <<.
unsigned PenaltyBreakFirstLessLess;
/// \brief The penalty for each line break introduced inside a string literal.
unsigned PenaltyBreakString;
/// \brief The penalty for each character outside of the column limit.
unsigned PenaltyExcessCharacter;
/// \brief Penalty for putting the return type of a function onto its own
/// line.
unsigned PenaltyReturnTypeOnItsOwnLine;
/// \brief The & and * alignment style.
enum PointerAlignmentStyle {
/// Align pointer to the left.
PAS_Left,
/// Align pointer to the right.
PAS_Right,
/// Align pointer in the middle.
PAS_Middle
};
/// Pointer and reference alignment style.
PointerAlignmentStyle PointerAlignment;
/// \brief If \c true, a space may be inserted after C style casts.
bool SpaceAfterCStyleCast;
/// \brief If \c false, spaces will be removed before assignment operators.
bool SpaceBeforeAssignmentOperators;
/// \brief Different ways to put a space before opening parentheses.
enum SpaceBeforeParensOptions {
/// Never put a space before opening parentheses.
SBPO_Never,
/// Put a space before opening parentheses only after control statement
/// keywords (<tt>for/if/while...</tt>).
SBPO_ControlStatements,
/// Always put a space before opening parentheses, except when it's
/// prohibited by the syntax rules (in function-like macro definitions) or
/// when determined by other style rules (after unary operators, opening
/// parentheses, etc.)
SBPO_Always
};
/// \brief Defines in which cases to put a space before opening parentheses.
SpaceBeforeParensOptions SpaceBeforeParens;
/// \brief If \c true, spaces may be inserted into '()'.
bool SpaceInEmptyParentheses;
/// \brief The number of spaces before trailing line comments
/// (\c // - comments).
///
/// This does not affect trailing block comments (\c /**/ - comments) as those
/// commonly have different usage patterns and a number of special cases.
unsigned SpacesBeforeTrailingComments;
/// \brief If \c true, spaces will be inserted after '<' and before '>' in
/// template argument lists
bool SpacesInAngles;
/// \brief If \c true, spaces are inserted inside container literals (e.g.
/// ObjC and Javascript array and dict literals).
bool SpacesInContainerLiterals;
/// \brief If \c true, spaces may be inserted into C style casts.
bool SpacesInCStyleCastParentheses;
/// \brief If \c true, spaces will be inserted after '(' and before ')'.
bool SpacesInParentheses;
/// \brief If \c true, spaces will be inserted after '[' and before ']'.
bool SpacesInSquareBrackets;
/// \brief Supported language standards.
enum LanguageStandard {
/// Use C++03-compatible syntax.
LS_Cpp03,
/// Use features of C++11 (e.g. \c A<A<int>> instead of
/// <tt>A<A<int> ></tt>).
LS_Cpp11,
/// Automatic detection based on the input.
LS_Auto
};
/// \brief Format compatible with this standard, e.g. use
/// <tt>A<A<int> ></tt> instead of \c A<A<int>> for LS_Cpp03.
LanguageStandard Standard;
/// \brief The number of columns used for tab stops.
unsigned TabWidth;
/// \brief Different ways to use tab in formatting.
enum UseTabStyle {
/// Never use tab.
UT_Never,
/// Use tabs only for indentation.
UT_ForIndentation,
/// Use tabs whenever we need to fill whitespace that spans at least from
/// one tab stop to the next one.
UT_Always
};
/// \brief The way to use tab characters in the resulting file.
UseTabStyle UseTab;
bool operator==(const FormatStyle &R) const {
return AccessModifierOffset == R.AccessModifierOffset &&
AlignAfterOpenBracket == R.AlignAfterOpenBracket &&
AlignConsecutiveAssignments == R.AlignConsecutiveAssignments &&
AlignEscapedNewlinesLeft == R.AlignEscapedNewlinesLeft &&
AlignOperands == R.AlignOperands &&
AlignTrailingComments == R.AlignTrailingComments &&
AllowAllParametersOfDeclarationOnNextLine ==
R.AllowAllParametersOfDeclarationOnNextLine &&
AllowShortBlocksOnASingleLine == R.AllowShortBlocksOnASingleLine &&
AllowShortCaseLabelsOnASingleLine ==
R.AllowShortCaseLabelsOnASingleLine &&
AllowShortFunctionsOnASingleLine ==
R.AllowShortFunctionsOnASingleLine &&
AllowShortIfStatementsOnASingleLine ==
R.AllowShortIfStatementsOnASingleLine &&
AllowShortLoopsOnASingleLine == R.AllowShortLoopsOnASingleLine &&
AlwaysBreakAfterDefinitionReturnType ==
R.AlwaysBreakAfterDefinitionReturnType &&
AlwaysBreakBeforeMultilineStrings ==
R.AlwaysBreakBeforeMultilineStrings &&
AlwaysBreakTemplateDeclarations ==
R.AlwaysBreakTemplateDeclarations &&
BinPackArguments == R.BinPackArguments &&
BinPackParameters == R.BinPackParameters &&
BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&
BreakBeforeBraces == R.BreakBeforeBraces &&
BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
BreakConstructorInitializersBeforeComma ==
R.BreakConstructorInitializersBeforeComma &&
ColumnLimit == R.ColumnLimit &&
CommentPragmas == R.CommentPragmas &&
ConstructorInitializerAllOnOneLineOrOnePerLine ==
R.ConstructorInitializerAllOnOneLineOrOnePerLine &&
ConstructorInitializerIndentWidth ==
R.ConstructorInitializerIndentWidth &&
ContinuationIndentWidth == R.ContinuationIndentWidth &&
Cpp11BracedListStyle == R.Cpp11BracedListStyle &&
DerivePointerAlignment == R.DerivePointerAlignment &&
DisableFormat == R.DisableFormat &&
ExperimentalAutoDetectBinPacking ==
R.ExperimentalAutoDetectBinPacking &&
ForEachMacros == R.ForEachMacros &&
IndentCaseLabels == R.IndentCaseLabels &&
IndentWidth == R.IndentWidth && Language == R.Language &&
IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
KeepEmptyLinesAtTheStartOfBlocks ==
R.KeepEmptyLinesAtTheStartOfBlocks &&
MacroBlockBegin == R.MacroBlockBegin &&
MacroBlockEnd == R.MacroBlockEnd &&
MaxEmptyLinesToKeep == R.MaxEmptyLinesToKeep &&
NamespaceIndentation == R.NamespaceIndentation &&
ObjCBlockIndentWidth == R.ObjCBlockIndentWidth &&
ObjCSpaceAfterProperty == R.ObjCSpaceAfterProperty &&
ObjCSpaceBeforeProtocolList == R.ObjCSpaceBeforeProtocolList &&
PenaltyBreakBeforeFirstCallParameter ==
R.PenaltyBreakBeforeFirstCallParameter &&
PenaltyBreakComment == R.PenaltyBreakComment &&
PenaltyBreakFirstLessLess == R.PenaltyBreakFirstLessLess &&
PenaltyBreakString == R.PenaltyBreakString &&
PenaltyExcessCharacter == R.PenaltyExcessCharacter &&
PenaltyReturnTypeOnItsOwnLine == R.PenaltyReturnTypeOnItsOwnLine &&
PointerAlignment == R.PointerAlignment &&
SpaceAfterCStyleCast == R.SpaceAfterCStyleCast &&
SpaceBeforeAssignmentOperators == R.SpaceBeforeAssignmentOperators &&
SpaceBeforeParens == R.SpaceBeforeParens &&
SpaceInEmptyParentheses == R.SpaceInEmptyParentheses &&
SpacesBeforeTrailingComments == R.SpacesBeforeTrailingComments &&
SpacesInAngles == R.SpacesInAngles &&
SpacesInContainerLiterals == R.SpacesInContainerLiterals &&
SpacesInCStyleCastParentheses == R.SpacesInCStyleCastParentheses &&
SpacesInParentheses == R.SpacesInParentheses &&
SpacesInSquareBrackets == R.SpacesInSquareBrackets &&
Standard == R.Standard &&
TabWidth == R.TabWidth &&
UseTab == R.UseTab;
}
};
/// \brief Returns a format style complying with the LLVM coding standards:
/// http://llvm.org/docs/CodingStandards.html.
FormatStyle getLLVMStyle();
/// \brief Returns a format style complying with one of Google's style guides:
/// http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml.
/// http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml.
/// https://developers.google.com/protocol-buffers/docs/style.
FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language);
/// \brief Returns a format style complying with Chromium's style guide:
/// http://www.chromium.org/developers/coding-style.
FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language);
/// \brief Returns a format style complying with Mozilla's style guide:
/// https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style.
FormatStyle getMozillaStyle();
/// \brief Returns a format style complying with Webkit's style guide:
/// http://www.webkit.org/coding/coding-style.html
FormatStyle getWebKitStyle();
/// \brief Returns a format style complying with GNU Coding Standards:
/// http://www.gnu.org/prep/standards/standards.html
FormatStyle getGNUStyle();
/// \brief Returns style indicating formatting should be not applied at all.
FormatStyle getNoStyle();
/// \brief Gets a predefined style for the specified language by name.
///
/// Currently supported names: LLVM, Google, Chromium, Mozilla. Names are
/// compared case-insensitively.
///
/// Returns \c true if the Style has been set.
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
FormatStyle *Style);
/// \brief Parse configuration from YAML-formatted text.
///
/// Style->Language is used to get the base style, if the \c BasedOnStyle
/// option is present.
///
/// When \c BasedOnStyle is not present, options not present in the YAML
/// document, are retained in \p Style.
std::error_code parseConfiguration(StringRef Text, FormatStyle *Style);
/// \brief Gets configuration in a YAML string.
std::string configurationAsText(const FormatStyle &Style);
/// \brief Reformats the given \p Ranges in the file \p ID.
///
/// Each range is extended on either end to its next bigger logic unit, i.e.
/// everything that might influence its formatting or might be influenced by its
/// formatting.
///
/// Returns the \c Replacements necessary to make all \p Ranges comply with
/// \p Style.
///
/// If \c IncompleteFormat is non-null, its value will be set to true if any
/// of the affected ranges were not formatted due to a non-recoverable syntax
/// error.
tooling::Replacements reformat(const FormatStyle &Style,
SourceManager &SourceMgr, FileID ID,
ArrayRef<CharSourceRange> Ranges,
bool *IncompleteFormat = nullptr);
/// \brief Reformats the given \p Ranges in \p Code.
///
/// Otherwise identical to the reformat() function using a file ID.
tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
ArrayRef<tooling::Range> Ranges,
StringRef FileName = "<stdin>",
bool *IncompleteFormat = nullptr);
/// \brief Returns the \c LangOpts that the formatter expects you to set.
///
/// \param Style determines specific settings for lexing mode.
LangOptions getFormattingLangOpts(const FormatStyle &Style = getLLVMStyle());
/// \brief Description to be used for help text for a llvm::cl option for
/// specifying format style. The description is closely related to the operation
/// of getStyle().
extern const char *StyleOptionHelpDescription;
/// \brief Construct a FormatStyle based on \c StyleName.
///
/// \c StyleName can take several forms:
/// \li "{<key>: <value>, ...}" - Set specic style parameters.
/// \li "<style name>" - One of the style names supported by
/// getPredefinedStyle().
/// \li "file" - Load style configuration from a file called '.clang-format'
/// located in one of the parent directories of \c FileName or the current
/// directory if \c FileName is empty.
///
/// \param[in] StyleName Style name to interpret according to the description
/// above.
/// \param[in] FileName Path to start search for .clang-format if \c StyleName
/// == "file".
/// \param[in] FallbackStyle The name of a predefined style used to fallback to
/// in case the style can't be determined from \p StyleName.
///
/// \returns FormatStyle as specified by \c StyleName. If no style could be
/// determined, the default is LLVM Style (see getLLVMStyle()).
FormatStyle getStyle(StringRef StyleName, StringRef FileName,
StringRef FallbackStyle);
} // end namespace format
} // end namespace clang
namespace std {
template <>
struct is_error_code_enum<clang::format::ParseError> : std::true_type {};
}
#endif // LLVM_CLANG_FORMAT_FORMAT_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/DelayedDiagnostic.h | //===--- DelayedDiagnostic.h - Delayed declarator diagnostics ---*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Defines the classes clang::DelayedDiagnostic and
/// clang::AccessedEntity.
///
/// DelayedDiangostic is used to record diagnostics that are being
/// conditionally produced during declarator parsing. Certain kinds of
/// diagnostics -- notably deprecation and access control -- are suppressed
/// based on semantic properties of the parsed declaration that aren't known
/// until it is fully parsed.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_DELAYEDDIAGNOSTIC_H
#define LLVM_CLANG_SEMA_DELAYEDDIAGNOSTIC_H
#include "clang/Sema/Sema.h"
namespace clang {
namespace sema {
/// A declaration being accessed, together with information about how
/// it was accessed.
class AccessedEntity {
public:
/// A member declaration found through lookup. The target is the
/// member.
enum MemberNonce { Member };
/// A hierarchy (base-to-derived or derived-to-base) conversion.
/// The target is the base class.
enum BaseNonce { Base };
bool isMemberAccess() const { return IsMember; }
AccessedEntity(PartialDiagnostic::StorageAllocator &Allocator,
MemberNonce _,
CXXRecordDecl *NamingClass,
DeclAccessPair FoundDecl,
QualType BaseObjectType)
: Access(FoundDecl.getAccess()), IsMember(true),
Target(FoundDecl.getDecl()), NamingClass(NamingClass),
BaseObjectType(BaseObjectType), Diag(0, Allocator) {
}
AccessedEntity(PartialDiagnostic::StorageAllocator &Allocator,
BaseNonce _,
CXXRecordDecl *BaseClass,
CXXRecordDecl *DerivedClass,
AccessSpecifier Access)
: Access(Access), IsMember(false),
Target(BaseClass),
NamingClass(DerivedClass),
Diag(0, Allocator) {
}
bool isQuiet() const { return Diag.getDiagID() == 0; }
AccessSpecifier getAccess() const { return AccessSpecifier(Access); }
// These apply to member decls...
NamedDecl *getTargetDecl() const { return Target; }
CXXRecordDecl *getNamingClass() const { return NamingClass; }
// ...and these apply to hierarchy conversions.
CXXRecordDecl *getBaseClass() const {
assert(!IsMember); return cast<CXXRecordDecl>(Target);
}
CXXRecordDecl *getDerivedClass() const { return NamingClass; }
/// Retrieves the base object type, important when accessing
/// an instance member.
QualType getBaseObjectType() const { return BaseObjectType; }
/// Sets a diagnostic to be performed. The diagnostic is given
/// four (additional) arguments:
/// %0 - 0 if the entity was private, 1 if protected
/// %1 - the DeclarationName of the entity
/// %2 - the TypeDecl type of the naming class
/// %3 - the TypeDecl type of the declaring class
void setDiag(const PartialDiagnostic &PDiag) {
assert(isQuiet() && "partial diagnostic already defined");
Diag = PDiag;
}
PartialDiagnostic &setDiag(unsigned DiagID) {
assert(isQuiet() && "partial diagnostic already defined");
assert(DiagID && "creating null diagnostic");
Diag.Reset(DiagID);
return Diag;
}
const PartialDiagnostic &getDiag() const {
return Diag;
}
private:
unsigned Access : 2;
unsigned IsMember : 1;
NamedDecl *Target;
CXXRecordDecl *NamingClass;
QualType BaseObjectType;
PartialDiagnostic Diag;
};
/// A diagnostic message which has been conditionally emitted pending
/// the complete parsing of the current declaration.
class DelayedDiagnostic {
public:
enum DDKind { Deprecation, Unavailable, Access, ForbiddenType };
unsigned char Kind; // actually a DDKind
bool Triggered;
SourceLocation Loc;
void Destroy();
static DelayedDiagnostic makeAvailability(Sema::AvailabilityDiagnostic AD,
SourceLocation Loc,
const NamedDecl *D,
const ObjCInterfaceDecl *UnknownObjCClass,
const ObjCPropertyDecl *ObjCProperty,
StringRef Msg,
bool ObjCPropertyAccess);
static DelayedDiagnostic makeAccess(SourceLocation Loc,
const AccessedEntity &Entity) {
DelayedDiagnostic DD;
DD.Kind = Access;
DD.Triggered = false;
DD.Loc = Loc;
new (&DD.getAccessData()) AccessedEntity(Entity);
return DD;
}
static DelayedDiagnostic makeForbiddenType(SourceLocation loc,
unsigned diagnostic,
QualType type,
unsigned argument) {
DelayedDiagnostic DD;
DD.Kind = ForbiddenType;
DD.Triggered = false;
DD.Loc = loc;
DD.ForbiddenTypeData.Diagnostic = diagnostic;
DD.ForbiddenTypeData.OperandType = type.getAsOpaquePtr();
DD.ForbiddenTypeData.Argument = argument;
return DD;
}
AccessedEntity &getAccessData() {
assert(Kind == Access && "Not an access diagnostic.");
return *reinterpret_cast<AccessedEntity*>(AccessData);
}
const AccessedEntity &getAccessData() const {
assert(Kind == Access && "Not an access diagnostic.");
return *reinterpret_cast<const AccessedEntity*>(AccessData);
}
const NamedDecl *getDeprecationDecl() const {
assert((Kind == Deprecation || Kind == Unavailable) &&
"Not a deprecation diagnostic.");
return DeprecationData.Decl;
}
StringRef getDeprecationMessage() const {
assert((Kind == Deprecation || Kind == Unavailable) &&
"Not a deprecation diagnostic.");
return StringRef(DeprecationData.Message,
DeprecationData.MessageLen);
}
/// The diagnostic ID to emit. Used like so:
/// Diag(diag.Loc, diag.getForbiddenTypeDiagnostic())
/// << diag.getForbiddenTypeOperand()
/// << diag.getForbiddenTypeArgument();
unsigned getForbiddenTypeDiagnostic() const {
assert(Kind == ForbiddenType && "not a forbidden-type diagnostic");
return ForbiddenTypeData.Diagnostic;
}
unsigned getForbiddenTypeArgument() const {
assert(Kind == ForbiddenType && "not a forbidden-type diagnostic");
return ForbiddenTypeData.Argument;
}
QualType getForbiddenTypeOperand() const {
assert(Kind == ForbiddenType && "not a forbidden-type diagnostic");
return QualType::getFromOpaquePtr(ForbiddenTypeData.OperandType);
}
const ObjCInterfaceDecl *getUnknownObjCClass() const {
return DeprecationData.UnknownObjCClass;
}
const ObjCPropertyDecl *getObjCProperty() const {
return DeprecationData.ObjCProperty;
}
bool getObjCPropertyAccess() const {
return DeprecationData.ObjCPropertyAccess;
}
private:
struct DD {
const NamedDecl *Decl;
const ObjCInterfaceDecl *UnknownObjCClass;
const ObjCPropertyDecl *ObjCProperty;
const char *Message;
size_t MessageLen;
bool ObjCPropertyAccess;
};
struct FTD {
unsigned Diagnostic;
unsigned Argument;
void *OperandType;
};
union {
/// Deprecation
struct DD DeprecationData;
struct FTD ForbiddenTypeData;
/// Access control.
char AccessData[sizeof(AccessedEntity)];
};
};
/// \brief A collection of diagnostics which were delayed.
class DelayedDiagnosticPool {
const DelayedDiagnosticPool *Parent;
SmallVector<DelayedDiagnostic, 4> Diagnostics;
DelayedDiagnosticPool(const DelayedDiagnosticPool &) = delete;
void operator=(const DelayedDiagnosticPool &) = delete;
public:
DelayedDiagnosticPool(const DelayedDiagnosticPool *parent) : Parent(parent) {}
~DelayedDiagnosticPool() {
for (SmallVectorImpl<DelayedDiagnostic>::iterator
i = Diagnostics.begin(), e = Diagnostics.end(); i != e; ++i)
i->Destroy();
}
DelayedDiagnosticPool(DelayedDiagnosticPool &&Other)
: Parent(Other.Parent), Diagnostics(std::move(Other.Diagnostics)) {
Other.Diagnostics.clear();
}
DelayedDiagnosticPool &operator=(DelayedDiagnosticPool &&Other) {
Parent = Other.Parent;
Diagnostics = std::move(Other.Diagnostics);
Other.Diagnostics.clear();
return *this;
}
const DelayedDiagnosticPool *getParent() const { return Parent; }
/// Does this pool, or any of its ancestors, contain any diagnostics?
bool empty() const {
return (Diagnostics.empty() && (!Parent || Parent->empty()));
}
/// Add a diagnostic to this pool.
void add(const DelayedDiagnostic &diag) {
Diagnostics.push_back(diag);
}
/// Steal the diagnostics from the given pool.
void steal(DelayedDiagnosticPool &pool) {
if (pool.Diagnostics.empty()) return;
if (Diagnostics.empty()) {
Diagnostics = std::move(pool.Diagnostics);
} else {
Diagnostics.append(pool.pool_begin(), pool.pool_end());
}
pool.Diagnostics.clear();
}
typedef SmallVectorImpl<DelayedDiagnostic>::const_iterator pool_iterator;
pool_iterator pool_begin() const { return Diagnostics.begin(); }
pool_iterator pool_end() const { return Diagnostics.end(); }
bool pool_empty() const { return Diagnostics.empty(); }
};
}
/// Add a diagnostic to the current delay pool.
inline void Sema::DelayedDiagnostics::add(const sema::DelayedDiagnostic &diag) {
assert(shouldDelayDiagnostics() && "trying to delay without pool");
CurPool->add(diag);
}
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/IdentifierResolver.h | //===- IdentifierResolver.h - Lexical Scope Name lookup ---------*- 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 IdentifierResolver class, which is used for lexical
// scoped lookup, based on declaration names.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_IDENTIFIERRESOLVER_H
#define LLVM_CLANG_SEMA_IDENTIFIERRESOLVER_H
#include "clang/Basic/IdentifierTable.h"
#include "llvm/ADT/SmallVector.h"
namespace clang {
class ASTContext;
class Decl;
class DeclContext;
class DeclarationName;
class ExternalPreprocessorSource;
class NamedDecl;
class Preprocessor;
class Scope;
/// IdentifierResolver - Keeps track of shadowed decls on enclosing
/// scopes. It manages the shadowing chains of declaration names and
/// implements efficient decl lookup based on a declaration name.
class IdentifierResolver {
/// IdDeclInfo - Keeps track of information about decls associated
/// to a particular declaration name. IdDeclInfos are lazily
/// constructed and assigned to a declaration name the first time a
/// decl with that declaration name is shadowed in some scope.
class IdDeclInfo {
public:
typedef SmallVector<NamedDecl*, 2> DeclsTy;
inline DeclsTy::iterator decls_begin() { return Decls.begin(); }
inline DeclsTy::iterator decls_end() { return Decls.end(); }
void AddDecl(NamedDecl *D) { Decls.push_back(D); }
/// RemoveDecl - Remove the decl from the scope chain.
/// The decl must already be part of the decl chain.
void RemoveDecl(NamedDecl *D);
/// \brief Insert the given declaration at the given position in the list.
void InsertDecl(DeclsTy::iterator Pos, NamedDecl *D) {
Decls.insert(Pos, D);
}
private:
DeclsTy Decls;
};
public:
/// iterator - Iterate over the decls of a specified declaration name.
/// It will walk or not the parent declaration contexts depending on how
/// it was instantiated.
class iterator {
public:
typedef NamedDecl * value_type;
typedef NamedDecl * reference;
typedef NamedDecl * pointer;
typedef std::input_iterator_tag iterator_category;
typedef std::ptrdiff_t difference_type;
/// Ptr - There are 3 forms that 'Ptr' represents:
/// 1) A single NamedDecl. (Ptr & 0x1 == 0)
/// 2) A IdDeclInfo::DeclsTy::iterator that traverses only the decls of the
/// same declaration context. (Ptr & 0x3 == 0x1)
/// 3) A IdDeclInfo::DeclsTy::iterator that traverses the decls of parent
/// declaration contexts too. (Ptr & 0x3 == 0x3)
uintptr_t Ptr;
typedef IdDeclInfo::DeclsTy::iterator BaseIter;
/// A single NamedDecl. (Ptr & 0x1 == 0)
iterator(NamedDecl *D) {
Ptr = reinterpret_cast<uintptr_t>(D);
assert((Ptr & 0x1) == 0 && "Invalid Ptr!");
}
/// A IdDeclInfo::DeclsTy::iterator that walks or not the parent declaration
/// contexts depending on 'LookInParentCtx'.
iterator(BaseIter I) {
Ptr = reinterpret_cast<uintptr_t>(I) | 0x1;
}
bool isIterator() const { return (Ptr & 0x1); }
BaseIter getIterator() const {
assert(isIterator() && "Ptr not an iterator!");
return reinterpret_cast<BaseIter>(Ptr & ~0x3);
}
friend class IdentifierResolver;
void incrementSlowCase();
public:
iterator() : Ptr(0) {}
NamedDecl *operator*() const {
if (isIterator())
return *getIterator();
else
return reinterpret_cast<NamedDecl*>(Ptr);
}
bool operator==(const iterator &RHS) const {
return Ptr == RHS.Ptr;
}
bool operator!=(const iterator &RHS) const {
return Ptr != RHS.Ptr;
}
// Preincrement.
iterator& operator++() {
if (!isIterator()) // common case.
Ptr = 0;
else
incrementSlowCase();
return *this;
}
uintptr_t getAsOpaqueValue() const { return Ptr; }
static iterator getFromOpaqueValue(uintptr_t P) {
iterator Result;
Result.Ptr = P;
return Result;
}
};
/// begin - Returns an iterator for decls with the name 'Name'.
iterator begin(DeclarationName Name);
/// end - Returns an iterator that has 'finished'.
iterator end() {
return iterator();
}
/// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
/// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
/// true if 'D' belongs to the given declaration context.
///
/// \param AllowInlineNamespace If \c true, we are checking whether a prior
/// declaration is in scope in a declaration that requires a prior
/// declaration (because it is either explicitly qualified or is a
/// template instantiation or specialization). In this case, a
/// declaration is in scope if it's in the inline namespace set of the
/// context.
bool isDeclInScope(Decl *D, DeclContext *Ctx, Scope *S = nullptr,
bool AllowInlineNamespace = false) const;
/// AddDecl - Link the decl to its shadowed decl chain.
void AddDecl(NamedDecl *D);
/// RemoveDecl - Unlink the decl from its shadowed decl chain.
/// The decl must already be part of the decl chain.
void RemoveDecl(NamedDecl *D);
/// \brief Insert the given declaration after the given iterator
/// position.
void InsertDeclAfter(iterator Pos, NamedDecl *D);
/// \brief Try to add the given declaration to the top level scope, if it
/// (or a redeclaration of it) hasn't already been added.
///
/// \param D The externally-produced declaration to add.
///
/// \param Name The name of the externally-produced declaration.
///
/// \returns true if the declaration was added, false otherwise.
bool tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name);
explicit IdentifierResolver(Preprocessor &PP);
~IdentifierResolver();
private:
const LangOptions &LangOpt;
Preprocessor &PP;
class IdDeclInfoMap;
IdDeclInfoMap *IdDeclInfos;
void updatingIdentifier(IdentifierInfo &II);
void readingIdentifier(IdentifierInfo &II);
/// FETokenInfo contains a Decl pointer if lower bit == 0.
static inline bool isDeclPtr(void *Ptr) {
return (reinterpret_cast<uintptr_t>(Ptr) & 0x1) == 0;
}
/// FETokenInfo contains a IdDeclInfo pointer if lower bit == 1.
static inline IdDeclInfo *toIdDeclInfo(void *Ptr) {
assert((reinterpret_cast<uintptr_t>(Ptr) & 0x1) == 1
&& "Ptr not a IdDeclInfo* !");
return reinterpret_cast<IdDeclInfo*>(
reinterpret_cast<uintptr_t>(Ptr) & ~0x1
);
}
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/Sema.h | //===--- Sema.h - Semantic Analysis & AST Building --------------*- 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 Sema class, which performs semantic analysis and
// builds ASTs.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMA_H
#define LLVM_CLANG_SEMA_SEMA_H
#include "clang/AST/Attr.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/MangleNumberingContext.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/OpenMPKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TemplateKinds.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Sema/AnalysisBasedWarnings.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/IdentifierResolver.h"
#include "clang/Sema/LocInfoType.h"
#include "clang/Sema/ObjCMethodList.h"
#include "clang/Sema/Ownership.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/TypoCorrection.h"
#include "clang/Sema/Weak.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <deque>
#include <memory>
#include <string>
#include <vector>
// HLSL Change Starts
#include "llvm/Support/OacrIgnoreCond.h" // HLSL Change - all sema use is heavily language-dependant
namespace hlsl {
struct UnusualAnnotation;
class ShaderModel;
}
// HLSL Change Ends
namespace llvm {
class APSInt;
template <typename ValueT> struct DenseMapInfo;
template <typename ValueT, typename ValueInfoT> class DenseSet;
class SmallBitVector;
class InlineAsmIdentifierInfo;
}
namespace clang {
class ADLResult;
class ASTConsumer;
class ASTContext;
class ASTMutationListener;
class ASTReader;
class ASTWriter;
class ArrayType;
class AttributeList;
class BlockDecl;
class CapturedDecl;
class CXXBasePath;
class CXXBasePaths;
class CXXBindTemporaryExpr;
typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
class CXXConstructorDecl;
class CXXConversionDecl;
class CXXDeleteExpr;
class CXXDestructorDecl;
class CXXFieldCollector;
class CXXMemberCallExpr;
class CXXMethodDecl;
class CXXScopeSpec;
class CXXTemporary;
class CXXTryStmt;
class CallExpr;
class ClassTemplateDecl;
class ClassTemplatePartialSpecializationDecl;
class ClassTemplateSpecializationDecl;
class VarTemplatePartialSpecializationDecl;
class CodeCompleteConsumer;
class CodeCompletionAllocator;
class CodeCompletionTUInfo;
class CodeCompletionResult;
class Decl;
class DeclAccessPair;
class DeclContext;
class DeclRefExpr;
class DeclaratorDecl;
class DeducedTemplateArgument;
class DependentDiagnostic;
class DesignatedInitExpr;
class Designation;
class EnableIfAttr;
class EnumConstantDecl;
class Expr;
class ExtVectorType;
class ExternalSemaSource;
class FormatAttr;
class FriendDecl;
class FunctionDecl;
class FunctionProtoType;
class FunctionTemplateDecl;
class ImplicitConversionSequence;
class InitListExpr;
class InitializationKind;
class InitializationSequence;
class InitializedEntity;
class IntegerLiteral;
class LabelStmt;
class LambdaExpr;
class LangOptions;
class LocalInstantiationScope;
class LookupResult;
class MacroInfo;
typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
class ModuleLoader;
class MultiLevelTemplateArgumentList;
class NamedDecl;
class ObjCCategoryDecl;
class ObjCCategoryImplDecl;
class ObjCCompatibleAliasDecl;
class ObjCContainerDecl;
class ObjCImplDecl;
class ObjCImplementationDecl;
class ObjCInterfaceDecl;
class ObjCIvarDecl;
template <class T> class ObjCList;
class ObjCMessageExpr;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ObjCProtocolDecl;
class OMPThreadPrivateDecl;
class OMPClause;
class OverloadCandidateSet;
class OverloadExpr;
class ParenListExpr;
class ParmVarDecl;
class Preprocessor;
class PseudoDestructorTypeStorage;
class PseudoObjectExpr;
class QualType;
class StandardConversionSequence;
class Stmt;
class StringLiteral;
class SwitchStmt;
class TemplateArgument;
class TemplateArgumentList;
class TemplateArgumentLoc;
class TemplateDecl;
class TemplateParameterList;
class TemplatePartialOrderingContext;
class TemplateTemplateParmDecl;
class Token;
class TypeAliasDecl;
class TypedefDecl;
class TypedefNameDecl;
class TypeLoc;
class TypoCorrectionConsumer;
class UnqualifiedId;
class UnresolvedLookupExpr;
class UnresolvedMemberExpr;
class UnresolvedSetImpl;
class UnresolvedSetIterator;
class UsingDecl;
class UsingShadowDecl;
class ValueDecl;
class VarDecl;
class VarTemplateSpecializationDecl;
class VisibilityAttr;
class VisibleDeclConsumer;
class IndirectFieldDecl;
struct DeductionFailureInfo;
class TemplateSpecCandidateSet;
class CXXThisExpr; // HLSL Change
namespace sema {
class AccessedEntity;
class BlockScopeInfo;
class CapturedRegionScopeInfo;
class CapturingScopeInfo;
class CompoundScopeInfo;
class DelayedDiagnostic;
class DelayedDiagnosticPool;
class FunctionScopeInfo;
class LambdaScopeInfo;
class PossiblyUnreachableDiag;
class TemplateDeductionInfo;
}
namespace threadSafety {
class BeforeSet;
void threadSafetyCleanup(BeforeSet* Cache);
}
// FIXME: No way to easily map from TemplateTypeParmTypes to
// TemplateTypeParmDecls, so we have this horrible PointerUnion.
typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
SourceLocation> UnexpandedParameterPack;
/// Describes whether we've seen any nullability information for the given
/// file.
struct FileNullability {
/// The first pointer declarator (of any pointer kind) in the file that does
/// not have a corresponding nullability annotation.
SourceLocation PointerLoc;
/// Which kind of pointer declarator we saw.
uint8_t PointerKind;
/// Whether we saw any type nullability annotations in the given file.
bool SawTypeNullability = false;
};
/// A mapping from file IDs to a record of whether we've seen nullability
/// information in that file.
class FileNullabilityMap {
/// A mapping from file IDs to the nullability information for each file ID.
llvm::DenseMap<FileID, FileNullability> Map;
/// A single-element cache based on the file ID.
struct {
FileID File;
FileNullability Nullability;
} Cache;
public:
FileNullability &operator[](FileID file) {
// Check the single-element cache.
if (file == Cache.File)
return Cache.Nullability;
// It's not in the single-element cache; flush the cache if we have one.
if (!Cache.File.isInvalid()) {
Map[Cache.File] = Cache.Nullability;
}
// Pull this entry into the cache.
Cache.File = file;
Cache.Nullability = Map[file];
return Cache.Nullability;
}
};
/// Sema - This implements semantic analysis and AST building for C.
class Sema {
Sema(const Sema &) = delete;
void operator=(const Sema &) = delete;
///\brief Source of additional semantic information.
ExternalSemaSource *ExternalSource;
///\brief Whether Sema has generated a multiplexer and has to delete it.
bool isMultiplexExternalSource;
static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
bool isVisibleSlow(const NamedDecl *D);
bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
const NamedDecl *New) {
// We are about to link these. It is now safe to compute the linkage of
// the new decl. If the new decl has external linkage, we will
// link it with the hidden decl (which also has external linkage) and
// it will keep having external linkage. If it has internal linkage, we
// will not link it. Since it has no previous decls, it will remain
// with internal linkage.
if (getLangOpts().ModulesHideInternalLinkage)
return isVisible(Old) || New->isExternallyVisible();
return true;
}
public:
typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
typedef OpaquePtr<TemplateName> TemplateTy;
typedef OpaquePtr<QualType> TypeTy;
OpenCLOptions OpenCLFeatures;
FPOptions FPFeatures;
const LangOptions &LangOpts;
Preprocessor &PP;
ASTContext &Context;
ASTConsumer &Consumer;
DiagnosticsEngine &Diags;
SourceManager &SourceMgr;
/// \brief Flag indicating whether or not to collect detailed statistics.
bool CollectStats;
/// \brief Code-completion consumer.
CodeCompleteConsumer *CodeCompleter;
/// CurContext - This is the current declaration context of parsing.
DeclContext *CurContext;
/// \brief Generally null except when we temporarily switch decl contexts,
/// like in \see ActOnObjCTemporaryExitContainerContext.
DeclContext *OriginalLexicalContext;
/// VAListTagName - The declaration name corresponding to __va_list_tag.
/// This is used as part of a hack to omit that class from ADL results.
DeclarationName VAListTagName;
/// PackContext - Manages the stack for \#pragma pack. An alignment
/// of 0 indicates default alignment.
void *PackContext; // Really a "PragmaPackStack*"
bool MSStructPragmaOn; // True when \#pragma ms_struct on
/// \brief Controls member pointer representation format under the MS ABI.
LangOptions::PragmaMSPointersToMembersKind
MSPointerToMemberRepresentationMethod;
// HLSL Change Begin
// The HLSL rewriter doesn't define a default matrix pack,
// so we must preserve the lack of annotations to avoid changing semantics.
bool HasDefaultMatrixPack = false;
// Uses of #pragma pack_matrix change the default pack.
bool DefaultMatrixPackRowMajor = false;
// HLSL Change End.
enum PragmaVtorDispKind {
PVDK_Push, ///< #pragma vtordisp(push, mode)
PVDK_Set, ///< #pragma vtordisp(mode)
PVDK_Pop, ///< #pragma vtordisp(pop)
PVDK_Reset ///< #pragma vtordisp()
};
enum PragmaMsStackAction {
PSK_Reset, // #pragma ()
PSK_Set, // #pragma ("name")
PSK_Push, // #pragma (push[, id])
PSK_Push_Set, // #pragma (push[, id], "name")
PSK_Pop, // #pragma (pop[, id])
PSK_Pop_Set, // #pragma (pop[, id], "name")
};
/// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
/// C++ ABI. Possible values are 0, 1, and 2, which mean:
///
/// 0: Suppress all vtordisps
/// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
/// structors
/// 2: Always insert vtordisps to support RTTI on partially constructed
/// objects
///
/// The stack always has at least one element in it.
SmallVector<MSVtorDispAttr::Mode, 2> VtorDispModeStack;
/// Stack of active SEH __finally scopes. Can be empty.
SmallVector<Scope*, 2> CurrentSEHFinally;
/// \brief Source location for newly created implicit MSInheritanceAttrs
SourceLocation ImplicitMSInheritanceAttrLoc;
template<typename ValueType>
struct PragmaStack {
struct Slot {
llvm::StringRef StackSlotLabel;
ValueType Value;
SourceLocation PragmaLocation;
Slot(llvm::StringRef StackSlotLabel,
ValueType Value,
SourceLocation PragmaLocation)
: StackSlotLabel(StackSlotLabel), Value(Value),
PragmaLocation(PragmaLocation) {}
};
void Act(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
ValueType Value);
explicit PragmaStack(const ValueType &Value)
: CurrentValue(Value) {}
SmallVector<Slot, 2> Stack;
ValueType CurrentValue;
SourceLocation CurrentPragmaLocation;
};
// FIXME: We should serialize / deserialize these if they occur in a PCH (but
// we shouldn't do so if they're in a module).
PragmaStack<StringLiteral *> DataSegStack;
PragmaStack<StringLiteral *> BSSSegStack;
PragmaStack<StringLiteral *> ConstSegStack;
PragmaStack<StringLiteral *> CodeSegStack;
/// A mapping that describes the nullability we've seen in each header file.
FileNullabilityMap NullabilityMap;
/// Last section used with #pragma init_seg.
StringLiteral *CurInitSeg;
SourceLocation CurInitSegLoc;
/// VisContext - Manages the stack for \#pragma GCC visibility.
void *VisContext; // Really a "PragmaVisStack*"
/// \brief This represents the last location of a "#pragma clang optimize off"
/// directive if such a directive has not been closed by an "on" yet. If
/// optimizations are currently "on", this is set to an invalid location.
SourceLocation OptimizeOffPragmaLocation;
/// \brief Flag indicating if Sema is building a recovery call expression.
///
/// This flag is used to avoid building recovery call expressions
/// if Sema is already doing so, which would cause infinite recursions.
bool IsBuildingRecoveryCallExpr;
/// ExprNeedsCleanups - True if the current evaluation context
/// requires cleanups to be run at its conclusion.
bool ExprNeedsCleanups;
/// ExprCleanupObjects - This is the stack of objects requiring
/// cleanup that are created by the current full expression. The
/// element type here is ExprWithCleanups::Object.
SmallVector<BlockDecl*, 8> ExprCleanupObjects;
/// \brief Store a list of either DeclRefExprs or MemberExprs
/// that contain a reference to a variable (constant) that may or may not
/// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
/// and discarded value conversions have been applied to all subexpressions
/// of the enclosing full expression. This is cleared at the end of each
/// full expression.
llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
/// \brief Stack containing information about each of the nested
/// function, block, and method scopes that are currently active.
///
/// This array is never empty. Clients should ignore the first
/// element, which is used to cache a single FunctionScopeInfo
/// that's used to parse every top-level function.
SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadExtVectorDecls, 2, 2>
ExtVectorDeclsType;
/// ExtVectorDecls - This is a list all the extended vector types. This allows
/// us to associate a raw vector type with one of the ext_vector type names.
/// This is only necessary for issuing pretty diagnostics.
ExtVectorDeclsType ExtVectorDecls;
/// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
std::unique_ptr<CXXFieldCollector> FieldCollector;
typedef llvm::SmallSetVector<const NamedDecl*, 16> NamedDeclSetType;
/// \brief Set containing all declared private fields that are not used.
NamedDeclSetType UnusedPrivateFields;
/// \brief Set containing all typedefs that are likely unused.
llvm::SmallSetVector<const TypedefNameDecl *, 4>
UnusedLocalTypedefNameCandidates;
/// \brief Delete-expressions to be analyzed at the end of translation unit
///
/// This list contains class members, and locations of delete-expressions
/// that could not be proven as to whether they mismatch with new-expression
/// used in initializer of the field.
typedef std::pair<SourceLocation, bool> DeleteExprLoc;
typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
/// PureVirtualClassDiagSet - a set of class declarations which we have
/// emitted a list of pure virtual functions. Used to prevent emitting the
/// same list more than once.
std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
/// ParsingInitForAutoVars - a set of declarations with auto types for which
/// we are currently parsing the initializer.
llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
/// \brief Look for a locally scoped extern "C" declaration by the given name.
NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
typedef LazyVector<VarDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
TentativeDefinitionsType;
/// \brief All the tentative definitions encountered in the TU.
TentativeDefinitionsType TentativeDefinitions;
typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
UnusedFileScopedDeclsType;
/// \brief The set of file scoped decls seen so far that have not been used
/// and must warn if not used. Only contains the first declaration.
UnusedFileScopedDeclsType UnusedFileScopedDecls;
typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
&ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
DelegatingCtorDeclsType;
/// \brief All the delegating constructors seen so far in the file, used for
/// cycle detection at the end of the TU.
DelegatingCtorDeclsType DelegatingCtorDecls;
/// \brief All the overriding functions seen during a class definition
/// that had their exception spec checks delayed, plus the overridden
/// function.
SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
DelayedExceptionSpecChecks;
/// \brief All the members seen during a class definition which were both
/// explicitly defaulted and had explicitly-specified exception
/// specifications, along with the function type containing their
/// user-specified exception specification. Those exception specifications
/// were overridden with the default specifications, but we still need to
/// check whether they are compatible with the default specification, and
/// we can't do that until the nesting set of class definitions is complete.
SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2>
DelayedDefaultedMemberExceptionSpecs;
typedef llvm::MapVector<const FunctionDecl *, LateParsedTemplate *>
LateParsedTemplateMapT;
LateParsedTemplateMapT LateParsedTemplateMap;
/// \brief Callback to the parser to parse templated functions when needed.
typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
typedef void LateTemplateParserCleanupCB(void *P);
LateTemplateParserCB *LateTemplateParser;
LateTemplateParserCleanupCB *LateTemplateParserCleanup;
void *OpaqueParser;
void SetLateTemplateParser(LateTemplateParserCB *LTP,
LateTemplateParserCleanupCB *LTPCleanup,
void *P) {
LateTemplateParser = LTP;
LateTemplateParserCleanup = LTPCleanup;
OpaqueParser = P;
}
class DelayedDiagnostics;
class DelayedDiagnosticsState {
sema::DelayedDiagnosticPool *SavedPool;
friend class Sema::DelayedDiagnostics;
};
typedef DelayedDiagnosticsState ParsingDeclState;
typedef DelayedDiagnosticsState ProcessingContextState;
/// A class which encapsulates the logic for delaying diagnostics
/// during parsing and other processing.
class DelayedDiagnostics {
/// \brief The current pool of diagnostics into which delayed
/// diagnostics should go.
sema::DelayedDiagnosticPool *CurPool;
public:
DelayedDiagnostics() : CurPool(nullptr) {}
/// Adds a delayed diagnostic.
void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
/// Determines whether diagnostics should be delayed.
bool shouldDelayDiagnostics() { return CurPool != nullptr; }
/// Returns the current delayed-diagnostics pool.
sema::DelayedDiagnosticPool *getCurrentPool() const {
return CurPool;
}
/// Enter a new scope. Access and deprecation diagnostics will be
/// collected in this pool.
DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = &pool;
return state;
}
/// Leave a delayed-diagnostic state that was previously pushed.
/// Do not emit any of the diagnostics. This is performed as part
/// of the bookkeeping of popping a pool "properly".
void popWithoutEmitting(DelayedDiagnosticsState state) {
CurPool = state.SavedPool;
}
/// Enter a new scope where access and deprecation diagnostics are
/// not delayed.
DelayedDiagnosticsState pushUndelayed() {
DelayedDiagnosticsState state;
state.SavedPool = CurPool;
CurPool = nullptr;
return state;
}
/// Undo a previous pushUndelayed().
void popUndelayed(DelayedDiagnosticsState state) {
assert(CurPool == nullptr);
CurPool = state.SavedPool;
}
} DelayedDiagnostics;
/// A RAII object to temporarily push a declaration context.
class ContextRAII {
private:
Sema &S;
DeclContext *SavedContext;
ProcessingContextState SavedContextState;
QualType SavedCXXThisTypeOverride;
public:
ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
: S(S), SavedContext(S.CurContext),
SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
SavedCXXThisTypeOverride(S.CXXThisTypeOverride)
{
assert(ContextToPush && "pushing null context");
S.CurContext = ContextToPush;
if (NewThisContext)
S.CXXThisTypeOverride = QualType();
}
void pop() {
if (!SavedContext) return;
S.CurContext = SavedContext;
S.DelayedDiagnostics.popUndelayed(SavedContextState);
S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
SavedContext = nullptr;
}
~ContextRAII() {
pop();
}
};
/// \brief RAII object to handle the state changes required to synthesize
/// a function body.
class SynthesizedFunctionScope {
Sema &S;
Sema::ContextRAII SavedContext;
public:
SynthesizedFunctionScope(Sema &S, DeclContext *DC)
: S(S), SavedContext(S, DC)
{
S.PushFunctionScope();
S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
}
~SynthesizedFunctionScope() {
S.PopExpressionEvaluationContext();
S.PopFunctionScopeInfo();
}
};
/// WeakUndeclaredIdentifiers - Identifiers contained in
/// \#pragma weak before declared. rare. may alias another
/// identifier, declared or undeclared
llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers;
/// ExtnameUndeclaredIdentifiers - Identifiers contained in
/// \#pragma redefine_extname before declared. Used in Solaris system headers
/// to define functions that occur in multiple standards to call the version
/// in the currently selected standard.
llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
/// \brief Load weak undeclared identifiers from the external source.
void LoadExternalWeakUndeclaredIdentifiers();
/// WeakTopLevelDecl - Translation-unit scoped declarations generated by
/// \#pragma weak during processing of other Decls.
/// I couldn't figure out a clean way to generate these in-line, so
/// we store them here and handle separately -- which is a hack.
/// It would be best to refactor this.
SmallVector<Decl*,2> WeakTopLevelDecl;
IdentifierResolver IdResolver;
/// Translation Unit Scope - useful to Objective-C actions that need
/// to lookup file scope declarations in the "ordinary" C decl namespace.
/// For example, user-defined classes, built-in "id" type, etc.
Scope *TUScope;
/// \brief The C++ "std" namespace, where the standard library resides.
LazyDeclPtr StdNamespace;
/// \brief The C++ "std::bad_alloc" class, which is defined by the C++
/// standard library.
LazyDeclPtr StdBadAlloc;
/// \brief The C++ "std::initializer_list" template, which is defined in
/// \<initializer_list>.
ClassTemplateDecl *StdInitializerList;
/// \brief The C++ "type_info" declaration, which is defined in \<typeinfo>.
RecordDecl *CXXTypeInfoDecl;
/// \brief The MSVC "_GUID" struct, which is defined in MSVC header files.
RecordDecl *MSVCGuidDecl;
/// \brief Caches identifiers/selectors for NSFoundation APIs.
// std::unique_ptr<NSAPI> NSAPIObj; // HLSL Change
/// \brief The declaration of the Objective-C NSNumber class.
ObjCInterfaceDecl *NSNumberDecl;
/// \brief The declaration of the Objective-C NSValue class.
ObjCInterfaceDecl *NSValueDecl;
/// \brief Pointer to NSNumber type (NSNumber *).
QualType NSNumberPointer;
/// \brief Pointer to NSValue type (NSValue *).
QualType NSValuePointer;
/// \brief The Objective-C NSNumber methods used to create NSNumber literals.
ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
/// \brief The declaration of the Objective-C NSString class.
ObjCInterfaceDecl *NSStringDecl;
/// \brief Pointer to NSString type (NSString *).
QualType NSStringPointer;
/// \brief The declaration of the stringWithUTF8String: method.
ObjCMethodDecl *StringWithUTF8StringMethod;
/// \brief The declaration of the valueWithBytes:objCType: method.
ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
/// \brief The declaration of the Objective-C NSArray class.
ObjCInterfaceDecl *NSArrayDecl;
/// \brief The declaration of the arrayWithObjects:count: method.
ObjCMethodDecl *ArrayWithObjectsMethod;
/// \brief The declaration of the Objective-C NSDictionary class.
ObjCInterfaceDecl *NSDictionaryDecl;
/// \brief The declaration of the dictionaryWithObjects:forKeys:count: method.
ObjCMethodDecl *DictionaryWithObjectsMethod;
/// \brief id<NSCopying> type.
QualType QIDNSCopying;
/// \brief will hold 'respondsToSelector:'
Selector RespondsToSelectorSel;
/// \brief counter for internal MS Asm label names.
unsigned MSAsmLabelNameCounter;
/// A flag to remember whether the implicit forms of operator new and delete
/// have been declared.
bool GlobalNewDeleteDeclared;
/// A flag to indicate that we're in a context that permits abstract
/// references to fields. This is really a
bool AllowAbstractFieldReference;
/// \brief Describes how the expressions currently being parsed are
/// evaluated at run-time, if at all.
enum ExpressionEvaluationContext {
/// \brief The current expression and its subexpressions occur within an
/// unevaluated operand (C++11 [expr]p7), such as the subexpression of
/// \c sizeof, where the type of the expression may be significant but
/// no code will be generated to evaluate the value of the expression at
/// run time.
Unevaluated,
/// \brief The current expression occurs within an unevaluated
/// operand that unconditionally permits abstract references to
/// fields, such as a SIZE operator in MS-style inline assembly.
UnevaluatedAbstract,
/// \brief The current context is "potentially evaluated" in C++11 terms,
/// but the expression is evaluated at compile-time (like the values of
/// cases in a switch statement).
ConstantEvaluated,
/// \brief The current expression is potentially evaluated at run time,
/// which means that code may be generated to evaluate the value of the
/// expression at run time.
PotentiallyEvaluated,
/// \brief The current expression is potentially evaluated, but any
/// declarations referenced inside that expression are only used if
/// in fact the current expression is used.
///
/// This value is used when parsing default function arguments, for which
/// we would like to provide diagnostics (e.g., passing non-POD arguments
/// through varargs) but do not want to mark declarations as "referenced"
/// until the default argument is used.
PotentiallyEvaluatedIfUsed
};
/// \brief Data structure used to record current or nested
/// expression evaluation contexts.
struct ExpressionEvaluationContextRecord {
/// \brief The expression evaluation context.
ExpressionEvaluationContext Context;
/// \brief Whether the enclosing context needed a cleanup.
bool ParentNeedsCleanups;
/// \brief Whether we are in a decltype expression.
bool IsDecltype;
/// \brief The number of active cleanup objects when we entered
/// this expression evaluation context.
unsigned NumCleanupObjects;
/// \brief The number of typos encountered during this expression evaluation
/// context (i.e. the number of TypoExprs created).
unsigned NumTypos;
llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs;
/// \brief The lambdas that are present within this context, if it
/// is indeed an unevaluated context.
SmallVector<LambdaExpr *, 2> Lambdas;
/// \brief The declaration that provides context for lambda expressions
/// and block literals if the normal declaration context does not
/// suffice, e.g., in a default function argument.
Decl *ManglingContextDecl;
/// \brief The context information used to mangle lambda expressions
/// and block literals within this context.
///
/// This mangling information is allocated lazily, since most contexts
/// do not have lambda expressions or block literals.
IntrusiveRefCntPtr<MangleNumberingContext> MangleNumbering;
/// \brief If we are processing a decltype type, a set of call expressions
/// for which we have deferred checking the completeness of the return type.
SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
/// \brief If we are processing a decltype type, a set of temporary binding
/// expressions for which we have deferred checking the destructor.
SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
unsigned NumCleanupObjects,
bool ParentNeedsCleanups,
Decl *ManglingContextDecl,
bool IsDecltype)
: Context(Context), ParentNeedsCleanups(ParentNeedsCleanups),
IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects),
NumTypos(0),
ManglingContextDecl(ManglingContextDecl), MangleNumbering() { }
/// \brief Retrieve the mangling numbering context, used to consistently
/// number constructs like lambdas for mangling.
MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx);
bool isUnevaluated() const {
return Context == Unevaluated || Context == UnevaluatedAbstract;
}
};
/// A stack of expression evaluation contexts.
SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
/// \brief Compute the mangling number context for a lambda expression or
/// block literal.
///
/// \param DC - The DeclContext containing the lambda expression or
/// block literal.
/// \param[out] ManglingContextDecl - Returns the ManglingContextDecl
/// associated with the context, if relevant.
MangleNumberingContext *getCurrentMangleNumberContext(
const DeclContext *DC,
Decl *&ManglingContextDecl);
/// SpecialMemberOverloadResult - The overloading result for a special member
/// function.
///
/// This is basically a wrapper around PointerIntPair. The lowest bits of the
/// integer are used to determine whether overload resolution succeeded.
class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode {
public:
enum Kind {
NoMemberOrDeleted,
Ambiguous,
Success
};
private:
llvm::PointerIntPair<CXXMethodDecl*, 2> Pair;
public:
SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID)
: FastFoldingSetNode(ID)
{}
CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
void setKind(Kind K) { Pair.setInt(K); }
};
/// \brief A cache of special member function overload resolution results
/// for C++ records.
llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache;
/// \brief The kind of translation unit we are processing.
///
/// When we're processing a complete translation unit, Sema will perform
/// end-of-translation-unit semantic tasks (such as creating
/// initializers for tentative definitions in C) once parsing has
/// completed. Modules and precompiled headers perform different kinds of
/// checks.
TranslationUnitKind TUKind;
llvm::BumpPtrAllocator BumpAlloc;
/// \brief The number of SFINAE diagnostics that have been trapped.
unsigned NumSFINAEErrors;
typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
UnparsedDefaultArgInstantiationsMap;
/// \brief A mapping from parameters with unparsed default arguments to the
/// set of instantiations of each parameter.
///
/// This mapping is a temporary data structure used when parsing
/// nested class templates or nested classes of class templates,
/// where we might end up instantiating an inner class before the
/// default arguments of its methods have been parsed.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
// Contains the locations of the beginning of unparsed default
// argument locations.
llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
/// UndefinedInternals - all the used, undefined objects which require a
/// definition in this translation unit.
llvm::DenseMap<NamedDecl *, SourceLocation> UndefinedButUsed;
/// Obtain a sorted list of functions that are undefined but ODR-used.
void getUndefinedButUsed(
SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
/// Retrieves list of suspicious delete-expressions that will be checked at
/// the end of translation unit.
const llvm::MapVector<FieldDecl *, DeleteLocs> &
getMismatchingDeleteExpressions() const;
typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods;
typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool;
/// Method Pool - allows efficient lookup when typechecking messages to "id".
/// We need to maintain a list, since selectors can have differing signatures
/// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
/// of selectors are "overloaded").
/// At the head of the list it is recorded whether there were 0, 1, or >= 2
/// methods inside categories with a particular selector.
GlobalMethodPool MethodPool;
/// Method selectors used in a \@selector expression. Used for implementation
/// of -Wselector.
llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
/// Kinds of C++ special members.
enum CXXSpecialMember {
CXXDefaultConstructor,
CXXCopyConstructor,
CXXMoveConstructor,
CXXCopyAssignment,
CXXMoveAssignment,
CXXDestructor,
CXXInvalid
};
typedef std::pair<CXXRecordDecl*, CXXSpecialMember> SpecialMemberDecl;
/// The C++ special members which we are currently in the process of
/// declaring. If this process recursively triggers the declaration of the
/// same special member, we should act as if it is not yet declared.
llvm::SmallSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
void ReadMethodPool(Selector Sel);
/// Private Helper predicate to check for 'self'.
bool isSelfExpr(Expr *RExpr);
bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
/// \brief Cause the active diagnostic on the DiagosticsEngine to be
/// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
/// should not be used elsewhere.
void EmitCurrentDiagnostic(unsigned DiagID);
/// Records and restores the FP_CONTRACT state on entry/exit of compound
/// statements.
class FPContractStateRAII {
public:
FPContractStateRAII(Sema& S)
: S(S), OldFPContractState(S.FPFeatures.fp_contract) {}
~FPContractStateRAII() {
S.FPFeatures.fp_contract = OldFPContractState;
}
private:
Sema& S;
bool OldFPContractState : 1;
};
void addImplicitTypedef(StringRef Name, QualType T);
public:
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
TranslationUnitKind TUKind = TU_Complete,
CodeCompleteConsumer *CompletionConsumer = nullptr);
~Sema();
/// \brief Perform initialization that occurs after the parser has been
/// initialized but before it parses anything.
void Initialize();
const LangOptions &getLangOpts() const { return LangOpts; }
OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
FPOptions &getFPOptions() { return FPFeatures; }
DiagnosticsEngine &getDiagnostics() const { return Diags; }
SourceManager &getSourceManager() const { return SourceMgr; }
Preprocessor &getPreprocessor() const { return PP; }
ASTContext &getASTContext() const { return Context; }
ASTConsumer &getASTConsumer() const { return Consumer; }
ASTMutationListener *getASTMutationListener() const;
ExternalSemaSource* getExternalSource() const { return ExternalSource; }
///\brief Registers an external source. If an external source already exists,
/// creates a multiplex external source and appends to it.
///
///\param[in] E - A non-null external sema source.
///
void addExternalSource(ExternalSemaSource *E);
void PrintStats() const;
/// \brief Helper class that creates diagnostics with optional
/// template instantiation stacks.
///
/// This class provides a wrapper around the basic DiagnosticBuilder
/// class that emits diagnostics. SemaDiagnosticBuilder is
/// responsible for emitting the diagnostic (as DiagnosticBuilder
/// does) and, if the diagnostic comes from inside a template
/// instantiation, printing the template instantiation stack as
/// well.
class SemaDiagnosticBuilder : public DiagnosticBuilder {
Sema &SemaRef;
unsigned DiagID;
public:
SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
: DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { }
~SemaDiagnosticBuilder() {
// If we aren't active, there is nothing to do.
if (!isActive()) return;
// Otherwise, we need to emit the diagnostic. First flush the underlying
// DiagnosticBuilder data, and clear the diagnostic builder itself so it
// won't emit the diagnostic in its own destructor.
//
// This seems wasteful, in that as written the DiagnosticBuilder dtor will
// do its own needless checks to see if the diagnostic needs to be
// emitted. However, because we take care to ensure that the builder
// objects never escape, a sufficiently smart compiler will be able to
// eliminate that code.
FlushCounts();
Clear();
// Dispatch to Sema to emit the diagnostic.
SemaRef.EmitCurrentDiagnostic(DiagID);
}
/// Teach operator<< to produce an object of the correct type.
template<typename T>
friend const SemaDiagnosticBuilder &operator<<(
const SemaDiagnosticBuilder &Diag, const T &Value) {
const DiagnosticBuilder &BaseDiag = Diag;
BaseDiag << Value;
return Diag;
}
};
/// \brief Emit a diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) {
DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
return SemaDiagnosticBuilder(DB, *this, DiagID);
}
/// \brief Emit a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD);
/// \brief Build a partial diagnostic.
PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
bool findMacroSpelling(SourceLocation &loc, StringRef name);
/// \brief Get a string to suggest for zero-initialization of a type.
std::string
getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
/// \brief Calls \c Lexer::getLocForEndOfToken()
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
/// \brief Retrieve the module loader associated with the preprocessor.
ModuleLoader &getModuleLoader() const;
void emitAndClearUnusedLocalTypedefWarnings();
void ActOnEndOfTranslationUnit();
void CheckDelegatingCtorCycles();
Scope *getScopeForContext(DeclContext *Ctx);
void PushFunctionScope();
void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
sema::LambdaScopeInfo *PushLambdaScope();
/// \brief This is used to inform Sema what the current TemplateParameterDepth
/// is during Parsing. Currently it is used to pass on the depth
/// when parsing generic lambda 'auto' parameters.
void RecordParsingTemplateParameterDepth(unsigned Depth);
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
RecordDecl *RD,
CapturedRegionKind K);
void
PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
const Decl *D = nullptr,
const BlockExpr *blkExpr = nullptr);
sema::FunctionScopeInfo *getCurFunction() const {
return FunctionScopes.back();
}
sema::FunctionScopeInfo *getEnclosingFunction() const {
if (FunctionScopes.empty())
return nullptr;
for (int e = FunctionScopes.size()-1; e >= 0; --e) {
if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
continue;
return FunctionScopes[e];
}
return nullptr;
}
template <typename ExprT>
void recordUseOfEvaluatedWeak(const ExprT *E, bool IsRead=true) {
if (!isUnevaluatedContext())
getCurFunction()->recordUseOfWeak(E, IsRead);
}
void PushCompoundScope();
void PopCompoundScope();
sema::CompoundScopeInfo &getCurCompoundScope() const;
bool hasAnyUnrecoverableErrorsInThisFunction() const;
/// \brief Retrieve the current block, if any.
sema::BlockScopeInfo *getCurBlock();
/// \brief Retrieve the current lambda scope info, if any.
sema::LambdaScopeInfo *getCurLambda();
/// \brief Retrieve the current generic lambda info, if any.
sema::LambdaScopeInfo *getCurGenericLambda();
/// \brief Retrieve the current captured region, if any.
sema::CapturedRegionScopeInfo *getCurCapturedRegion();
/// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
void ActOnComment(SourceRange Comment);
//===--------------------------------------------------------------------===//
// Type Analysis / Processing: SemaType.cpp.
//
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
const DeclSpec *DS = nullptr);
QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
const DeclSpec *DS = nullptr);
QualType BuildPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildReferenceType(QualType T, bool LValueRef,
SourceLocation Loc, DeclarationName Entity);
QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
Expr *ArraySize, unsigned Quals,
SourceRange Brackets, DeclarationName Entity);
QualType BuildExtVectorType(QualType T, Expr *ArraySize,
SourceLocation AttrLoc);
bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
unsigned deduceWeakPropertyFromType(QualType T) {
if ((getLangOpts().getGC() != LangOptions::NonGC &&
T.isObjCGCWeak()) ||
(getLangOpts().ObjCAutoRefCount &&
T.getObjCLifetime() == Qualifiers::OCL_Weak))
return ObjCDeclSpec::DQ_PR_weak;
return 0;
}
/// \brief Build a function type.
///
/// This routine checks the function type according to C++ rules and
/// under the assumption that the result type and parameter types have
/// just been instantiated from a template. It therefore duplicates
/// some of the behavior of GetTypeForDeclarator, but in a much
/// simpler form that is only suitable for this narrow use case.
///
/// \param T The return type of the function.
///
/// \param ParamTypes The parameter types of the function. This array
/// will be modified to account for adjustments to the types of the
/// function parameters.
///
/// \param Loc The location of the entity whose type involves this
/// function type or, if there is no such entity, the location of the
/// type that will have function type.
///
/// \param Entity The name of the entity that involves the function
/// type, if known.
///
/// \param EPI Extra information about the function type. Usually this will
/// be taken from an existing function with the same prototype.
///
/// \returns A suitable function type, if there are no errors. The
/// unqualified type will always be a FunctionProtoType.
/// Otherwise, returns a NULL type.
// HLSL Change - FIX - We should move param mods to parameter QualTypes
QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes,
SourceLocation Loc, DeclarationName Entity,
const FunctionProtoType::ExtProtoInfo &EPI,
ArrayRef<hlsl::ParameterModifier> ParamMods);
// HLSL Change - End
QualType BuildMemberPointerType(QualType T, QualType Class,
SourceLocation Loc,
DeclarationName Entity);
QualType BuildBlockPointerType(QualType T,
SourceLocation Loc, DeclarationName Entity);
QualType BuildParenType(QualType T);
QualType BuildAtomicType(QualType T, SourceLocation Loc);
TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
TypeSourceInfo *ReturnTypeInfo);
/// \brief Package the given type and TSI into a ParsedType.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
DeclarationNameInfo GetNameForDeclarator(Declarator &D);
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
static QualType GetTypeFromParser(ParsedType Ty,
TypeSourceInfo **TInfo = nullptr);
CanThrowResult canThrow(const Expr *E);
const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
const FunctionProtoType *FPT);
void UpdateExceptionSpec(FunctionDecl *FD,
const FunctionProtoType::ExceptionSpecInfo &ESI);
bool CheckSpecifiedExceptionType(QualType &T, const SourceRange &Range);
bool CheckDistantExceptionSpec(QualType T);
bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
bool CheckEquivalentExceptionSpec(
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc);
bool CheckEquivalentExceptionSpec(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Old, SourceLocation OldLoc,
const FunctionProtoType *New, SourceLocation NewLoc,
bool *MissingExceptionSpecification = nullptr,
bool *MissingEmptyExceptionSpecification = nullptr,
bool AllowNoexceptAllMatchWithNoSpec = false,
bool IsOperatorNew = false);
bool CheckExceptionSpecSubset(
const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
const FunctionProtoType *Superset, SourceLocation SuperLoc,
const FunctionProtoType *Subset, SourceLocation SubLoc);
bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID,
const FunctionProtoType *Target, SourceLocation TargetLoc,
const FunctionProtoType *Source, SourceLocation SourceLoc);
TypeResult ActOnTypeName(Scope *S, Declarator &D);
/// \brief The parser has parsed the context-sensitive type 'instancetype'
/// in an Objective-C message declaration. Return the appropriate type.
ParsedType ActOnObjCInstanceType(SourceLocation Loc);
/// \brief Abstract class used to diagnose incomplete types.
struct TypeDiagnoser {
bool Suppressed;
TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { }
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
virtual ~TypeDiagnoser() {}
};
static int getPrintable(int I) { return I; }
static unsigned getPrintable(unsigned I) { return I; }
static bool getPrintable(bool B) { return B; }
static const char * getPrintable(const char *S) { return S; }
static StringRef getPrintable(StringRef S) { return S; }
static const std::string &getPrintable(const std::string &S) { return S; }
static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
return II;
}
static DeclarationName getPrintable(DeclarationName N) { return N; }
static QualType getPrintable(QualType T) { return T; }
static SourceRange getPrintable(SourceRange R) { return R; }
static SourceRange getPrintable(SourceLocation L) { return L; }
static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
unsigned DiagID;
std::tuple<const Ts &...> Args;
template <std::size_t... Is>
void emit(const SemaDiagnosticBuilder &DB,
llvm::index_sequence<Is...>) const {
// Apply all tuple elements to the builder in order.
bool Dummy[] = {(DB << getPrintable(std::get<Is>(Args)))...};
(void)Dummy;
}
public:
BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
: TypeDiagnoser(DiagID == 0), DiagID(DiagID), Args(Args...) {}
void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
if (Suppressed)
return;
const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
emit(DB, llvm::index_sequence_for<Ts...>());
DB << T;
}
};
private:
bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
VisibleModuleSet VisibleModules;
llvm::SmallVector<VisibleModuleSet, 16> VisibleModulesStack;
Module *CachedFakeTopLevelModule;
public:
/// \brief Get the module owning an entity.
Module *getOwningModule(Decl *Entity);
/// \brief Make a merged definition of an existing hidden definition \p ND
/// visible at the specified location.
void makeMergedDefinitionVisible(NamedDecl *ND, SourceLocation Loc);
bool isModuleVisible(Module *M) { return VisibleModules.isVisible(M); }
/// Determine whether a declaration is visible to name lookup.
bool isVisible(const NamedDecl *D) {
return !D->isHidden() || isVisibleSlow(D);
}
bool hasVisibleMergedDefinition(NamedDecl *Def);
/// Determine if \p D has a visible definition. If not, suggest a declaration
/// that should be made visible to expose the definition.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
bool OnlyNeedComplete = false);
bool hasVisibleDefinition(const NamedDecl *D) {
NamedDecl *Hidden;
return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
}
/// Determine if the template parameter \p D has a visible default argument.
bool
hasVisibleDefaultArgument(const NamedDecl *D,
llvm::SmallVectorImpl<Module *> *Modules = nullptr);
bool RequireCompleteType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireCompleteType(SourceLocation Loc, QualType T,
unsigned DiagID);
template <typename... Ts>
bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteType(Loc, T, Diagnoser);
}
bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser);
bool RequireCompleteExprType(Expr *E, unsigned DiagID);
template <typename... Ts>
bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireCompleteExprType(E, Diagnoser);
}
bool RequireLiteralType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
template <typename... Ts>
bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireLiteralType(Loc, T, Diagnoser);
}
QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
const CXXScopeSpec &SS, QualType T);
QualType BuildTypeofExprType(Expr *E, SourceLocation Loc);
/// If AsUnevaluated is false, E is treated as though it were an evaluated
/// context, such as when building a type for decltype(auto).
QualType BuildDecltypeType(Expr *E, SourceLocation Loc,
bool AsUnevaluated = true);
QualType BuildUnaryTransformType(QualType BaseType,
UnaryTransformType::UTTKind UKind,
SourceLocation Loc);
//===--------------------------------------------------------------------===//
// Symbol table / Decl tracking callbacks: SemaDecl.cpp.
//
/// List of decls defined in a function prototype. This contains EnumConstants
/// that incorrectly end up in translation unit scope because there is no
/// function to pin them on. ActOnFunctionDeclarator reads this list and patches
/// them into the FunctionDecl.
std::vector<NamedDecl*> DeclsInPrototypeScope;
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
void DiagnoseUseOfUnimplementedSelectors();
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec *SS = nullptr,
bool isClassName = false,
bool HasTrailingDot = false,
ParsedType ObjectType = ParsedType(),
bool IsCtorOrDtorName = false,
bool WantNontrivialTypeSourceInfo = false,
IdentifierInfo **CorrectedII = nullptr);
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
void DiagnoseUnknownTypeName(IdentifierInfo *&II,
SourceLocation IILoc,
Scope *S,
CXXScopeSpec *SS,
ParsedType &SuggestedType,
bool AllowClassTemplates = false);
/// \brief For compatibility with MSVC, we delay parsing of some default
/// template type arguments until instantiation time. Emits a warning and
/// returns a synthesized DependentNameType that isn't really dependent on any
/// other template arguments.
ParsedType ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
SourceLocation NameLoc);
/// \brief Describes the result of the name lookup and resolution performed
/// by \c ClassifyName().
enum NameClassificationKind {
NC_Unknown,
NC_Error,
NC_Keyword,
NC_Type,
NC_Expression,
NC_NestedNameSpecifier,
NC_TypeTemplate,
NC_VarTemplate,
NC_FunctionTemplate
};
class NameClassification {
NameClassificationKind Kind;
ExprResult Expr;
TemplateName Template;
ParsedType Type;
explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
public:
NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {}
NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
NameClassification(const IdentifierInfo *)
: Kind(NC_Keyword) {
}
static NameClassification Error() {
return NameClassification(NC_Error);
}
static NameClassification Unknown() {
return NameClassification(NC_Unknown);
}
static NameClassification NestedNameSpecifier() {
return NameClassification(NC_NestedNameSpecifier);
}
static NameClassification TypeTemplate(TemplateName Name) {
NameClassification Result(NC_TypeTemplate);
Result.Template = Name;
return Result;
}
static NameClassification VarTemplate(TemplateName Name) {
NameClassification Result(NC_VarTemplate);
Result.Template = Name;
return Result;
}
static NameClassification FunctionTemplate(TemplateName Name) {
NameClassification Result(NC_FunctionTemplate);
Result.Template = Name;
return Result;
}
NameClassificationKind getKind() const { return Kind; }
ParsedType getType() const {
assert(Kind == NC_Type);
return Type;
}
ExprResult getExpression() const {
assert(Kind == NC_Expression);
return Expr;
}
TemplateName getTemplateName() const {
assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||
Kind == NC_VarTemplate);
return Template;
}
TemplateNameKind getTemplateNameKind() const {
switch (Kind) {
case NC_TypeTemplate:
return TNK_Type_template;
case NC_FunctionTemplate:
return TNK_Function_template;
case NC_VarTemplate:
return TNK_Var_template;
default:
llvm_unreachable("unsupported name classification.");
}
}
};
/// \brief Perform name lookup on the given name, classifying it based on
/// the results of name lookup and the following token.
///
/// This routine is used by the parser to resolve identifiers and help direct
/// parsing. When the identifier cannot be found, this routine will attempt
/// to correct the typo and classify based on the resulting name.
///
/// \param S The scope in which we're performing name lookup.
///
/// \param SS The nested-name-specifier that precedes the name.
///
/// \param Name The identifier. If typo correction finds an alternative name,
/// this pointer parameter will be updated accordingly.
///
/// \param NameLoc The location of the identifier.
///
/// \param NextToken The token following the identifier. Used to help
/// disambiguate the name.
///
/// \param IsAddressOfOperand True if this name is the operand of a unary
/// address of ('&') expression, assuming it is classified as an
/// expression.
///
/// \param CCC The correction callback, if typo correction is desired.
NameClassification
ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
SourceLocation NameLoc, const Token &NextToken,
bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr);
Decl *ActOnDeclarator(Scope *S, Declarator &D);
NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParameterLists);
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
DeclarationName Name,
SourceLocation Loc);
void
diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
SourceLocation FallbackLoc,
SourceLocation ConstQualLoc = SourceLocation(),
SourceLocation VolatileQualLoc = SourceLocation(),
SourceLocation RestrictQualLoc = SourceLocation(),
SourceLocation AtomicQualLoc = SourceLocation());
static bool adjustContextForLocalExternDecl(DeclContext *&DC);
void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R);
void CheckShadow(Scope *S, VarDecl *D);
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
TypedefNameDecl *NewTD);
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous);
NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
LookupResult &Previous, bool &Redeclaration);
// HLSL Change Starts
// This enumeration is used to determine whether a variable declaration
// should shadow a prior declaration rather than merging.
enum ShadowMergeState {
ShadowMergeState_Disallowed, // shadowing is not allowed
ShadowMergeState_Possible, // shadowing is possible (but may not occur)
ShadowMergeState_Effective // the declaration should shadow a prior one
};
// HLSL Change Ends
NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope,
ShadowMergeState MergeState = ShadowMergeState_Disallowed); // HLSL Change - add merge state
// Returns true if the variable declaration is a redeclaration
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous, ShadowMergeState MergeState = ShadowMergeState_Disallowed); // HLSL Change - add merge state
void CheckVariableDeclarationType(VarDecl *NewVD);
void CheckCompleteVariableDeclaration(VarDecl *var);
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
TypeSourceInfo *TInfo,
LookupResult &Previous,
MultiTemplateParamsArg TemplateParamLists,
bool &AddToScope);
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
bool CheckConstexprFunctionDecl(const FunctionDecl *FD);
bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body);
void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
void FindHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
// Returns true if the function declaration is a redeclaration
bool CheckFunctionDeclaration(Scope *S,
FunctionDecl *NewFD, LookupResult &Previous,
bool IsExplicitSpecialization);
void CheckMain(FunctionDecl *FD, const DeclSpec &D);
void CheckMSVCRTEntryPoint(FunctionDecl *FD);
Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
SourceLocation Loc,
QualType T);
ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
SourceLocation NameLoc, IdentifierInfo *Name,
QualType T, TypeSourceInfo *TSInfo,
StorageClass SCm, hlsl::ParameterModifier ParamMod); // HLSL Change
void ActOnParamDefaultArgument(Decl *param,
SourceLocation EqualLoc,
Expr *defarg);
void ActOnParamUnparsedDefaultArgument(Decl *param,
SourceLocation EqualLoc,
SourceLocation ArgLoc);
void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
SourceLocation EqualLoc);
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit,
bool TypeMayContainAuto);
void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto);
void ActOnInitializerError(Decl *Dcl);
void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
void ActOnCXXForRangeDecl(Decl *D);
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
IdentifierInfo *Ident,
ParsedAttributes &Attrs,
SourceLocation AttrEnd);
void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
void FinalizeDeclaration(Decl *D);
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
ArrayRef<Decl *> Group);
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
bool TypeMayContainAuto = true);
/// Should be called on all declarations that might have attached
/// documentation comments.
void ActOnDocumentableDecl(Decl *D);
void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
SourceLocation LocAfterDecls);
void CheckForFunctionRedefinition(FunctionDecl *FD,
const FunctionDecl *EffectiveDefinition =
nullptr);
Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D);
Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D);
void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
bool isObjCMethodDecl(Decl *D) {
return D && isa<ObjCMethodDecl>(D);
}
/// \brief Determine whether we can delay parsing the body of a function or
/// function template until it is used, assuming we don't care about emitting
/// code for that function.
///
/// This will be \c false if we may need the body of the function in the
/// middle of parsing an expression (where it's impractical to switch to
/// parsing a different function), for instance, if it's constexpr in C++11
/// or has an 'auto' return type in C++14. These cases are essentially bugs.
bool canDelayFunctionBody(const Declarator &D);
/// \brief Determine whether we can skip parsing the body of a function
/// definition, assuming we don't care about analyzing its body or emitting
/// code for that function.
///
/// This will be \c false only if we may need the body of the function in
/// order to parse the rest of the program (for instance, if it is
/// \c constexpr in C++11 or has an 'auto' return type in C++14).
bool canSkipFunctionBody(Decl *D);
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
Decl *ActOnSkippedFunctionBody(Decl *Decl);
void ActOnFinishInlineMethodDef(CXXMethodDecl *D);
/// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
/// attribute for which parsing is delayed.
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
/// \brief Diagnose any unused parameters in the given sequence of
/// ParmVarDecl pointers.
void DiagnoseUnusedParameters(ParmVarDecl * const *Begin,
ParmVarDecl * const *End);
/// \brief Diagnose whether the size of parameters or return value of a
/// function or obj-c method definition is pass-by-value and larger than a
/// specified threshold.
void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin,
ParmVarDecl * const *End,
QualType ReturnTy,
NamedDecl *D);
void DiagnoseInvalidJumps(Stmt *Body);
Decl *ActOnFileScopeAsmDecl(Expr *expr,
SourceLocation AsmLoc,
SourceLocation RParenLoc);
/// \brief Handle a C++11 empty-declaration and attribute-declaration.
Decl *ActOnEmptyDeclaration(Scope *S,
AttributeList *AttrList,
SourceLocation SemiLoc);
/// \brief The parser has processed a module import declaration.
///
/// \param AtLoc The location of the '@' symbol, if any.
///
/// \param ImportLoc The location of the 'import' keyword.
///
/// \param Path The module access path.
DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc,
ModuleIdPath Path);
/// \brief The parser has processed a module import translated from a
/// #include or similar preprocessing directive.
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
/// \brief The parsed has entered a submodule.
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
/// \brief The parser has left a submodule.
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
/// \brief Create an implicit import of the given module at the given
/// source location, for error recovery, if possible.
///
/// This routine is typically used when an entity found by name lookup
/// is actually hidden within a module that we know about but the user
/// has forgotten to import.
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
Module *Mod);
/// Kinds of missing import. Note, the values of these enumerators correspond
/// to %select values in diagnostics.
enum class MissingImportKind {
Declaration,
Definition,
DefaultArgument
};
/// \brief Diagnose that the specified declaration needs to be visible but
/// isn't, and suggest a module import that would resolve the problem.
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
bool NeedDefinition, bool Recover = true);
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
SourceLocation DeclLoc, ArrayRef<Module *> Modules,
MissingImportKind MIK, bool Recover);
/// \brief Retrieve a suitable printing policy.
PrintingPolicy getPrintingPolicy() const {
return getPrintingPolicy(Context, PP);
}
/// \brief Retrieve a suitable printing policy.
static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
const Preprocessor &PP);
/// Scope actions.
void ActOnPopScope(SourceLocation Loc, Scope *S);
void ActOnTranslationUnitScope(Scope *S);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
DeclSpec &DS);
Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
DeclSpec &DS,
MultiTemplateParamsArg TemplateParams,
bool IsExplicitInstantiation = false);
Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
AccessSpecifier AS,
RecordDecl *Record,
const PrintingPolicy &Policy);
Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
RecordDecl *Record);
bool isAcceptableTagRedeclaration(const TagDecl *Previous,
TagTypeKind NewTag, bool isDefinition,
SourceLocation NewTagLoc,
const IdentifierInfo *Name);
enum TagUseKind {
TUK_Reference, // Reference to a tag: 'struct foo *X;'
TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
TUK_Friend // Friend declaration: 'friend struct foo;'
};
struct SkipBodyInfo {
SkipBodyInfo() : ShouldSkip(false), Previous(nullptr) {}
bool ShouldSkip;
NamedDecl *Previous;
};
Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *Attr, AccessSpecifier AS,
SourceLocation ModulePrivateLoc,
MultiTemplateParamsArg TemplateParameterLists,
bool &OwnedDecl, bool &IsDependent,
SourceLocation ScopedEnumKWLoc,
bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
bool IsTypeSpecifier, SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
unsigned TagSpec, SourceLocation TagLoc,
CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *Attr,
MultiTemplateParamsArg TempParamLists);
TypeResult ActOnDependentTag(Scope *S,
unsigned TagSpec,
TagUseKind TUK,
const CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation TagLoc,
SourceLocation NameLoc);
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
IdentifierInfo *ClassName,
SmallVectorImpl<Decl *> &Decls);
Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth);
FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS);
MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
AccessSpecifier AS,
AttributeList *MSPropertyAttr);
FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
TypeSourceInfo *TInfo,
RecordDecl *Record, SourceLocation Loc,
bool Mutable, Expr *BitfieldWidth,
InClassInitStyle InitStyle,
SourceLocation TSSL,
AccessSpecifier AS, NamedDecl *PrevDecl,
Declarator *D = nullptr);
bool CheckNontrivialField(FieldDecl *FD);
void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
bool Diagnose = false);
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD);
void ActOnLastBitfield(SourceLocation DeclStart,
SmallVectorImpl<Decl *> &AllIvarDecls);
Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
Declarator &D, Expr *BitfieldWidth,
tok::ObjCKeywordKind visibility);
// This is used for both record definitions and ObjC interface declarations.
void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl,
ArrayRef<Decl *> Fields,
SourceLocation LBrac, SourceLocation RBrac,
AttributeList *AttrList);
/// ActOnTagStartDefinition - Invoked when we have entered the
/// scope of a tag's definition (e.g., for an enumeration, class,
/// struct, or union).
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
typedef void *SkippedDefinitionContext;
/// \brief Invoked when we enter a tag definition that we're skipping.
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
/// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
/// C++ record definition's base-specifiers clause and are starting its
/// member declarations.
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
SourceLocation FinalLoc,
bool IsFinalSpelledSealed,
SourceLocation LBraceLoc);
/// ActOnTagFinishDefinition - Invoked once we have finished parsing
/// the definition of a tag (enumeration, class, struct, or union).
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
SourceLocation RBraceLoc);
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
void ActOnObjCContainerFinishDefinition();
/// \brief Invoked when we must temporarily exit the objective-c container
/// scope for parsing/looking-up C constructs.
///
/// Must be followed by a call to \see ActOnObjCReenterContainerContext
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
void ActOnObjCReenterContainerContext(DeclContext *DC);
/// ActOnTagDefinitionError - Invoked when there was an unrecoverable
/// error parsing the definition of a tag.
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
EnumConstantDecl *LastEnumConst,
SourceLocation IdLoc,
IdentifierInfo *Id,
Expr *val);
bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
QualType EnumUnderlyingTy, const EnumDecl *Prev);
/// Determine whether the body of an anonymous enumeration should be skipped.
/// \param II The name of the first enumerator.
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
SourceLocation IILoc);
Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
SourceLocation IdLoc, IdentifierInfo *Id,
AttributeList *Attrs,
SourceLocation EqualLoc, Expr *Val);
void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
SourceLocation RBraceLoc, Decl *EnumDecl,
ArrayRef<Decl *> Elements,
Scope *S, AttributeList *Attr);
DeclContext *getContainingDC(DeclContext *DC);
/// Set the current declaration context until it gets popped.
void PushDeclContext(Scope *S, DeclContext *DC);
void PopDeclContext();
/// EnterDeclaratorContext - Used when we must lookup names in the context
/// of a declarator's nested name specifier.
void EnterDeclaratorContext(Scope *S, DeclContext *DC);
void ExitDeclaratorContext(Scope *S);
/// Push the parameters of D, which must be a function, into scope.
void ActOnReenterFunctionContext(Scope* S, Decl* D);
void ActOnExitFunctionContext();
DeclContext *getFunctionLevelDeclContext();
/// getCurFunctionDecl - If inside of a function body, this returns a pointer
/// to the function decl for the function being parsed. If we're currently
/// in a 'block', this returns the containing context.
FunctionDecl *getCurFunctionDecl();
/// getCurMethodDecl - If inside of a method body, this returns a pointer to
/// the method decl for the method being parsed. If we're currently
/// in a 'block', this returns the containing context.
ObjCMethodDecl *getCurMethodDecl();
/// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
/// or C function we're in, otherwise return null. If we're currently
/// in a 'block', this returns the containing context.
NamedDecl *getCurFunctionOrMethodDecl();
/// Add this decl to the scope shadowed decl chains.
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
/// \brief Make the given externally-produced declaration visible at the
/// top level scope.
///
/// \param D The externally-produced declaration to push.
///
/// \param Name The name of the externally-produced declaration.
void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name);
/// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
/// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
/// true if 'D' belongs to the given declaration context.
///
/// \param AllowInlineNamespace If \c true, allow the declaration to be in the
/// enclosing namespace set of the context, rather than contained
/// directly within it.
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
bool AllowInlineNamespace = false);
/// Finds the scope corresponding to the given decl context, if it
/// happens to be an enclosing scope. Otherwise return NULL.
static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
/// Subroutines of ActOnDeclarator().
TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
TypeSourceInfo *TInfo);
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
/// Attribute merging methods. Return true if a new attribute was added.
AvailabilityAttr *mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
IdentifierInfo *Platform,
VersionTuple Introduced,
VersionTuple Deprecated,
VersionTuple Obsoleted,
bool IsUnavailable,
StringRef Message,
bool Override,
unsigned AttrSpellingListIndex);
TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
TypeVisibilityAttr::VisibilityType Vis,
unsigned AttrSpellingListIndex);
VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range,
VisibilityAttr::VisibilityType Vis,
unsigned AttrSpellingListIndex);
DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
MSInheritanceAttr *
mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase,
unsigned AttrSpellingListIndex,
MSInheritanceAttr::Spelling SemanticSpelling);
FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range,
IdentifierInfo *Format, int FormatIdx,
int FirstArg, unsigned AttrSpellingListIndex);
SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name,
unsigned AttrSpellingListIndex);
AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
IdentifierInfo *Ident,
unsigned AttrSpellingListIndex);
MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
unsigned AttrSpellingListIndex);
/// \brief Describes the kind of merge to perform for availability
/// attributes (including "deprecated", "unavailable", and "availability").
enum AvailabilityMergeKind {
/// \brief Don't merge availability attributes at all.
AMK_None,
/// \brief Merge availability attributes for a redeclaration, which requires
/// an exact match.
AMK_Redeclaration,
/// \brief Merge availability attributes for an override, which requires
/// an exact match or a weakening of constraints.
AMK_Override
};
void mergeDeclAttributes(NamedDecl *New, Decl *Old,
AvailabilityMergeKind AMK = AMK_Redeclaration);
void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls);
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
bool MergeTypeWithOld);
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
Scope *S, bool MergeTypeWithOld);
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
void MergeVarDecl(VarDecl *New, LookupResult &Previous, ShadowMergeState& MergeState); // HLSL Change - add merge state
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld, ShadowMergeState& MergeState); // HLSL Change - add merge state
void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
// AssignmentAction - This is used by all the assignment diagnostic functions
// to represent what is actually causing the operation
enum AssignmentAction {
AA_Assigning,
AA_Passing,
AA_Returning,
AA_Converting,
AA_Initializing,
AA_Sending,
AA_Casting,
AA_Passing_CFAudited
};
/// C++ Overloading.
enum OverloadKind {
/// This is a legitimate overload: the existing declarations are
/// functions or function templates with different signatures.
Ovl_Overload,
/// This is not an overload because the signature exactly matches
/// an existing declaration.
Ovl_Match,
/// This is not an overload because the lookup results contain a
/// non-function.
Ovl_NonFunction
};
OverloadKind CheckOverload(Scope *S,
FunctionDecl *New,
const LookupResult &OldDecls,
NamedDecl *&OldDecl,
bool IsForUsingDecl);
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl);
/// \brief Checks availability of the function depending on the current
/// function context.Inside an unavailable function,unavailability is ignored.
///
/// \returns true if \p FD is unavailable and current context is inside
/// an available function, false otherwise.
bool isFunctionConsideredUnavailable(FunctionDecl *FD);
ImplicitConversionSequence
TryImplicitConversion(Expr *From, QualType ToType,
bool SuppressUserConversions,
bool AllowExplicit,
bool InOverloadResolution,
bool CStyle,
bool AllowObjCWritebackConversion);
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
bool IsComplexPromotion(QualType FromType, QualType ToType);
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType, bool &IncompatibleObjC);
bool isObjCWritebackConversion(QualType FromType, QualType ToType,
QualType &ConvertedType);
bool IsBlockPointerConversion(QualType FromType, QualType ToType,
QualType& ConvertedType);
bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
const FunctionProtoType *NewType,
unsigned *ArgPos = nullptr);
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
QualType FromType, QualType ToType);
void maybeExtendBlockObject(ExprResult &E);
CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
bool CheckPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath& BasePath,
bool IgnoreBaseAccess);
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
bool InOverloadResolution,
QualType &ConvertedType);
bool CheckMemberPointerConversion(Expr *From, QualType ToType,
CastKind &Kind,
CXXCastPath &BasePath,
bool IgnoreBaseAccess);
bool IsQualificationConversion(QualType FromType, QualType ToType,
bool CStyle, bool &ObjCLifetimeConversion);
bool IsNoReturnConversion(QualType FromType, QualType ToType,
QualType &ResultTy);
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg);
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
const VarDecl *NRVOCandidate,
QualType ResultType,
Expr *Value,
bool AllowNRVO = true);
bool CanPerformCopyInitialization(const InitializedEntity &Entity,
ExprResult Init);
ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
SourceLocation EqualLoc,
ExprResult Init,
bool TopLevelOfInitList = false,
bool AllowExplicit = false);
ExprResult PerformObjectArgumentInitialization(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
CXXMethodDecl *Method);
ExprResult PerformContextuallyConvertToBool(Expr *From);
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
/// Contexts in which a converted constant expression is required.
enum CCEKind {
CCEK_CaseValue, ///< Expression in a case label.
CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
CCEK_TemplateArg, ///< Value of a non-type template parameter.
CCEK_NewExpr ///< Constant expression in a noptr-new-declarator.
};
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
llvm::APSInt &Value, CCEKind CCE);
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
APValue &Value, CCEKind CCE);
/// \brief Abstract base class used to perform a contextual implicit
/// conversion from an expression to any type passing a filter.
class ContextualImplicitConverter {
public:
bool Suppress;
bool SuppressConversion;
ContextualImplicitConverter(bool Suppress = false,
bool SuppressConversion = false)
: Suppress(Suppress), SuppressConversion(SuppressConversion) {}
/// \brief Determine whether the specified type is a valid destination type
/// for this conversion.
virtual bool match(QualType T) = 0;
/// \brief Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a diagnostic when the expression has incomplete class type.
virtual SemaDiagnosticBuilder
diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a diagnostic when the only matching conversion function
/// is explicit.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
/// \brief Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder
noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// \brief Emits a diagnostic when there are multiple possible conversion
/// functions.
virtual SemaDiagnosticBuilder
diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
/// \brief Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder
noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
/// \brief Emits a diagnostic when we picked a conversion function
/// (for cases when we are not allowed to pick a conversion function).
virtual SemaDiagnosticBuilder diagnoseConversion(
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
virtual ~ContextualImplicitConverter() {}
};
class ICEConvertDiagnoser : public ContextualImplicitConverter {
bool AllowScopedEnumerations;
public:
ICEConvertDiagnoser(bool AllowScopedEnumerations,
bool Suppress, bool SuppressConversion)
: ContextualImplicitConverter(Suppress, SuppressConversion),
AllowScopedEnumerations(AllowScopedEnumerations) {}
/// Match an integral or (possibly scoped) enumeration type.
bool match(QualType T) override;
SemaDiagnosticBuilder
diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
return diagnoseNotInt(S, Loc, T);
}
/// \brief Emits a diagnostic complaining that the expression does not have
/// integral or enumeration type.
virtual SemaDiagnosticBuilder
diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
};
/// Perform a contextual implicit conversion.
ExprResult PerformContextualImplicitConversion(
SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
enum ObjCSubscriptKind {
OS_Array,
OS_Dictionary,
OS_Error
};
ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
// Note that LK_String is intentionally after the other literals, as
// this is used for diagnostics logic.
enum ObjCLiteralKind {
LK_Array,
LK_Dictionary,
LK_Numeric,
LK_Boxed,
LK_String,
LK_Block,
LK_None
};
ObjCLiteralKind CheckLiteralKind(Expr *FromE);
ExprResult PerformObjectMemberConversion(Expr *From,
NestedNameSpecifier *Qualifier,
NamedDecl *FoundDecl,
NamedDecl *Member);
// Members have to be NamespaceDecl* or TranslationUnitDecl*.
// TODO: make this is a typesafe union.
typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet;
typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet;
void AddOverloadCandidate(FunctionDecl *Function,
DeclAccessPair FoundDecl,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false,
bool AllowExplicit = false);
void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddMethodCandidate(DeclAccessPair FoundDecl,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversion = false);
void AddMethodCandidate(CXXMethodDecl *Method,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext, QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ObjectType,
Expr::Classification ObjectClassification,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
DeclAccessPair FoundDecl,
TemplateArgumentListInfo *ExplicitTemplateArgs,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool SuppressUserConversions = false,
bool PartialOverloading = false);
void AddConversionCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
Expr *From, QualType ToType,
OverloadCandidateSet& CandidateSet,
bool AllowObjCConversionOnExplicit);
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
Expr *From, QualType ToType,
OverloadCandidateSet &CandidateSet,
bool AllowObjCConversionOnExplicit);
void AddSurrogateCandidate(CXXConversionDecl *Conversion,
DeclAccessPair FoundDecl,
CXXRecordDecl *ActingContext,
const FunctionProtoType *Proto,
Expr *Object, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
SourceRange OpRange = SourceRange());
void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet,
bool IsAssignmentOperator = false,
unsigned NumContextualBoolArguments = 0);
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
SourceLocation OpLoc, ArrayRef<Expr *> Args,
OverloadCandidateSet& CandidateSet);
void AddArgumentDependentLookupCandidates(DeclarationName Name,
SourceLocation Loc,
ArrayRef<Expr *> Args,
TemplateArgumentListInfo *ExplicitTemplateArgs,
OverloadCandidateSet& CandidateSet,
bool PartialOverloading = false);
// Emit as a 'note' the specific overload candidate
void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType());
// Emit as a series of 'note's all template and non-templates
// identified by the expression Expr
void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType());
/// Check the enable_if expressions on the given function. Returns the first
/// failing attribute, or NULL if they were all successful.
EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
bool MissingImplicitThis = false);
// [PossiblyAFunctionType] --> [Return]
// NonFunctionType --> NonFunctionType
// R (A) --> R(A)
// R (*)(A) --> R (A)
// R (&)(A) --> R (A)
// R (S::*)(A) --> R (A)
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
FunctionDecl *
ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
QualType TargetType,
bool Complain,
DeclAccessPair &Found,
bool *pHadMultipleCandidates = nullptr);
FunctionDecl *
ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
bool Complain = false,
DeclAccessPair *Found = nullptr);
bool ResolveAndFixSingleFunctionTemplateSpecialization(
ExprResult &SrcExpr,
bool DoFunctionPointerConverion = false,
bool Complain = false,
const SourceRange& OpRangeForComplaining = SourceRange(),
QualType DestTypeForComplaining = QualType(),
unsigned DiagIDForComplaining = 0);
Expr *FixOverloadedFunctionReference(Expr *E,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
ExprResult FixOverloadedFunctionReference(ExprResult,
DeclAccessPair FoundDecl,
FunctionDecl *Fn);
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool PartialOverloading = false);
// An enum used to represent the different possible results of building a
// range-based for loop.
enum ForRangeStatus {
FRS_Success,
FRS_NoViableFunction,
FRS_DiagnosticIssued
};
// An enum to represent whether something is dealing with a call to begin()
// or a call to end() in a range-based for loop.
enum BeginEndFunction {
BEF_begin,
BEF_end
};
ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
SourceLocation RangeLoc,
VarDecl *Decl,
BeginEndFunction BEF,
const DeclarationNameInfo &NameInfo,
LookupResult &MemberLookup,
OverloadCandidateSet *CandidateSet,
Expr *Range, ExprResult *CallExpr);
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
UnresolvedLookupExpr *ULE,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc,
Expr *ExecConfig,
bool AllowTypoCorrection=true);
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
MultiExprArg Args, SourceLocation RParenLoc,
OverloadCandidateSet *CandidateSet,
ExprResult *Result);
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
unsigned Opc,
const UnresolvedSetImpl &Fns,
Expr *input);
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
unsigned Opc,
const UnresolvedSetImpl &Fns,
Expr *LHS, Expr *RHS);
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
SourceLocation RLoc,
Expr *Base,Expr *Idx);
ExprResult
BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult
BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
MultiExprArg Args,
SourceLocation RParenLoc);
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool *NoArrowOperatorFound = nullptr);
/// CheckCallReturnType - Checks that a call expression's return type is
/// complete. Returns true on failure. The location passed in is the location
/// that best represents the call.
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
CallExpr *CE, FunctionDecl *FD);
/// Helpers for dealing with blocks and functions.
bool CheckParmsForFunctionDef(ParmVarDecl *const *Param,
ParmVarDecl *const *ParamEnd,
bool CheckParameterNames);
void CheckCXXDefaultArguments(FunctionDecl *FD);
void CheckExtraCXXDefaultArguments(Declarator &D);
Scope *getNonFieldDeclScope(Scope *S);
/// \name Name lookup
///
/// These routines provide name lookup that is used during semantic
/// analysis to resolve the various kinds of names (identifiers,
/// overloaded operator names, constructor names, etc.) into zero or
/// more declarations within a particular scope. The major entry
/// points are LookupName, which performs unqualified name lookup,
/// and LookupQualifiedName, which performs qualified name lookup.
///
/// All name lookup is performed based on some specific criteria,
/// which specify what names will be visible to name lookup and how
/// far name lookup should work. These criteria are important both
/// for capturing language semantics (certain lookups will ignore
/// certain names, for example) and for performance, since name
/// lookup is often a bottleneck in the compilation of C++. Name
/// lookup criteria is specified via the LookupCriteria enumeration.
///
/// The results of name lookup can vary based on the kind of name
/// lookup performed, the current language, and the translation
/// unit. In C, for example, name lookup will either return nothing
/// (no entity found) or a single declaration. In C++, name lookup
/// can additionally refer to a set of overloaded functions or
/// result in an ambiguity. All of the possible results of name
/// lookup are captured by the LookupResult class, which provides
/// the ability to distinguish among them.
//@{
/// @brief Describes the kind of name lookup to perform.
enum LookupNameKind {
/// Ordinary name lookup, which finds ordinary names (functions,
/// variables, typedefs, etc.) in C and most kinds of names
/// (functions, variables, members, types, etc.) in C++.
LookupOrdinaryName = 0,
/// Tag name lookup, which finds the names of enums, classes,
/// structs, and unions.
LookupTagName,
/// Label name lookup.
LookupLabel,
/// Member name lookup, which finds the names of
/// class/struct/union members.
LookupMemberName,
/// Look up of an operator name (e.g., operator+) for use with
/// operator overloading. This lookup is similar to ordinary name
/// lookup, but will ignore any declarations that are class members.
LookupOperatorName,
/// Look up of a name that precedes the '::' scope resolution
/// operator in C++. This lookup completely ignores operator, object,
/// function, and enumerator names (C++ [basic.lookup.qual]p1).
LookupNestedNameSpecifierName,
/// Look up a namespace name within a C++ using directive or
/// namespace alias definition, ignoring non-namespace names (C++
/// [basic.lookup.udir]p1).
LookupNamespaceName,
/// Look up all declarations in a scope with the given name,
/// including resolved using declarations. This is appropriate
/// for checking redeclarations for a using declaration.
LookupUsingDeclName,
/// Look up an ordinary name that is going to be redeclared as a
/// name with linkage. This lookup ignores any declarations that
/// are outside of the current scope unless they have linkage. See
/// C99 6.2.2p4-5 and C++ [basic.link]p6.
LookupRedeclarationWithLinkage,
/// Look up a friend of a local class. This lookup does not look
/// outside the innermost non-class scope. See C++11 [class.friend]p11.
LookupLocalFriendName,
/// Look up the name of an Objective-C protocol.
LookupObjCProtocolName,
/// Look up implicit 'self' parameter of an objective-c method.
LookupObjCImplicitSelfParam,
/// \brief Look up any declaration with any name.
LookupAnyName
};
/// \brief Specifies whether (or how) name lookup is being performed for a
/// redeclaration (vs. a reference).
enum RedeclarationKind {
/// \brief The lookup is a reference to this name that is not for the
/// purpose of redeclaring the name.
NotForRedeclaration = 0,
/// \brief The lookup results will be used for redeclaration of a name,
/// if an entity by that name already exists.
ForRedeclaration
};
/// \brief The possible outcomes of name lookup for a literal operator.
enum LiteralOperatorLookupResult {
/// \brief The lookup resulted in an error.
LOLR_Error,
/// \brief The lookup found a single 'cooked' literal operator, which
/// expects a normal literal to be built and passed to it.
LOLR_Cooked,
/// \brief The lookup found a single 'raw' literal operator, which expects
/// a string literal containing the spelling of the literal token.
LOLR_Raw,
/// \brief The lookup found an overload set of literal operator templates,
/// which expect the characters of the spelling of the literal token to be
/// passed as a non-type template argument pack.
LOLR_Template,
/// \brief The lookup found an overload set of literal operator templates,
/// which expect the character type and characters of the spelling of the
/// string literal token to be passed as template arguments.
LOLR_StringTemplate
};
SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D,
CXXSpecialMember SM,
bool ConstArg,
bool VolatileArg,
bool RValueThis,
bool ConstThis,
bool VolatileThis);
typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
TypoRecoveryCallback;
private:
bool CppLookupName(LookupResult &R, Scope *S);
struct TypoExprState {
std::unique_ptr<TypoCorrectionConsumer> Consumer;
TypoDiagnosticGenerator DiagHandler;
TypoRecoveryCallback RecoveryHandler;
TypoExprState();
TypoExprState(TypoExprState&& other) LLVM_NOEXCEPT;
TypoExprState& operator=(TypoExprState&& other) LLVM_NOEXCEPT;
};
/// \brief The set of unhandled TypoExprs and their associated state.
llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
/// \brief Creates a new TypoExpr AST node.
TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC);
// \brief The set of known/encountered (unique, canonicalized) NamespaceDecls.
//
// The boolean value will be true to indicate that the namespace was loaded
// from an AST/PCH file, or false otherwise.
llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
/// \brief Whether we have already loaded known namespaces from an extenal
/// source.
bool LoadedExternalKnownNamespaces;
/// \brief Helper for CorrectTypo and CorrectTypoDelayed used to create and
/// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
/// should be skipped entirely.
std::unique_ptr<TypoCorrectionConsumer>
makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
std::unique_ptr<CorrectionCandidateCallback> CCC,
DeclContext *MemberContext, bool EnteringContext,
const ObjCObjectPointerType *OPT,
bool ErrorRecovery);
/// HLSL Change Begin - back ported from llvm-project/c601377b2376.
bool addInstantiatedParametersToScope(
FunctionDecl *Function, const FunctionDecl *PatternDecl,
LocalInstantiationScope &Scope,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// HLSL Change End - back ported from llvm-project/c601377b2376.
public:
const TypoExprState &getTypoExprState(TypoExpr *TE) const;
/// \brief Clears the state of the given TypoExpr.
void clearDelayedTypo(TypoExpr *TE);
/// \brief Look up a name, looking for a single declaration. Return
/// null if the results were absent, ambiguous, or overloaded.
///
/// It is preferable to use the elaborated form and explicitly handle
/// ambiguity and overloaded.
NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
SourceLocation Loc,
LookupNameKind NameKind,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupName(LookupResult &R, Scope *S,
bool AllowBuiltinCreation = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
bool InUnqualifiedLookup = false);
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
CXXScopeSpec &SS);
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
bool AllowBuiltinCreation = false,
bool EnteringContext = false);
ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
RedeclarationKind Redecl
= NotForRedeclaration);
bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
QualType T1, QualType T2,
UnresolvedSetImpl &Functions);
void addOverloadedOperatorToUnresolvedSet(UnresolvedSetImpl &Functions,
DeclAccessPair Operator,
QualType T1, QualType T2);
LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
SourceLocation GnuLabelLoc = SourceLocation());
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
unsigned Quals);
CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
bool RValueThis, unsigned ThisQuals);
CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id);
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R,
ArrayRef<QualType> ArgTys,
bool AllowRaw,
bool AllowTemplate,
bool AllowStringTemplate);
bool isKnownName(StringRef name);
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
ArrayRef<Expr *> Args, ADLResult &Functions);
void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true);
void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
VisibleDeclConsumer &Consumer,
bool IncludeGlobalScope = true);
enum CorrectTypoKind {
CTK_NonError, // CorrectTypo used in a non error recovery situation.
CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
};
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind,
Scope *S, CXXScopeSpec *SS,
std::unique_ptr<CorrectionCandidateCallback> CCC,
CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr,
bool RecordFailure = true);
TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
Sema::LookupNameKind LookupKind, Scope *S,
CXXScopeSpec *SS,
std::unique_ptr<CorrectionCandidateCallback> CCC,
TypoDiagnosticGenerator TDG,
TypoRecoveryCallback TRC, CorrectTypoKind Mode,
DeclContext *MemberContext = nullptr,
bool EnteringContext = false,
const ObjCObjectPointerType *OPT = nullptr);
/// \brief Process any TypoExprs in the given Expr and its children,
/// generating diagnostics as appropriate and returning a new Expr if there
/// were typos that were all successfully corrected and ExprError if one or
/// more typos could not be corrected.
///
/// \param E The Expr to check for TypoExprs.
///
/// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
/// initializer.
///
/// \param Filter A function applied to a newly rebuilt Expr to determine if
/// it is an acceptable/usable result from a single combination of typo
/// corrections. As long as the filter returns ExprError, different
/// combinations of corrections will be tried until all are exhausted.
ExprResult
CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; });
ExprResult
CorrectDelayedTyposInExpr(Expr *E,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(E, nullptr, Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr,
llvm::function_ref<ExprResult(Expr *)> Filter =
[](Expr *E) -> ExprResult { return E; }) {
return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter);
}
ExprResult
CorrectDelayedTyposInExpr(ExprResult ER,
llvm::function_ref<ExprResult(Expr *)> Filter) {
return CorrectDelayedTyposInExpr(ER, nullptr, Filter);
}
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
bool ErrorRecovery = true);
void diagnoseTypo(const TypoCorrection &Correction,
const PartialDiagnostic &TypoDiag,
const PartialDiagnostic &PrevNote,
bool ErrorRecovery = true);
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
ArrayRef<Expr *> Args,
AssociatedNamespaceSet &AssociatedNamespaces,
AssociatedClassSet &AssociatedClasses);
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
bool ConsiderLinkage, bool AllowInlineNamespace);
void DiagnoseAmbiguousLookup(LookupResult &Result);
//@}
ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
SourceLocation IdLoc,
bool TypoCorrection = false);
NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
Scope *S, bool ForRedeclaration,
SourceLocation Loc);
NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
Scope *S);
void AddKnownFunctionAttributes(FunctionDecl *FD);
// More parsing and symbol table subroutines.
void ProcessPragmaWeak(Scope *S, Decl *D);
// Decl attributes - this routine is the top level dispatcher.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL,
bool IncludeCXX11Attributes = true);
bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
const AttributeList *AttrList);
void checkUnusedDeclAttributes(Declarator &D);
/// Determine if type T is a valid subject for a nonnull and similar
/// attributes. By default, we look through references (the behavior used by
/// nonnull), but if the second parameter is true, then we treat a reference
/// type as valid.
bool isValidPointerAttrType(QualType T, bool RefOkay = false);
bool CheckRegparmAttr(const AttributeList &attr, unsigned &value);
bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
const FunctionDecl *FD = nullptr);
bool CheckNoReturnAttr(const AttributeList &attr);
bool checkStringLiteralArgumentAttr(const AttributeList &Attr,
unsigned ArgNum, StringRef &Str,
SourceLocation *ArgLocation = nullptr);
bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
void checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
bool checkMSInheritanceAttrOnDefinition(
CXXRecordDecl *RD, SourceRange Range, bool BestCase,
MSInheritanceAttr::Spelling SemanticSpelling);
void CheckAlignasUnderalignment(Decl *D);
/// Adjust the calling convention of a method to be the ABI default if it
/// wasn't specified explicitly. This handles method types formed from
/// function type typedefs and typename template arguments.
void adjustMemberFunctionCC(QualType &T, bool IsStatic);
// Check if there is an explicit attribute, but only look through parens.
// The intent is to look for an attribute on the current declarator, but not
// one that came from a typedef.
bool hasExplicitCallingConv(QualType &T);
/// Get the outermost AttributedType node that sets a calling convention.
/// Valid types should not have multiple attributes with different CCs.
const AttributedType *getCallingConvAttributedType(QualType T) const;
/// Check whether a nullability type specifier can be added to the given
/// type.
///
/// \param type The type to which the nullability specifier will be
/// added. On success, this type will be updated appropriately.
///
/// \param nullability The nullability specifier to add.
///
/// \param nullabilityLoc The location of the nullability specifier.
///
/// \param isContextSensitive Whether this nullability specifier was
/// written as a context-sensitive keyword (in an Objective-C
/// method) or an Objective-C property attribute, rather than as an
/// underscored type specifier.
///
/// \returns true if nullability cannot be applied, false otherwise.
bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability,
SourceLocation nullabilityLoc,
bool isContextSensitive);
/// \brief Stmt attributes - this routine is the top level dispatcher.
StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs,
SourceRange Range);
void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
ObjCMethodDecl *Overridden,
bool IsProtocolMethodDecl);
void ValidateShaderAttributes(Decl *D, const AttributeList *A);
/// WarnExactTypedMethods - This routine issues a warning if method
/// implementation declaration matches exactly that of its declaration.
void WarnExactTypedMethods(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl);
typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap;
/// CheckImplementationIvars - This routine checks if the instance variables
/// listed in the implelementation match those listed in the interface.
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
ObjCIvarDecl **Fields, unsigned nIvars,
SourceLocation Loc);
/// ImplMethodsVsClassMethods - This is main routine to warn if any method
/// remains unimplemented in the class or category \@implementation.
void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool IncompleteImpl = false);
/// DiagnoseUnimplementedProperties - This routine warns on those properties
/// which must be implemented by this implementation.
void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl *CDecl,
bool SynthesizeProperties);
/// Diagnose any null-resettable synthesized setters.
void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
/// DefaultSynthesizeProperties - This routine default synthesizes all
/// properties which must be synthesized in the class's \@implementation.
void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl,
ObjCInterfaceDecl *IDecl);
void DefaultSynthesizeProperties(Scope *S, Decl *D);
/// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
/// an ivar synthesized for 'Method' and 'Method' is a property accessor
/// declared in class 'IFace'.
bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
ObjCMethodDecl *Method, ObjCIvarDecl *IV);
/// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
/// backs the property is not used in the property's accessor.
void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
const ObjCImplementationDecl *ImplD);
/// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
/// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
/// It also returns ivar's property on success.
ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
const ObjCPropertyDecl *&PDecl) const;
/// Called by ActOnProperty to handle \@property declarations in
/// class extensions.
ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
Selector SetterSel,
const bool isAssign,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
bool *isOverridingProperty,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind);
/// Called by ActOnProperty and HandlePropertyInClassExtension to
/// handle creating the ObjcPropertyDecl for a category or \@interface.
ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
ObjCContainerDecl *CDecl,
SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD,
Selector GetterSel,
Selector SetterSel,
const bool isAssign,
const bool isReadWrite,
const unsigned Attributes,
const unsigned AttributesAsWritten,
QualType T,
TypeSourceInfo *TSI,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
/// AtomicPropertySetterGetterRules - This routine enforces the rule (via
/// warning) when atomic property has one but not the other user-declared
/// setter or getter.
void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl);
void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
void DiagnoseMissingDesignatedInitOverrides(
const ObjCImplementationDecl *ImplD,
const ObjCInterfaceDecl *IFD);
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
enum MethodMatchStrategy {
MMS_loose,
MMS_strict
};
/// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
/// true, or false, accordingly.
bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
const ObjCMethodDecl *PrevMethod,
MethodMatchStrategy strategy = MMS_strict);
/// MatchAllMethodDeclarations - Check methods declaraed in interface or
/// or protocol against those declared in their implementations.
void MatchAllMethodDeclarations(const SelectorSet &InsMap,
const SelectorSet &ClsMap,
SelectorSet &InsMapSeen,
SelectorSet &ClsMapSeen,
ObjCImplDecl* IMPDecl,
ObjCContainerDecl* IDecl,
bool &IncompleteImpl,
bool ImmediateClass,
bool WarnCategoryMethodImpl=false);
/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
/// category matches with those implemented in its primary class and
/// warns each time an exact match is found.
void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
/// \brief Add the given method to the list of globally-known methods.
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
private:
/// AddMethodToGlobalPool - Add an instance or factory method to the global
/// pool. See descriptoin of AddInstanceMethodToGlobalPool.
void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
/// LookupMethodInGlobalPool - Returns the instance or factory method and
/// optionally warns if there are multiple signatures.
ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass,
bool instance);
public:
/// \brief - Returns instance or factory methods in global method pool for
/// given selector. If no such method or only one method found, function returns
/// false; otherwise, it returns true
bool CollectMultipleMethodsInGlobalPool(Selector Sel,
SmallVectorImpl<ObjCMethodDecl*>& Methods,
bool instance);
bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
SourceRange R,
bool receiverIdOrClass);
void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
Selector Sel, SourceRange R,
bool receiverIdOrClass);
private:
/// \brief - Returns a selector which best matches given argument list or
/// nullptr if none could be found
ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
bool IsInstance);
/// \brief Record the typo correction failure and return an empty correction.
TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
bool RecordFailure = true) {
if (RecordFailure)
TypoCorrectionFailures[Typo].insert(TypoLoc);
return TypoCorrection();
}
public:
/// AddInstanceMethodToGlobalPool - All instance methods in a translation
/// unit are added to a global pool. This allows us to efficiently associate
/// a selector with a method declaraation for purposes of typechecking
/// messages sent to "id" (where the class of the object is unknown).
void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/true);
}
/// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
AddMethodToGlobalPool(Method, impl, /*instance*/false);
}
/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
/// pool.
void AddAnyMethodToGlobalPool(Decl *D);
/// LookupInstanceMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/true);
}
/// LookupFactoryMethodInGlobalPool - Returns the method and warns if
/// there are multiple signatures.
ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass=false) {
return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
/*instance*/false);
}
const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
QualType ObjectType=QualType());
/// LookupImplementedMethodInGlobalPool - Returns the method which has an
/// implementation.
ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
/// initialization.
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
SmallVectorImpl<ObjCIvarDecl*> &Ivars);
//===--------------------------------------------------------------------===//
// Statement Parsing Callbacks: SemaStmt.cpp.
public:
class FullExprArg {
public:
FullExprArg(Sema &actions) : E(nullptr) { }
ExprResult release() {
return E;
}
Expr *get() const { return E; }
Expr *operator->() {
return E;
}
private:
// FIXME: No need to make the entire Sema class a friend when it's just
// Sema::MakeFullExpr that needs access to the constructor below.
friend class Sema;
explicit FullExprArg(Expr *expr) : E(expr) {}
Expr *E;
};
FullExprArg MakeFullExpr(Expr *Arg) {
return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
}
FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
return FullExprArg(ActOnFinishFullExpr(Arg, CC).get());
}
FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
ExprResult FE =
ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
/*DiscardedValue*/ true);
return FullExprArg(FE.get());
}
StmtResult ActOnExprStmt(ExprResult Arg);
StmtResult ActOnExprStmtError();
StmtResult ActOnHlslDiscardStmt(SourceLocation Loc); // HLSL Change
StmtResult ActOnNullStmt(SourceLocation SemiLoc,
bool HasLeadingEmptyMacro = false);
void ActOnStartOfCompoundStmt();
void ActOnFinishOfCompoundStmt();
StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
ArrayRef<Stmt *> Elts, bool isStmtExpr);
/// \brief A RAII object to enter scope of a compound statement.
class CompoundScopeRAII {
public:
CompoundScopeRAII(Sema &S): S(S) {
S.ActOnStartOfCompoundStmt();
}
~CompoundScopeRAII() {
S.ActOnFinishOfCompoundStmt();
}
private:
Sema &S;
};
/// An RAII helper that pops function a function scope on exit.
struct FunctionScopeRAII {
Sema &S;
bool Active;
FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
~FunctionScopeRAII() {
if (Active)
S.PopFunctionScopeInfo();
}
void disable() { Active = false; }
};
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
SourceLocation StartLoc,
SourceLocation EndLoc);
void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
StmtResult ActOnForEachLValueExpr(Expr *E);
StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal,
SourceLocation DotDotDotLoc, Expr *RHSVal,
SourceLocation ColonLoc);
void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
SourceLocation ColonLoc,
Stmt *SubStmt, Scope *CurScope);
StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
SourceLocation ColonLoc, Stmt *SubStmt);
StmtResult ActOnAttributedStmt(SourceLocation AttrLoc,
ArrayRef<const Attr*> Attrs,
Stmt *SubStmt);
StmtResult ActOnIfStmt(SourceLocation IfLoc,
FullExprArg CondVal, Decl *CondVar,
Stmt *ThenVal,
SourceLocation ElseLoc, Stmt *ElseVal);
StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
Expr *Cond,
Decl *CondVar);
StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
Stmt *Switch, Stmt *Body);
StmtResult ActOnWhileStmt(SourceLocation WhileLoc,
FullExprArg Cond,
Decl *CondVar, Stmt *Body);
StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
SourceLocation WhileLoc,
SourceLocation CondLParen, Expr *Cond,
SourceLocation CondRParen);
StmtResult ActOnForStmt(SourceLocation ForLoc,
SourceLocation LParenLoc,
Stmt *First, FullExprArg Second,
Decl *SecondVar,
FullExprArg Third,
SourceLocation RParenLoc,
Stmt *Body);
ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
Expr *collection);
StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
Stmt *First, Expr *collection,
SourceLocation RParenLoc);
StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
enum BuildForRangeKind {
/// Initial building of a for-range statement.
BFRK_Build,
/// Instantiation or recovery rebuild of a for-range statement. Don't
/// attempt any typo-correction.
BFRK_Rebuild,
/// Determining whether a for-range statement could be built. Avoid any
/// unnecessary or irreversible actions.
BFRK_Check
};
StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar,
SourceLocation ColonLoc, Expr *Collection,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
SourceLocation ColonLoc,
Stmt *RangeDecl, Stmt *BeginEndDecl,
Expr *Cond, Expr *Inc,
Stmt *LoopVarDecl,
SourceLocation RParenLoc,
BuildForRangeKind Kind);
StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
SourceLocation LabelLoc,
LabelDecl *TheDecl);
StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
SourceLocation StarLoc,
Expr *DestExp);
StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind, unsigned NumParams);
typedef std::pair<StringRef, QualType> CapturedParamNameType;
void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
CapturedRegionKind Kind,
ArrayRef<CapturedParamNameType> Params);
StmtResult ActOnCapturedRegionEnd(Stmt *S);
void ActOnCapturedRegionError();
RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
SourceLocation Loc,
unsigned NumParams);
VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E,
bool AllowFunctionParameters);
bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD,
bool AllowFunctionParameters);
StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
Scope *CurScope);
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp);
StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
bool IsVolatile, unsigned NumOutputs,
unsigned NumInputs, IdentifierInfo **Names,
MultiExprArg Constraints, MultiExprArg Exprs,
Expr *AsmString, MultiExprArg Clobbers,
SourceLocation RParenLoc);
ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Id,
llvm::InlineAsmIdentifierInfo &Info,
bool IsUnevaluatedContext);
bool LookupInlineAsmField(StringRef Base, StringRef Member,
unsigned &Offset, SourceLocation AsmLoc);
StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
ArrayRef<Token> AsmToks,
StringRef AsmString,
unsigned NumOutputs, unsigned NumInputs,
ArrayRef<StringRef> Constraints,
ArrayRef<StringRef> Clobbers,
ArrayRef<Expr*> Exprs,
SourceLocation EndLoc);
LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
SourceLocation Location,
bool AlwaysCreate);
VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
SourceLocation StartLoc,
SourceLocation IdLoc, IdentifierInfo *Id,
bool Invalid = false);
Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
Decl *Parm, Stmt *Body);
StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
MultiStmtArg Catch, Stmt *Finally);
StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
Scope *CurScope);
ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
Expr *operand);
StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
Expr *SynchExpr,
Stmt *SynchBody);
StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
SourceLocation StartLoc,
SourceLocation IdLoc,
IdentifierInfo *Id);
Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
Decl *ExDecl, Stmt *HandlerBlock);
StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
ArrayRef<Stmt *> Handlers);
StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
SourceLocation TryLoc, Stmt *TryBlock,
Stmt *Handler);
StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
Expr *FilterExpr,
Stmt *Block);
void ActOnStartSEHFinallyBlock();
void ActOnAbortSEHFinallyBlock();
StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
/// \brief If it's a file scoped decl that must warn if not used, keep track
/// of it.
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
/// DiagnoseUnusedExprResult - If the statement passed in is an expression
/// whose result is unused, warn.
void DiagnoseUnusedExprResult(const Stmt *S);
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
void DiagnoseUnusedDecl(const NamedDecl *ND);
/// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
/// statement as a \p Body, and it is located on the same line.
///
/// This helps prevent bugs due to typos, such as:
/// if (condition);
/// do_stuff();
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
const Stmt *Body,
unsigned DiagID);
/// Warn if a for/while loop statement \p S, which is followed by
/// \p PossibleBody, has a suspicious null statement as a body.
void DiagnoseEmptyLoopBody(const Stmt *S,
const Stmt *PossibleBody);
/// Warn if a value is moved to itself.
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
SourceLocation OpLoc);
ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
return DelayedDiagnostics.push(pool);
}
void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
typedef ProcessingContextState ParsingClassState;
ParsingClassState PushParsingClass() {
return DelayedDiagnostics.pushUndelayed();
}
void PopParsingClass(ParsingClassState state) {
DelayedDiagnostics.popUndelayed(state);
}
void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
enum AvailabilityDiagnostic { AD_Deprecation, AD_Unavailable, AD_Partial };
void EmitAvailabilityWarning(AvailabilityDiagnostic AD,
NamedDecl *D, StringRef Message,
SourceLocation Loc,
const ObjCInterfaceDecl *UnknownObjCClass,
const ObjCPropertyDecl *ObjCProperty,
bool ObjCPropertyAccess);
bool makeUnavailableInSystemHeader(SourceLocation loc,
StringRef message);
//===--------------------------------------------------------------------===//
// Expression Parsing Callbacks: SemaExpr.cpp.
bool CanUseDecl(NamedDecl *D);
bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
const ObjCInterfaceDecl *UnknownObjCClass=nullptr,
bool ObjCPropertyAccess=false);
void NoteDeletedFunction(FunctionDecl *FD);
std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD);
bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
ObjCMethodDecl *Getter,
SourceLocation Loc);
void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
ArrayRef<Expr *> Args);
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
bool IsDecltype = false);
enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
ReuseLambdaContextDecl_t,
bool IsDecltype = false);
void PopExpressionEvaluationContext();
void DiscardCleanupsInEvaluationContext();
ExprResult TransformToPotentiallyEvaluated(Expr *E);
ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
ExprResult ActOnConstantExpression(ExprResult Res);
// Functions for marking a declaration referenced. These functions also
// contain the relevant logic for marking if a reference to a function or
// variable is an odr-use (in the C++11 sense). There are separate variants
// for expressions referring to a decl; these exist because odr-use marking
// needs to be delayed for some constant variables when we build one of the
// named expressions.
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse);
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
bool OdrUse = true);
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
void MarkDeclRefReferenced(DeclRefExpr *E);
void MarkMemberReferenced(MemberExpr *E);
void UpdateMarkingForLValueToRValue(Expr *E);
void CleanupVarDeclMarking();
enum TryCaptureKind {
TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
};
/// \brief Try to capture the given variable.
///
/// \param Var The variable to capture.
///
/// \param Loc The location at which the capture occurs.
///
/// \param Kind The kind of capture, which may be implicit (for either a
/// block or a lambda), or explicit by-value or by-reference (for a lambda).
///
/// \param EllipsisLoc The location of the ellipsis, if one is provided in
/// an explicit lambda capture.
///
/// \param BuildAndDiagnose Whether we are actually supposed to add the
/// captures or diagnose errors. If false, this routine merely check whether
/// the capture can occur without performing the capture itself or complaining
/// if the variable cannot be captured.
///
/// \param CaptureType Will be set to the type of the field used to capture
/// this variable in the innermost block or lambda. Only valid when the
/// variable can be captured.
///
/// \param DeclRefType Will be set to the type of a reference to the capture
/// from within the current scope. Only valid when the variable can be
/// captured.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// variables that may or may not be used in certain specializations of
/// a nested generic lambda.
///
/// \returns true if an error occurred (i.e., the variable cannot be
/// captured) and false if the capture succeeded.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
SourceLocation EllipsisLoc, bool BuildAndDiagnose,
QualType &CaptureType,
QualType &DeclRefType,
const unsigned *const FunctionScopeIndexToStopAt);
/// \brief Try to capture the given variable.
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
TryCaptureKind Kind = TryCapture_Implicit,
SourceLocation EllipsisLoc = SourceLocation());
/// \brief Checks if the variable must be captured.
bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
/// \brief Given a variable, determine the type that a reference to that
/// variable will have in the given scope.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
void MarkDeclarationsReferencedInExpr(Expr *E,
bool SkipLocalVariables = false);
/// \brief Try to recover by turning the given expression into a
/// call. Returns true if recovery was attempted or an error was
/// emitted; this may also leave the ExprResult invalid.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
bool ForceComplain = false,
bool (*IsPlausibleResult)(QualType) = nullptr);
/// \brief Figure out if an expression could be turned into a call.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
UnresolvedSetImpl &NonTemplateOverloads);
/// \brief Conditionally issue a diagnostic based on the current
/// evaluation context.
///
/// \param Statement If Statement is non-null, delay reporting the
/// diagnostic until the function body is parsed, and then do a basic
/// reachability analysis to determine if the statement is reachable.
/// If it is unreachable, the diagnostic will not be emitted.
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
const PartialDiagnostic &PD);
// Primary Expressions.
SourceRange getExprRange(Expr *E) const;
ExprResult ActOnIdExpression(
Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr,
bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
void DecomposeUnqualifiedId(const UnqualifiedId &Id,
TemplateArgumentListInfo &Buffer,
DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *&TemplateArgs);
bool
DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
std::unique_ptr<CorrectionCandidateCallback> CCC,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
IdentifierInfo *II,
bool AllowBuiltinCreation=false);
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool isAddressOfOperand,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty,
ExprValueKind VK,
SourceLocation Loc,
const CXXScopeSpec *SS = nullptr);
ExprResult
BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
const DeclarationNameInfo &NameInfo,
const CXXScopeSpec *SS = nullptr,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr);
ExprResult
BuildAnonymousStructUnionMemberReference(
const CXXScopeSpec &SS,
SourceLocation nameLoc,
IndirectFieldDecl *indirectField,
DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
Expr *baseObjectExpr = nullptr,
SourceLocation opLoc = SourceLocation());
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool IsDefiniteInstance);
bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
const LookupResult &R,
bool HasTrailingLParen);
ExprResult BuildQualifiedDeclarationNameExpr(
CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI = nullptr);
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
LookupResult &R,
bool NeedsADL,
bool AcceptInvalidDecl = false);
ExprResult BuildDeclarationNameExpr(
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
NamedDecl *FoundD = nullptr,
const TemplateArgumentListInfo *TemplateArgs = nullptr,
bool AcceptInvalidDecl = false);
ExprResult BuildLiteralOperatorCall(LookupResult &R,
DeclarationNameInfo &SuffixInfo,
ArrayRef<Expr *> Args,
SourceLocation LitEndLoc,
TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
ExprResult BuildPredefinedExpr(SourceLocation Loc,
PredefinedExpr::IdentType IT);
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
ExprResult ActOnCharacterConstant(const Token &Tok,
Scope *UDLScope = nullptr);
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
ExprResult ActOnParenListExpr(SourceLocation L,
SourceLocation R,
MultiExprArg Val);
/// ActOnStringLiteral - The specified tokens were lexed as pasted string
/// fragments (e.g. "foo" "bar" L"baz").
ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
Scope *UDLScope = nullptr);
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<ParsedType> ArgTypes,
ArrayRef<Expr *> ArgExprs);
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
SourceLocation DefaultLoc,
SourceLocation RParenLoc,
Expr *ControllingExpr,
ArrayRef<TypeSourceInfo *> Types,
ArrayRef<Expr *> Exprs);
// Binary/Unary Operators. 'Tok' is the token for the operator.
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
Expr *InputExpr);
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opc, Expr *Input);
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Op, Expr *Input);
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
SourceRange R);
ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind);
ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
UnaryExprOrTypeTrait ExprKind,
bool IsType, void *TyOrEx,
const SourceRange &ArgRange);
ExprResult CheckPlaceholderExpr(Expr *E);
bool CheckVecStepExpr(Expr *E);
// HLSL Change Begins
bool CheckHLSLUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation Loc,
UnaryExprOrTypeTrait ExprKind);
void DiagnoseHLSLDeclAttr(const Decl *D, const Attr *A);
void DiagnoseGloballyCoherentMismatch(const Expr *SrcExpr,
QualType TargetType,
SourceLocation Loc);
void CheckHLSLFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
void DiagnoseReachableHLSLCall(CallExpr *CE, const hlsl::ShaderModel *SM,
hlsl::DXIL::ShaderKind EntrySK,
hlsl::DXIL::NodeLaunchType NodeLaunchTy,
const FunctionDecl *EntryDecl,
bool locallyVisited);
// HLSL Change Ends
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
SourceRange ExprRange,
UnaryExprOrTypeTrait ExprKind);
ExprResult ActOnSizeofParameterPackExpr(Scope *S,
SourceLocation OpLoc,
IdentifierInfo &Name,
SourceLocation NameLoc,
SourceLocation RParenLoc);
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
tok::TokenKind Kind, Expr *Input);
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Expr *Idx, SourceLocation RLoc);
// This struct is for use by ActOnMemberAccess to allow
// BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
// changing the access operator from a '.' to a '->' (to see if that is the
// change needed to fix an error about an unknown member, e.g. when the class
// defines a custom operator->).
struct ActOnMemberAccessExtraArgs {
Scope *S;
UnqualifiedId &Id;
Decl *ObjCImpDecl;
};
ExprResult BuildMemberReferenceExpr(
Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult
BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
bool IsArrow, const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope, LookupResult &R,
const TemplateArgumentListInfo *TemplateArgs,
bool SuppressQualifierCheck = false,
ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
const CXXScopeSpec &SS,
const LookupResult &R);
ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
bool IsArrow, SourceLocation OpLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierInScope,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Member,
Decl *ObjCImpDecl);
void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
FunctionDecl *FDecl,
const FunctionProtoType *Proto,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
bool ExecConfig = false);
void CheckStaticArrayArgument(SourceLocation CallLoc,
ParmVarDecl *Param,
const Expr *ArgExpr);
/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
/// This provides the location of the left/right parens and a list of comma
/// locations.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
MultiExprArg ArgExprs, SourceLocation RParenLoc,
Expr *ExecConfig = nullptr,
bool IsExecConfig = false);
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
SourceLocation LParenLoc,
ArrayRef<Expr *> Arg,
SourceLocation RParenLoc,
Expr *Config = nullptr,
bool IsExecConfig = false);
ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
MultiExprArg ExecConfig,
SourceLocation GGGLoc);
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
Declarator &D, ParsedType &Ty,
SourceLocation RParenLoc, Expr *CastExpr);
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
TypeSourceInfo *Ty,
SourceLocation RParenLoc,
Expr *Op);
CastKind PrepareScalarCast(ExprResult &src, QualType destType);
/// \brief Build an altivec or OpenCL literal.
ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
SourceLocation RParenLoc, Expr *E,
TypeSourceInfo *TInfo);
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc,
Expr *InitExpr);
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
TypeSourceInfo *TInfo,
SourceLocation RParenLoc,
Expr *LiteralExpr);
ExprResult ActOnInitList(SourceLocation LBraceLoc,
MultiExprArg InitArgList,
SourceLocation RBraceLoc);
ExprResult ActOnDesignatedInitializer(Designation &Desig,
SourceLocation Loc,
bool GNUSyntax,
ExprResult Init);
private:
static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
public:
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
Expr *LHSExpr, Expr *RHSExpr);
/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
/// in the case of a the GNU conditional expr extension.
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
SourceLocation ColonLoc,
Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
LabelDecl *TheDecl);
void ActOnStartStmtExpr();
ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
SourceLocation RPLoc); // "({..})"
void ActOnStmtExprError();
// __builtin_offsetof(type, identifier(.identifier|[expr])*)
struct OffsetOfComponent {
SourceLocation LocStart, LocEnd;
bool isBrackets; // true if [expr], false if .ident
union {
IdentifierInfo *IdentInfo;
Expr *E;
} U;
};
/// __builtin_offsetof(type, a.b[123][456].c)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
TypeSourceInfo *TInfo,
OffsetOfComponent *CompPtr,
unsigned NumComponents,
SourceLocation RParenLoc);
ExprResult ActOnBuiltinOffsetOf(Scope *S,
SourceLocation BuiltinLoc,
SourceLocation TypeLoc,
ParsedType ParsedArgTy,
OffsetOfComponent *CompPtr,
unsigned NumComponents,
SourceLocation RParenLoc);
// __builtin_choose_expr(constExpr, expr1, expr2)
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
Expr *CondExpr, Expr *LHSExpr,
Expr *RHSExpr, SourceLocation RPLoc);
// __builtin_va_arg(expr, type)
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
SourceLocation RPLoc);
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
TypeSourceInfo *TInfo, SourceLocation RPLoc);
// __null
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
bool CheckCaseExpression(Expr *E);
/// \brief Describes the result of an "if-exists" condition check.
enum IfExistsResult {
/// \brief The symbol exists.
IER_Exists,
/// \brief The symbol does not exist.
IER_DoesNotExist,
/// \brief The name is a dependent name, so the results will differ
/// from one instantiation to the next.
IER_Dependent,
/// \brief An error occurred.
IER_Error
};
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
const DeclarationNameInfo &TargetNameInfo);
IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
bool IsIfExists, CXXScopeSpec &SS,
UnqualifiedId &Name);
StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
NestedNameSpecifierLoc QualifierLoc,
DeclarationNameInfo NameInfo,
Stmt *Nested);
StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
bool IsIfExists,
CXXScopeSpec &SS, UnqualifiedId &Name,
Stmt *Nested);
//===------------------------- "Block" Extension ------------------------===//
/// ActOnBlockStart - This callback is invoked when a block literal is
/// started.
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockArguments - This callback allows processing of block arguments.
/// If there are no arguments, this is still invoked.
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
Scope *CurScope);
/// ActOnBlockError - If there is an error parsing a block, this callback
/// is invoked to pop the information about the block from the action impl.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
/// ActOnBlockStmtExpr - This is called when the body of a block statement
/// literal was successfully completed. ^(int x){...}
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
Scope *CurScope);
//===---------------------------- Clang Extensions ----------------------===//
/// __builtin_convertvector(...)
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
//===---------------------------- OpenCL Features -----------------------===//
/// __builtin_astype(...)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
// HLSL Change Starts
//===---------------------------- HLSL Features -------------------------===//
/// cbuffer/tbuffer
llvm::SmallVector<Decl*, 1> HLSLBuffers;
Decl* ActOnStartHLSLBuffer(Scope* bufferScope, bool cbuffer, SourceLocation KwLoc,
IdentifierInfo *Ident, SourceLocation IdentLoc,
std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
SourceLocation LBrace);
void ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace);
Decl* getActiveHLSLBuffer() const;
bool IsOnHLSLBufferView();
// HLSL Change Ends
//===---------------------------- C++ Features --------------------------===//
// Act on C++ namespaces
Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
SourceLocation NamespaceLoc,
SourceLocation IdentLoc,
IdentifierInfo *Ident,
SourceLocation LBrace,
AttributeList *AttrList);
void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
NamespaceDecl *getStdNamespace() const;
NamespaceDecl *getOrCreateStdNamespace();
CXXRecordDecl *getStdBadAlloc() const;
/// \brief Tests whether Ty is an instance of std::initializer_list and, if
/// it is and Element is not NULL, assigns the element type to Element.
bool isStdInitializerList(QualType Ty, QualType *Element);
/// \brief Looks for the std::initializer_list template and instantiates it
/// with Element, or emits an error if it's not found.
///
/// \returns The instantiated template, or null on error.
QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
/// \brief Determine whether Ctor is an initializer-list constructor, as
/// defined in [dcl.init.list]p2.
bool isInitListConstructor(const CXXConstructorDecl *Ctor);
Decl *ActOnUsingDirective(Scope *CurScope,
SourceLocation UsingLoc,
SourceLocation NamespcLoc,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *NamespcName,
AttributeList *AttrList);
void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
Decl *ActOnNamespaceAliasDef(Scope *CurScope,
SourceLocation NamespaceLoc,
SourceLocation AliasLoc,
IdentifierInfo *Alias,
CXXScopeSpec &SS,
SourceLocation IdentLoc,
IdentifierInfo *Ident);
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target,
const LookupResult &PreviousDecls,
UsingShadowDecl *&PrevShadow);
UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD,
NamedDecl *Target,
UsingShadowDecl *PrevDecl);
bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
bool HasTypenameKeyword,
const CXXScopeSpec &SS,
SourceLocation NameLoc,
const LookupResult &Previous);
bool CheckUsingDeclQualifier(SourceLocation UsingLoc,
const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
SourceLocation NameLoc);
NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
SourceLocation UsingLoc,
CXXScopeSpec &SS,
DeclarationNameInfo NameInfo,
AttributeList *AttrList,
bool IsInstantiation,
bool HasTypenameKeyword,
SourceLocation TypenameLoc);
bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
Decl *ActOnUsingDeclaration(Scope *CurScope,
AccessSpecifier AS,
bool HasUsingKeyword,
SourceLocation UsingLoc,
CXXScopeSpec &SS,
UnqualifiedId &Name,
AttributeList *AttrList,
bool HasTypenameKeyword,
SourceLocation TypenameLoc);
Decl *ActOnAliasDeclaration(Scope *CurScope,
AccessSpecifier AS,
MultiTemplateParamsArg TemplateParams,
SourceLocation UsingLoc,
UnqualifiedId &Name,
AttributeList *AttrList,
TypeResult Type,
Decl *DeclFromDeclSpec);
/// BuildCXXConstructExpr - Creates a complete call to a constructor,
/// including handling of its default argument expressions.
///
/// \param ConstructKind - a CXXConstructExpr::ConstructionKind
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, MultiExprArg Exprs,
bool HadMultipleCandidates, bool IsListInitialization,
bool IsStdInitListInitialization,
bool RequiresZeroInit, unsigned ConstructKind,
SourceRange ParenRange);
// FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
// the constructor can be elidable?
ExprResult
BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
CXXConstructorDecl *Constructor, bool Elidable,
MultiExprArg Exprs, bool HadMultipleCandidates,
bool IsListInitialization,
bool IsStdInitListInitialization, bool RequiresZeroInit,
unsigned ConstructKind, SourceRange ParenRange);
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
/// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
/// the default expr if needed.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
FunctionDecl *FD,
ParmVarDecl *Param);
/// FinalizeVarWithDestructor - Prepare for calling destructor on the
/// constructed variable.
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
/// \brief Helper class that collects exception specifications for
/// implicitly-declared special member functions.
class ImplicitExceptionSpecification {
// Pointer to allow copying
Sema *Self;
// We order exception specifications thus:
// noexcept is the most restrictive, but is only used in C++11.
// throw() comes next.
// Then a throw(collected exceptions)
// Finally no specification, which is expressed as noexcept(false).
// throw(...) is used instead if any called function uses it.
ExceptionSpecificationType ComputedEST;
llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
SmallVector<QualType, 4> Exceptions;
void ClearExceptions() {
ExceptionsSeen.clear();
Exceptions.clear();
}
public:
explicit ImplicitExceptionSpecification(Sema &Self)
: Self(&Self), ComputedEST(EST_BasicNoexcept) {
if (!Self.getLangOpts().CPlusPlus11)
ComputedEST = EST_DynamicNone;
}
/// \brief Get the computed exception specification type.
ExceptionSpecificationType getExceptionSpecType() const {
assert(ComputedEST != EST_ComputedNoexcept &&
"noexcept(expr) should not be a possible result");
return ComputedEST;
}
/// \brief The number of exceptions in the exception specification.
unsigned size() const { return Exceptions.size(); }
/// \brief The set of exceptions in the exception specification.
const QualType *data() const { return Exceptions.data(); }
/// \brief Integrate another called method into the collected data.
void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
/// \brief Integrate an invoked expression into the collected data.
void CalledExpr(Expr *E);
/// \brief Overwrite an EPI's exception specification with this
/// computed exception specification.
FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
FunctionProtoType::ExceptionSpecInfo ESI;
ESI.Type = getExceptionSpecType();
if (ESI.Type == EST_Dynamic) {
ESI.Exceptions = Exceptions;
} else if (ESI.Type == EST_None) {
/// C++11 [except.spec]p14:
/// The exception-specification is noexcept(false) if the set of
/// potential exceptions of the special member function contains "any"
ESI.Type = EST_ComputedNoexcept;
ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
tok::kw_false).get();
}
return ESI;
}
};
/// \brief Determine what sort of exception specification a defaulted
/// copy constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc,
CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted
/// default constructor of a class will have, and whether the parameter
/// will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defautled
/// copy assignment operator of a class will have, and whether the
/// parameter will be const.
ImplicitExceptionSpecification
ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted move
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted move
/// assignment operator of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification a defaulted
/// destructor of a class will have.
ImplicitExceptionSpecification
ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD);
/// \brief Determine what sort of exception specification an inheriting
/// constructor of a class will have.
ImplicitExceptionSpecification
ComputeInheritingCtorExceptionSpec(CXXConstructorDecl *CD);
/// \brief Evaluate the implicit exception specification for a defaulted
/// special member function.
void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD);
/// \brief Check the given exception-specification and update the
/// exception specification information with the results.
void checkExceptionSpecification(bool IsTopLevel,
ExceptionSpecificationType EST,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr,
SmallVectorImpl<QualType> &Exceptions,
FunctionProtoType::ExceptionSpecInfo &ESI);
/// \brief Determine if we're in a case where we need to (incorrectly) eagerly
/// parse an exception specification to work around a libstdc++ bug.
bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
/// \brief Add an exception-specification to the given member function
/// (or member function template). The exception-specification was parsed
/// after the method itself was declared.
void actOnDelayedExceptionSpecification(Decl *Method,
ExceptionSpecificationType EST,
SourceRange SpecificationRange,
ArrayRef<ParsedType> DynamicExceptions,
ArrayRef<SourceRange> DynamicExceptionRanges,
Expr *NoexceptExpr);
/// \brief Determine if a special member function should have a deleted
/// definition when it is defaulted.
bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
bool Diagnose = false);
/// \brief Declare the implicit default constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// default constructor will be added.
///
/// \returns The implicitly-declared default constructor.
CXXConstructorDecl *DeclareImplicitDefaultConstructor(
CXXRecordDecl *ClassDecl);
/// DefineImplicitDefaultConstructor - Checks for feasibility of
/// defining this constructor as the default constructor.
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit destructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// destructor will be added.
///
/// \returns The implicitly-declared destructor.
CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitDestructor - Checks for feasibility of
/// defining this destructor as the default destructor.
void DefineImplicitDestructor(SourceLocation CurrentLocation,
CXXDestructorDecl *Destructor);
/// \brief Build an exception spec for destructors that don't have one.
///
/// C++11 says that user-defined destructors with no exception spec get one
/// that looks as if the destructor was implicitly declared.
void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
CXXDestructorDecl *Destructor);
/// \brief Declare all inheriting constructors for the given class.
///
/// \param ClassDecl The class declaration into which the inheriting
/// constructors will be added.
void DeclareInheritingConstructors(CXXRecordDecl *ClassDecl);
/// \brief Define the specified inheriting constructor.
void DefineInheritingConstructor(SourceLocation UseLoc,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit copy constructor for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy constructor will be added.
///
/// \returns The implicitly-declared copy constructor.
CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitCopyConstructor - Checks for feasibility of
/// defining this constructor as the copy constructor.
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit move constructor for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move constructor will be added.
///
/// \returns The implicitly-declared move constructor, or NULL if it wasn't
/// declared.
CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
/// DefineImplicitMoveConstructor - Checks for feasibility of
/// defining this constructor as the move constructor.
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
CXXConstructorDecl *Constructor);
/// \brief Declare the implicit copy assignment operator for the given class.
///
/// \param ClassDecl The class declaration into which the implicit
/// copy assignment operator will be added.
///
/// \returns The implicitly-declared copy assignment operator.
CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
/// \brief Defines an implicitly-declared copy assignment operator.
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// \brief Declare the implicit move assignment operator for the given class.
///
/// \param ClassDecl The Class declaration into which the implicit
/// move assignment operator will be added.
///
/// \returns The implicitly-declared move assignment operator, or NULL if it
/// wasn't declared.
CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
/// \brief Defines an implicitly-declared move assignment operator.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
CXXMethodDecl *MethodDecl);
/// \brief Force the declaration of any implicitly-declared members of this
/// class.
void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
/// \brief Determine whether the given function is an implicitly-deleted
/// special member function.
bool isImplicitlyDeleted(FunctionDecl *FD);
/// \brief Check whether 'this' shows up in the type of a static member
/// function after the (naturally empty) cv-qualifier-seq would be.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
/// \brief Whether this' shows up in the exception specification of a static
/// member function.
bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
/// \brief Check whether 'this' shows up in the attributes of the given
/// static member function.
///
/// \returns true if an error occurred.
bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
/// MaybeBindToTemporary - If the passed in expression has a record type with
/// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
/// it simply returns the passed in expression.
ExprResult MaybeBindToTemporary(Expr *E);
bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
MultiExprArg ArgsPtr,
SourceLocation Loc,
SmallVectorImpl<Expr*> &ConvertedArgs,
bool AllowExplicit = false,
bool IsListInitialization = false);
ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
SourceLocation NameLoc,
IdentifierInfo &Name);
ParsedType getDestructorName(SourceLocation TildeLoc,
IdentifierInfo &II, SourceLocation NameLoc,
Scope *S, CXXScopeSpec &SS,
ParsedType ObjectType,
bool EnteringContext);
ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType);
// Checks that reinterpret casts don't have undefined behavior.
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
bool IsDereference, SourceRange Range);
/// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's.
ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
SourceLocation LAngleBracketLoc,
Declarator &D,
SourceLocation RAngleBracketLoc,
SourceLocation LParenLoc,
Expr *E,
SourceLocation RParenLoc);
ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
tok::TokenKind Kind,
TypeSourceInfo *Ty,
Expr *E,
SourceRange AngleBrackets,
SourceRange Parens);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeId(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXTypeid - Parse typeid( something ).
ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
TypeSourceInfo *Operand,
SourceLocation RParenLoc);
ExprResult BuildCXXUuidof(QualType TypeInfoType,
SourceLocation TypeidLoc,
Expr *Operand,
SourceLocation RParenLoc);
/// ActOnCXXUuidof - Parse __uuidof( something ).
ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
SourceLocation LParenLoc, bool isType,
void *TyOrExpr,
SourceLocation RParenLoc);
/// \brief Handle a C++1z fold-expression: ( expr op ... op expr ).
ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
tok::TokenKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS,
BinaryOperatorKind Operator,
SourceLocation EllipsisLoc, Expr *RHS,
SourceLocation RParenLoc);
ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
BinaryOperatorKind Operator);
//// ActOnCXXThis - Parse 'this' pointer.
ExprResult ActOnCXXThis(SourceLocation loc);
/// \brief Try to retrieve the type of the 'this' pointer.
///
/// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
QualType getCurrentThisType();
/// \brief When non-NULL, the C++ 'this' expression is allowed despite the
/// current context not being a non-static member function. In such cases,
/// this provides the type used for 'this'.
QualType CXXThisTypeOverride;
/// \brief RAII object used to temporarily allow the C++ 'this' expression
/// to be used, with the given qualifiers on the current class type.
class CXXThisScopeRAII {
Sema &S;
QualType OldCXXThisTypeOverride;
bool Enabled;
public:
/// \brief Introduce a new scope where 'this' may be allowed (when enabled),
/// using the given declaration (which is either a class template or a
/// class) along with the given qualifiers.
/// along with the qualifiers placed on '*this'.
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals,
bool Enabled = true);
~CXXThisScopeRAII();
};
/// \brief Make sure the value of 'this' is actually available in the current
/// context, if it is a potentially evaluated context.
///
/// \param Loc The location at which the capture of 'this' occurs.
///
/// \param Explicit Whether 'this' is explicitly captured in a lambda
/// capture list.
///
/// \param FunctionScopeIndexToStopAt If non-null, it points to the index
/// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
/// This is useful when enclosing lambdas must speculatively capture
/// 'this' that may or may not be used in certain specializations of
/// a nested generic lambda (depending on whether the name resolves to
/// a non-static member function or a static function).
/// \return returns 'true' if failed, 'false' if success.
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
bool BuildAndDiagnose = true,
const unsigned *const FunctionScopeIndexToStopAt = nullptr);
/// \brief Determine whether the given type is the type of *this that is used
/// outside of the body of a member function for a type that is currently
/// being defined.
bool isThisOutsideMemberFunctionBody(QualType BaseType);
/// ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
//// ActOnCXXThrow - Parse throw expressions.
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
bool IsThrownVarInScope);
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
/// Can be interpreted either as function-style casting ("int(x)")
/// or class type construction ("ClassType(x,y,z)")
/// or creation of a value-initialized type ("int()").
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc);
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
MultiExprArg Exprs,
SourceLocation RParenLoc);
/// ActOnCXXNew - Parsed a C++ 'new' expression.
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens, Declarator &D,
Expr *Initializer);
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
SourceLocation PlacementLParen,
MultiExprArg PlacementArgs,
SourceLocation PlacementRParen,
SourceRange TypeIdParens,
QualType AllocType,
TypeSourceInfo *AllocTypeInfo,
Expr *ArraySize,
SourceRange DirectInitRange,
Expr *Initializer,
bool TypeMayContainAuto = true);
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
SourceRange R);
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
bool UseGlobal, QualType AllocType, bool IsArray,
MultiExprArg PlaceArgs,
FunctionDecl *&OperatorNew,
FunctionDecl *&OperatorDelete);
bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
DeclarationName Name, MultiExprArg Args,
DeclContext *Ctx,
bool AllowMissing, FunctionDecl *&Operator,
bool Diagnose = true);
void DeclareGlobalNewDelete();
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
QualType Param1,
QualType Param2 = QualType(),
bool addRestrictAttr = false);
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
DeclarationName Name, FunctionDecl* &Operator,
bool Diagnose = true);
FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
bool CanProvideSize,
DeclarationName Name);
/// ActOnCXXDelete - Parsed a C++ 'delete' expression
ExprResult ActOnCXXDelete(SourceLocation StartLoc,
bool UseGlobal, bool ArrayForm,
Expr *Operand);
DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
ExprResult CheckConditionVariable(VarDecl *ConditionVar,
SourceLocation StmtLoc,
bool ConvertToBoolean);
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
Expr *Operand, SourceLocation RParen);
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
SourceLocation RParen);
/// \brief Parsed one of the type trait support pseudo-functions.
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<ParsedType> Args,
SourceLocation RParenLoc);
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc);
/// ActOnArrayTypeTrait - Parsed one of the bianry type trait support
/// pseudo-functions.
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
ParsedType LhsTy,
Expr *DimExpr,
SourceLocation RParen);
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
SourceLocation KWLoc,
TypeSourceInfo *TSInfo,
Expr *DimExpr,
SourceLocation RParen);
/// ActOnExpressionTrait - Parsed one of the unary type trait support
/// pseudo-functions.
ExprResult ActOnExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult BuildExpressionTrait(ExpressionTrait OET,
SourceLocation KWLoc,
Expr *Queried,
SourceLocation RParen);
ExprResult ActOnStartCXXMemberReference(Scope *S,
Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
ParsedType &ObjectType,
bool &MayBePseudoDestructor);
ExprResult BuildPseudoDestructorExpr(Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
const CXXScopeSpec &SS,
TypeSourceInfo *ScopeType,
SourceLocation CCLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
CXXScopeSpec &SS,
UnqualifiedId &FirstTypeName,
SourceLocation CCLoc,
SourceLocation TildeLoc,
UnqualifiedId &SecondTypeName);
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
tok::TokenKind OpKind,
SourceLocation TildeLoc,
const DeclSpec& DS);
/// MaybeCreateExprWithCleanups - If the current full-expression
/// requires any cleanups, surround it with a ExprWithCleanups node.
/// Otherwise, just returns the passed-in expression.
Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
ExprResult ActOnFinishFullExpr(Expr *Expr) {
return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc()
: SourceLocation());
}
ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
bool DiscardedValue = false,
bool IsConstexpr = false,
bool IsLambdaInitCaptureInitializer = false);
StmtResult ActOnFinishFullStmt(Stmt *Stmt);
// Marks SS invalid if it represents an incomplete type.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
DeclContext *computeDeclContext(QualType T);
DeclContext *computeDeclContext(const CXXScopeSpec &SS,
bool EnteringContext = false);
bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
/// \brief The parser has parsed a global nested-name-specifier '::'.
///
/// \param CCLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
/// \brief The parser has parsed a '__super' nested-name-specifier.
///
/// \param SuperLoc The location of the '__super' keyword.
///
/// \param ColonColonLoc The location of the '::'.
///
/// \param SS The nested-name-specifier, which will be updated in-place
/// to reflect the parsed nested-name-specifier.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
SourceLocation ColonColonLoc, CXXScopeSpec &SS);
bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
bool *CanCorrect = nullptr);
NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
SourceLocation IdLoc,
IdentifierInfo &II,
ParsedType ObjectType);
bool BuildCXXNestedNameSpecifier(Scope *S,
IdentifierInfo &Identifier,
SourceLocation IdentifierLoc,
SourceLocation CCLoc,
QualType ObjectType,
bool EnteringContext,
CXXScopeSpec &SS,
NamedDecl *ScopeLookupResult,
bool ErrorRecoveryLookup,
bool *IsCorrectedToColon = nullptr);
/// \brief The parser has parsed a nested-name-specifier 'identifier::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param Identifier The identifier preceding the '::'.
///
/// \param IdentifierLoc The location of the identifier.
///
/// \param CCLoc The location of the '::'.
///
/// \param ObjectType The type of the object, if we're parsing
/// nested-name-specifier in a member access expression.
///
/// \param EnteringContext Whether we're entering the context nominated by
/// this nested-name-specifier.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param ErrorRecoveryLookup If true, then this method is called to improve
/// error recovery. In this case do not emit error message.
///
/// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
/// are allowed. The bool value pointed by this parameter is set to 'true'
/// if the identifier is treated as if it was followed by ':', not '::'.
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
IdentifierInfo &Identifier,
SourceLocation IdentifierLoc,
SourceLocation CCLoc,
ParsedType ObjectType,
bool EnteringContext,
CXXScopeSpec &SS,
bool ErrorRecoveryLookup = false,
bool *IsCorrectedToColon = nullptr);
ExprResult ActOnDecltypeExpression(Expr *E);
bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
const DeclSpec &DS,
SourceLocation ColonColonLoc);
bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
IdentifierInfo &Identifier,
SourceLocation IdentifierLoc,
SourceLocation ColonLoc,
ParsedType ObjectType,
bool EnteringContext);
/// \brief The parser has parsed a nested-name-specifier
/// 'template[opt] template-name < template-args >::'.
///
/// \param S The scope in which this nested-name-specifier occurs.
///
/// \param SS The nested-name-specifier, which is both an input
/// parameter (the nested-name-specifier before this type) and an
/// output parameter (containing the full nested-name-specifier,
/// including this new type).
///
/// \param TemplateKWLoc the location of the 'template' keyword, if any.
/// \param TemplateName the template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
/// \param CCLoc The location of the '::'.
///
/// \param EnteringContext Whether we're entering the context of the
/// nested-name-specifier.
///
///
/// \returns true if an error occurred, false otherwise.
bool ActOnCXXNestedNameSpecifier(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
SourceLocation CCLoc,
bool EnteringContext);
/// \brief Given a C++ nested-name-specifier, produce an annotation value
/// that the parser can use later to reconstruct the given
/// nested-name-specifier.
///
/// \param SS A nested-name-specifier.
///
/// \returns A pointer containing all of the information in the
/// nested-name-specifier \p SS.
void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
/// \brief Given an annotation pointer for a nested-name-specifier, restore
/// the nested-name-specifier structure.
///
/// \param Annotation The annotation pointer, produced by
/// \c SaveNestedNameSpecifierAnnotation().
///
/// \param AnnotationRange The source range corresponding to the annotation.
///
/// \param SS The nested-name-specifier that will be updated with the contents
/// of the annotation pointer.
void RestoreNestedNameSpecifierAnnotation(void *Annotation,
SourceRange AnnotationRange,
CXXScopeSpec &SS);
bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
/// scope or nested-name-specifier) is parsed, part of a declarator-id.
/// After this method is called, according to [C++ 3.4.3p3], names should be
/// looked up in the declarator-id's scope, until the declarator is parsed and
/// ActOnCXXExitDeclaratorScope is called.
/// The 'SS' should be a non-empty valid CXXScopeSpec.
bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
/// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
/// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
/// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
/// Used to indicate that names should revert to being looked up in the
/// defining scope.
void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
/// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
/// initializer for the declaration 'Dcl'.
/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
/// static data member of class X, names should be looked up in the scope of
/// class X.
void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
/// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
/// initializer for the declaration 'Dcl'.
void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
/// \brief Create a new lambda closure type.
CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
TypeSourceInfo *Info,
bool KnownDependent,
LambdaCaptureDefault CaptureDefault);
/// \brief Start the definition of a lambda expression.
CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
SourceRange IntroducerRange,
TypeSourceInfo *MethodType,
SourceLocation EndLoc,
ArrayRef<ParmVarDecl *> Params);
/// \brief Endow the lambda scope info with the relevant properties.
void buildLambdaScope(sema::LambdaScopeInfo *LSI,
CXXMethodDecl *CallOperator,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
bool ExplicitParams,
bool ExplicitResultType,
bool Mutable);
/// \brief Perform initialization analysis of the init-capture and perform
/// any implicit conversions such as an lvalue-to-rvalue conversion if
/// not being used to initialize a reference.
QualType performLambdaInitCaptureInitialization(SourceLocation Loc,
bool ByRef, IdentifierInfo *Id, Expr *&Init);
/// \brief Create a dummy variable within the declcontext of the lambda's
/// call operator, for name lookup purposes for a lambda init capture.
///
/// CodeGen handles emission of lambda captures, ignoring these dummy
/// variables appropriately.
VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc,
QualType InitCaptureType, IdentifierInfo *Id, Expr *Init);
/// \brief Build the implicit field for an init-capture.
FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var);
/// \brief Note that we have finished the explicit captures for the
/// given lambda.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
/// \brief Introduce the lambda parameters into scope.
void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope);
/// \brief Deduce a block or lambda's return type based on the return
/// statements present in the body.
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
/// ActOnStartOfLambdaDefinition - This is called just before we start
/// parsing the body of a lambda; it analyzes the explicit captures and
/// arguments, and sets up various data-structures for the body of the
/// lambda.
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Declarator &ParamInfo, Scope *CurScope);
/// ActOnLambdaError - If there is an error parsing a lambda, this callback
/// is invoked to pop the information about the lambda.
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
bool IsInstantiation = false);
/// ActOnLambdaExpr - This is called when the body of a lambda expression
/// was successfully completed.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Scope *CurScope);
/// \brief Complete a lambda-expression having processed and attached the
/// lambda body.
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
sema::LambdaScopeInfo *LSI);
/// \brief Define the "body" of the conversion from a lambda object to a
/// function pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToFunctionPointerConversion(
SourceLocation CurrentLoc, CXXConversionDecl *Conv);
/// \brief Define the "body" of the conversion from a lambda object to a
/// block pointer.
///
/// This routine doesn't actually define a sensible body; rather, it fills
/// in the initialization expression needed to copy the lambda object into
/// the block, and IR generation actually generates the real body of the
/// block pointer conversion.
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
CXXConversionDecl *Conv);
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
SourceLocation ConvLocation,
CXXConversionDecl *Conv,
Expr *Src);
// ParseObjCStringLiteral - Parse Objective-C string literals.
ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
Expr **Strings,
unsigned NumStrings);
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
/// numeric literal expression. Type of the expression will be "NSNumber *"
/// or "id" if NSNumber is unavailable.
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
bool Value);
ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
/// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
/// '@' prefixed parenthesized expression. The type of the expression will
/// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
/// of ValueType, which is allowed to be a built-in numeric type, "char *",
/// "const char *" or C structure with attribute 'objc_boxable'.
ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
Expr *IndexExpr,
ObjCMethodDecl *getterMethod,
ObjCMethodDecl *setterMethod);
ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
ObjCDictionaryElement *Elements,
unsigned NumElements);
ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
TypeSourceInfo *EncodedTypeInfo,
SourceLocation RParenLoc);
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
CXXConversionDecl *Method,
bool HadMultipleCandidates);
ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
SourceLocation EncodeLoc,
SourceLocation LParenLoc,
ParsedType Ty,
SourceLocation RParenLoc);
/// ParseObjCSelectorExpression - Build selector expression for \@selector
ExprResult ParseObjCSelectorExpression(Selector Sel,
SourceLocation AtLoc,
SourceLocation SelLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool WarnMultipleSelectors);
/// ParseObjCProtocolExpression - Build protocol expression for \@protocol
ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
SourceLocation AtLoc,
SourceLocation ProtoLoc,
SourceLocation LParenLoc,
SourceLocation ProtoIdLoc,
SourceLocation RParenLoc);
//===--------------------------------------------------------------------===//
// C++ Declarations
//
Decl *ActOnStartLinkageSpecification(Scope *S,
SourceLocation ExternLoc,
Expr *LangStr,
SourceLocation LBraceLoc);
Decl *ActOnFinishLinkageSpecification(Scope *S,
Decl *LinkageSpec,
SourceLocation RBraceLoc);
//===--------------------------------------------------------------------===//
// C++ Classes
//
bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
const CXXScopeSpec *SS = nullptr);
bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
bool ActOnAccessSpecifier(AccessSpecifier Access,
SourceLocation ASLoc,
SourceLocation ColonLoc,
AttributeList *Attrs = nullptr);
NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
Declarator &D,
MultiTemplateParamsArg TemplateParameterLists,
Expr *BitfieldWidth, const VirtSpecifiers &VS,
InClassInitStyle InitStyle);
void ActOnStartCXXInClassMemberInitializer();
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
SourceLocation EqualLoc,
Expr *Init);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
SourceLocation LParenLoc,
ArrayRef<Expr *> Args,
SourceLocation RParenLoc,
SourceLocation EllipsisLoc);
MemInitResult ActOnMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *InitList,
SourceLocation EllipsisLoc);
MemInitResult BuildMemInitializer(Decl *ConstructorD,
Scope *S,
CXXScopeSpec &SS,
IdentifierInfo *MemberOrBase,
ParsedType TemplateTypeTy,
const DeclSpec &DS,
SourceLocation IdLoc,
Expr *Init,
SourceLocation EllipsisLoc);
MemInitResult BuildMemberInitializer(ValueDecl *Member,
Expr *Init,
SourceLocation IdLoc);
MemInitResult BuildBaseInitializer(QualType BaseType,
TypeSourceInfo *BaseTInfo,
Expr *Init,
CXXRecordDecl *ClassDecl,
SourceLocation EllipsisLoc);
MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
Expr *Init,
CXXRecordDecl *ClassDecl);
bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
CXXCtorInitializer *Initializer);
bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
ArrayRef<CXXCtorInitializer *> Initializers = None);
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
/// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
/// mark all the non-trivial destructors of its members and bases as
/// referenced.
void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
CXXRecordDecl *Record);
/// \brief The list of classes whose vtables have been used within
/// this translation unit, and the source locations at which the
/// first use occurred.
typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
/// \brief The list of vtables that are required but have not yet been
/// materialized.
SmallVector<VTableUse, 16> VTableUses;
/// \brief The set of classes whose vtables have been used within
/// this translation unit, and a bit that will be true if the vtable is
/// required to be emitted (otherwise, it should be emitted only if needed
/// by code generation).
llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
/// \brief Load any externally-stored vtable uses.
void LoadExternalVTableUses();
/// \brief Note that the vtable for the given class was used at the
/// given location.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
bool DefinitionRequired = false);
/// \brief Mark the exception specifications of all virtual member functions
/// in the given class as needed.
void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
const CXXRecordDecl *RD);
/// MarkVirtualMembersReferenced - Will mark all members of the given
/// CXXRecordDecl referenced.
void MarkVirtualMembersReferenced(SourceLocation Loc,
const CXXRecordDecl *RD);
/// \brief Define all of the vtables that have been used in this
/// translation unit and reference any virtual members used by those
/// vtables.
///
/// \returns true if any work was done, false otherwise.
bool DefineUsedVTables();
void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
void ActOnMemInitializers(Decl *ConstructorDecl,
SourceLocation ColonLoc,
ArrayRef<CXXCtorInitializer*> MemInits,
bool AnyErrors);
void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
void propagateDLLAttrToBaseClassTemplate(
CXXRecordDecl *Class, Attr *ClassAttr,
ClassTemplateSpecializationDecl *BaseTemplateSpec,
SourceLocation BaseLoc);
void CheckCompletedCXXClass(CXXRecordDecl *Record);
void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
Decl *TagDecl,
SourceLocation LBrac,
SourceLocation RBrac,
AttributeList *AttrList);
void ActOnFinishCXXMemberDecls();
void ActOnFinishCXXMemberDefaultArgs(Decl *D);
void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template);
void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
void ActOnFinishDelayedMemberInitializers(Decl *Record);
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
CachedTokens &Toks);
void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
bool IsInsideALocalClassWithinATemplateFunction();
Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
Expr *AssertMessageExpr,
SourceLocation RParenLoc);
Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
Expr *AssertExpr,
StringLiteral *AssertMessageExpr,
SourceLocation RParenLoc,
bool Failed);
FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
SourceLocation FriendLoc,
TypeSourceInfo *TSInfo);
Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
MultiTemplateParamsArg TemplateParams);
NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
MultiTemplateParamsArg TemplateParams);
QualType CheckConstructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
void CheckConstructor(CXXConstructorDecl *Constructor);
QualType CheckDestructorDeclarator(Declarator &D, QualType R,
StorageClass& SC);
bool CheckDestructor(CXXDestructorDecl *Destructor);
void CheckConversionDeclarator(Declarator &D, QualType &R,
StorageClass& SC);
Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD);
void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD,
const FunctionProtoType *T);
void CheckDelayedMemberExceptionSpecs();
//===--------------------------------------------------------------------===//
// C++ Derived Classes
//
/// ActOnBaseSpecifier - Parsed a base specifier
CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
SourceRange SpecifierRange,
bool Virtual, AccessSpecifier Access,
TypeSourceInfo *TInfo,
SourceLocation EllipsisLoc);
BaseResult ActOnBaseSpecifier(Decl *classdecl,
SourceRange SpecifierRange,
ParsedAttributes &Attrs,
bool Virtual, AccessSpecifier Access,
ParsedType basetype,
SourceLocation BaseLoc,
SourceLocation EllipsisLoc);
bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases,
unsigned NumBases);
void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases,
unsigned NumBases);
bool IsDerivedFrom(QualType Derived, QualType Base);
bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths);
// FIXME: I don't like this name.
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
SourceLocation Loc, SourceRange Range,
CXXCastPath *BasePath = nullptr,
bool IgnoreAccess = false);
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
unsigned InaccessibleBaseID,
unsigned AmbigiousBaseConvID,
SourceLocation Loc, SourceRange Range,
DeclarationName Name,
CXXCastPath *BasePath);
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionReturnType - Checks whether the return types are
/// covariant, according to C++ [class.virtual]p5.
bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
/// CheckOverridingFunctionExceptionSpec - Checks whether the exception
/// spec is a subset of base spec.
bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
/// CheckOverrideControl - Check C++11 override control semantics.
void CheckOverrideControl(NamedDecl *D);
/// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
/// not used in the declaration of an overriding method.
void DiagnoseAbsenceOfOverrideControl(NamedDecl *D);
/// CheckForFunctionMarkedFinal - Checks whether a virtual member function
/// overrides a virtual member function marked 'final', according to
/// C++11 [class.virtual]p4.
bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
const CXXMethodDecl *Old);
//===--------------------------------------------------------------------===//
// C++ Access Control
//
enum AccessResult {
AR_accessible,
AR_inaccessible,
AR_dependent,
AR_delayed
};
bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
NamedDecl *PrevMemberDecl,
AccessSpecifier LexicalAS);
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
DeclAccessPair FoundDecl);
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
SourceRange PlacementRange,
CXXRecordDecl *NamingClass,
DeclAccessPair FoundDecl,
bool Diagnose = true);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
const InitializedEntity &Entity,
AccessSpecifier Access,
bool IsCopyBindingRefToTemp = false);
AccessResult CheckConstructorAccess(SourceLocation Loc,
CXXConstructorDecl *D,
const InitializedEntity &Entity,
AccessSpecifier Access,
const PartialDiagnostic &PDiag);
AccessResult CheckDestructorAccess(SourceLocation Loc,
CXXDestructorDecl *Dtor,
const PartialDiagnostic &PDiag,
QualType objectType = QualType());
AccessResult CheckFriendAccess(NamedDecl *D);
AccessResult CheckMemberAccess(SourceLocation UseLoc,
CXXRecordDecl *NamingClass,
DeclAccessPair Found);
AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
Expr *ObjectExpr,
Expr *ArgExpr,
DeclAccessPair FoundDecl);
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
DeclAccessPair FoundDecl);
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
QualType Base, QualType Derived,
const CXXBasePath &Path,
unsigned DiagID,
bool ForceCheck = false,
bool ForceUnprivileged = false);
void CheckLookupAccess(const LookupResult &R);
bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx);
bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
AccessSpecifier access,
QualType objectType);
void HandleDependentAccessCheck(const DependentDiagnostic &DD,
const MultiLevelTemplateArgumentList &TemplateArgs);
void PerformDependentDiagnostics(const DeclContext *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
/// \brief When true, access checking violations are treated as SFINAE
/// failures rather than hard errors.
bool AccessCheckingSFINAE;
enum AbstractDiagSelID {
AbstractNone = -1,
AbstractReturnType,
AbstractParamType,
AbstractVariableType,
AbstractFieldType,
AbstractIvarType,
AbstractSynthesizedIvarType,
AbstractArrayType
};
bool RequireNonAbstractType(SourceLocation Loc, QualType T,
TypeDiagnoser &Diagnoser);
template <typename... Ts>
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
const Ts &...Args) {
BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
return RequireNonAbstractType(Loc, T, Diagnoser);
}
void DiagnoseAbstractType(const CXXRecordDecl *RD);
bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
AbstractDiagSelID SelID = AbstractNone);
//===--------------------------------------------------------------------===//
// C++ Overloaded Operators [C++ 13.5]
//
bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
//===--------------------------------------------------------------------===//
// C++ Templates [C++ 14]
//
void FilterAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true);
bool hasAnyAcceptableTemplateNames(LookupResult &R,
bool AllowFunctionTemplates = true);
void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS,
QualType ObjectType, bool EnteringContext,
bool &MemberOfUnknownSpecialization);
TemplateNameKind isTemplateName(Scope *S,
CXXScopeSpec &SS,
bool hasTemplateKeyword,
UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template,
bool &MemberOfUnknownSpecialization);
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
SourceLocation IILoc,
Scope *S,
const CXXScopeSpec *SS,
TemplateTy &SuggestedTemplate,
TemplateNameKind &SuggestedKind);
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
Decl *ActOnTypeParameter(Scope *S, bool Typename,
SourceLocation EllipsisLoc,
SourceLocation KeyLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth, unsigned Position,
SourceLocation EqualLoc,
ParsedType DefaultArg);
QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
Expr *DefaultArg);
Decl *ActOnTemplateTemplateParameter(Scope *S,
SourceLocation TmpLoc,
TemplateParameterList *Params,
SourceLocation EllipsisLoc,
IdentifierInfo *ParamName,
SourceLocation ParamNameLoc,
unsigned Depth,
unsigned Position,
SourceLocation EqualLoc,
ParsedTemplateArgument DefaultArg);
TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,
SourceLocation ExportLoc,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
Decl **Params, unsigned NumParams,
SourceLocation RAngleLoc);
/// \brief The context in which we are checking a template parameter list.
enum TemplateParamListContext {
TPC_ClassTemplate,
TPC_VarTemplate,
TPC_FunctionTemplate,
TPC_ClassTemplateMember,
TPC_FriendClassTemplate,
TPC_FriendFunctionTemplate,
TPC_FriendFunctionTemplateDefinition,
TPC_TypeAliasTemplate
};
bool CheckTemplateParameterList(TemplateParameterList *NewParams,
TemplateParameterList *OldParams,
TemplateParamListContext TPC);
TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
SourceLocation DeclStartLoc, SourceLocation DeclLoc,
const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
ArrayRef<TemplateParameterList *> ParamLists,
bool IsFriend, bool &IsExplicitSpecialization, bool &Invalid);
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc, CXXScopeSpec &SS,
IdentifierInfo *Name, SourceLocation NameLoc,
AttributeList *Attr,
TemplateParameterList *TemplateParams,
AccessSpecifier AS,
SourceLocation ModulePrivateLoc,
SourceLocation FriendLoc,
unsigned NumOuterTemplateParamLists,
TemplateParameterList **OuterTemplateParamLists,
SkipBodyInfo *SkipBody = nullptr);
void translateTemplateArguments(const ASTTemplateArgsPtr &In,
TemplateArgumentListInfo &Out);
void NoteAllFoundTemplates(TemplateName Name);
QualType CheckTemplateIdType(TemplateName Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs);
TypeResult
ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
TemplateTy Template, SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
bool IsCtorOrDtorName = false);
/// \brief Parsed an elaborated-type-specifier that refers to a template-id,
/// such as \c class T::template apply<U>.
TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
TypeSpecifierType TagSpec,
SourceLocation TagLoc,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
TemplateTy TemplateD,
SourceLocation TemplateLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgsIn,
SourceLocation RAngleLoc);
DeclResult ActOnVarTemplateSpecialization(
Scope *S, Declarator &D, TypeSourceInfo *DI,
SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
StorageClass SC, bool IsPartialSpecialization);
DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation TemplateNameLoc,
const TemplateArgumentListInfo &TemplateArgs);
ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
const DeclarationNameInfo &NameInfo,
VarTemplateDecl *Template,
SourceLocation TemplateLoc,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
LookupResult &R,
bool RequiresADL,
const TemplateArgumentListInfo *TemplateArgs);
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
TemplateNameKind ActOnDependentTemplateName(Scope *S,
CXXScopeSpec &SS,
SourceLocation TemplateKWLoc,
UnqualifiedId &Name,
ParsedType ObjectType,
bool EnteringContext,
TemplateTy &Template);
DeclResult
ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK,
SourceLocation KWLoc,
SourceLocation ModulePrivateLoc,
TemplateIdAnnotation &TemplateId,
AttributeList *Attr,
MultiTemplateParamsArg TemplateParameterLists,
SkipBodyInfo *SkipBody = nullptr);
Decl *ActOnTemplateDeclarator(Scope *S,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
MultiTemplateParamsArg TemplateParameterLists,
Declarator &D);
bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
TemplateSpecializationKind NewTSK,
NamedDecl *PrevDecl,
TemplateSpecializationKind PrevTSK,
SourceLocation PrevPtOfInstantiation,
bool &SuppressNew);
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
const TemplateArgumentListInfo &ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD,
TemplateArgumentListInfo *ExplicitTemplateArgs,
LookupResult &Previous);
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
DeclResult
ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec,
SourceLocation KWLoc,
const CXXScopeSpec &SS,
TemplateTy Template,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc,
AttributeList *Attr);
DeclResult
ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
unsigned TagSpec,
SourceLocation KWLoc,
CXXScopeSpec &SS,
IdentifierInfo *Name,
SourceLocation NameLoc,
AttributeList *Attr);
DeclResult ActOnExplicitInstantiation(Scope *S,
SourceLocation ExternLoc,
SourceLocation TemplateLoc,
Declarator &D);
TemplateArgumentLoc
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
Decl *Param,
SmallVectorImpl<TemplateArgument>
&Converted,
bool &HasDefaultArg);
/// \brief Specifies the context in which a particular template
/// argument is being checked.
enum CheckTemplateArgumentKind {
/// \brief The template argument was specified in the code or was
/// instantiated with some deduced template arguments.
CTAK_Specified,
/// \brief The template argument was deduced via template argument
/// deduction.
CTAK_Deduced,
/// \brief The template argument was deduced from an array bound
/// via template argument deduction.
CTAK_DeducedFromArrayBound
};
bool CheckTemplateArgument(NamedDecl *Param,
TemplateArgumentLoc &Arg,
NamedDecl *Template,
SourceLocation TemplateLoc,
SourceLocation RAngleLoc,
unsigned ArgumentPackIndex,
SmallVectorImpl<TemplateArgument> &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
/// \brief Check that the given template arguments can be be provided to
/// the given template, converting the arguments along the way.
///
/// \param Template The template to which the template arguments are being
/// provided.
///
/// \param TemplateLoc The location of the template name in the source.
///
/// \param TemplateArgs The list of template arguments. If the template is
/// a template template parameter, this function may extend the set of
/// template arguments to also include substituted, defaulted template
/// arguments.
///
/// \param PartialTemplateArgs True if the list of template arguments is
/// intentionally partial, e.g., because we're checking just the initial
/// set of template arguments.
///
/// \param Converted Will receive the converted, canonicalized template
/// arguments.
///
/// \returns true if an error occurred, false otherwise.
bool CheckTemplateArgumentList(TemplateDecl *Template,
SourceLocation TemplateLoc,
TemplateArgumentListInfo &TemplateArgs,
bool PartialTemplateArgs,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
TemplateArgumentLoc &Arg,
SmallVectorImpl<TemplateArgument> &Converted);
bool CheckTemplateArgument(TemplateTypeParmDecl *Param,
TypeSourceInfo *Arg);
ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
QualType InstantiatedParamType, Expr *Arg,
TemplateArgument &Converted,
CheckTemplateArgumentKind CTAK = CTAK_Specified);
bool CheckTemplateArgument(TemplateTemplateParmDecl *Param,
TemplateArgumentLoc &Arg,
unsigned ArgumentPackIndex);
ExprResult
BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
QualType ParamType,
SourceLocation Loc);
ExprResult
BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
SourceLocation Loc);
/// \brief Enumeration describing how template parameter lists are compared
/// for equality.
enum TemplateParameterListEqualKind {
/// \brief We are matching the template parameter lists of two templates
/// that might be redeclarations.
///
/// \code
/// template<typename T> struct X;
/// template<typename T> struct X;
/// \endcode
TPL_TemplateMatch,
/// \brief We are matching the template parameter lists of two template
/// template parameters as part of matching the template parameter lists
/// of two templates that might be redeclarations.
///
/// \code
/// template<template<int I> class TT> struct X;
/// template<template<int Value> class Other> struct X;
/// \endcode
TPL_TemplateTemplateParmMatch,
/// \brief We are matching the template parameter lists of a template
/// template argument against the template parameter lists of a template
/// template parameter.
///
/// \code
/// template<template<int Value> class Metafun> struct X;
/// template<int Value> struct integer_c;
/// X<integer_c> xic;
/// \endcode
TPL_TemplateTemplateArgumentMatch
};
bool TemplateParameterListsAreEqual(TemplateParameterList *New,
TemplateParameterList *Old,
bool Complain,
TemplateParameterListEqualKind Kind,
SourceLocation TemplateArgLoc
= SourceLocation());
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
/// \brief Called when the parser has parsed a C++ typename
/// specifier, e.g., "typename T::type".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param II the identifier we're retrieving (e.g., 'type' in the example).
/// \param IdLoc the location of the identifier.
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS, const IdentifierInfo &II,
SourceLocation IdLoc);
/// \brief Called when the parser has parsed a C++ typename
/// specifier that ends in a template-id, e.g.,
/// "typename MetaFun::template apply<T1, T2>".
///
/// \param S The scope in which this typename type occurs.
/// \param TypenameLoc the location of the 'typename' keyword
/// \param SS the nested-name-specifier following the typename (e.g., 'T::').
/// \param TemplateLoc the location of the 'template' keyword, if any.
/// \param TemplateName The template name.
/// \param TemplateNameLoc The location of the template name.
/// \param LAngleLoc The location of the opening angle bracket ('<').
/// \param TemplateArgs The template arguments.
/// \param RAngleLoc The location of the closing angle bracket ('>').
TypeResult
ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
const CXXScopeSpec &SS,
SourceLocation TemplateLoc,
TemplateTy TemplateName,
SourceLocation TemplateNameLoc,
SourceLocation LAngleLoc,
ASTTemplateArgsPtr TemplateArgs,
SourceLocation RAngleLoc);
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
SourceLocation KeywordLoc,
NestedNameSpecifierLoc QualifierLoc,
const IdentifierInfo &II,
SourceLocation IILoc);
TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
SourceLocation Loc,
DeclarationName Name);
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
ExprResult RebuildExprInCurrentInstantiation(Expr *E);
bool RebuildTemplateParamsInCurrentInstantiation(
TemplateParameterList *Params);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgumentList &Args);
std::string
getTemplateArgumentBindingsText(const TemplateParameterList *Params,
const TemplateArgument *Args,
unsigned NumArgs);
//===--------------------------------------------------------------------===//
// C++ Variadic Templates (C++0x [temp.variadic])
//===--------------------------------------------------------------------===//
/// Determine whether an unexpanded parameter pack might be permitted in this
/// location. Useful for error recovery.
bool isUnexpandedParameterPackPermitted();
/// \brief The context in which an unexpanded parameter pack is
/// being diagnosed.
///
/// Note that the values of this enumeration line up with the first
/// argument to the \c err_unexpanded_parameter_pack diagnostic.
enum UnexpandedParameterPackContext {
/// \brief An arbitrary expression.
UPPC_Expression = 0,
/// \brief The base type of a class type.
UPPC_BaseType,
/// \brief The type of an arbitrary declaration.
UPPC_DeclarationType,
/// \brief The type of a data member.
UPPC_DataMemberType,
/// \brief The size of a bit-field.
UPPC_BitFieldWidth,
/// \brief The expression in a static assertion.
UPPC_StaticAssertExpression,
/// \brief The fixed underlying type of an enumeration.
UPPC_FixedUnderlyingType,
/// \brief The enumerator value.
UPPC_EnumeratorValue,
/// \brief A using declaration.
UPPC_UsingDeclaration,
/// \brief A friend declaration.
UPPC_FriendDeclaration,
/// \brief A declaration qualifier.
UPPC_DeclarationQualifier,
/// \brief An initializer.
UPPC_Initializer,
/// \brief A default argument.
UPPC_DefaultArgument,
/// \brief The type of a non-type template parameter.
UPPC_NonTypeTemplateParameterType,
/// \brief The type of an exception.
UPPC_ExceptionType,
/// \brief Partial specialization.
UPPC_PartialSpecialization,
/// \brief Microsoft __if_exists.
UPPC_IfExists,
/// \brief Microsoft __if_not_exists.
UPPC_IfNotExists,
/// \brief Lambda expression.
UPPC_Lambda,
/// \brief Block expression,
UPPC_Block
};
/// \brief Diagnose unexpanded parameter packs.
///
/// \param Loc The location at which we should emit the diagnostic.
///
/// \param UPPC The context in which we are diagnosing unexpanded
/// parameter packs.
///
/// \param Unexpanded the set of unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
UnexpandedParameterPackContext UPPC,
ArrayRef<UnexpandedParameterPack> Unexpanded);
/// \brief If the given type contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The source location where a diagnostc should be emitted.
///
/// \param T The type that is being checked for unexpanded parameter
/// packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
UnexpandedParameterPackContext UPPC);
/// \brief If the given expression contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param E The expression that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(Expr *E,
UnexpandedParameterPackContext UPPC = UPPC_Expression);
/// \brief If the given nested-name-specifier contains an unexpanded
/// parameter pack, diagnose the error.
///
/// \param SS The nested-name-specifier that is being checked for
/// unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
UnexpandedParameterPackContext UPPC);
/// \brief If the given name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param NameInfo The name (with source location information) that
/// is being checked for unexpanded parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
UnexpandedParameterPackContext UPPC);
/// \brief If the given template name contains an unexpanded parameter pack,
/// diagnose the error.
///
/// \param Loc The location of the template name.
///
/// \param Template The template name that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
TemplateName Template,
UnexpandedParameterPackContext UPPC);
/// \brief If the given template argument contains an unexpanded parameter
/// pack, diagnose the error.
///
/// \param Arg The template argument that is being checked for unexpanded
/// parameter packs.
///
/// \returns true if an error occurred, false otherwise.
bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
UnexpandedParameterPackContext UPPC);
/// \brief Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgument Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// template argument.
///
/// \param Arg The template argument that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param T The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(QualType T,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// type.
///
/// \param TL The type that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(TypeLoc TL,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// nested-name-specifier.
///
/// \param SS The nested-name-specifier that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(CXXScopeSpec &SS,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Collect the set of unexpanded parameter packs within the given
/// name.
///
/// \param NameInfo The name that will be traversed to find
/// unexpanded parameter packs.
void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
/// \brief Invoked when parsing a template argument followed by an
/// ellipsis, which creates a pack expansion.
///
/// \param Arg The template argument preceding the ellipsis, which
/// may already be invalid.
///
/// \param EllipsisLoc The location of the ellipsis.
ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
SourceLocation EllipsisLoc);
/// \brief Invoked when parsing a type followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Type The type preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
/// \brief Construct a pack expansion type from the pattern of the pack
/// expansion.
TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief Construct a pack expansion type from the pattern of the pack
/// expansion.
QualType CheckPackExpansion(QualType Pattern,
SourceRange PatternRange,
SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
/// \brief Invoked when parsing an expression followed by an ellipsis, which
/// creates a pack expansion.
///
/// \param Pattern The expression preceding the ellipsis, which will become
/// the pattern of the pack expansion.
///
/// \param EllipsisLoc The location of the ellipsis.
ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions);
/// \brief Determine whether we could expand a pack expansion with the
/// given set of parameter packs into separate arguments by repeatedly
/// transforming the pattern.
///
/// \param EllipsisLoc The location of the ellipsis that identifies the
/// pack expansion.
///
/// \param PatternRange The source range that covers the entire pattern of
/// the pack expansion.
///
/// \param Unexpanded The set of unexpanded parameter packs within the
/// pattern.
///
/// \param ShouldExpand Will be set to \c true if the transformer should
/// expand the corresponding pack expansions into separate arguments. When
/// set, \c NumExpansions must also be set.
///
/// \param RetainExpansion Whether the caller should add an unexpanded
/// pack expansion after all of the expanded arguments. This is used
/// when extending explicitly-specified template argument packs per
/// C++0x [temp.arg.explicit]p9.
///
/// \param NumExpansions The number of separate arguments that will be in
/// the expanded form of the corresponding pack expansion. This is both an
/// input and an output parameter, which can be set by the caller if the
/// number of expansions is known a priori (e.g., due to a prior substitution)
/// and will be set by the callee when the number of expansions is known.
/// The callee must set this value when \c ShouldExpand is \c true; it may
/// set this value in other cases.
///
/// \returns true if an error occurred (e.g., because the parameter packs
/// are to be instantiated with arguments of different lengths), false
/// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
/// must be set.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
SourceRange PatternRange,
ArrayRef<UnexpandedParameterPack> Unexpanded,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool &ShouldExpand,
bool &RetainExpansion,
Optional<unsigned> &NumExpansions);
/// \brief Determine the number of arguments in the given pack expansion
/// type.
///
/// This routine assumes that the number of arguments in the expansion is
/// consistent across all of the unexpanded parameter packs in its pattern.
///
/// Returns an empty Optional if the type can't be expanded.
Optional<unsigned> getNumArgumentsInExpansion(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// \brief Determine whether the given declarator contains any unexpanded
/// parameter packs.
///
/// This routine is used by the parser to disambiguate function declarators
/// with an ellipsis prior to the ')', e.g.,
///
/// \code
/// void f(T...);
/// \endcode
///
/// To determine whether we have an (unnamed) function parameter pack or
/// a variadic function.
///
/// \returns true if the declarator contains any unexpanded parameter packs,
/// false otherwise.
bool containsUnexpandedParameterPacks(Declarator &D);
/// \brief Returns the pattern of the pack expansion for a template argument.
///
/// \param OrigLoc The template argument to expand.
///
/// \param Ellipsis Will be set to the location of the ellipsis.
///
/// \param NumExpansions Will be set to the number of expansions that will
/// be generated from this pack expansion, if known a priori.
TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
TemplateArgumentLoc OrigLoc,
SourceLocation &Ellipsis,
Optional<unsigned> &NumExpansions) const;
//===--------------------------------------------------------------------===//
// C++ Template Argument Deduction (C++ [temp.deduct])
//===--------------------------------------------------------------------===//
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType);
/// \brief Describes the result of template argument deduction.
///
/// The TemplateDeductionResult enumeration describes the result of
/// template argument deduction, as returned from
/// DeduceTemplateArguments(). The separate TemplateDeductionInfo
/// structure provides additional information about the results of
/// template argument deduction, e.g., the deduced template argument
/// list (if successful) or the specific template parameters or
/// deduced arguments that were involved in the failure.
enum TemplateDeductionResult {
/// \brief Template argument deduction was successful.
TDK_Success = 0,
/// \brief The declaration was invalid; do nothing.
TDK_Invalid,
/// \brief Template argument deduction exceeded the maximum template
/// instantiation depth (which has already been diagnosed).
TDK_InstantiationDepth,
/// \brief Template argument deduction did not deduce a value
/// for every template parameter.
TDK_Incomplete,
/// \brief Template argument deduction produced inconsistent
/// deduced values for the given template parameter.
TDK_Inconsistent,
/// \brief Template argument deduction failed due to inconsistent
/// cv-qualifiers on a template parameter type that would
/// otherwise be deduced, e.g., we tried to deduce T in "const T"
/// but were given a non-const "X".
TDK_Underqualified,
/// \brief Substitution of the deduced template argument values
/// resulted in an error.
TDK_SubstitutionFailure,
/// \brief A non-depnedent component of the parameter did not match the
/// corresponding component of the argument.
TDK_NonDeducedMismatch,
/// \brief When performing template argument deduction for a function
/// template, there were too many call arguments.
TDK_TooManyArguments,
/// \brief When performing template argument deduction for a function
/// template, there were too few call arguments.
TDK_TooFewArguments,
/// \brief The explicitly-specified template arguments were not valid
/// template arguments for the given template.
TDK_InvalidExplicitArguments,
/// \brief The arguments included an overloaded function name that could
/// not be resolved to a suitable function.
TDK_FailedOverloadResolution,
/// \brief Deduction failed; that's all we know.
TDK_MiscellaneousDeductionFailure
};
TemplateDeductionResult
DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
const TemplateArgumentList &TemplateArgs,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult SubstituteExplicitTemplateArguments(
FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo &ExplicitTemplateArgs,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
sema::TemplateDeductionInfo &Info);
/// brief A function argument from which we performed template argument
// deduction for a call.
struct OriginalCallArg {
OriginalCallArg(QualType OriginalParamType,
unsigned ArgIdx,
QualType OriginalArgType)
: OriginalParamType(OriginalParamType), ArgIdx(ArgIdx),
OriginalArgType(OriginalArgType) { }
QualType OriginalParamType;
unsigned ArgIdx;
QualType OriginalArgType;
};
TemplateDeductionResult
FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate,
SmallVectorImpl<DeducedTemplateArgument> &Deduced,
unsigned NumExplicitlySpecified,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
bool PartialOverloading = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
ArrayRef<Expr *> Args,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool PartialOverloading = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
QualType ArgFunctionType,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool InOverloadResolution = false);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
QualType ToType,
CXXConversionDecl *&Specialization,
sema::TemplateDeductionInfo &Info);
TemplateDeductionResult
DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
TemplateArgumentListInfo *ExplicitTemplateArgs,
FunctionDecl *&Specialization,
sema::TemplateDeductionInfo &Info,
bool InOverloadResolution = false);
/// \brief Substitute Replacement for \p auto in \p TypeWithAuto
QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
/// \brief Substitute Replacement for auto in TypeWithAuto
TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
QualType Replacement);
/// \brief Result type of DeduceAutoType.
enum DeduceAutoResult {
DAR_Succeeded,
DAR_Failed,
DAR_FailedAlreadyDiagnosed
};
DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer,
QualType &Result);
DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer,
QualType &Result);
void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
bool Diagnose = true);
TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
SourceLocation ReturnLoc,
Expr *&RetExpr, AutoType *AT);
FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1,
FunctionTemplateDecl *FT2,
SourceLocation Loc,
TemplatePartialOrderingContext TPOC,
unsigned NumCallArguments1,
unsigned NumCallArguments2);
UnresolvedSetIterator
getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
TemplateSpecCandidateSet &FailedCandidates,
SourceLocation Loc,
const PartialDiagnostic &NoneDiag,
const PartialDiagnostic &AmbigDiag,
const PartialDiagnostic &CandidateDiag,
bool Complain = true, QualType TargetType = QualType());
ClassTemplatePartialSpecializationDecl *
getMoreSpecializedPartialSpecialization(
ClassTemplatePartialSpecializationDecl *PS1,
ClassTemplatePartialSpecializationDecl *PS2,
SourceLocation Loc);
VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
VarTemplatePartialSpecializationDecl *PS1,
VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
bool OnlyDeduced,
unsigned Depth,
llvm::SmallBitVector &Used);
void MarkDeducedTemplateParameters(
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced) {
return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
}
static void MarkDeducedTemplateParameters(ASTContext &Ctx,
const FunctionTemplateDecl *FunctionTemplate,
llvm::SmallBitVector &Deduced);
//===--------------------------------------------------------------------===//
// C++ Template Instantiation
//
MultiLevelTemplateArgumentList
getTemplateInstantiationArgs(NamedDecl *D,
const TemplateArgumentList *Innermost = nullptr,
bool RelativeToPrimary = false,
const FunctionDecl *Pattern = nullptr);
/// \brief A template instantiation that is currently in progress.
struct ActiveTemplateInstantiation {
/// \brief The kind of template instantiation we are performing
enum InstantiationKind {
/// We are instantiating a template declaration. The entity is
/// the declaration we're instantiating (e.g., a CXXRecordDecl).
TemplateInstantiation,
/// We are instantiating a default argument for a template
/// parameter. The Entity is the template, and
/// TemplateArgs/NumTemplateArguments provides the template
/// arguments as specified.
/// FIXME: Use a TemplateArgumentList
DefaultTemplateArgumentInstantiation,
/// We are instantiating a default argument for a function.
/// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
/// provides the template arguments as specified.
DefaultFunctionArgumentInstantiation,
/// We are substituting explicit template arguments provided for
/// a function template. The entity is a FunctionTemplateDecl.
ExplicitTemplateArgumentSubstitution,
/// We are substituting template argument determined as part of
/// template argument deduction for either a class template
/// partial specialization or a function template. The
/// Entity is either a ClassTemplatePartialSpecializationDecl or
/// a FunctionTemplateDecl.
DeducedTemplateArgumentSubstitution,
/// We are substituting prior template arguments into a new
/// template parameter. The template parameter itself is either a
/// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
PriorTemplateArgumentSubstitution,
/// We are checking the validity of a default template argument that
/// has been used when naming a template-id.
DefaultTemplateArgumentChecking,
/// We are instantiating the exception specification for a function
/// template which was deferred until it was needed.
ExceptionSpecInstantiation
} Kind;
/// \brief The point of instantiation within the source code.
SourceLocation PointOfInstantiation;
/// \brief The template (or partial specialization) in which we are
/// performing the instantiation, for substitutions of prior template
/// arguments.
NamedDecl *Template;
/// \brief The entity that is being instantiated.
Decl *Entity;
/// \brief The list of template arguments we are substituting, if they
/// are not part of the entity.
const TemplateArgument *TemplateArgs;
/// \brief The number of template arguments in TemplateArgs.
unsigned NumTemplateArgs;
/// \brief The template deduction info object associated with the
/// substitution or checking of explicit or deduced template arguments.
sema::TemplateDeductionInfo *DeductionInfo;
/// \brief The source range that covers the construct that cause
/// the instantiation, e.g., the template-id that causes a class
/// template instantiation.
SourceRange InstantiationRange;
ActiveTemplateInstantiation()
: Kind(TemplateInstantiation), Template(nullptr), Entity(nullptr),
TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {}
/// \brief Determines whether this template is an actual instantiation
/// that should be counted toward the maximum instantiation depth.
bool isInstantiationRecord() const;
friend bool operator==(const ActiveTemplateInstantiation &X,
const ActiveTemplateInstantiation &Y) {
if (X.Kind != Y.Kind)
return false;
if (X.Entity != Y.Entity)
return false;
switch (X.Kind) {
case TemplateInstantiation:
case ExceptionSpecInstantiation:
return true;
case PriorTemplateArgumentSubstitution:
case DefaultTemplateArgumentChecking:
return X.Template == Y.Template && X.TemplateArgs == Y.TemplateArgs;
case DefaultTemplateArgumentInstantiation:
case ExplicitTemplateArgumentSubstitution:
case DeducedTemplateArgumentSubstitution:
case DefaultFunctionArgumentInstantiation:
return X.TemplateArgs == Y.TemplateArgs;
}
llvm_unreachable("Invalid InstantiationKind!");
}
friend bool operator!=(const ActiveTemplateInstantiation &X,
const ActiveTemplateInstantiation &Y) {
return !(X == Y);
}
};
/// \brief List of active template instantiations.
///
/// This vector is treated as a stack. As one template instantiation
/// requires another template instantiation, additional
/// instantiations are pushed onto the stack up to a
/// user-configurable limit LangOptions::InstantiationDepth.
SmallVector<ActiveTemplateInstantiation, 16>
ActiveTemplateInstantiations;
/// \brief Extra modules inspected when performing a lookup during a template
/// instantiation. Computed lazily.
SmallVector<Module*, 16> ActiveTemplateInstantiationLookupModules;
/// \brief Cache of additional modules that should be used for name lookup
/// within the current template instantiation. Computed lazily; use
/// getLookupModules() to get a complete set.
llvm::DenseSet<Module*> LookupModulesCache;
/// \brief Get the set of additional modules that should be checked during
/// name lookup. A module and its imports become visible when instanting a
/// template defined within it.
llvm::DenseSet<Module*> &getLookupModules();
/// \brief Whether we are in a SFINAE context that is not associated with
/// template instantiation.
///
/// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
/// of a template instantiation or template argument deduction.
bool InNonInstantiationSFINAEContext;
/// \brief The number of ActiveTemplateInstantiation entries in
/// \c ActiveTemplateInstantiations that are not actual instantiations and,
/// therefore, should not be counted as part of the instantiation depth.
unsigned NonInstantiationEntries;
/// \brief The last template from which a template instantiation
/// error or warning was produced.
///
/// This value is used to suppress printing of redundant template
/// instantiation backtraces when there are multiple errors in the
/// same instantiation. FIXME: Does this belong in Sema? It's tough
/// to implement it anywhere else.
ActiveTemplateInstantiation LastTemplateInstantiationErrorContext;
/// \brief The current index into pack expansion arguments that will be
/// used for substitution of parameter packs.
///
/// The pack expansion index will be -1 to indicate that parameter packs
/// should be instantiated as themselves. Otherwise, the index specifies
/// which argument within the parameter pack will be used for substitution.
int ArgumentPackSubstitutionIndex;
/// \brief RAII object used to change the argument pack substitution index
/// within a \c Sema object.
///
/// See \c ArgumentPackSubstitutionIndex for more information.
class ArgumentPackSubstitutionIndexRAII {
Sema &Self;
int OldSubstitutionIndex;
public:
ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
: Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
}
~ArgumentPackSubstitutionIndexRAII() {
Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
}
};
friend class ArgumentPackSubstitutionRAII;
/// \brief The stack of calls expression undergoing template instantiation.
///
/// The top of this stack is used by a fixit instantiating unresolved
/// function calls to fix the AST to match the textual change it prints.
SmallVector<CallExpr *, 8> CallsUndergoingInstantiation;
/// \brief For each declaration that involved template argument deduction, the
/// set of diagnostics that were suppressed during that template argument
/// deduction.
///
/// FIXME: Serialize this structure to the AST file.
typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
SuppressedDiagnosticsMap;
SuppressedDiagnosticsMap SuppressedDiagnostics;
/// \brief A stack object to be created when performing template
/// instantiation.
///
/// Construction of an object of type \c InstantiatingTemplate
/// pushes the current instantiation onto the stack of active
/// instantiations. If the size of this stack exceeds the maximum
/// number of recursive template instantiations, construction
/// produces an error and evaluates true.
///
/// Destruction of this object will pop the named instantiation off
/// the stack.
struct InstantiatingTemplate {
/// \brief Note that we are instantiating a class template,
/// function template, or a member thereof.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Decl *Entity,
SourceRange InstantiationRange = SourceRange());
struct ExceptionSpecification {};
/// \brief Note that we are instantiating an exception specification
/// of a function template.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionDecl *Entity, ExceptionSpecification,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating a default argument in a
/// template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
FunctionTemplateDecl *FunctionTemplate,
ArrayRef<TemplateArgument> TemplateArgs,
ActiveTemplateInstantiation::InstantiationKind Kind,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating as part of template
/// argument deduction for a class template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ClassTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are instantiating as part of template
/// argument deduction for a variable template partial
/// specialization.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
VarTemplatePartialSpecializationDecl *PartialSpec,
ArrayRef<TemplateArgument> TemplateArgs,
sema::TemplateDeductionInfo &DeductionInfo,
SourceRange InstantiationRange = SourceRange());
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
ParmVarDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange = SourceRange());
/// \brief Note that we are substituting prior template arguments into a
/// non-type parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
NonTypeTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// \brief Note that we are substituting prior template arguments into a
/// template template parameter.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
NamedDecl *Template,
TemplateTemplateParmDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// \brief Note that we are checking the default template argument
/// against the template parameter for a given template-id.
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
TemplateDecl *Template,
NamedDecl *Param,
ArrayRef<TemplateArgument> TemplateArgs,
SourceRange InstantiationRange);
/// \brief Note that we have finished instantiating this template.
void Clear();
~InstantiatingTemplate() { Clear(); }
/// \brief Determines whether we have exceeded the maximum
/// recursive template instantiations.
bool isInvalid() const { return Invalid; }
private:
Sema &SemaRef;
bool Invalid;
bool SavedInNonInstantiationSFINAEContext;
bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
SourceRange InstantiationRange);
InstantiatingTemplate(
Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
Decl *Entity, NamedDecl *Template = nullptr,
ArrayRef<TemplateArgument> TemplateArgs = ArrayRef<TemplateArgument>(),
sema::TemplateDeductionInfo *DeductionInfo = nullptr);
InstantiatingTemplate(const InstantiatingTemplate&) = delete;
InstantiatingTemplate&
operator=(const InstantiatingTemplate&) = delete;
};
void PrintInstantiationStack();
/// \brief Determines whether we are currently in a context where
/// template argument substitution failures are not considered
/// errors.
///
/// \returns An empty \c Optional if we're not in a SFINAE context.
/// Otherwise, contains a pointer that, if non-NULL, contains the nearest
/// template-deduction context object, which can be used to capture
/// diagnostics that will be suppressed.
Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
/// \brief Determines whether we are currently in a context that
/// is not evaluated as per C++ [expr] p5.
bool isUnevaluatedContext() const {
assert(!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context");
return ExprEvalContexts.back().isUnevaluated();
}
/// \brief RAII class used to determine whether SFINAE has
/// trapped any errors that occur during template argument
/// deduction.
class SFINAETrap {
Sema &SemaRef;
unsigned PrevSFINAEErrors;
bool PrevInNonInstantiationSFINAEContext;
bool PrevAccessCheckingSFINAE;
public:
explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
: SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
PrevInNonInstantiationSFINAEContext(
SemaRef.InNonInstantiationSFINAEContext),
PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE)
{
if (!SemaRef.isSFINAEContext())
SemaRef.InNonInstantiationSFINAEContext = true;
SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
}
~SFINAETrap() {
SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
SemaRef.InNonInstantiationSFINAEContext
= PrevInNonInstantiationSFINAEContext;
SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
}
/// \brief Determine whether any SFINAE errors have been trapped.
bool hasErrorOccurred() const {
return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
}
};
/// \brief RAII class used to indicate that we are performing provisional
/// semantic analysis to determine the validity of a construct, so
/// typo-correction and diagnostics in the immediate context (not within
/// implicitly-instantiated templates) should be suppressed.
class TentativeAnalysisScope {
Sema &SemaRef;
// FIXME: Using a SFINAETrap for this is a hack.
SFINAETrap Trap;
bool PrevDisableTypoCorrection;
public:
explicit TentativeAnalysisScope(Sema &SemaRef)
: SemaRef(SemaRef), Trap(SemaRef, true),
PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
SemaRef.DisableTypoCorrection = true;
}
~TentativeAnalysisScope() {
SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
}
};
/// \brief The current instantiation scope used to store local
/// variables.
LocalInstantiationScope *CurrentInstantiationScope;
/// \brief Tracks whether we are in a context where typo correction is
/// disabled.
bool DisableTypoCorrection;
/// \brief The number of typos corrected by CorrectTypo.
unsigned TyposCorrected;
typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
/// \brief A cache containing identifiers for which typo correction failed and
/// their locations, so that repeated attempts to correct an identifier in a
/// given location are ignored if typo correction already failed for it.
IdentifierSourceLocations TypoCorrectionFailures;
/// \brief Worker object for performing CFG-based warnings.
sema::AnalysisBasedWarnings AnalysisWarnings;
threadSafety::BeforeSet *ThreadSafetyDeclCache;
/// \brief An entity for which implicit template instantiation is required.
///
/// The source location associated with the declaration is the first place in
/// the source code where the declaration was "used". It is not necessarily
/// the point of instantiation (which will be either before or after the
/// namespace-scope declaration that triggered this implicit instantiation),
/// However, it is the location that diagnostics should generally refer to,
/// because users will need to know what code triggered the instantiation.
typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
/// \brief The queue of implicit template instantiations that are required
/// but have not yet been performed.
std::deque<PendingImplicitInstantiation> PendingInstantiations;
class SavePendingInstantiationsAndVTableUsesRAII {
public:
SavePendingInstantiationsAndVTableUsesRAII(Sema &S, bool Enabled)
: S(S), Enabled(Enabled) {
if (!Enabled) return;
SavedPendingInstantiations.swap(S.PendingInstantiations);
SavedVTableUses.swap(S.VTableUses);
}
~SavePendingInstantiationsAndVTableUsesRAII() {
if (!Enabled) return;
// Restore the set of pending vtables.
assert(S.VTableUses.empty() &&
"VTableUses should be empty before it is discarded.");
S.VTableUses.swap(SavedVTableUses);
// Restore the set of pending implicit instantiations.
assert(S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded.");
S.PendingInstantiations.swap(SavedPendingInstantiations);
}
private:
Sema &S;
SmallVector<VTableUse, 16> SavedVTableUses;
std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
bool Enabled;
};
/// \brief The queue of implicit template instantiations that are required
/// and must be performed within the current local scope.
///
/// This queue is only used for member functions of local classes in
/// templates, which must be instantiated in the same scope as their
/// enclosing function, so that they can reference function-local
/// types, static variables, enumerators, etc.
std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
class SavePendingLocalImplicitInstantiationsRAII {
public:
SavePendingLocalImplicitInstantiationsRAII(Sema &S): S(S) {
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
~SavePendingLocalImplicitInstantiationsRAII() {
assert(S.PendingLocalImplicitInstantiations.empty() &&
"there shouldn't be any pending local implicit instantiations");
SavedPendingLocalImplicitInstantiations.swap(
S.PendingLocalImplicitInstantiations);
}
private:
Sema &S;
std::deque<PendingImplicitInstantiation>
SavedPendingLocalImplicitInstantiations;
};
void PerformPendingInstantiations(bool LocalOnly = false);
TypeSourceInfo *SubstType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
QualType SubstType(QualType T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstType(TypeLoc TL,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc, DeclarationName Entity);
TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
const MultiLevelTemplateArgumentList &TemplateArgs,
SourceLocation Loc,
DeclarationName Entity,
CXXRecordDecl *ThisContext,
unsigned ThisTypeQuals);
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
const MultiLevelTemplateArgumentList &Args);
ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs,
int indexAdjustment,
Optional<unsigned> NumExpansions,
bool ExpectParameterPack);
bool SubstParmTypes(SourceLocation Loc,
ParmVarDecl **Params, unsigned NumParams,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<QualType> &ParamTypes,
SmallVectorImpl<ParmVarDecl *> *OutParams = nullptr);
/// HLSL Change Begin - back ported from llvm-project/4409a83c2935.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool ForCallExpr = false);
/// HLSL Change End - back ported from llvm-project/4409a83c2935.
ExprResult SubstExpr(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs);
/// \brief Substitute the given template arguments into a list of
/// expressions, expanding pack expansions if required.
///
/// \param Exprs The list of expressions to substitute into.
///
/// \param NumExprs The number of expressions in \p Exprs.
///
/// \param IsCall Whether this is some form of call, in which case
/// default arguments will be dropped.
///
/// \param TemplateArgs The set of template arguments to substitute.
///
/// \param Outputs Will receive all of the substituted arguments.
///
/// \returns true if an error occurred, false otherwise.
bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
const MultiLevelTemplateArgumentList &TemplateArgs,
SmallVectorImpl<Expr *> &Outputs);
StmtResult SubstStmt(Stmt *S,
const MultiLevelTemplateArgumentList &TemplateArgs);
Decl *SubstDecl(Decl *D, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs);
ExprResult SubstInitializer(Expr *E,
const MultiLevelTemplateArgumentList &TemplateArgs,
bool CXXDirectInit);
bool
SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool
InstantiateClass(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK,
bool Complain = true);
bool InstantiateEnum(SourceLocation PointOfInstantiation,
EnumDecl *Instantiation, EnumDecl *Pattern,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
bool InstantiateInClassInitializer(
SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
struct LateInstantiatedAttribute {
const Attr *TmplAttr;
LocalInstantiationScope *Scope;
Decl *NewDecl;
LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
Decl *D)
: TmplAttr(A), Scope(S), NewDecl(D)
{ }
};
typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
const Decl *Pattern, Decl *Inst,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *OuterMostScope = nullptr);
bool
InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK,
bool Complain = true);
void InstantiateClassMembers(SourceLocation PointOfInstantiation,
CXXRecordDecl *Instantiation,
const MultiLevelTemplateArgumentList &TemplateArgs,
TemplateSpecializationKind TSK);
void InstantiateClassTemplateSpecializationMembers(
SourceLocation PointOfInstantiation,
ClassTemplateSpecializationDecl *ClassTemplateSpec,
TemplateSpecializationKind TSK);
NestedNameSpecifierLoc
SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclarationNameInfo
SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
const MultiLevelTemplateArgumentList &TemplateArgs);
TemplateName
SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
SourceLocation Loc,
const MultiLevelTemplateArgumentList &TemplateArgs);
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
TemplateArgumentListInfo &Result,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
FunctionDecl *Function);
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
FunctionDecl *Function,
bool Recursive = false,
bool DefinitionRequired = false);
VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
VarTemplateDecl *VarTemplate, VarDecl *FromVar,
const TemplateArgumentList &TemplateArgList,
const TemplateArgumentListInfo &TemplateArgsInfo,
SmallVectorImpl<TemplateArgument> &Converted,
SourceLocation PointOfInstantiation, void *InsertPos,
LateInstantiatedAttrVec *LateAttrs = nullptr,
LocalInstantiationScope *StartingScope = nullptr);
VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
const MultiLevelTemplateArgumentList &TemplateArgs);
void
BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs,
LateInstantiatedAttrVec *LateAttrs,
DeclContext *Owner,
LocalInstantiationScope *StartingScope,
bool InstantiatingVarTemplate = false);
void InstantiateVariableInitializer(
VarDecl *Var, VarDecl *OldVar,
const MultiLevelTemplateArgumentList &TemplateArgs);
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
VarDecl *Var, bool Recursive = false,
bool DefinitionRequired = false);
void InstantiateStaticDataMemberDefinition(
SourceLocation PointOfInstantiation,
VarDecl *Var,
bool Recursive = false,
bool DefinitionRequired = false);
void InstantiateMemInitializers(CXXConstructorDecl *New,
const CXXConstructorDecl *Tmpl,
const MultiLevelTemplateArgumentList &TemplateArgs);
NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
const MultiLevelTemplateArgumentList &TemplateArgs);
DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
const MultiLevelTemplateArgumentList &TemplateArgs);
// Objective-C declarations.
enum ObjCContainerKind {
OCK_None = -1,
OCK_Interface = 0,
OCK_Protocol,
OCK_Category,
OCK_ClassExtension,
OCK_Implementation,
OCK_CategoryImplementation
};
ObjCContainerKind getObjCContainerKind() const;
DeclResult actOnObjCTypeParam(Scope *S,
ObjCTypeParamVariance variance,
SourceLocation varianceLoc,
unsigned index,
IdentifierInfo *paramName,
SourceLocation paramLoc,
SourceLocation colonLoc,
ParsedType typeBound);
ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
ArrayRef<Decl *> typeParams,
SourceLocation rAngleLoc);
void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
Decl *ActOnStartClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
ObjCTypeParamList *typeParamList,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange,
Decl * const *ProtoRefs,
unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc,
AttributeList *AttrList);
void ActOnSuperClassOfClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
ObjCInterfaceDecl *IDecl,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange);
void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
IdentifierInfo *SuperName,
SourceLocation SuperLoc);
Decl *ActOnCompatibilityAlias(
SourceLocation AtCompatibilityAliasLoc,
IdentifierInfo *AliasName, SourceLocation AliasLocation,
IdentifierInfo *ClassName, SourceLocation ClassLocation);
bool CheckForwardProtocolDeclarationForCircularDependency(
IdentifierInfo *PName,
SourceLocation &PLoc, SourceLocation PrevLoc,
const ObjCList<ObjCProtocolDecl> &PList);
Decl *ActOnStartProtocolInterface(
SourceLocation AtProtoInterfaceLoc,
IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc,
Decl * const *ProtoRefNames, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc,
AttributeList *AttrList);
Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
ObjCTypeParamList *typeParamList,
IdentifierInfo *CategoryName,
SourceLocation CategoryLoc,
Decl * const *ProtoRefs,
unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc);
Decl *ActOnStartClassImplementation(
SourceLocation AtClassImplLoc,
IdentifierInfo *ClassName, SourceLocation ClassLoc,
IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc);
Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *CatName,
SourceLocation CatLoc);
DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
ArrayRef<Decl *> Decls);
DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
IdentifierInfo **IdentList,
SourceLocation *IdentLocs,
ArrayRef<ObjCTypeParamList *> TypeParamLists,
unsigned NumElts);
DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
const IdentifierLocPair *IdentList,
unsigned NumElts,
AttributeList *attrList);
void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
const IdentifierLocPair *ProtocolId,
unsigned NumProtocols,
SmallVectorImpl<Decl *> &Protocols);
/// Given a list of identifiers (and their locations), resolve the
/// names to either Objective-C protocol qualifiers or type
/// arguments, as appropriate.
void actOnObjCTypeArgsOrProtocolQualifiers(
Scope *S,
ParsedType baseType,
SourceLocation lAngleLoc,
ArrayRef<IdentifierInfo *> identifiers,
ArrayRef<SourceLocation> identifierLocs,
SourceLocation rAngleLoc,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SourceLocation &protocolRAngleLoc,
bool warnOnIncompleteProtocols);
/// Build a an Objective-C protocol-qualified 'id' type where no
/// base type was specified.
TypeResult actOnObjCProtocolQualifierType(
SourceLocation lAngleLoc,
ArrayRef<Decl *> protocols,
ArrayRef<SourceLocation> protocolLocs,
SourceLocation rAngleLoc);
/// Build a specialized and/or protocol-qualified Objective-C type.
TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
Scope *S,
SourceLocation Loc,
ParsedType BaseType,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<ParsedType> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<Decl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc);
/// Build an Objective-C object pointer type.
QualType BuildObjCObjectType(QualType BaseType,
SourceLocation Loc,
SourceLocation TypeArgsLAngleLoc,
ArrayRef<TypeSourceInfo *> TypeArgs,
SourceLocation TypeArgsRAngleLoc,
SourceLocation ProtocolLAngleLoc,
ArrayRef<ObjCProtocolDecl *> Protocols,
ArrayRef<SourceLocation> ProtocolLocs,
SourceLocation ProtocolRAngleLoc,
bool FailOnError = false);
/// Check the application of the Objective-C '__kindof' qualifier to
/// the given type.
bool checkObjCKindOfType(QualType &type, SourceLocation loc);
/// Ensure attributes are consistent with type.
/// \param [in, out] Attributes The attributes to check; they will
/// be modified to be consistent with \p PropertyTy.
void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
SourceLocation Loc,
unsigned &Attributes,
bool propertyInPrimaryClass);
/// Process the specified property declaration and create decls for the
/// setters and getters as needed.
/// \param property The property declaration being processed
/// \param CD The semantic container for the property
/// \param redeclaredProperty Declaration for property if redeclared
/// in class extension.
/// \param lexicalDC Container for redeclaredProperty.
void ProcessPropertyDecl(ObjCPropertyDecl *property,
ObjCContainerDecl *CD,
ObjCPropertyDecl *redeclaredProperty = nullptr,
ObjCContainerDecl *lexicalDC = nullptr);
void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
ObjCPropertyDecl *SuperProperty,
const IdentifierInfo *Name,
bool OverridingProtocolProperty);
void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
ObjCInterfaceDecl *ID);
Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
ArrayRef<Decl *> allMethods = None,
ArrayRef<DeclGroupPtrTy> allTUVars = None);
Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
SourceLocation LParenLoc,
FieldDeclarator &FD, ObjCDeclSpec &ODS,
Selector GetterSel, Selector SetterSel,
bool *OverridingProperty,
tok::ObjCKeywordKind MethodImplKind,
DeclContext *lexicalDC = nullptr);
Decl *ActOnPropertyImplDecl(Scope *S,
SourceLocation AtLoc,
SourceLocation PropertyLoc,
bool ImplKind,
IdentifierInfo *PropertyId,
IdentifierInfo *PropertyIvar,
SourceLocation PropertyIvarLoc);
enum ObjCSpecialMethodKind {
OSMK_None,
OSMK_Alloc,
OSMK_New,
OSMK_Copy,
OSMK_RetainingInit,
OSMK_NonRetainingInit
};
struct ObjCArgInfo {
IdentifierInfo *Name;
SourceLocation NameLoc;
// The Type is null if no type was specified, and the DeclSpec is invalid
// in this case.
ParsedType Type;
ObjCDeclSpec DeclSpec;
/// ArgAttrs - Attribute list for this argument.
AttributeList *ArgAttrs;
};
Decl *ActOnMethodDeclaration(
Scope *S,
SourceLocation BeginLoc, // location of the + or -.
SourceLocation EndLoc, // location of the ; or {.
tok::TokenKind MethodType,
ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
// optional arguments. The number of types/arguments is obtained
// from the Sel.getNumArgs().
ObjCArgInfo *ArgInfo,
DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind,
bool isVariadic, bool MethodDefinition);
ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
const ObjCObjectPointerType *OPT,
bool IsInstance);
ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
bool IsInstance);
bool CheckARCMethodDecl(ObjCMethodDecl *method);
bool inferObjCARCLifetime(ValueDecl *decl);
ExprResult
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Expr *BaseExpr,
SourceLocation OpLoc,
DeclarationName MemberName,
SourceLocation MemberLoc,
SourceLocation SuperLoc, QualType SuperType,
bool Super);
ExprResult
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
IdentifierInfo &propertyName,
SourceLocation receiverNameLoc,
SourceLocation propertyNameLoc);
ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
/// \brief Describes the kind of message expression indicated by a message
/// send that starts with an identifier.
enum ObjCMessageKind {
/// \brief The message is sent to 'super'.
ObjCSuperMessage,
/// \brief The message is an instance message.
ObjCInstanceMessage,
/// \brief The message is a class message, and the identifier is a type
/// name.
ObjCClassMessage
};
ObjCMessageKind getObjCMessageKind(Scope *S,
IdentifierInfo *Name,
SourceLocation NameLoc,
bool IsSuper,
bool HasTrailingDot,
ParsedType &ReceiverType);
ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildClassMessageImplicit(QualType ReceiverType,
bool isSuperReceiver,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnClassMessage(Scope *S,
ParsedType Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildInstanceMessage(Expr *Receiver,
QualType ReceiverType,
SourceLocation SuperLoc,
Selector Sel,
ObjCMethodDecl *Method,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args,
bool isImplicit = false);
ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
QualType ReceiverType,
SourceLocation Loc,
Selector Sel,
ObjCMethodDecl *Method,
MultiExprArg Args);
ExprResult ActOnInstanceMessage(Scope *S,
Expr *Receiver,
Selector Sel,
SourceLocation LBracLoc,
ArrayRef<SourceLocation> SelectorLocs,
SourceLocation RBracLoc,
MultiExprArg Args);
ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
TypeSourceInfo *TSInfo,
Expr *SubExpr);
ExprResult ActOnObjCBridgedCast(Scope *S,
SourceLocation LParenLoc,
ObjCBridgeCastKind Kind,
SourceLocation BridgeKeywordLoc,
ParsedType Type,
SourceLocation RParenLoc,
Expr *SubExpr);
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
CastKind &Kind);
bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
QualType DestType, QualType SrcType,
ObjCInterfaceDecl *&RelatedClass,
ObjCMethodDecl *&ClassMethod,
ObjCMethodDecl *&InstanceMethod,
TypedefNameDecl *&TDNDecl,
bool CfToNs);
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
QualType DestType, QualType SrcType,
Expr *&SrcExpr);
bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr);
bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
/// \brief Check whether the given new method is a valid override of the
/// given overridden method, and set any properties that should be inherited.
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
const ObjCMethodDecl *Overridden);
/// \brief Describes the compatibility of a result type with its method.
enum ResultTypeCompatibilityKind {
RTC_Compatible,
RTC_Incompatible,
RTC_Unknown
};
void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
ObjCInterfaceDecl *CurrentClass,
ResultTypeCompatibilityKind RTC);
enum PragmaOptionsAlignKind {
POAK_Native, // #pragma options align=native
POAK_Natural, // #pragma options align=natural
POAK_Packed, // #pragma options align=packed
POAK_Power, // #pragma options align=power
POAK_Mac68k, // #pragma options align=mac68k
POAK_Reset // #pragma options align=reset
};
/// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
SourceLocation PragmaLoc);
enum PragmaPackKind {
PPK_Default, // #pragma pack([n])
PPK_Show, // #pragma pack(show), only supported by MSVC.
PPK_Push, // #pragma pack(push, [identifier], [n])
PPK_Pop // #pragma pack(pop, [identifier], [n])
};
enum PragmaMSStructKind {
PMSST_OFF, // #pragms ms_struct off
PMSST_ON // #pragms ms_struct on
};
enum PragmaMSCommentKind {
PCK_Unknown,
PCK_Linker, // #pragma comment(linker, ...)
PCK_Lib, // #pragma comment(lib, ...)
PCK_Compiler, // #pragma comment(compiler, ...)
PCK_ExeStr, // #pragma comment(exestr, ...)
PCK_User // #pragma comment(user, ...)
};
/// ActOnPragmaPack - Called on well formed \#pragma pack(...).
void ActOnPragmaPack(PragmaPackKind Kind,
IdentifierInfo *Name,
Expr *Alignment,
SourceLocation PragmaLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc);
/// ActOnPragmaPackMatrix - Called on well formed \#pragma pack_matrix(...).
void ActOnPragmaPackMatrix(bool bRowMajor, SourceLocation PragmaLoc);
/// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
/// ActOnPragmaMSComment - Called on well formed
/// \#pragma comment(kind, "arg").
void ActOnPragmaMSComment(PragmaMSCommentKind Kind, StringRef Arg);
/// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
/// pointers_to_members(representation method[, general purpose
/// representation]).
void ActOnPragmaMSPointersToMembers(
LangOptions::PragmaMSPointersToMembersKind Kind,
SourceLocation PragmaLoc);
/// \brief Called on well formed \#pragma vtordisp().
void ActOnPragmaMSVtorDisp(PragmaVtorDispKind Kind, SourceLocation PragmaLoc,
MSVtorDispAttr::Mode Value);
enum PragmaSectionKind {
PSK_DataSeg,
PSK_BSSSeg,
PSK_ConstSeg,
PSK_CodeSeg,
};
bool UnifySection(StringRef SectionName,
int SectionFlags,
DeclaratorDecl *TheDecl);
bool UnifySection(StringRef SectionName,
int SectionFlags,
SourceLocation PragmaSectionLocation);
/// \brief Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
PragmaMsStackAction Action,
llvm::StringRef StackSlotLabel,
StringLiteral *SegmentName,
llvm::StringRef PragmaName);
/// \brief Called on well formed \#pragma section().
void ActOnPragmaMSSection(SourceLocation PragmaLocation,
int SectionFlags, StringLiteral *SegmentName);
/// \brief Called on well-formed \#pragma init_seg().
void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
StringLiteral *SegmentName);
/// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
void ActOnPragmaDetectMismatch(StringRef Name, StringRef Value);
/// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
void ActOnPragmaUnused(const Token &Identifier,
Scope *curScope,
SourceLocation PragmaLoc);
/// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
void ActOnPragmaVisibility(const IdentifierInfo* VisType,
SourceLocation PragmaLoc);
NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II,
SourceLocation Loc);
void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W);
/// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
void ActOnPragmaWeakID(IdentifierInfo* WeakName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc);
/// ActOnPragmaRedefineExtname - Called on well formed
/// \#pragma redefine_extname oldname newname.
void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
IdentifierInfo* AliasName,
SourceLocation PragmaLoc,
SourceLocation WeakNameLoc,
SourceLocation AliasNameLoc);
/// ActOnPragmaFPContract - Called on well formed
/// \#pragma {STDC,OPENCL} FP_CONTRACT
void ActOnPragmaFPContract(tok::OnOffSwitch OOS);
/// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
/// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
void AddAlignmentAttributesForRecord(RecordDecl *RD);
/// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
void AddMsStructLayoutForRecord(RecordDecl *RD);
/// FreePackedContext - Deallocate and null out PackContext.
void FreePackedContext();
/// PushNamespaceVisibilityAttr - Note that we've entered a
/// namespace with a visibility attribute.
void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
SourceLocation Loc);
/// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
/// add an appropriate visibility attribute.
void AddPushedVisibilityAttribute(Decl *RD);
/// PopPragmaVisibility - Pop the top element of the visibility stack; used
/// for '\#pragma GCC visibility' and visibility attributes on namespaces.
void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
/// FreeVisContext - Deallocate and null out VisContext.
void FreeVisContext();
/// AddCFAuditedAttribute - Check whether we're currently within
/// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
/// the appropriate attribute.
void AddCFAuditedAttribute(Decl *D);
/// \brief Called on well formed \#pragma clang optimize.
void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
/// \brief Get the location for the currently active "\#pragma clang optimize
/// off". If this location is invalid, then the state of the pragma is "on".
SourceLocation getOptimizeOffPragmaLocation() const {
return OptimizeOffPragmaLocation;
}
/// \brief Only called on function definitions; if there is a pragma in scope
/// with the effect of a range-based optnone, consider marking the function
/// with attribute optnone.
void AddRangeBasedOptnone(FunctionDecl *FD);
/// \brief Adds the 'optnone' attribute to the function declaration if there
/// are no conflicts; Loc represents the location causing the 'optnone'
/// attribute to be added (usually because of a pragma).
void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
/// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex, bool IsPackExpansion);
void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T,
unsigned SpellingListIndex, bool IsPackExpansion);
/// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
/// declaration.
void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE,
unsigned SpellingListIndex);
/// AddAlignValueAttr - Adds an align_value attribute to a particular
/// declaration.
void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
unsigned SpellingListIndex);
/// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
/// declaration.
void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
Expr *MinBlocks, unsigned SpellingListIndex);
// OpenMP directives and clauses.
private:
void *VarDataSharingAttributesStack;
/// \brief Initialization of data-sharing attributes stack.
void InitDataSharingAttributesStack();
void DestroyDataSharingAttributesStack();
ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op,
OpenMPClauseKind CKind);
public:
/// \brief Check if the specified variable is used in a private clause in
/// Checks if the specified variable is used in one of the private
/// clauses in OpenMP constructs.
bool IsOpenMPCapturedVar(VarDecl *VD);
/// OpenMP constructs.
/// \param Level Relative level of nested OpenMP construct for that the check
/// is performed.
bool isOpenMPPrivateVar(VarDecl *VD, unsigned Level);
ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
Expr *Op);
/// \brief Called on start of new data sharing attribute block.
void StartOpenMPDSABlock(OpenMPDirectiveKind K,
const DeclarationNameInfo &DirName, Scope *CurScope,
SourceLocation Loc);
/// \brief Start analysis of clauses.
void StartOpenMPClause(OpenMPClauseKind K);
/// \brief End analysis of clauses.
void EndOpenMPClause();
/// \brief Called on end of data sharing attribute block.
void EndOpenMPDSABlock(Stmt *CurDirective);
/// \brief Check if the current region is an OpenMP loop region and if it is,
/// mark loop control variable, used in \p Init for loop initialization, as
/// private by default.
/// \param Init First part of the for loop.
void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
// OpenMP directives and clauses.
/// \brief Called on correct id-expression from the '#pragma omp
/// threadprivate'.
ExprResult ActOnOpenMPIdExpression(Scope *CurScope,
CXXScopeSpec &ScopeSpec,
const DeclarationNameInfo &Id);
/// \brief Called on well-formed '#pragma omp threadprivate'.
DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// \brief Builds a new OpenMPThreadPrivateDecl and checks its correctness.
OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(
SourceLocation Loc,
ArrayRef<Expr *> VarList);
/// \brief Initialization of captured region for OpenMP region.
void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
/// \brief End of OpenMP region.
///
/// \param S Statement associated with the current OpenMP region.
/// \param Clauses List of clauses for the current OpenMP region.
///
/// \returns Statement for finished OpenMP region.
StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
StmtResult ActOnOpenMPExecutableDirective(
OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp parallel' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp for simd' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp sections' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp section' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp single' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp master' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp critical' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp parallel for' after parsing
/// of the associated statement.
StmtResult ActOnOpenMPParallelForDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp parallel for simd' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelForSimdDirective(
ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc,
llvm::DenseMap<VarDecl *, Expr *> &VarsWithImplicitDSA);
/// \brief Called on well-formed '\#pragma omp parallel sections' after
/// parsing of the associated statement.
StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp task' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskyield'.
StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp barrier'.
StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskwait'.
StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp taskgroup'.
StmtResult ActOnOpenMPTaskgroupDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp flush'.
StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp ordered' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPOrderedDirective(Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp atomic' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp target' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp teams' after parsing of the
/// associated statement.
StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
Stmt *AStmt, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed '\#pragma omp cancellation point'.
StmtResult
ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
/// \brief Called on well-formed '\#pragma omp cancel'.
StmtResult ActOnOpenMPCancelDirective(SourceLocation StartLoc,
SourceLocation EndLoc,
OpenMPDirectiveKind CancelRegion);
OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'if' clause.
OMPClause *ActOnOpenMPIfClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'final' clause.
OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'num_threads' clause.
OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'safelen' clause.
OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'collapse' clause.
OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
unsigned Argument,
SourceLocation ArgumentLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'default' clause.
OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'proc_bind' clause.
OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
SourceLocation KindLoc,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind,
unsigned Argument, Expr *Expr,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ArgumentLoc,
SourceLocation CommaLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'schedule' clause.
OMPClause *ActOnOpenMPScheduleClause(OpenMPScheduleClauseKind Kind,
Expr *ChunkSize, SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation KindLoc,
SourceLocation CommaLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'ordered' clause.
OMPClause *ActOnOpenMPOrderedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'nowait' clause.
OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'untied' clause.
OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'mergeable' clause.
OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'read' clause.
OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'write' clause.
OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'update' clause.
OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'capture' clause.
OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'seq_cst' clause.
OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
SourceLocation EndLoc);
OMPClause *ActOnOpenMPVarListClause(
OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation ColonLoc, SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
SourceLocation DepLoc);
/// \brief Called on well-formed 'private' clause.
OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'firstprivate' clause.
OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'lastprivate' clause.
OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'shared' clause.
OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'reduction' clause.
OMPClause *
ActOnOpenMPReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
SourceLocation LParenLoc, SourceLocation ColonLoc,
SourceLocation EndLoc,
CXXScopeSpec &ReductionIdScopeSpec,
const DeclarationNameInfo &ReductionId);
/// \brief Called on well-formed 'linear' clause.
OMPClause *ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList,
Expr *Step,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'aligned' clause.
OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
Expr *Alignment,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation ColonLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'copyin' clause.
OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'copyprivate' clause.
OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'flush' pseudo clause.
OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
SourceLocation StartLoc,
SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief Called on well-formed 'depend' clause.
OMPClause *
ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc,
SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
SourceLocation StartLoc, SourceLocation LParenLoc,
SourceLocation EndLoc);
/// \brief The kind of conversion being performed.
enum CheckedConversionKind {
/// \brief An implicit conversion.
CCK_ImplicitConversion,
/// \brief A C-style cast.
CCK_CStyleCast,
/// \brief A functional-style cast.
CCK_FunctionalCast,
/// \brief A cast other than a C-style cast.
CCK_OtherCast
};
/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
/// cast. If there is already an implicit cast, merge into the existing one.
/// If isLvalue, the result of the cast is an lvalue.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
ExprValueKind VK = VK_RValue,
const CXXCastPath *BasePath = nullptr,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
/// to the conversion from scalar type ScalarTy to the Boolean type.
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
/// IgnoredValueConversions - Given that an expression's result is
/// syntactically ignored, perform any conversions that are
/// required.
ExprResult IgnoredValueConversions(Expr *E);
// UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
// functions and arrays to their respective pointers (C99 6.3.2.1).
ExprResult UsualUnaryConversions(Expr *E);
/// CallExprUnaryConversions - a special case of an unary conversion
/// performed on a function designator of a call expression.
ExprResult CallExprUnaryConversions(Expr *E);
// DefaultFunctionArrayConversion - converts functions and arrays
// to their respective pointers (C99 6.3.2.1).
ExprResult DefaultFunctionArrayConversion(Expr *E);
// DefaultFunctionArrayLvalueConversion - converts functions and
// arrays to their respective pointers and performs the
// lvalue-to-rvalue conversion.
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E);
// DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
// the operand. This is DefaultFunctionArrayLvalueConversion,
// except that it assumes the operand isn't of function or array
// type.
ExprResult DefaultLvalueConversion(Expr *E);
// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
// do not have a prototype. Integer promotions are performed on each
// argument, and arguments that have type float are promoted to double.
ExprResult DefaultArgumentPromotion(Expr *E);
// Used for emitting the right warning by DefaultVariadicArgumentPromotion
enum VariadicCallType {
VariadicFunction,
VariadicBlock,
VariadicMethod,
VariadicConstructor,
VariadicDoesNotApply
};
VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
const FunctionProtoType *Proto,
Expr *Fn);
// Used for determining in which context a type is allowed to be passed to a
// vararg function.
enum VarArgKind {
VAK_Valid,
VAK_ValidInCXX11,
VAK_Undefined,
VAK_MSVCUndefined,
VAK_Invalid
};
// Determines which VarArgKind fits an expression.
VarArgKind isValidVarArgType(const QualType &Ty);
/// Check to see if the given expression is a valid argument to a variadic
/// function, issuing a diagnostic if not.
void checkVariadicArgument(const Expr *E, VariadicCallType CT);
/// Check to see if a given expression could have '.c_str()' called on it.
bool hasCStrMethod(const Expr *E);
/// GatherArgumentsForCall - Collector argument expressions for various
/// form of call prototypes.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
const FunctionProtoType *Proto,
unsigned FirstParam, ArrayRef<Expr *> Args,
SmallVectorImpl<Expr *> &AllArgs,
VariadicCallType CallType = VariadicDoesNotApply,
bool AllowExplicit = false,
bool IsListInitialization = false);
// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
// will create a runtime trap if the resulting type is not a POD type.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
FunctionDecl *FDecl);
// UsualArithmeticConversions - performs the UsualUnaryConversions on it's
// operands and then handles various conversions that are common to binary
// operators (C99 6.3.1.8). If both operands aren't arithmetic, this
// routine returns the first non-arithmetic type found. The client is
// responsible for emitting appropriate error diagnostics.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
bool IsCompAssign = false);
/// AssignConvertType - All of the 'assignment' semantic checks return this
/// enum to indicate whether the assignment was allowed. These checks are
/// done for simple assignments, as well as initialization, return from
/// function, argument passing, etc. The query is phrased in terms of a
/// source and destination type.
enum AssignConvertType {
/// Compatible - the types are compatible according to the standard.
Compatible,
/// PointerToInt - The assignment converts a pointer to an int, which we
/// accept as an extension.
PointerToInt,
/// IntToPointer - The assignment converts an int to a pointer, which we
/// accept as an extension.
IntToPointer,
/// FunctionVoidPointer - The assignment is between a function pointer and
/// void*, which the standard doesn't allow, but we accept as an extension.
FunctionVoidPointer,
/// IncompatiblePointer - The assignment is between two pointers types that
/// are not compatible, but we accept them as an extension.
IncompatiblePointer,
/// IncompatiblePointer - The assignment is between two pointers types which
/// point to integers which have a different sign, but are otherwise
/// identical. This is a subset of the above, but broken out because it's by
/// far the most common case of incompatible pointers.
IncompatiblePointerSign,
/// CompatiblePointerDiscardsQualifiers - The assignment discards
/// c/v/r qualifiers, which we accept as an extension.
CompatiblePointerDiscardsQualifiers,
/// IncompatiblePointerDiscardsQualifiers - The assignment
/// discards qualifiers that we don't permit to be discarded,
/// like address spaces.
IncompatiblePointerDiscardsQualifiers,
/// IncompatibleNestedPointerQualifiers - The assignment is between two
/// nested pointer types, and the qualifiers other than the first two
/// levels differ e.g. char ** -> const char **, but we accept them as an
/// extension.
IncompatibleNestedPointerQualifiers,
/// IncompatibleVectors - The assignment is between two vector types that
/// have the same size, which we accept as an extension.
IncompatibleVectors,
/// IntToBlockPointer - The assignment converts an int to a block
/// pointer. We disallow this.
IntToBlockPointer,
/// IncompatibleBlockPointer - The assignment is between two block
/// pointers types that are not compatible.
IncompatibleBlockPointer,
/// IncompatibleObjCQualifiedId - The assignment is between a qualified
/// id type and something else (that is incompatible with it). For example,
/// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
IncompatibleObjCQualifiedId,
/// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
/// object with __weak qualifier.
IncompatibleObjCWeakRef,
/// Incompatible - We reject this conversion outright, it is invalid to
/// represent it in the AST.
Incompatible
};
/// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
/// assignment conversion type specified by ConvTy. This returns true if the
/// conversion was invalid or false if the conversion was accepted.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
SourceLocation Loc,
QualType DstType, QualType SrcType,
Expr *SrcExpr, AssignmentAction Action,
bool *Complained = nullptr);
/// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
/// enum. If AllowMask is true, then we also allow the complement of a valid
/// value, to be used as a mask.
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
bool AllowMask) const;
/// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
/// integer not in the range of enum values.
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
Expr *SrcExpr);
/// CheckAssignmentConstraints - Perform type checking for assignment,
/// argument passing, variable initialization, and function return values.
/// C99 6.5.16.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
QualType LHSType,
QualType RHSType);
/// Check assignment constraints and prepare for a conversion of the
/// RHS to the LHS type.
AssignConvertType CheckAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
CastKind &Kind);
// CheckSingleAssignmentConstraints - Currently used by
// CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking,
// this routine performs the default function/array converions.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType,
ExprResult &RHS,
bool Diagnose = true,
bool DiagnoseCFAudited = false);
// \brief If the lhs type is a transparent union, check whether we
// can initialize the transparent union with the given expression.
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
ExprResult &RHS);
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit = false);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
AssignmentAction Action,
bool AllowExplicit,
ImplicitConversionSequence& ICS);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const ImplicitConversionSequence& ICS,
AssignmentAction Action,
CheckedConversionKind CCK
= CCK_ImplicitConversion);
ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
const StandardConversionSequence& SCS,
AssignmentAction Action,
CheckedConversionKind CCK);
/// the following "Check" methods will return a valid/converted QualType
/// or a null QualType (indicating an error diagnostic was issued).
/// type checking binary operators (subroutines of CreateBuiltinBinOp).
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
ExprResult &RHS);
QualType CheckPointerToMemberOperands( // C++ 5.5
ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
SourceLocation OpLoc, bool isIndirect);
QualType CheckMultiplyDivideOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
bool IsDivide);
QualType CheckRemainderOperands( // C99 6.5.5
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckAdditionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
QualType* CompLHSTy = nullptr);
QualType CheckSubtractionOperands( // C99 6.5.6
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
QualType* CompLHSTy = nullptr);
QualType CheckShiftOperands( // C99 6.5.7
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
bool IsCompAssign = false);
QualType CheckCompareOperands( // C99 6.5.8/9
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc,
bool isRelational);
QualType CheckBitwiseOperands( // C99 6.5.[10...12]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
bool IsCompAssign = false);
QualType CheckLogicalOperands( // C99 6.5.[13,14]
ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc);
// CheckAssignmentOperands is used for both simple and compound assignment.
// For simple assignment, pass both expressions and a null converted type.
// For compound assignment, pass both expressions and the converted type.
QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
UnaryOperatorKind Opcode, Expr *Op);
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
BinaryOperatorKind Opcode,
Expr *LHS, Expr *RHS);
ExprResult checkPseudoObjectRValue(Expr *E);
Expr *recreateSyntacticForm(PseudoObjectExpr *E);
QualType CheckConditionalOperands( // C99 6.5.15
ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
QualType CXXCheckConditionalOperands( // C++ 5.16
ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
bool *NonStandardCompositeType = nullptr);
QualType FindCompositePointerType(SourceLocation Loc,
ExprResult &E1, ExprResult &E2,
bool *NonStandardCompositeType = nullptr) {
Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp,
NonStandardCompositeType);
E1 = E1Tmp;
E2 = E2Tmp;
return Composite;
}
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
SourceLocation QuestionLoc);
bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
SourceLocation QuestionLoc);
void DiagnoseAlwaysNonNullPointer(Expr *E,
Expr::NullPointerConstantKind NullType,
bool IsEqual, SourceRange Range);
/// type checking for vector binary operators.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool IsCompAssign,
bool AllowBothBool, bool AllowBoolConversion);
QualType GetSignedVectorType(QualType V);
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc, bool isRelational);
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
SourceLocation Loc);
bool isLaxVectorConversion(QualType srcType, QualType destType);
/// type checking declaration initializers (C99 6.7.8)
bool CheckForConstantInitializer(Expr *e, QualType t);
// type checking C++ declaration initializers (C++ [dcl.init]).
/// ReferenceCompareResult - Expresses the result of comparing two
/// types (cv1 T1 and cv2 T2) to determine their compatibility for the
/// purposes of initialization by reference (C++ [dcl.init.ref]p4).
enum ReferenceCompareResult {
/// Ref_Incompatible - The two types are incompatible, so direct
/// reference binding is not possible.
Ref_Incompatible = 0,
/// Ref_Related - The two types are reference-related, which means
/// that their unqualified forms (T1 and T2) are either the same
/// or T1 is a base class of T2.
Ref_Related,
/// Ref_Compatible_With_Added_Qualification - The two types are
/// reference-compatible with added qualification, meaning that
/// they are reference-compatible and the qualifiers on T1 (cv1)
/// are greater than the qualifiers on T2 (cv2).
Ref_Compatible_With_Added_Qualification,
/// Ref_Compatible - The two types are reference-compatible and
/// have equivalent qualifiers (cv1 == cv2).
Ref_Compatible
};
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc,
QualType T1, QualType T2,
bool &DerivedToBase,
bool &ObjCConversion,
bool &ObjCLifetimeConversion);
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
Expr *CastExpr, CastKind &CastKind,
ExprValueKind &VK, CXXCastPath &Path);
/// \brief Force an expression with unknown-type to an expression of the
/// given type.
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
/// \brief Type-check an expression that's being passed to an
/// __unknown_anytype parameter.
ExprResult checkUnknownAnyArg(SourceLocation callLoc,
Expr *result, QualType ¶mType);
// CheckVectorCast - check type constraints for vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size.
// returns true if the cast is invalid
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
CastKind &Kind);
// CheckExtVectorCast - check type constraints for extended vectors.
// Since vectors are an extension, there are no C standard reference for this.
// We allow casting between vectors and integer datatypes of the same size,
// or vectors and the element type of that vector.
// returns the cast expr
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
CastKind &Kind);
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
SourceLocation LParenLoc,
Expr *CastExpr,
SourceLocation RParenLoc);
enum ARCConversionResult { ACR_okay, ACR_unbridged };
/// \brief Checks for invalid conversions and casts between
/// retainable pointers and other pointer kinds.
ARCConversionResult CheckObjCARCConversion(SourceRange castRange,
QualType castType, Expr *&op,
CheckedConversionKind CCK,
bool DiagnoseCFAudited = false,
BinaryOperatorKind Opc = BO_PtrMemD
);
Expr *stripARCUnbridgedCast(Expr *e);
void diagnoseARCUnbridgedCast(Expr *e);
bool CheckObjCARCUnavailableWeakConversion(QualType castType,
QualType ExprType);
/// checkRetainCycles - Check whether an Objective-C message send
/// might create an obvious retain cycle.
void checkRetainCycles(ObjCMessageExpr *msg);
void checkRetainCycles(Expr *receiver, Expr *argument);
void checkRetainCycles(VarDecl *Var, Expr *Init);
/// checkUnsafeAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained type.
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
/// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
/// to weak/__unsafe_unretained expression.
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
/// CheckMessageArgumentTypes - Check types in an Obj-C message send.
/// \param Method - May be null.
/// \param [out] ReturnType - The return type of the send.
/// \return true iff there were any incompatible types.
bool CheckMessageArgumentTypes(QualType ReceiverType,
MultiExprArg Args, Selector Sel,
ArrayRef<SourceLocation> SelectorLocs,
ObjCMethodDecl *Method, bool isClassMessage,
bool isSuperMessage,
SourceLocation lbrac, SourceLocation rbrac,
SourceRange RecRange,
QualType &ReturnType, ExprValueKind &VK);
/// \brief Determine the result of a message send expression based on
/// the type of the receiver, the method expected to receive the message,
/// and the form of the message send.
QualType getMessageSendResultType(QualType ReceiverType,
ObjCMethodDecl *Method,
bool isClassMessage, bool isSuperMessage);
/// \brief If the given expression involves a message send to a method
/// with a related result type, emit a note describing what happened.
void EmitRelatedResultTypeNote(const Expr *E);
/// \brief Given that we had incompatible pointer types in a return
/// statement, check whether we're in a method with a related result
/// type, and if so, emit a note describing what happened.
void EmitRelatedResultTypeNoteForReturn(QualType destType);
/// CheckBooleanCondition - Diagnose problems involving the use of
/// the given expression as a boolean condition (e.g. in an if
/// statement). Also performs the standard function and array
/// decays, possibly changing the input variable.
///
/// \param Loc - A location associated with the condition, e.g. the
/// 'if' keyword.
/// \return true iff there were any errors
ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc);
ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Expr *SubExpr);
/// DiagnoseAssignmentAsCondition - Given that an expression is
/// being used as a boolean condition, warn if it's an assignment.
void DiagnoseAssignmentAsCondition(Expr *E);
/// \brief Redundant parentheses over an equality comparison can indicate
/// that the user intended an assignment used as condition.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
/// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckCXXBooleanCondition(Expr *CondExpr);
/// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
/// the specified width and sign. If an overflow occurs, detect it and emit
/// the specified diagnostic.
void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
unsigned NewWidth, bool NewSign,
SourceLocation Loc, unsigned DiagID);
/// Checks that the Objective-C declaration is declared in the global scope.
/// Emits an error and marks the declaration as invalid if it's not declared
/// in the global scope.
bool CheckObjCDeclScope(Decl *D);
/// \brief Abstract base class used for diagnosing integer constant
/// expression violations.
class VerifyICEDiagnoser {
public:
bool Suppress;
VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0;
virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR);
virtual ~VerifyICEDiagnoser() { }
};
/// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
/// and reports the appropriate diagnostics. Returns false on success.
/// Can optionally return the value of the expression.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
VerifyICEDiagnoser &Diagnoser,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
unsigned DiagID,
bool AllowFold = true);
ExprResult VerifyIntegerConstantExpression(Expr *E,
llvm::APSInt *Result = nullptr);
/// VerifyBitField - verifies that a bit field expression is an ICE and has
/// the correct width, and that the field type is valid.
/// Returns false on success.
/// Can optionally return whether the bit-field is of width 0
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
QualType FieldTy, bool IsMsStruct,
Expr *BitWidth, bool *ZeroWidth = nullptr);
enum CUDAFunctionTarget {
CFT_Device,
CFT_Global,
CFT_Host,
CFT_HostDevice,
CFT_InvalidTarget
};
CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D);
bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee);
/// Given a implicit special member, infer its CUDA target from the
/// calls it needs to make to underlying base/field special members.
/// \param ClassDecl the class for which the member is being created.
/// \param CSM the kind of special member.
/// \param MemberDecl the special member itself.
/// \param ConstRHS true if this is a copy operation with a const object on
/// its RHS.
/// \param Diagnose true if this call should emit diagnostics.
/// \return true if there was an error inferring.
/// The result of this call is implicit CUDA target attribute(s) attached to
/// the member declaration.
bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
CXXSpecialMember CSM,
CXXMethodDecl *MemberDecl,
bool ConstRHS,
bool Diagnose);
/// \name Code completion
//@{
/// \brief Describes the context in which code completion occurs.
enum ParserCompletionContext {
/// \brief Code completion occurs at top-level or namespace context.
PCC_Namespace,
/// \brief Code completion occurs within a class, struct, or union.
PCC_Class,
/// \brief Code completion occurs within an Objective-C interface, protocol,
/// or category.
PCC_ObjCInterface,
/// \brief Code completion occurs within an Objective-C implementation or
/// category implementation
PCC_ObjCImplementation,
/// \brief Code completion occurs within the list of instance variables
/// in an Objective-C interface, protocol, category, or implementation.
PCC_ObjCInstanceVariableList,
/// \brief Code completion occurs following one or more template
/// headers.
PCC_Template,
/// \brief Code completion occurs following one or more template
/// headers within a class.
PCC_MemberTemplate,
/// \brief Code completion occurs within an expression.
PCC_Expression,
/// \brief Code completion occurs within a statement, which may
/// also be an expression or a declaration.
PCC_Statement,
/// \brief Code completion occurs at the beginning of the
/// initialization statement (or expression) in a for loop.
PCC_ForInit,
/// \brief Code completion occurs within the condition of an if,
/// while, switch, or for statement.
PCC_Condition,
/// \brief Code completion occurs within the body of a function on a
/// recovery path, where we do not have a specific handle on our position
/// in the grammar.
PCC_RecoveryInFunction,
/// \brief Code completion occurs where only a type is permitted.
PCC_Type,
/// \brief Code completion occurs in a parenthesized expression, which
/// might also be a type cast.
PCC_ParenthesizedExpression,
/// \brief Code completion occurs within a sequence of declaration
/// specifiers within a function, method, or block.
PCC_LocalDeclarationSpecifiers
};
void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
void CodeCompleteOrdinaryName(Scope *S,
ParserCompletionContext CompletionContext);
void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
bool AllowNonIdentifiers,
bool AllowNestedNameSpecifiers);
struct CodeCompleteExpressionData;
void CodeCompleteExpression(Scope *S,
const CodeCompleteExpressionData &Data);
void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
SourceLocation OpLoc,
bool IsArrow);
void CodeCompletePostfixExpression(Scope *S, ExprResult LHS);
void CodeCompleteTag(Scope *S, unsigned TagSpec);
void CodeCompleteTypeQualifiers(DeclSpec &DS);
void CodeCompleteCase(Scope *S);
void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args);
void CodeCompleteConstructor(Scope *S, QualType Type, SourceLocation Loc,
ArrayRef<Expr *> Args);
void CodeCompleteInitializer(Scope *S, Decl *D);
void CodeCompleteReturn(Scope *S);
void CodeCompleteAfterIf(Scope *S);
void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS);
void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
bool EnteringContext);
void CodeCompleteUsing(Scope *S);
void CodeCompleteUsingDirective(Scope *S);
void CodeCompleteNamespaceDecl(Scope *S);
void CodeCompleteNamespaceAliasDecl(Scope *S);
void CodeCompleteOperatorName(Scope *S);
void CodeCompleteConstructorInitializer(
Decl *Constructor,
ArrayRef<CXXCtorInitializer *> Initializers);
void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
bool AfterAmpersand);
void CodeCompleteObjCAtDirective(Scope *S);
void CodeCompleteObjCAtVisibility(Scope *S);
void CodeCompleteObjCAtStatement(Scope *S);
void CodeCompleteObjCAtExpression(Scope *S);
void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
void CodeCompleteObjCPropertyGetter(Scope *S);
void CodeCompleteObjCPropertySetter(Scope *S);
void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
bool IsParameter);
void CodeCompleteObjCMessageReceiver(Scope *S);
void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression);
void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
bool IsSuper = false);
void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
ArrayRef<IdentifierInfo *> SelIdents,
bool AtArgumentExpression,
ObjCInterfaceDecl *Super = nullptr);
void CodeCompleteObjCForCollection(Scope *S,
DeclGroupPtrTy IterationVar);
void CodeCompleteObjCSelector(Scope *S,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
unsigned NumProtocols);
void CodeCompleteObjCProtocolDecl(Scope *S);
void CodeCompleteObjCInterfaceDecl(Scope *S);
void CodeCompleteObjCSuperclass(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationDecl(Scope *S);
void CodeCompleteObjCInterfaceCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCImplementationCategory(Scope *S,
IdentifierInfo *ClassName,
SourceLocation ClassNameLoc);
void CodeCompleteObjCPropertyDefinition(Scope *S);
void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
IdentifierInfo *PropertyName);
void CodeCompleteObjCMethodDecl(Scope *S,
bool IsInstanceMethod,
ParsedType ReturnType);
void CodeCompleteObjCMethodDeclSelector(Scope *S,
bool IsInstanceMethod,
bool AtParameterName,
ParsedType ReturnType,
ArrayRef<IdentifierInfo *> SelIdents);
void CodeCompletePreprocessorDirective(bool InConditional);
void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
void CodeCompletePreprocessorMacroName(bool IsDefinition);
void CodeCompletePreprocessorExpression();
void CodeCompletePreprocessorMacroArgument(Scope *S,
IdentifierInfo *Macro,
MacroInfo *MacroInfo,
unsigned Argument);
void CodeCompleteNaturalLanguage();
void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
SmallVectorImpl<CodeCompletionResult> &Results);
//@}
//===--------------------------------------------------------------------===//
// Extra semantic analysis beyond the C type system
public:
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
unsigned ByteNo) const;
private:
void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
const ArraySubscriptExpr *ASE=nullptr,
bool AllowOnePastEnd=true, bool IndexNegated=false);
// HLSL Change Starts - checking array subscript access to vector or matrix member
void CheckHLSLArrayAccess(const Expr *expr);
bool CheckHLSLIntrinsicCall(FunctionDecl *FDecl, CallExpr *TheCall);
bool CheckHLSLFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall);
// HLSL Change ends
void CheckArrayAccess(const Expr *E);
// Used to grab the relevant information from a FormatAttr and a
// FunctionDeclaration.
struct FormatStringInfo {
unsigned FormatIdx;
unsigned FirstDataArg;
bool HasVAListArg;
};
bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
FormatStringInfo *FSI);
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
ArrayRef<const Expr *> Args);
bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
const FunctionProtoType *Proto);
bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
void CheckConstructorCall(FunctionDecl *FDecl,
ArrayRef<const Expr *> Args,
const FunctionProtoType *Proto,
SourceLocation Loc);
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
ArrayRef<const Expr *> Args, bool IsMemberFunction,
SourceLocation Loc, SourceRange Range,
VariadicCallType CallType);
bool CheckObjCString(Expr *Arg);
ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
unsigned MaxWidth);
bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
bool SemaBuiltinVAStart(CallExpr *TheCall);
bool SemaBuiltinVAStartARM(CallExpr *Call);
bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
public:
// Used by C++ template instantiation.
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
SourceLocation BuiltinLoc,
SourceLocation RParenLoc);
private:
bool SemaBuiltinPrefetch(CallExpr *TheCall);
bool SemaBuiltinAssume(CallExpr *TheCall);
bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
bool SemaBuiltinLongjmp(CallExpr *TheCall);
bool SemaBuiltinSetjmp(CallExpr *TheCall);
ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
AtomicExpr::AtomicOp Op);
bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
llvm::APSInt &Result);
bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
int Low, int High);
bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
int ArgNum, unsigned ExpectedFieldNum,
bool AllowName);
bool SemaBuiltinCpuSupports(CallExpr *TheCall);
public:
enum FormatStringType {
FST_Scanf,
FST_Printf,
FST_NSString,
FST_Strftime,
FST_Strfmon,
FST_Kprintf,
FST_FreeBSDKPrintf,
FST_OSTrace,
FST_Unknown
};
static FormatStringType GetFormatStringType(const FormatAttr *Format);
void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr,
ArrayRef<const Expr *> Args, bool HasVAListArg,
unsigned format_idx, unsigned firstDataArg,
FormatStringType Type, bool inFunctionCall,
VariadicCallType CallType,
llvm::SmallBitVector &CheckedVarArgs);
bool FormatStringHasSArg(const StringLiteral *FExpr);
bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
private:
bool CheckFormatArguments(const FormatAttr *Format,
ArrayRef<const Expr *> Args,
bool IsCXXMember,
VariadicCallType CallType,
SourceLocation Loc, SourceRange Range,
llvm::SmallBitVector &CheckedVarArgs);
bool CheckFormatArguments(ArrayRef<const Expr *> Args,
bool HasVAListArg, unsigned format_idx,
unsigned firstDataArg, FormatStringType Type,
VariadicCallType CallType,
SourceLocation Loc, SourceRange range,
llvm::SmallBitVector &CheckedVarArgs);
void CheckAbsoluteValueFunction(const CallExpr *Call,
const FunctionDecl *FDecl,
IdentifierInfo *FnInfo);
void CheckMemaccessArguments(const CallExpr *Call,
unsigned BId,
IdentifierInfo *FnName);
void CheckStrlcpycatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckStrncatArguments(const CallExpr *Call,
IdentifierInfo *FnName);
void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
SourceLocation ReturnLoc,
bool isObjCMethod = false,
const AttrVec *Attrs = nullptr,
const FunctionDecl *FD = nullptr);
void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS);
void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
void CheckForIntOverflow(Expr *E);
void CheckUnsequencedOperations(Expr *E);
/// \brief Perform semantic checks on a completed expression. This will either
/// be a full-expression or a default argument expression.
void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
bool IsConstexpr = false);
void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
Expr *Init);
/// \brief Check if the given expression contains 'break' or 'continue'
/// statement that produces control flow different from GCC.
void CheckBreakContinueBinding(Expr *E);
/// \brief Check whether receiver is mutable ObjC container which
/// attempts to add itself into the container
void CheckObjCCircularContainer(ObjCMessageExpr *Message);
void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
bool DeleteWasArrayForm);
public:
/// \brief Register a magic integral constant to be used as a type tag.
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
uint64_t MagicValue, QualType Type,
bool LayoutCompatible, bool MustBeNull);
struct TypeTagData {
TypeTagData() {}
TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
Type(Type), LayoutCompatible(LayoutCompatible),
MustBeNull(MustBeNull)
{}
QualType Type;
/// If true, \c Type should be compared with other expression's types for
/// layout-compatibility.
unsigned LayoutCompatible : 1;
unsigned MustBeNull : 1;
};
/// A pair of ArgumentKind identifier and magic value. This uniquely
/// identifies the magic value.
typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
private:
/// \brief A map from magic value to type information.
std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
TypeTagForDatatypeMagicValues;
/// \brief Peform checks on a call of a function with argument_with_type_tag
/// or pointer_with_type_tag attributes.
void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
const Expr * const *ExprArgs);
/// \brief The parser's current scope.
///
/// The parser maintains this state here.
Scope *CurScope;
mutable IdentifierInfo *Ident_super;
mutable IdentifierInfo *Ident___float128;
// HLSL Change Starts
bool DiagnoseHLSLDecl(Declarator& D, DeclContext* DC, Expr *BitWidth, TypeSourceInfo* TInfo, bool isParameter);
void TransferUnusualAttributes(Declarator& D, NamedDecl* NewDecl);
// HLSL Change Ends
/// Nullability type specifiers.
IdentifierInfo *Ident__Nonnull = nullptr;
IdentifierInfo *Ident__Nullable = nullptr;
IdentifierInfo *Ident__Null_unspecified = nullptr;
IdentifierInfo *Ident_NSError = nullptr;
protected:
friend class Parser;
friend class InitializationSequence;
friend class ASTReader;
friend class ASTDeclReader;
friend class ASTWriter;
public:
/// Retrieve the keyword associated
IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
/// The struct behind the CFErrorRef pointer.
RecordDecl *CFError = nullptr;
/// Retrieve the identifier "NSError".
IdentifierInfo *getNSErrorIdent();
/// \brief Retrieve the parser's current scope.
///
/// This routine must only be used when it is certain that semantic analysis
/// and the parser are in precisely the same context, which is not the case
/// when, e.g., we are performing any kind of template instantiation.
/// Therefore, the only safe places to use this scope are in the parser
/// itself and in routines directly invoked from the parser and *never* from
/// template substitution or instantiation.
Scope *getCurScope() const { return CurScope; }
void incrementMSManglingNumber() const {
return CurScope->incrementMSManglingNumber();
}
IdentifierInfo *getSuperIdentifier() const;
IdentifierInfo *getFloat128Identifier() const;
Decl *getObjCDeclContext() const;
DeclContext *getCurLexicalContext() const {
return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
}
AvailabilityResult getCurContextAvailability() const;
const DeclContext *getCurObjCLexicalContext() const {
const DeclContext *DC = getCurLexicalContext();
// A category implicitly has the attribute of the interface.
if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
DC = CatD->getClassInterface();
return DC;
}
/// \brief To be used for checking whether the arguments being passed to
/// function exceeds the number of parameters expected for it.
static bool TooManyArguments(size_t NumParams, size_t NumArgs,
bool PartialOverloading = false) {
// We check whether we're just after a comma in code-completion.
if (NumArgs > 0 && PartialOverloading)
return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
return NumArgs > NumParams;
}
// HLSL Change Begin - adjust this from T* to T&-like
CXXThisExpr *genereateHLSLThis(SourceLocation Loc, QualType ThisType,
bool isImplicit);
QualType getHLSLDefaultSpecialization(TemplateDecl *Decl);
// HLSL Change End - adjust this from T* to T&-like
void DiagnoseSemanticDecl(hlsl::SemanticDecl *Decl); // HLSL Change
};
/// \brief RAII object that enters a new expression evaluation context.
class EnterExpressionEvaluationContext {
Sema &Actions;
public:
EnterExpressionEvaluationContext(Sema &Actions,
Sema::ExpressionEvaluationContext NewContext,
Decl *LambdaContextDecl = nullptr,
bool IsDecltype = false)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
IsDecltype);
}
EnterExpressionEvaluationContext(Sema &Actions,
Sema::ExpressionEvaluationContext NewContext,
Sema::ReuseLambdaContextDecl_t,
bool IsDecltype = false)
: Actions(Actions) {
Actions.PushExpressionEvaluationContext(NewContext,
Sema::ReuseLambdaContextDecl,
IsDecltype);
}
~EnterExpressionEvaluationContext() {
Actions.PopExpressionEvaluationContext();
}
};
DeductionFailureInfo
MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
sema::TemplateDeductionInfo &Info);
/// \brief Contains a late templated function.
/// Will be parsed at the end of the translation unit, used by Sema & Parser.
struct LateParsedTemplate {
CachedTokens Toks;
/// \brief The template function declaration to be late parsed.
Decl *D;
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/ExternalSemaSource.h | //===--- ExternalSemaSource.h - External Sema Interface ---------*- 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 ExternalSemaSource interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_EXTERNALSEMASOURCE_H
#define LLVM_CLANG_SEMA_EXTERNALSEMASOURCE_H
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/Type.h"
#include "clang/Sema/TypoCorrection.h"
#include "clang/Sema/Weak.h"
#include "llvm/ADT/MapVector.h"
#include <utility>
namespace llvm {
template <class T, unsigned n> class SmallSetVector;
}
namespace clang {
class CXXConstructorDecl;
class CXXDeleteExpr;
class CXXRecordDecl;
class DeclaratorDecl;
class LookupResult;
struct ObjCMethodList;
class Scope;
class Sema;
class TypedefNameDecl;
class ValueDecl;
class VarDecl;
struct LateParsedTemplate;
class OverloadCandidateSet; // HLSL Change
class UnresolvedLookupExpr; // HLSL Change
/// \brief A simple structure that captures a vtable use for the purposes of
/// the \c ExternalSemaSource.
struct ExternalVTableUse {
CXXRecordDecl *Record;
SourceLocation Location;
bool DefinitionRequired;
};
/// \brief An abstract interface that should be implemented by
/// external AST sources that also provide information for semantic
/// analysis.
class ExternalSemaSource : public ExternalASTSource {
public:
ExternalSemaSource() {
ExternalASTSource::SemaSource = true;
}
~ExternalSemaSource() override;
/// \brief Initialize the semantic source with the Sema instance
/// being used to perform semantic analysis on the abstract syntax
/// tree.
virtual void InitializeSema(Sema &S) {}
/// \brief Inform the semantic consumer that Sema is no longer available.
virtual void ForgetSema() {}
/// \brief Load the contents of the global method pool for a given
/// selector.
virtual void ReadMethodPool(Selector Sel);
/// \brief Load the set of namespaces that are known to the external source,
/// which will be used during typo correction.
virtual void ReadKnownNamespaces(
SmallVectorImpl<NamespaceDecl *> &Namespaces);
/// \brief Load the set of used but not defined functions or variables with
/// internal linkage, or used but not defined internal functions.
virtual void ReadUndefinedButUsed(
llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined);
virtual void ReadMismatchingDeleteExpressions(llvm::MapVector<
FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &);
/// \brief Do last resort, unqualified lookup on a LookupResult that
/// Sema cannot find.
///
/// \param R a LookupResult that is being recovered.
///
/// \param S the Scope of the identifier occurrence.
///
/// \return true to tell Sema to recover using the LookupResult.
virtual bool LookupUnqualified(LookupResult &R, Scope *S) { return false; }
/// \brief Read the set of tentative definitions known to the external Sema
/// source.
///
/// The external source should append its own tentative definitions to the
/// given vector of tentative definitions. Note that this routine may be
/// invoked multiple times; the external source should take care not to
/// introduce the same declarations repeatedly.
virtual void ReadTentativeDefinitions(
SmallVectorImpl<VarDecl *> &TentativeDefs) {}
/// \brief Read the set of unused file-scope declarations known to the
/// external Sema source.
///
/// The external source should append its own unused, filed-scope to the
/// given vector of declarations. Note that this routine may be
/// invoked multiple times; the external source should take care not to
/// introduce the same declarations repeatedly.
virtual void ReadUnusedFileScopedDecls(
SmallVectorImpl<const DeclaratorDecl *> &Decls) {}
/// \brief Read the set of delegating constructors known to the
/// external Sema source.
///
/// The external source should append its own delegating constructors to the
/// given vector of declarations. Note that this routine may be
/// invoked multiple times; the external source should take care not to
/// introduce the same declarations repeatedly.
virtual void ReadDelegatingConstructors(
SmallVectorImpl<CXXConstructorDecl *> &Decls) {}
/// \brief Read the set of ext_vector type declarations known to the
/// external Sema source.
///
/// The external source should append its own ext_vector type declarations to
/// the given vector of declarations. Note that this routine may be
/// invoked multiple times; the external source should take care not to
/// introduce the same declarations repeatedly.
virtual void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {}
/// \brief Read the set of potentially unused typedefs known to the source.
///
/// The external source should append its own potentially unused local
/// typedefs to the given vector of declarations. Note that this routine may
/// be invoked multiple times; the external source should take care not to
/// introduce the same declarations repeatedly.
virtual void ReadUnusedLocalTypedefNameCandidates(
llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {};
/// \brief Read the set of referenced selectors known to the
/// external Sema source.
///
/// The external source should append its own referenced selectors to the
/// given vector of selectors. Note that this routine
/// may be invoked multiple times; the external source should take care not
/// to introduce the same selectors repeatedly.
virtual void ReadReferencedSelectors(
SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {}
/// \brief Read the set of weak, undeclared identifiers known to the
/// external Sema source.
///
/// The external source should append its own weak, undeclared identifiers to
/// the given vector. Note that this routine may be invoked multiple times;
/// the external source should take care not to introduce the same identifiers
/// repeatedly.
virtual void ReadWeakUndeclaredIdentifiers(
SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WI) {}
/// \brief Read the set of used vtables known to the external Sema source.
///
/// The external source should append its own used vtables to the given
/// vector. Note that this routine may be invoked multiple times; the external
/// source should take care not to introduce the same vtables repeatedly.
virtual void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {}
/// \brief Read the set of pending instantiations known to the external
/// Sema source.
///
/// The external source should append its own pending instantiations to the
/// given vector. Note that this routine may be invoked multiple times; the
/// external source should take care not to introduce the same instantiations
/// repeatedly.
virtual void ReadPendingInstantiations(
SmallVectorImpl<std::pair<ValueDecl *,
SourceLocation> > &Pending) {}
/// \brief Read the set of late parsed template functions for this source.
///
/// The external source should insert its own late parsed template functions
/// into the map. Note that this routine may be invoked multiple times; the
/// external source should take care not to introduce the same map entries
/// repeatedly.
virtual void ReadLateParsedTemplates(
llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {}
/// \copydoc Sema::CorrectTypo
/// \note LookupKind must correspond to a valid Sema::LookupNameKind
///
/// ExternalSemaSource::CorrectTypo is always given the first chance to
/// correct a typo (really, to offer suggestions to repair a failed lookup).
/// It will even be called when SpellChecking is turned off or after a
/// fatal error has already been detected.
virtual TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
int LookupKind, Scope *S, CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
DeclContext *MemberContext,
bool EnteringContext,
const ObjCObjectPointerType *OPT) {
return TypoCorrection();
}
// HLSL Change Starts
// ExternalSemaSource::AddOverloadedCallCandidates is given the chance to
// add call candidates to the given expression. It returns 'true'
// if standard overload search should be suppressed; false otherwise.
virtual bool AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
ArrayRef<Expr *> Args,
OverloadCandidateSet &CandidateSet,
bool PartialOverloading)
{
return false;
}
// HLSL Change Ends
/// \brief Produces a diagnostic note if the external source contains a
/// complete definition for \p T.
///
/// \param Loc the location at which a complete type was required but not
/// provided
///
/// \param T the \c QualType that should have been complete at \p Loc
///
/// \return true if a diagnostic was produced, false otherwise.
virtual bool MaybeDiagnoseMissingCompleteType(SourceLocation Loc,
QualType T) {
return false;
}
// isa/cast/dyn_cast support
static bool classof(const ExternalASTSource *Source) {
return Source->SemaSource;
}
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/Designator.h | //===--- Designator.h - Initialization Designator ---------------*- 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 interfaces used to represent designators (a la
// C99 designated initializers) during parsing.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_DESIGNATOR_H
#define LLVM_CLANG_SEMA_DESIGNATOR_H
#include "clang/Basic/SourceLocation.h"
#include "llvm/ADT/SmallVector.h"
namespace clang {
class Expr;
class IdentifierInfo;
class Sema;
/// Designator - A designator in a C99 designated initializer.
///
/// This class is a discriminated union which holds the various
/// different sorts of designators possible. A Designation is an array of
/// these. An example of a designator are things like this:
/// [8] .field [47] // C99 designation: 3 designators
/// [8 ... 47] field: // GNU extensions: 2 designators
/// These occur in initializers, e.g.:
/// int a[10] = {2, 4, [8]=9, 10};
///
class Designator {
public:
enum DesignatorKind {
FieldDesignator, ArrayDesignator, ArrayRangeDesignator
};
private:
DesignatorKind Kind;
struct FieldDesignatorInfo {
const IdentifierInfo *II;
unsigned DotLoc;
unsigned NameLoc;
};
struct ArrayDesignatorInfo {
Expr *Index;
unsigned LBracketLoc;
mutable unsigned RBracketLoc;
};
struct ArrayRangeDesignatorInfo {
Expr *Start, *End;
unsigned LBracketLoc, EllipsisLoc;
mutable unsigned RBracketLoc;
};
union {
FieldDesignatorInfo FieldInfo;
ArrayDesignatorInfo ArrayInfo;
ArrayRangeDesignatorInfo ArrayRangeInfo;
};
public:
DesignatorKind getKind() const { return Kind; }
bool isFieldDesignator() const { return Kind == FieldDesignator; }
bool isArrayDesignator() const { return Kind == ArrayDesignator; }
bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
const IdentifierInfo *getField() const {
assert(isFieldDesignator() && "Invalid accessor");
return FieldInfo.II;
}
SourceLocation getDotLoc() const {
assert(isFieldDesignator() && "Invalid accessor");
return SourceLocation::getFromRawEncoding(FieldInfo.DotLoc);
}
SourceLocation getFieldLoc() const {
assert(isFieldDesignator() && "Invalid accessor");
return SourceLocation::getFromRawEncoding(FieldInfo.NameLoc);
}
Expr *getArrayIndex() const {
assert(isArrayDesignator() && "Invalid accessor");
return ArrayInfo.Index;
}
Expr *getArrayRangeStart() const {
assert(isArrayRangeDesignator() && "Invalid accessor");
return ArrayRangeInfo.Start;
}
Expr *getArrayRangeEnd() const {
assert(isArrayRangeDesignator() && "Invalid accessor");
return ArrayRangeInfo.End;
}
SourceLocation getLBracketLoc() const {
assert((isArrayDesignator() || isArrayRangeDesignator()) &&
"Invalid accessor");
if (isArrayDesignator())
return SourceLocation::getFromRawEncoding(ArrayInfo.LBracketLoc);
else
return SourceLocation::getFromRawEncoding(ArrayRangeInfo.LBracketLoc);
}
SourceLocation getRBracketLoc() const {
assert((isArrayDesignator() || isArrayRangeDesignator()) &&
"Invalid accessor");
if (isArrayDesignator())
return SourceLocation::getFromRawEncoding(ArrayInfo.RBracketLoc);
else
return SourceLocation::getFromRawEncoding(ArrayRangeInfo.RBracketLoc);
}
SourceLocation getEllipsisLoc() const {
assert(isArrayRangeDesignator() && "Invalid accessor");
return SourceLocation::getFromRawEncoding(ArrayRangeInfo.EllipsisLoc);
}
static Designator getField(const IdentifierInfo *II, SourceLocation DotLoc,
SourceLocation NameLoc) {
Designator D;
D.Kind = FieldDesignator;
D.FieldInfo.II = II;
D.FieldInfo.DotLoc = DotLoc.getRawEncoding();
D.FieldInfo.NameLoc = NameLoc.getRawEncoding();
return D;
}
static Designator getArray(Expr *Index,
SourceLocation LBracketLoc) {
Designator D;
D.Kind = ArrayDesignator;
D.ArrayInfo.Index = Index;
D.ArrayInfo.LBracketLoc = LBracketLoc.getRawEncoding();
D.ArrayInfo.RBracketLoc = 0;
return D;
}
static Designator getArrayRange(Expr *Start,
Expr *End,
SourceLocation LBracketLoc,
SourceLocation EllipsisLoc) {
Designator D;
D.Kind = ArrayRangeDesignator;
D.ArrayRangeInfo.Start = Start;
D.ArrayRangeInfo.End = End;
D.ArrayRangeInfo.LBracketLoc = LBracketLoc.getRawEncoding();
D.ArrayRangeInfo.EllipsisLoc = EllipsisLoc.getRawEncoding();
D.ArrayRangeInfo.RBracketLoc = 0;
return D;
}
void setRBracketLoc(SourceLocation RBracketLoc) const {
assert((isArrayDesignator() || isArrayRangeDesignator()) &&
"Invalid accessor");
if (isArrayDesignator())
ArrayInfo.RBracketLoc = RBracketLoc.getRawEncoding();
else
ArrayRangeInfo.RBracketLoc = RBracketLoc.getRawEncoding();
}
/// ClearExprs - Null out any expression references, which prevents
/// them from being 'delete'd later.
void ClearExprs(Sema &Actions) {}
/// FreeExprs - Release any unclaimed memory for the expressions in
/// this designator.
void FreeExprs(Sema &Actions) {}
};
/// Designation - Represent a full designation, which is a sequence of
/// designators. This class is mostly a helper for InitListDesignations.
class Designation {
/// Designators - The actual designators for this initializer.
SmallVector<Designator, 2> Designators;
public:
/// AddDesignator - Add a designator to the end of this list.
void AddDesignator(Designator D) {
Designators.push_back(D);
}
bool empty() const { return Designators.empty(); }
unsigned getNumDesignators() const { return Designators.size(); }
const Designator &getDesignator(unsigned Idx) const {
assert(Idx < Designators.size());
return Designators[Idx];
}
/// ClearExprs - Null out any expression references, which prevents them from
/// being 'delete'd later.
void ClearExprs(Sema &Actions) {}
/// FreeExprs - Release any unclaimed memory for the expressions in this
/// designation.
void FreeExprs(Sema &Actions) {}
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/ParsedTemplate.h | //===--- ParsedTemplate.h - Template Parsing Data Types -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides data structures that store the parsed representation of
// templates.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_PARSEDTEMPLATE_H
#define LLVM_CLANG_SEMA_PARSEDTEMPLATE_H
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Ownership.h"
#include <cassert>
namespace clang {
/// \brief Represents the parsed form of a C++ template argument.
class ParsedTemplateArgument {
public:
/// \brief Describes the kind of template argument that was parsed.
enum KindType {
/// \brief A template type parameter, stored as a type.
Type,
/// \brief A non-type template parameter, stored as an expression.
NonType,
/// \brief A template template argument, stored as a template name.
Template
};
/// \brief Build an empty template argument.
///
/// This template argument is invalid.
ParsedTemplateArgument() : Kind(Type), Arg(nullptr) { }
/// \brief Create a template type argument or non-type template argument.
///
/// \param Arg the template type argument or non-type template argument.
/// \param Loc the location of the type.
ParsedTemplateArgument(KindType Kind, void *Arg, SourceLocation Loc)
: Kind(Kind), Arg(Arg), Loc(Loc) { }
/// \brief Create a template template argument.
///
/// \param SS the C++ scope specifier that precedes the template name, if
/// any.
///
/// \param Template the template to which this template template
/// argument refers.
///
/// \param TemplateLoc the location of the template name.
ParsedTemplateArgument(const CXXScopeSpec &SS,
ParsedTemplateTy Template,
SourceLocation TemplateLoc)
: Kind(ParsedTemplateArgument::Template),
Arg(Template.getAsOpaquePtr()),
SS(SS), Loc(TemplateLoc), EllipsisLoc() { }
/// \brief Determine whether the given template argument is invalid.
bool isInvalid() const { return Arg == nullptr; }
/// \brief Determine what kind of template argument we have.
KindType getKind() const { return Kind; }
/// \brief Retrieve the template type argument's type.
ParsedType getAsType() const {
assert(Kind == Type && "Not a template type argument");
return ParsedType::getFromOpaquePtr(Arg);
}
/// \brief Retrieve the non-type template argument's expression.
Expr *getAsExpr() const {
assert(Kind == NonType && "Not a non-type template argument");
return static_cast<Expr*>(Arg);
}
/// \brief Retrieve the template template argument's template name.
ParsedTemplateTy getAsTemplate() const {
assert(Kind == Template && "Not a template template argument");
return ParsedTemplateTy::getFromOpaquePtr(Arg);
}
/// \brief Retrieve the location of the template argument.
SourceLocation getLocation() const { return Loc; }
/// \brief Retrieve the nested-name-specifier that precedes the template
/// name in a template template argument.
const CXXScopeSpec &getScopeSpec() const {
assert(Kind == Template &&
"Only template template arguments can have a scope specifier");
return SS;
}
/// \brief Retrieve the location of the ellipsis that makes a template
/// template argument into a pack expansion.
SourceLocation getEllipsisLoc() const {
assert(Kind == Template &&
"Only template template arguments can have an ellipsis");
return EllipsisLoc;
}
/// \brief Retrieve a pack expansion of the given template template
/// argument.
///
/// \param EllipsisLoc The location of the ellipsis.
ParsedTemplateArgument getTemplatePackExpansion(
SourceLocation EllipsisLoc) const;
private:
KindType Kind;
/// \brief The actual template argument representation, which may be
/// an \c ActionBase::TypeTy* (for a type), an Expr* (for an
/// expression), or an ActionBase::TemplateTy (for a template).
void *Arg;
/// \brief The nested-name-specifier that can accompany a template template
/// argument.
CXXScopeSpec SS;
/// \brief the location of the template argument.
SourceLocation Loc;
/// \brief The ellipsis location that can accompany a template template
/// argument (turning it into a template template argument expansion).
SourceLocation EllipsisLoc;
};
/// \brief Information about a template-id annotation
/// token.
///
/// A template-id annotation token contains the template declaration,
/// template arguments, whether those template arguments were types,
/// expressions, or template names, and the source locations for important
/// tokens. All of the information about template arguments is allocated
/// directly after this structure.
struct TemplateIdAnnotation {
/// \brief The nested-name-specifier that precedes the template name.
CXXScopeSpec SS;
/// TemplateKWLoc - The location of the template keyword within the
/// source.
SourceLocation TemplateKWLoc;
/// TemplateNameLoc - The location of the template name within the
/// source.
SourceLocation TemplateNameLoc;
/// FIXME: Temporarily stores the name of a specialization
IdentifierInfo *Name;
/// FIXME: Temporarily stores the overloaded operator kind.
OverloadedOperatorKind Operator;
/// The declaration of the template corresponding to the
/// template-name.
ParsedTemplateTy Template;
/// The kind of template that Template refers to.
TemplateNameKind Kind;
/// The location of the '<' before the template argument
/// list.
SourceLocation LAngleLoc;
/// The location of the '>' after the template argument
/// list.
SourceLocation RAngleLoc;
/// NumArgs - The number of template arguments.
unsigned NumArgs;
/// \brief Retrieves a pointer to the template arguments
ParsedTemplateArgument *getTemplateArgs() {
return reinterpret_cast<ParsedTemplateArgument *>(this + 1);
}
/// \brief Creates a new TemplateIdAnnotation with NumArgs arguments and
/// appends it to List.
static TemplateIdAnnotation *
Allocate(unsigned NumArgs, SmallVectorImpl<TemplateIdAnnotation*> &List) {
TemplateIdAnnotation *TemplateId
= (TemplateIdAnnotation *)::operator new(sizeof(TemplateIdAnnotation) +
sizeof(ParsedTemplateArgument) * NumArgs); // HLSL Change: Use overridable operator new
TemplateId->NumArgs = NumArgs;
// Default-construct nested-name-specifier.
new (&TemplateId->SS) CXXScopeSpec();
// Default-construct parsed template arguments.
ParsedTemplateArgument *TemplateArgs = TemplateId->getTemplateArgs();
for (unsigned I = 0; I != NumArgs; ++I)
new (TemplateArgs + I) ParsedTemplateArgument();
List.push_back(TemplateId);
return TemplateId;
}
void Destroy() {
SS.~CXXScopeSpec();
::operator delete(this); // HLSL Change: Use overridable operator delete
}
};
/// Retrieves the range of the given template parameter lists.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params,
unsigned NumParams);
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/Initialization.h | //===--- Initialization.h - Semantic Analysis for Initializers --*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides supporting data types for initialization of objects.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_INITIALIZATION_H
#define LLVM_CLANG_SEMA_INITIALIZATION_H
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Type.h"
#include "clang/AST/UnresolvedSet.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/Overload.h"
#include "clang/Sema/Ownership.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/SmallVector.h"
#include <cassert>
namespace clang {
class CXXBaseSpecifier;
class DeclaratorDecl;
class DeclaratorInfo;
class FieldDecl;
class FunctionDecl;
class ParmVarDecl;
class Sema;
class TypeLoc;
class VarDecl;
class ObjCMethodDecl;
/// \brief Describes an entity that is being initialized.
class InitializedEntity {
public:
/// \brief Specifies the kind of entity being initialized.
enum EntityKind {
/// \brief The entity being initialized is a variable.
EK_Variable,
/// \brief The entity being initialized is a function parameter.
EK_Parameter,
/// \brief The entity being initialized is the result of a function call.
EK_Result,
/// \brief The entity being initialized is an exception object that
/// is being thrown.
EK_Exception,
/// \brief The entity being initialized is a non-static data member
/// subobject.
EK_Member,
/// \brief The entity being initialized is an element of an array.
EK_ArrayElement,
/// \brief The entity being initialized is an object (or array of
/// objects) allocated via new.
EK_New,
/// \brief The entity being initialized is a temporary object.
EK_Temporary,
/// \brief The entity being initialized is a base member subobject.
EK_Base,
/// \brief The initialization is being done by a delegating constructor.
EK_Delegating,
/// \brief The entity being initialized is an element of a vector.
/// or vector.
EK_VectorElement,
/// \brief The entity being initialized is a field of block descriptor for
/// the copied-in c++ object.
EK_BlockElement,
/// \brief The entity being initialized is the real or imaginary part of a
/// complex number.
EK_ComplexElement,
/// \brief The entity being initialized is the field that captures a
/// variable in a lambda.
EK_LambdaCapture,
/// \brief The entity being initialized is the initializer for a compound
/// literal.
EK_CompoundLiteralInit,
/// \brief The entity being implicitly initialized back to the formal
/// result type.
EK_RelatedResult,
/// \brief The entity being initialized is a function parameter; function
/// is member of group of audited CF APIs.
EK_Parameter_CF_Audited
// Note: err_init_conversion_failed in DiagnosticSemaKinds.td uses this
// enum as an index for its first %select. When modifying this list,
// that diagnostic text needs to be updated as well.
};
private:
/// \brief The kind of entity being initialized.
EntityKind Kind;
/// \brief If non-NULL, the parent entity in which this
/// initialization occurs.
const InitializedEntity *Parent;
/// \brief The type of the object or reference being initialized.
QualType Type;
/// \brief The mangling number for the next reference temporary to be created.
mutable unsigned ManglingNumber;
struct LN {
/// \brief When Kind == EK_Result, EK_Exception, EK_New, the
/// location of the 'return', 'throw', or 'new' keyword,
/// respectively. When Kind == EK_Temporary, the location where
/// the temporary is being created.
unsigned Location;
/// \brief Whether the entity being initialized may end up using the
/// named return value optimization (NRVO).
bool NRVO;
};
struct C {
/// \brief The name of the variable being captured by an EK_LambdaCapture.
IdentifierInfo *VarID;
/// \brief The source location at which the capture occurs.
unsigned Location;
};
union {
/// \brief When Kind == EK_Variable, or EK_Member, the VarDecl or
/// FieldDecl, respectively.
DeclaratorDecl *VariableOrMember;
/// \brief When Kind == EK_RelatedResult, the ObjectiveC method where
/// result type was implicitly changed to accommodate ARC semantics.
ObjCMethodDecl *MethodDecl;
/// \brief When Kind == EK_Parameter, the ParmVarDecl, with the
/// low bit indicating whether the parameter is "consumed".
uintptr_t Parameter;
/// \brief When Kind == EK_Temporary or EK_CompoundLiteralInit, the type
/// source information for the temporary.
TypeSourceInfo *TypeInfo;
struct LN LocAndNRVO;
/// \brief When Kind == EK_Base, the base specifier that provides the
/// base class. The lower bit specifies whether the base is an inherited
/// virtual base.
uintptr_t Base;
/// \brief When Kind == EK_ArrayElement, EK_VectorElement, or
/// EK_ComplexElement, the index of the array or vector element being
/// initialized.
unsigned Index;
struct C Capture;
};
InitializedEntity() : ManglingNumber(0) {}
/// \brief Create the initialization entity for a variable.
InitializedEntity(VarDecl *Var)
: Kind(EK_Variable), Parent(nullptr), Type(Var->getType()),
ManglingNumber(0), VariableOrMember(Var) { }
/// \brief Create the initialization entity for the result of a
/// function, throwing an object, performing an explicit cast, or
/// initializing a parameter for which there is no declaration.
InitializedEntity(EntityKind Kind, SourceLocation Loc, QualType Type,
bool NRVO = false)
: Kind(Kind), Parent(nullptr), Type(Type), ManglingNumber(0)
{
LocAndNRVO.Location = Loc.getRawEncoding();
LocAndNRVO.NRVO = NRVO;
}
/// \brief Create the initialization entity for a member subobject.
InitializedEntity(FieldDecl *Member, const InitializedEntity *Parent)
: Kind(EK_Member), Parent(Parent), Type(Member->getType()),
ManglingNumber(0), VariableOrMember(Member) { }
/// \brief Create the initialization entity for an array element.
InitializedEntity(ASTContext &Context, unsigned Index,
const InitializedEntity &Parent);
/// \brief Create the initialization entity for a lambda capture.
InitializedEntity(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
: Kind(EK_LambdaCapture), Parent(nullptr), Type(FieldType),
ManglingNumber(0)
{
Capture.VarID = VarID;
Capture.Location = Loc.getRawEncoding();
}
public:
/// \brief Create the initialization entity for a variable.
static InitializedEntity InitializeVariable(VarDecl *Var) {
return InitializedEntity(Var);
}
/// \brief Create the initialization entity for a parameter.
static InitializedEntity InitializeParameter(ASTContext &Context,
ParmVarDecl *Parm) {
return InitializeParameter(Context, Parm, Parm->getType());
}
/// \brief Create the initialization entity for a parameter, but use
/// another type.
static InitializedEntity InitializeParameter(ASTContext &Context,
ParmVarDecl *Parm,
QualType Type) {
bool Consumed = (Context.getLangOpts().ObjCAutoRefCount &&
Parm->hasAttr<NSConsumedAttr>());
InitializedEntity Entity;
Entity.Kind = EK_Parameter;
Entity.Type =
Context.getVariableArrayDecayedType(Type.getUnqualifiedType());
Entity.Parent = nullptr;
Entity.Parameter
= (static_cast<uintptr_t>(Consumed) | reinterpret_cast<uintptr_t>(Parm));
return Entity;
}
/// \brief Create the initialization entity for a parameter that is
/// only known by its type.
static InitializedEntity InitializeParameter(ASTContext &Context,
QualType Type,
bool Consumed) {
InitializedEntity Entity;
Entity.Kind = EK_Parameter;
Entity.Type = Context.getVariableArrayDecayedType(Type);
Entity.Parent = nullptr;
Entity.Parameter = (Consumed);
return Entity;
}
/// \brief Create the initialization entity for the result of a function.
static InitializedEntity InitializeResult(SourceLocation ReturnLoc,
QualType Type, bool NRVO) {
return InitializedEntity(EK_Result, ReturnLoc, Type, NRVO);
}
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc,
QualType Type, bool NRVO) {
return InitializedEntity(EK_BlockElement, BlockVarLoc, Type, NRVO);
}
/// \brief Create the initialization entity for an exception object.
static InitializedEntity InitializeException(SourceLocation ThrowLoc,
QualType Type, bool NRVO) {
return InitializedEntity(EK_Exception, ThrowLoc, Type, NRVO);
}
/// \brief Create the initialization entity for an object allocated via new.
static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type) {
return InitializedEntity(EK_New, NewLoc, Type);
}
/// \brief Create the initialization entity for a temporary.
static InitializedEntity InitializeTemporary(QualType Type) {
InitializedEntity Result(EK_Temporary, SourceLocation(), Type);
Result.TypeInfo = nullptr;
return Result;
}
/// \brief Create the initialization entity for a temporary.
static InitializedEntity InitializeTemporary(TypeSourceInfo *TypeInfo) {
InitializedEntity Result(EK_Temporary, SourceLocation(),
TypeInfo->getType());
Result.TypeInfo = TypeInfo;
return Result;
}
/// \brief Create the initialization entity for a related result.
static InitializedEntity InitializeRelatedResult(ObjCMethodDecl *MD,
QualType Type) {
InitializedEntity Result(EK_RelatedResult, SourceLocation(), Type);
Result.MethodDecl = MD;
return Result;
}
/// \brief Create the initialization entity for a base class subobject.
static InitializedEntity InitializeBase(ASTContext &Context,
const CXXBaseSpecifier *Base,
bool IsInheritedVirtualBase);
/// \brief Create the initialization entity for a delegated constructor.
static InitializedEntity InitializeDelegation(QualType Type) {
return InitializedEntity(EK_Delegating, SourceLocation(), Type);
}
/// \brief Create the initialization entity for a member subobject.
static InitializedEntity
InitializeMember(FieldDecl *Member,
const InitializedEntity *Parent = nullptr) {
return InitializedEntity(Member, Parent);
}
/// \brief Create the initialization entity for a member subobject.
static InitializedEntity
InitializeMember(IndirectFieldDecl *Member,
const InitializedEntity *Parent = nullptr) {
return InitializedEntity(Member->getAnonField(), Parent);
}
/// \brief Create the initialization entity for an array element.
static InitializedEntity InitializeElement(ASTContext &Context,
unsigned Index,
const InitializedEntity &Parent) {
return InitializedEntity(Context, Index, Parent);
}
/// \brief Create the initialization entity for a lambda capture.
static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID,
QualType FieldType,
SourceLocation Loc) {
return InitializedEntity(VarID, FieldType, Loc);
}
/// \brief Create the entity for a compound literal initializer.
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI) {
InitializedEntity Result(EK_CompoundLiteralInit, SourceLocation(),
TSI->getType());
Result.TypeInfo = TSI;
return Result;
}
/// \brief Determine the kind of initialization.
EntityKind getKind() const { return Kind; }
/// \brief Retrieve the parent of the entity being initialized, when
/// the initialization itself is occurring within the context of a
/// larger initialization.
const InitializedEntity *getParent() const { return Parent; }
/// \brief Retrieve type being initialized.
QualType getType() const { return Type; }
/// \brief Retrieve complete type-source information for the object being
/// constructed, if known.
TypeSourceInfo *getTypeSourceInfo() const {
if (Kind == EK_Temporary || Kind == EK_CompoundLiteralInit)
return TypeInfo;
return nullptr;
}
/// \brief Retrieve the name of the entity being initialized.
DeclarationName getName() const;
/// \brief Retrieve the variable, parameter, or field being
/// initialized.
DeclaratorDecl *getDecl() const;
/// \brief Retrieve the ObjectiveC method being initialized.
ObjCMethodDecl *getMethodDecl() const { return MethodDecl; }
/// \brief Determine whether this initialization allows the named return
/// value optimization, which also applies to thrown objects.
bool allowsNRVO() const;
bool isParameterKind() const {
return (getKind() == EK_Parameter ||
getKind() == EK_Parameter_CF_Audited);
}
/// \brief Determine whether this initialization consumes the
/// parameter.
bool isParameterConsumed() const {
assert(isParameterKind() && "Not a parameter");
return (Parameter & 1);
}
/// \brief Retrieve the base specifier.
const CXXBaseSpecifier *getBaseSpecifier() const {
assert(getKind() == EK_Base && "Not a base specifier");
return reinterpret_cast<const CXXBaseSpecifier *>(Base & ~0x1);
}
/// \brief Return whether the base is an inherited virtual base.
bool isInheritedVirtualBase() const {
assert(getKind() == EK_Base && "Not a base specifier");
return Base & 0x1;
}
/// \brief Determine the location of the 'return' keyword when initializing
/// the result of a function call.
SourceLocation getReturnLoc() const {
assert(getKind() == EK_Result && "No 'return' location!");
return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
}
/// \brief Determine the location of the 'throw' keyword when initializing
/// an exception object.
SourceLocation getThrowLoc() const {
assert(getKind() == EK_Exception && "No 'throw' location!");
return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
}
/// \brief If this is an array, vector, or complex number element, get the
/// element's index.
unsigned getElementIndex() const {
assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
getKind() == EK_ComplexElement);
return Index;
}
/// \brief If this is already the initializer for an array or vector
/// element, sets the element index.
void setElementIndex(unsigned Index) {
assert(getKind() == EK_ArrayElement || getKind() == EK_VectorElement ||
getKind() == EK_ComplexElement);
this->Index = Index;
}
/// \brief For a lambda capture, return the capture's name.
StringRef getCapturedVarName() const {
assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
return Capture.VarID->getName();
}
/// \brief Determine the location of the capture when initializing
/// field from a captured variable in a lambda.
SourceLocation getCaptureLoc() const {
assert(getKind() == EK_LambdaCapture && "Not a lambda capture!");
return SourceLocation::getFromRawEncoding(Capture.Location);
}
void setParameterCFAudited() {
Kind = EK_Parameter_CF_Audited;
}
unsigned allocateManglingNumber() const { return ++ManglingNumber; }
/// Dump a representation of the initialized entity to standard error,
/// for debugging purposes.
void dump() const;
// HLSL Change Starts
SourceLocation getDiagLoc() const {
switch (getKind()) {
case EK_Result:
case EK_Exception:
case EK_Temporary:
case EK_New:
return SourceLocation::getFromRawEncoding(LocAndNRVO.Location);
case EK_LambdaCapture:
return SourceLocation::getFromRawEncoding(Capture.Location);
default:
// Consider adding additional cases such as EK_Variable
return SourceLocation();
}
}
// HLSL Change Ends
private:
unsigned dumpImpl(raw_ostream &OS) const;
};
/// \brief Describes the kind of initialization being performed, along with
/// location information for tokens related to the initialization (equal sign,
/// parentheses).
class InitializationKind {
public:
/// \brief The kind of initialization being performed.
enum InitKind {
IK_Direct, ///< Direct initialization
IK_DirectList, ///< Direct list-initialization
IK_Copy, ///< Copy initialization
IK_Default, ///< Default initialization
IK_Value ///< Value initialization
};
private:
/// \brief The context of the initialization.
enum InitContext {
IC_Normal, ///< Normal context
IC_ExplicitConvs, ///< Normal context, but allows explicit conversion funcs
IC_Implicit, ///< Implicit context (value initialization)
IC_StaticCast, ///< Static cast context
IC_CStyleCast, ///< C-style cast context
IC_FunctionalCast ///< Functional cast context
};
/// \brief The kind of initialization being performed.
InitKind Kind : 8;
/// \brief The context of the initialization.
InitContext Context : 8;
/// \brief The source locations involved in the initialization.
SourceLocation Locations[3];
InitializationKind(InitKind Kind, InitContext Context, SourceLocation Loc1,
SourceLocation Loc2, SourceLocation Loc3)
: Kind(Kind), Context(Context)
{
Locations[0] = Loc1;
Locations[1] = Loc2;
Locations[2] = Loc3;
}
public:
/// \brief Create a direct initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc) {
return InitializationKind(IK_Direct, IC_Normal,
InitLoc, LParenLoc, RParenLoc);
}
static InitializationKind CreateDirectList(SourceLocation InitLoc) {
return InitializationKind(IK_DirectList, IC_Normal,
InitLoc, InitLoc, InitLoc);
}
/// \brief Create a direct initialization due to a cast that isn't a C-style
/// or functional cast.
static InitializationKind CreateCast(SourceRange TypeRange) {
return InitializationKind(IK_Direct, IC_StaticCast, TypeRange.getBegin(),
TypeRange.getBegin(), TypeRange.getEnd());
}
/// \brief Create a direct initialization for a C-style cast.
static InitializationKind CreateCStyleCast(SourceLocation StartLoc,
SourceRange TypeRange,
bool InitList) {
// C++ cast syntax doesn't permit init lists, but C compound literals are
// exactly that.
return InitializationKind(InitList ? IK_DirectList : IK_Direct,
IC_CStyleCast, StartLoc, TypeRange.getBegin(),
TypeRange.getEnd());
}
/// \brief Create a direct initialization for a functional cast.
static InitializationKind CreateFunctionalCast(SourceRange TypeRange,
bool InitList) {
return InitializationKind(InitList ? IK_DirectList : IK_Direct,
IC_FunctionalCast, TypeRange.getBegin(),
TypeRange.getBegin(), TypeRange.getEnd());
}
/// \brief Create a copy initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc,
SourceLocation EqualLoc,
bool AllowExplicitConvs = false) {
return InitializationKind(IK_Copy,
AllowExplicitConvs? IC_ExplicitConvs : IC_Normal,
InitLoc, EqualLoc, EqualLoc);
}
/// \brief Create a default initialization.
static InitializationKind CreateDefault(SourceLocation InitLoc) {
return InitializationKind(IK_Default, IC_Normal, InitLoc, InitLoc, InitLoc);
}
/// \brief Create a value initialization.
static InitializationKind CreateValue(SourceLocation InitLoc,
SourceLocation LParenLoc,
SourceLocation RParenLoc,
bool isImplicit = false) {
return InitializationKind(IK_Value, isImplicit ? IC_Implicit : IC_Normal,
InitLoc, LParenLoc, RParenLoc);
}
/// \brief Determine the initialization kind.
InitKind getKind() const {
return Kind;
}
/// \brief Determine whether this initialization is an explicit cast.
bool isExplicitCast() const {
return Context >= IC_StaticCast;
}
/// \brief Determine whether this initialization is a C-style cast.
bool isCStyleOrFunctionalCast() const {
return Context >= IC_CStyleCast;
}
/// \brief Determine whether this is a C-style cast.
bool isCStyleCast() const {
return Context == IC_CStyleCast;
}
/// \brief Determine whether this is a functional-style cast.
bool isFunctionalCast() const {
return Context == IC_FunctionalCast;
}
/// \brief Determine whether this initialization is an implicit
/// value-initialization, e.g., as occurs during aggregate
/// initialization.
bool isImplicitValueInit() const { return Context == IC_Implicit; }
/// \brief Retrieve the location at which initialization is occurring.
SourceLocation getLocation() const { return Locations[0]; }
/// \brief Retrieve the source range that covers the initialization.
SourceRange getRange() const {
return SourceRange(Locations[0], Locations[2]);
}
/// \brief Retrieve the location of the equal sign for copy initialization
/// (if present).
SourceLocation getEqualLoc() const {
assert(Kind == IK_Copy && "Only copy initialization has an '='");
return Locations[1];
}
bool isCopyInit() const { return Kind == IK_Copy; }
/// \brief Retrieve whether this initialization allows the use of explicit
/// constructors.
bool AllowExplicit() const { return !isCopyInit(); }
/// \brief Retrieve whether this initialization allows the use of explicit
/// conversion functions when binding a reference. If the reference is the
/// first parameter in a copy or move constructor, such conversions are
/// permitted even though we are performing copy-initialization.
bool allowExplicitConversionFunctionsInRefBinding() const {
return !isCopyInit() || Context == IC_ExplicitConvs;
}
/// \brief Retrieve the source range containing the locations of the open
/// and closing parentheses for value and direct initializations.
SourceRange getParenRange() const {
assert((Kind == IK_Direct || Kind == IK_Value) &&
"Only direct- and value-initialization have parentheses");
return SourceRange(Locations[1], Locations[2]);
}
};
/// \brief Describes the sequence of initializations required to initialize
/// a given object or reference with a set of arguments.
class InitializationSequence {
public:
/// \brief Describes the kind of initialization sequence computed.
enum SequenceKind {
/// \brief A failed initialization sequence. The failure kind tells what
/// happened.
FailedSequence = 0,
/// \brief A dependent initialization, which could not be
/// type-checked due to the presence of dependent types or
/// dependently-typed expressions.
DependentSequence,
/// \brief A normal sequence.
NormalSequence
};
/// \brief Describes the kind of a particular step in an initialization
/// sequence.
enum StepKind {
/// \brief Resolve the address of an overloaded function to a specific
/// function declaration.
SK_ResolveAddressOfOverloadedFunction,
/// \brief Perform a derived-to-base cast, producing an rvalue.
SK_CastDerivedToBaseRValue,
/// \brief Perform a derived-to-base cast, producing an xvalue.
SK_CastDerivedToBaseXValue,
/// \brief Perform a derived-to-base cast, producing an lvalue.
SK_CastDerivedToBaseLValue,
/// \brief Reference binding to an lvalue.
SK_BindReference,
/// \brief Reference binding to a temporary.
SK_BindReferenceToTemporary,
/// \brief An optional copy of a temporary object to another
/// temporary object, which is permitted (but not required) by
/// C++98/03 but not C++0x.
SK_ExtraneousCopyToTemporary,
/// \brief Perform a user-defined conversion, either via a conversion
/// function or via a constructor.
SK_UserConversion,
/// \brief Perform a qualification conversion, producing an rvalue.
SK_QualificationConversionRValue,
/// \brief Perform a qualification conversion, producing an xvalue.
SK_QualificationConversionXValue,
/// \brief Perform a qualification conversion, producing an lvalue.
SK_QualificationConversionLValue,
/// \brief Perform a conversion adding _Atomic to a type.
SK_AtomicConversion,
/// \brief Perform a load from a glvalue, producing an rvalue.
SK_LValueToRValue,
/// \brief Perform an implicit conversion sequence.
SK_ConversionSequence,
/// \brief Perform an implicit conversion sequence without narrowing.
SK_ConversionSequenceNoNarrowing,
/// \brief Perform list-initialization without a constructor.
SK_ListInitialization,
/// \brief Unwrap the single-element initializer list for a reference.
SK_UnwrapInitList,
/// \brief Rewrap the single-element initializer list for a reference.
SK_RewrapInitList,
/// \brief Perform initialization via a constructor.
SK_ConstructorInitialization,
/// \brief Perform initialization via a constructor, taking arguments from
/// a single InitListExpr.
SK_ConstructorInitializationFromList,
/// \brief Zero-initialize the object
SK_ZeroInitialization,
/// \brief C assignment
SK_CAssignment,
/// \brief Initialization by string
SK_StringInit,
/// \brief An initialization that "converts" an Objective-C object
/// (not a point to an object) to another Objective-C object type.
SK_ObjCObjectConversion,
/// \brief Array initialization (from an array rvalue).
/// This is a GNU C extension.
SK_ArrayInit,
/// \brief Array initialization from a parenthesized initializer list.
/// This is a GNU C++ extension.
SK_ParenthesizedArrayInit,
/// \brief Pass an object by indirect copy-and-restore.
SK_PassByIndirectCopyRestore,
/// \brief Pass an object by indirect restore.
SK_PassByIndirectRestore,
/// \brief Produce an Objective-C object pointer.
SK_ProduceObjCObject,
/// \brief Construct a std::initializer_list from an initializer list.
SK_StdInitializerList,
/// \brief Perform initialization via a constructor taking a single
/// std::initializer_list argument.
SK_StdInitializerListConstructorCall,
/// \brief Initialize an OpenCL sampler from an integer.
SK_OCLSamplerInit,
/// \brief Passing zero to a function where OpenCL event_t is expected.
SK_OCLZeroEvent
};
/// \brief A single step in the initialization sequence.
class Step {
public:
/// \brief The kind of conversion or initialization step we are taking.
StepKind Kind;
// \brief The type that results from this initialization.
QualType Type;
struct F {
bool HadMultipleCandidates;
FunctionDecl *Function;
DeclAccessPair FoundDecl;
};
union {
/// \brief When Kind == SK_ResolvedOverloadedFunction or Kind ==
/// SK_UserConversion, the function that the expression should be
/// resolved to or the conversion function to call, respectively.
/// When Kind == SK_ConstructorInitialization or SK_ListConstruction,
/// the constructor to be called.
///
/// Always a FunctionDecl, plus a Boolean flag telling if it was
/// selected from an overloaded set having size greater than 1.
/// For conversion decls, the naming class is the source type.
/// For construct decls, the naming class is the target type.
struct F Function;
/// \brief When Kind = SK_ConversionSequence, the implicit conversion
/// sequence.
ImplicitConversionSequence *ICS;
/// \brief When Kind = SK_RewrapInitList, the syntactic form of the
/// wrapping list.
InitListExpr *WrappingSyntacticList;
};
void Destroy();
};
private:
/// \brief The kind of initialization sequence computed.
enum SequenceKind SequenceKind;
/// \brief Steps taken by this initialization.
SmallVector<Step, 4> Steps;
public:
/// \brief Describes why initialization failed.
enum FailureKind {
/// \brief Too many initializers provided for a reference.
FK_TooManyInitsForReference,
/// \brief Array must be initialized with an initializer list.
FK_ArrayNeedsInitList,
/// \brief Array must be initialized with an initializer list or a
/// string literal.
FK_ArrayNeedsInitListOrStringLiteral,
/// \brief Array must be initialized with an initializer list or a
/// wide string literal.
FK_ArrayNeedsInitListOrWideStringLiteral,
/// \brief Initializing a wide char array with narrow string literal.
FK_NarrowStringIntoWideCharArray,
/// \brief Initializing char array with wide string literal.
FK_WideStringIntoCharArray,
/// \brief Initializing wide char array with incompatible wide string
/// literal.
FK_IncompatWideStringIntoWideChar,
/// \brief Array type mismatch.
FK_ArrayTypeMismatch,
/// \brief Non-constant array initializer
FK_NonConstantArrayInit,
/// \brief Cannot resolve the address of an overloaded function.
FK_AddressOfOverloadFailed,
/// \brief Overloading due to reference initialization failed.
FK_ReferenceInitOverloadFailed,
/// \brief Non-const lvalue reference binding to a temporary.
FK_NonConstLValueReferenceBindingToTemporary,
/// \brief Non-const lvalue reference binding to an lvalue of unrelated
/// type.
FK_NonConstLValueReferenceBindingToUnrelated,
/// \brief Rvalue reference binding to an lvalue.
FK_RValueReferenceBindingToLValue,
/// \brief Reference binding drops qualifiers.
FK_ReferenceInitDropsQualifiers,
/// \brief Reference binding failed.
FK_ReferenceInitFailed,
/// \brief Implicit conversion failed.
FK_ConversionFailed,
/// \brief Implicit conversion failed.
FK_ConversionFromPropertyFailed,
/// \brief Too many initializers for scalar
FK_TooManyInitsForScalar,
/// \brief Reference initialization from an initializer list
FK_ReferenceBindingToInitList,
/// \brief Initialization of some unused destination type with an
/// initializer list.
FK_InitListBadDestinationType,
/// \brief Overloading for a user-defined conversion failed.
FK_UserConversionOverloadFailed,
/// \brief Overloading for initialization by constructor failed.
FK_ConstructorOverloadFailed,
/// \brief Overloading for list-initialization by constructor failed.
FK_ListConstructorOverloadFailed,
/// \brief Default-initialization of a 'const' object.
FK_DefaultInitOfConst,
/// \brief Initialization of an incomplete type.
FK_Incomplete,
/// \brief Variable-length array must not have an initializer.
FK_VariableLengthArrayHasInitializer,
/// \brief List initialization failed at some point.
FK_ListInitializationFailed,
/// \brief Initializer has a placeholder type which cannot be
/// resolved by initialization.
FK_PlaceholderType,
/// \brief List-copy-initialization chose an explicit constructor.
FK_ExplicitConstructor
};
private:
/// \brief The reason why initialization failed.
FailureKind Failure;
/// \brief The failed result of overload resolution.
OverloadingResult FailedOverloadResult;
/// \brief The candidate set created when initialization failed.
OverloadCandidateSet FailedCandidateSet;
/// \brief The incomplete type that caused a failure.
QualType FailedIncompleteType;
/// \brief The fixit that needs to be applied to make this initialization
/// succeed.
std::string ZeroInitializationFixit;
SourceLocation ZeroInitializationFixitLoc;
public:
/// \brief Call for initializations are invalid but that would be valid
/// zero initialzations if Fixit was applied.
void SetZeroInitializationFixit(const std::string& Fixit, SourceLocation L) {
ZeroInitializationFixit = Fixit;
ZeroInitializationFixitLoc = L;
}
private:
/// \brief Prints a follow-up note that highlights the location of
/// the initialized entity, if it's remote.
void PrintInitLocationNote(Sema &S, const InitializedEntity &Entity);
public:
/// \brief Try to perform initialization of the given entity, creating a
/// record of the steps required to perform the initialization.
///
/// The generated initialization sequence will either contain enough
/// information to diagnose
///
/// \param S the semantic analysis object.
///
/// \param Entity the entity being initialized.
///
/// \param Kind the kind of initialization being performed.
///
/// \param Args the argument(s) provided for initialization.
///
/// \param TopLevelOfInitList true if we are initializing from an expression
/// at the top level inside an initializer list. This disallows
/// narrowing conversions in C++11 onwards.
InitializationSequence(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
MultiExprArg Args,
bool TopLevelOfInitList = false);
void InitializeFrom(Sema &S, const InitializedEntity &Entity,
const InitializationKind &Kind, MultiExprArg Args,
bool TopLevelOfInitList);
~InitializationSequence();
/// \brief Perform the actual initialization of the given entity based on
/// the computed initialization sequence.
///
/// \param S the semantic analysis object.
///
/// \param Entity the entity being initialized.
///
/// \param Kind the kind of initialization being performed.
///
/// \param Args the argument(s) provided for initialization, ownership of
/// which is transferred into the routine.
///
/// \param ResultType if non-NULL, will be set to the type of the
/// initialized object, which is the type of the declaration in most
/// cases. However, when the initialized object is a variable of
/// incomplete array type and the initializer is an initializer
/// list, this type will be set to the completed array type.
///
/// \returns an expression that performs the actual object initialization, if
/// the initialization is well-formed. Otherwise, emits diagnostics
/// and returns an invalid expression.
ExprResult Perform(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
MultiExprArg Args,
QualType *ResultType = nullptr);
/// \brief Diagnose an potentially-invalid initialization sequence.
///
/// \returns true if the initialization sequence was ill-formed,
/// false otherwise.
bool Diagnose(Sema &S,
const InitializedEntity &Entity,
const InitializationKind &Kind,
ArrayRef<Expr *> Args);
/// \brief Determine the kind of initialization sequence computed.
enum SequenceKind getKind() const { return SequenceKind; }
/// \brief Set the kind of sequence computed.
void setSequenceKind(enum SequenceKind SK) { SequenceKind = SK; }
/// \brief Determine whether the initialization sequence is valid.
explicit operator bool() const { return !Failed(); }
/// \brief Determine whether the initialization sequence is invalid.
bool Failed() const { return SequenceKind == FailedSequence; }
typedef SmallVectorImpl<Step>::const_iterator step_iterator;
step_iterator step_begin() const { return Steps.begin(); }
step_iterator step_end() const { return Steps.end(); }
/// \brief Determine whether this initialization is a direct reference
/// binding (C++ [dcl.init.ref]).
bool isDirectReferenceBinding() const;
/// \brief Determine whether this initialization failed due to an ambiguity.
bool isAmbiguous() const;
/// \brief Determine whether this initialization is direct call to a
/// constructor.
bool isConstructorInitialization() const;
/// \brief Returns whether the last step in this initialization sequence is a
/// narrowing conversion, defined by C++0x [dcl.init.list]p7.
///
/// If this function returns true, *isInitializerConstant will be set to
/// describe whether *Initializer was a constant expression. If
/// *isInitializerConstant is set to true, *ConstantValue will be set to the
/// evaluated value of *Initializer.
bool endsWithNarrowing(ASTContext &Ctx, const Expr *Initializer,
bool *isInitializerConstant,
APValue *ConstantValue) const;
/// \brief Add a new step in the initialization that resolves the address
/// of an overloaded function to a specific function declaration.
///
/// \param Function the function to which the overloaded function reference
/// resolves.
void AddAddressOverloadResolutionStep(FunctionDecl *Function,
DeclAccessPair Found,
bool HadMultipleCandidates);
/// \brief Add a new step in the initialization that performs a derived-to-
/// base cast.
///
/// \param BaseType the base type to which we will be casting.
///
/// \param Category Indicates whether the result will be treated as an
/// rvalue, an xvalue, or an lvalue.
void AddDerivedToBaseCastStep(QualType BaseType,
ExprValueKind Category);
/// \brief Add a new step binding a reference to an object.
///
/// \param BindingTemporary True if we are binding a reference to a temporary
/// object (thereby extending its lifetime); false if we are binding to an
/// lvalue or an lvalue treated as an rvalue.
void AddReferenceBindingStep(QualType T, bool BindingTemporary);
/// \brief Add a new step that makes an extraneous copy of the input
/// to a temporary of the same class type.
///
/// This extraneous copy only occurs during reference binding in
/// C++98/03, where we are permitted (but not required) to introduce
/// an extra copy. At a bare minimum, we must check that we could
/// call the copy constructor, and produce a diagnostic if the copy
/// constructor is inaccessible or no copy constructor matches.
//
/// \param T The type of the temporary being created.
void AddExtraneousCopyToTemporary(QualType T);
/// \brief Add a new step invoking a conversion function, which is either
/// a constructor or a conversion function.
void AddUserConversionStep(FunctionDecl *Function,
DeclAccessPair FoundDecl,
QualType T,
bool HadMultipleCandidates);
/// \brief Add a new step that performs a qualification conversion to the
/// given type.
void AddQualificationConversionStep(QualType Ty,
ExprValueKind Category);
/// \brief Add a new step that performs conversion from non-atomic to atomic
/// type.
void AddAtomicConversionStep(QualType Ty);
/// \brief Add a new step that performs a load of the given type.
///
/// Although the term "LValueToRValue" is conventional, this applies to both
/// lvalues and xvalues.
void AddLValueToRValueStep(QualType Ty);
/// \brief Add a new step that applies an implicit conversion sequence.
void AddConversionSequenceStep(const ImplicitConversionSequence &ICS,
QualType T, bool TopLevelOfInitList = false);
/// \brief Add a list-initialization step.
void AddListInitializationStep(QualType T);
/// \brief Add a constructor-initialization step.
///
/// \param FromInitList The constructor call is syntactically an initializer
/// list.
/// \param AsInitList The constructor is called as an init list constructor.
void AddConstructorInitializationStep(CXXConstructorDecl *Constructor,
AccessSpecifier Access,
QualType T,
bool HadMultipleCandidates,
bool FromInitList, bool AsInitList);
/// \brief Add a zero-initialization step.
void AddZeroInitializationStep(QualType T);
/// \brief Add a C assignment step.
//
// FIXME: It isn't clear whether this should ever be needed;
// ideally, we would handle everything needed in C in the common
// path. However, that isn't the case yet.
void AddCAssignmentStep(QualType T);
/// \brief Add a string init step.
void AddStringInitStep(QualType T);
/// \brief Add an Objective-C object conversion step, which is
/// always a no-op.
void AddObjCObjectConversionStep(QualType T);
/// \brief Add an array initialization step.
void AddArrayInitStep(QualType T);
/// \brief Add a parenthesized array initialization step.
void AddParenthesizedArrayInitStep(QualType T);
/// \brief Add a step to pass an object by indirect copy-restore.
void AddPassByIndirectCopyRestoreStep(QualType T, bool shouldCopy);
/// \brief Add a step to "produce" an Objective-C object (by
/// retaining it).
void AddProduceObjCObjectStep(QualType T);
/// \brief Add a step to construct a std::initializer_list object from an
/// initializer list.
void AddStdInitializerListConstructionStep(QualType T);
/// \brief Add a step to initialize an OpenCL sampler from an integer
/// constant.
void AddOCLSamplerInitStep(QualType T);
/// \brief Add a step to initialize an OpenCL event_t from a NULL
/// constant.
void AddOCLZeroEventStep(QualType T);
/// \brief Add steps to unwrap a initializer list for a reference around a
/// single element and rewrap it at the end.
void RewrapReferenceInitList(QualType T, InitListExpr *Syntactic);
/// \brief Note that this initialization sequence failed.
void SetFailed(FailureKind Failure) {
SequenceKind = FailedSequence;
this->Failure = Failure;
assert((Failure != FK_Incomplete || !FailedIncompleteType.isNull()) &&
"Incomplete type failure requires a type!");
}
/// \brief Note that this initialization sequence failed due to failed
/// overload resolution.
void SetOverloadFailure(FailureKind Failure, OverloadingResult Result);
/// \brief Retrieve a reference to the candidate set when overload
/// resolution fails.
OverloadCandidateSet &getFailedCandidateSet() {
return FailedCandidateSet;
}
/// \brief Get the overloading result, for when the initialization
/// sequence failed due to a bad overload.
OverloadingResult getFailedOverloadResult() const {
return FailedOverloadResult;
}
/// \brief Note that this initialization sequence failed due to an
/// incomplete type.
void setIncompleteTypeFailure(QualType IncompleteType) {
FailedIncompleteType = IncompleteType;
SetFailed(FK_Incomplete);
}
/// \brief Determine why initialization failed.
FailureKind getFailureKind() const {
assert(Failed() && "Not an initialization failure!");
return Failure;
}
/// \brief Dump a representation of this initialization sequence to
/// the given stream, for debugging purposes.
void dump(raw_ostream &OS) const;
/// \brief Dump a representation of this initialization sequence to
/// standard error, for debugging purposes.
void dump() const;
};
} // end namespace clang
#endif // LLVM_CLANG_SEMA_INITIALIZATION_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/SemaConsumer.h | //===--- SemaConsumer.h - Abstract interface for AST semantics --*- 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 SemaConsumer class, a subclass of
// ASTConsumer that is used by AST clients that also require
// additional semantic analysis.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMACONSUMER_H
#define LLVM_CLANG_SEMA_SEMACONSUMER_H
#include "clang/AST/ASTConsumer.h"
namespace clang {
class Sema;
/// \brief An abstract interface that should be implemented by
/// clients that read ASTs and then require further semantic
/// analysis of the entities in those ASTs.
class SemaConsumer : public ASTConsumer {
virtual void anchor();
public:
SemaConsumer() {
ASTConsumer::SemaConsumer = true;
}
/// \brief Initialize the semantic consumer with the Sema instance
/// being used to perform semantic analysis on the abstract syntax
/// tree.
virtual void InitializeSema(Sema &S) {}
/// \brief Inform the semantic consumer that Sema is no longer available.
virtual void ForgetSema() {}
// isa/cast/dyn_cast support
static bool classof(const ASTConsumer *Consumer) {
return Consumer->SemaConsumer;
}
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/PrettyDeclStackTrace.h | //===- PrettyDeclStackTrace.h - Stack trace for decl processing -*- 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 an llvm::PrettyStackTraceEntry object for showing
// that a particular declaration was being processed when a crash
// occurred.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_PRETTYDECLSTACKTRACE_H
#define LLVM_CLANG_SEMA_PRETTYDECLSTACKTRACE_H
#include "clang/Basic/SourceLocation.h"
#include "llvm/Support/PrettyStackTrace.h"
namespace clang {
class Decl;
class Sema;
class SourceManager;
/// PrettyDeclStackTraceEntry - If a crash occurs in the parser while
/// parsing something related to a declaration, include that
/// declaration in the stack trace.
class PrettyDeclStackTraceEntry : public llvm::PrettyStackTraceEntry {
Sema &S;
Decl *TheDecl;
SourceLocation Loc;
const char *Message;
public:
PrettyDeclStackTraceEntry(Sema &S, Decl *D, SourceLocation Loc,
const char *Msg)
: S(S), TheDecl(D), Loc(Loc), Message(Msg) {}
void print(raw_ostream &OS) const override;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/TemplateDeduction.h | //===- TemplateDeduction.h - C++ template argument deduction ----*- C++ -*-===/
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//===----------------------------------------------------------------------===/
//
// This file provides types used with Sema's template argument deduction
// routines.
//
//===----------------------------------------------------------------------===/
#ifndef LLVM_CLANG_SEMA_TEMPLATEDEDUCTION_H
#define LLVM_CLANG_SEMA_TEMPLATEDEDUCTION_H
#include "clang/AST/DeclTemplate.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "llvm/ADT/SmallVector.h"
namespace clang {
struct DeducedPack;
class TemplateArgumentList;
class Sema;
namespace sema {
/// \brief Provides information about an attempted template argument
/// deduction, whose success or failure was described by a
/// TemplateDeductionResult value.
class TemplateDeductionInfo {
/// \brief The deduced template argument list.
///
TemplateArgumentList *Deduced;
/// \brief The source location at which template argument
/// deduction is occurring.
SourceLocation Loc;
/// \brief Have we suppressed an error during deduction?
bool HasSFINAEDiagnostic;
/// \brief Warnings (and follow-on notes) that were suppressed due to
/// SFINAE while performing template argument deduction.
SmallVector<PartialDiagnosticAt, 4> SuppressedDiagnostics;
TemplateDeductionInfo(const TemplateDeductionInfo &) = delete;
void operator=(const TemplateDeductionInfo &) = delete;
public:
TemplateDeductionInfo(SourceLocation Loc)
: Deduced(nullptr), Loc(Loc), HasSFINAEDiagnostic(false),
Expression(nullptr) {}
/// \brief Returns the location at which template argument is
/// occurring.
SourceLocation getLocation() const {
return Loc;
}
/// \brief Take ownership of the deduced template argument list.
TemplateArgumentList *take() {
TemplateArgumentList *Result = Deduced;
Deduced = nullptr;
return Result;
}
/// \brief Take ownership of the SFINAE diagnostic.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD) {
assert(HasSFINAEDiagnostic);
PD.first = SuppressedDiagnostics.front().first;
PD.second.swap(SuppressedDiagnostics.front().second);
SuppressedDiagnostics.clear();
HasSFINAEDiagnostic = false;
}
/// \brief Provide a new template argument list that contains the
/// results of template argument deduction.
void reset(TemplateArgumentList *NewDeduced) {
Deduced = NewDeduced;
}
/// \brief Is a SFINAE diagnostic available?
bool hasSFINAEDiagnostic() const {
return HasSFINAEDiagnostic;
}
/// \brief Set the diagnostic which caused the SFINAE failure.
void addSFINAEDiagnostic(SourceLocation Loc, PartialDiagnostic PD) {
// Only collect the first diagnostic.
if (HasSFINAEDiagnostic)
return;
SuppressedDiagnostics.clear();
SuppressedDiagnostics.emplace_back(Loc, std::move(PD));
HasSFINAEDiagnostic = true;
}
/// \brief Add a new diagnostic to the set of diagnostics
void addSuppressedDiagnostic(SourceLocation Loc,
PartialDiagnostic PD) {
if (HasSFINAEDiagnostic)
return;
SuppressedDiagnostics.emplace_back(Loc, std::move(PD));
}
/// \brief Iterator over the set of suppressed diagnostics.
typedef SmallVectorImpl<PartialDiagnosticAt>::const_iterator
diag_iterator;
/// \brief Returns an iterator at the beginning of the sequence of suppressed
/// diagnostics.
diag_iterator diag_begin() const { return SuppressedDiagnostics.begin(); }
/// \brief Returns an iterator at the end of the sequence of suppressed
/// diagnostics.
diag_iterator diag_end() const { return SuppressedDiagnostics.end(); }
/// \brief The template parameter to which a template argument
/// deduction failure refers.
///
/// Depending on the result of template argument deduction, this
/// template parameter may have different meanings:
///
/// TDK_Incomplete: this is the first template parameter whose
/// corresponding template argument was not deduced.
///
/// TDK_Inconsistent: this is the template parameter for which
/// two different template argument values were deduced.
TemplateParameter Param;
/// \brief The first template argument to which the template
/// argument deduction failure refers.
///
/// Depending on the result of the template argument deduction,
/// this template argument may have different meanings:
///
/// TDK_Inconsistent: this argument is the first value deduced
/// for the corresponding template parameter.
///
/// TDK_SubstitutionFailure: this argument is the template
/// argument we were instantiating when we encountered an error.
///
/// TDK_NonDeducedMismatch: this is the component of the 'parameter'
/// of the deduction, directly provided in the source code.
TemplateArgument FirstArg;
/// \brief The second template argument to which the template
/// argument deduction failure refers.
///
/// TDK_NonDeducedMismatch: this is the mismatching component of the
/// 'argument' of the deduction, from which we are deducing arguments.
///
/// FIXME: Finish documenting this.
TemplateArgument SecondArg;
/// \brief The expression which caused a deduction failure.
///
/// TDK_FailedOverloadResolution: this argument is the reference to
/// an overloaded function which could not be resolved to a specific
/// function.
Expr *Expression;
/// \brief Information on packs that we're currently expanding.
///
/// FIXME: This should be kept internal to SemaTemplateDeduction.
SmallVector<DeducedPack *, 8> PendingDeducedPacks;
};
} // end namespace sema
/// A structure used to record information about a failed
/// template argument deduction, for diagnosis.
struct DeductionFailureInfo {
/// A Sema::TemplateDeductionResult.
unsigned Result : 8;
/// \brief Indicates whether a diagnostic is stored in Diagnostic.
unsigned HasDiagnostic : 1;
/// \brief Opaque pointer containing additional data about
/// this deduction failure.
void *Data;
/// \brief A diagnostic indicating why deduction failed.
union {
void *Align;
char Diagnostic[sizeof(PartialDiagnosticAt)];
};
/// \brief Retrieve the diagnostic which caused this deduction failure,
/// if any.
PartialDiagnosticAt *getSFINAEDiagnostic();
/// \brief Retrieve the template parameter this deduction failure
/// refers to, if any.
TemplateParameter getTemplateParameter();
/// \brief Retrieve the template argument list associated with this
/// deduction failure, if any.
TemplateArgumentList *getTemplateArgumentList();
/// \brief Return the first template argument this deduction failure
/// refers to, if any.
const TemplateArgument *getFirstArg();
/// \brief Return the second template argument this deduction failure
/// refers to, if any.
const TemplateArgument *getSecondArg();
/// \brief Return the expression this deduction failure refers to,
/// if any.
Expr *getExpr();
/// \brief Free any memory associated with this deduction failure.
void Destroy();
};
/// TemplateSpecCandidate - This is a generalization of OverloadCandidate
/// which keeps track of template argument deduction failure info, when
/// handling explicit specializations (and instantiations) of templates
/// beyond function overloading.
/// For now, assume that the candidates are non-matching specializations.
/// TODO: In the future, we may need to unify/generalize this with
/// OverloadCandidate.
struct TemplateSpecCandidate {
/// Specialization - The actual specialization that this candidate
/// represents. When NULL, this may be a built-in candidate.
Decl *Specialization;
/// Template argument deduction info
DeductionFailureInfo DeductionFailure;
void set(Decl *Spec, DeductionFailureInfo Info) {
Specialization = Spec;
DeductionFailure = Info;
}
/// Diagnose a template argument deduction failure.
void NoteDeductionFailure(Sema &S);
};
/// TemplateSpecCandidateSet - A set of generalized overload candidates,
/// used in template specializations.
/// TODO: In the future, we may need to unify/generalize this with
/// OverloadCandidateSet.
class TemplateSpecCandidateSet {
SmallVector<TemplateSpecCandidate, 16> Candidates;
SourceLocation Loc;
TemplateSpecCandidateSet(
const TemplateSpecCandidateSet &) = delete;
void operator=(const TemplateSpecCandidateSet &) = delete;
void destroyCandidates();
public:
TemplateSpecCandidateSet(SourceLocation Loc) : Loc(Loc) {}
~TemplateSpecCandidateSet() { destroyCandidates(); }
SourceLocation getLocation() const { return Loc; }
/// \brief Clear out all of the candidates.
/// TODO: This may be unnecessary.
void clear();
typedef SmallVector<TemplateSpecCandidate, 16>::iterator iterator;
iterator begin() { return Candidates.begin(); }
iterator end() { return Candidates.end(); }
size_t size() const { return Candidates.size(); }
bool empty() const { return Candidates.empty(); }
/// \brief Add a new candidate with NumConversions conversion sequence slots
/// to the overload set.
TemplateSpecCandidate &addCandidate() {
Candidates.emplace_back();
return Candidates.back();
}
void NoteCandidates(Sema &S, SourceLocation Loc);
void NoteCandidates(Sema &S, SourceLocation Loc) const {
const_cast<TemplateSpecCandidateSet *>(this)->NoteCandidates(S, Loc);
}
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/TypoCorrection.h | //===--- TypoCorrection.h - Class for typo correction results ---*- 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 TypoCorrection class, which stores the results of
// Sema's typo correction (Sema::CorrectTypo).
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_TYPOCORRECTION_H
#define LLVM_CLANG_SEMA_TYPOCORRECTION_H
#include "clang/AST/DeclCXX.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Ownership.h"
#include "llvm/ADT/SmallVector.h"
namespace clang {
/// @brief Simple class containing the result of Sema::CorrectTypo
class TypoCorrection {
public:
// "Distance" for unusable corrections
static const unsigned InvalidDistance = ~0U;
// The largest distance still considered valid (larger edit distances are
// mapped to InvalidDistance by getEditDistance).
static const unsigned MaximumDistance = 10000U;
// Relative weightings of the "edit distance" components. The higher the
// weight, the more of a penalty to fitness the component will give (higher
// weights mean greater contribution to the total edit distance, with the
// best correction candidates having the lowest edit distance).
static const unsigned CharDistanceWeight = 100U;
static const unsigned QualifierDistanceWeight = 110U;
static const unsigned CallbackDistanceWeight = 150U;
TypoCorrection(const DeclarationName &Name, NamedDecl *NameDecl,
NestedNameSpecifier *NNS = nullptr, unsigned CharDistance = 0,
unsigned QualifierDistance = 0)
: CorrectionName(Name), CorrectionNameSpec(NNS),
CharDistance(CharDistance), QualifierDistance(QualifierDistance),
CallbackDistance(0), ForceSpecifierReplacement(false),
RequiresImport(false) {
if (NameDecl)
CorrectionDecls.push_back(NameDecl);
}
TypoCorrection(NamedDecl *Name, NestedNameSpecifier *NNS = nullptr,
unsigned CharDistance = 0)
: CorrectionName(Name->getDeclName()), CorrectionNameSpec(NNS),
CharDistance(CharDistance), QualifierDistance(0), CallbackDistance(0),
ForceSpecifierReplacement(false), RequiresImport(false) {
if (Name)
CorrectionDecls.push_back(Name);
}
TypoCorrection(DeclarationName Name, NestedNameSpecifier *NNS = nullptr,
unsigned CharDistance = 0)
: CorrectionName(Name), CorrectionNameSpec(NNS),
CharDistance(CharDistance), QualifierDistance(0), CallbackDistance(0),
ForceSpecifierReplacement(false), RequiresImport(false) {}
TypoCorrection()
: CorrectionNameSpec(nullptr), CharDistance(0), QualifierDistance(0),
CallbackDistance(0), ForceSpecifierReplacement(false),
RequiresImport(false) {}
/// \brief Gets the DeclarationName of the typo correction
DeclarationName getCorrection() const { return CorrectionName; }
IdentifierInfo* getCorrectionAsIdentifierInfo() const {
return CorrectionName.getAsIdentifierInfo();
}
/// \brief Gets the NestedNameSpecifier needed to use the typo correction
NestedNameSpecifier* getCorrectionSpecifier() const {
return CorrectionNameSpec;
}
void setCorrectionSpecifier(NestedNameSpecifier* NNS) {
CorrectionNameSpec = NNS;
ForceSpecifierReplacement = (NNS != nullptr);
}
void WillReplaceSpecifier(bool ForceReplacement) {
ForceSpecifierReplacement = ForceReplacement;
}
bool WillReplaceSpecifier() const {
return ForceSpecifierReplacement;
}
void setQualifierDistance(unsigned ED) {
QualifierDistance = ED;
}
void setCallbackDistance(unsigned ED) {
CallbackDistance = ED;
}
// Convert the given weighted edit distance to a roughly equivalent number of
// single-character edits (typically for comparison to the length of the
// string being edited).
static unsigned NormalizeEditDistance(unsigned ED) {
if (ED > MaximumDistance)
return InvalidDistance;
return (ED + CharDistanceWeight / 2) / CharDistanceWeight;
}
/// \brief Gets the "edit distance" of the typo correction from the typo.
/// If Normalized is true, scale the distance down by the CharDistanceWeight
/// to return the edit distance in terms of single-character edits.
unsigned getEditDistance(bool Normalized = true) const {
if (CharDistance > MaximumDistance || QualifierDistance > MaximumDistance ||
CallbackDistance > MaximumDistance)
return InvalidDistance;
unsigned ED =
CharDistance * CharDistanceWeight +
QualifierDistance * QualifierDistanceWeight +
CallbackDistance * CallbackDistanceWeight;
if (ED > MaximumDistance)
return InvalidDistance;
// Half the CharDistanceWeight is added to ED to simulate rounding since
// integer division truncates the value (i.e. round-to-nearest-int instead
// of round-to-zero).
return Normalized ? NormalizeEditDistance(ED) : ED;
}
/// \brief Gets the pointer to the declaration of the typo correction
NamedDecl *getCorrectionDecl() const {
return hasCorrectionDecl() ? *(CorrectionDecls.begin()) : nullptr;
}
template <class DeclClass>
DeclClass *getCorrectionDeclAs() const {
return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
}
/// \brief Clears the list of NamedDecls.
void ClearCorrectionDecls() {
CorrectionDecls.clear();
}
/// \brief Clears the list of NamedDecls before adding the new one.
void setCorrectionDecl(NamedDecl *CDecl) {
CorrectionDecls.clear();
addCorrectionDecl(CDecl);
}
/// \brief Clears the list of NamedDecls and adds the given set.
void setCorrectionDecls(ArrayRef<NamedDecl*> Decls) {
CorrectionDecls.clear();
CorrectionDecls.insert(CorrectionDecls.begin(), Decls.begin(), Decls.end());
}
/// \brief Add the given NamedDecl to the list of NamedDecls that are the
/// declarations associated with the DeclarationName of this TypoCorrection
void addCorrectionDecl(NamedDecl *CDecl);
std::string getAsString(const LangOptions &LO) const;
std::string getQuoted(const LangOptions &LO) const {
return "'" + getAsString(LO) + "'";
}
/// \brief Returns whether this TypoCorrection has a non-empty DeclarationName
explicit operator bool() const { return bool(CorrectionName); }
/// \brief Mark this TypoCorrection as being a keyword.
/// Since addCorrectionDeclsand setCorrectionDecl don't allow NULL to be
/// added to the list of the correction's NamedDecl pointers, NULL is added
/// as the only element in the list to mark this TypoCorrection as a keyword.
void makeKeyword() {
CorrectionDecls.clear();
CorrectionDecls.push_back(nullptr);
ForceSpecifierReplacement = true;
}
// Check if this TypoCorrection is a keyword by checking if the first
// item in CorrectionDecls is NULL.
bool isKeyword() const {
return !CorrectionDecls.empty() &&
CorrectionDecls.front() == nullptr;
}
// Check if this TypoCorrection is the given keyword.
template<std::size_t StrLen>
bool isKeyword(const char (&Str)[StrLen]) const {
return isKeyword() && getCorrectionAsIdentifierInfo()->isStr(Str);
}
// Returns true if the correction either is a keyword or has a known decl.
bool isResolved() const { return !CorrectionDecls.empty(); }
bool isOverloaded() const {
return CorrectionDecls.size() > 1;
}
void setCorrectionRange(CXXScopeSpec *SS,
const DeclarationNameInfo &TypoName) {
CorrectionRange = TypoName.getSourceRange();
if (ForceSpecifierReplacement && SS && !SS->isEmpty())
CorrectionRange.setBegin(SS->getBeginLoc());
}
SourceRange getCorrectionRange() const {
return CorrectionRange;
}
typedef SmallVectorImpl<NamedDecl *>::iterator decl_iterator;
decl_iterator begin() {
return isKeyword() ? CorrectionDecls.end() : CorrectionDecls.begin();
}
decl_iterator end() { return CorrectionDecls.end(); }
typedef SmallVectorImpl<NamedDecl *>::const_iterator const_decl_iterator;
const_decl_iterator begin() const {
return isKeyword() ? CorrectionDecls.end() : CorrectionDecls.begin();
}
const_decl_iterator end() const { return CorrectionDecls.end(); }
/// \brief Returns whether this typo correction is correcting to a
/// declaration that was declared in a module that has not been imported.
bool requiresImport() const { return RequiresImport; }
void setRequiresImport(bool Req) { RequiresImport = Req; }
private:
bool hasCorrectionDecl() const {
return (!isKeyword() && !CorrectionDecls.empty());
}
// Results.
DeclarationName CorrectionName;
NestedNameSpecifier *CorrectionNameSpec;
SmallVector<NamedDecl *, 1> CorrectionDecls;
unsigned CharDistance;
unsigned QualifierDistance;
unsigned CallbackDistance;
SourceRange CorrectionRange;
bool ForceSpecifierReplacement;
bool RequiresImport;
};
/// @brief Base class for callback objects used by Sema::CorrectTypo to check
/// the validity of a potential typo correction.
class CorrectionCandidateCallback {
public:
static const unsigned InvalidDistance = TypoCorrection::InvalidDistance;
explicit CorrectionCandidateCallback(IdentifierInfo *Typo = nullptr,
NestedNameSpecifier *TypoNNS = nullptr)
: WantTypeSpecifiers(true), WantExpressionKeywords(true),
WantCXXNamedCasts(true), WantFunctionLikeCasts(true),
WantRemainingKeywords(true), WantObjCSuper(false),
IsObjCIvarLookup(false), IsAddressOfOperand(false), Typo(Typo),
TypoNNS(TypoNNS) {}
virtual ~CorrectionCandidateCallback() {}
/// \brief Simple predicate used by the default RankCandidate to
/// determine whether to return an edit distance of 0 or InvalidDistance.
/// This can be overrided by validators that only need to determine if a
/// candidate is viable, without ranking potentially viable candidates.
/// Only ValidateCandidate or RankCandidate need to be overriden by a
/// callback wishing to check the viability of correction candidates.
/// The default predicate always returns true if the candidate is not a type
/// name or keyword, true for types if WantTypeSpecifiers is true, and true
/// for keywords if WantTypeSpecifiers, WantExpressionKeywords,
/// WantCXXNamedCasts, WantRemainingKeywords, or WantObjCSuper is true.
virtual bool ValidateCandidate(const TypoCorrection &candidate);
/// \brief Method used by Sema::CorrectTypo to assign an "edit distance" rank
/// to a candidate (where a lower value represents a better candidate), or
/// returning InvalidDistance if the candidate is not at all viable. For
/// validation callbacks that only need to determine if a candidate is viable,
/// the default RankCandidate returns either 0 or InvalidDistance depending
/// whether ValidateCandidate returns true or false.
virtual unsigned RankCandidate(const TypoCorrection &candidate) {
return (!MatchesTypo(candidate) && ValidateCandidate(candidate))
? 0
: InvalidDistance;
}
void setTypoName(IdentifierInfo *II) { Typo = II; }
void setTypoNNS(NestedNameSpecifier *NNS) { TypoNNS = NNS; }
// Flags for context-dependent keywords. WantFunctionLikeCasts is only
// used/meaningful when WantCXXNamedCasts is false.
// TODO: Expand these to apply to non-keywords or possibly remove them.
bool WantTypeSpecifiers;
bool WantExpressionKeywords;
bool WantCXXNamedCasts;
bool WantFunctionLikeCasts;
bool WantRemainingKeywords;
bool WantObjCSuper;
// Temporary hack for the one case where a CorrectTypoContext enum is used
// when looking up results.
bool IsObjCIvarLookup;
bool IsAddressOfOperand;
protected:
bool MatchesTypo(const TypoCorrection &candidate) {
return Typo && candidate.isResolved() && !candidate.requiresImport() &&
candidate.getCorrectionAsIdentifierInfo() == Typo &&
// FIXME: This probably does not return true when both
// NestedNameSpecifiers have the same textual representation.
candidate.getCorrectionSpecifier() == TypoNNS;
}
IdentifierInfo *Typo;
NestedNameSpecifier *TypoNNS;
};
/// @brief Simple template class for restricting typo correction candidates
/// to ones having a single Decl* of the given type.
template <class C>
class DeclFilterCCC : public CorrectionCandidateCallback {
public:
bool ValidateCandidate(const TypoCorrection &candidate) override {
return candidate.getCorrectionDeclAs<C>();
}
};
// @brief Callback class to limit the allowed keywords and to only accept typo
// corrections that are keywords or whose decls refer to functions (or template
// functions) that accept the given number of arguments.
class FunctionCallFilterCCC : public CorrectionCandidateCallback {
public:
FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
bool HasExplicitTemplateArgs,
MemberExpr *ME = nullptr);
bool ValidateCandidate(const TypoCorrection &candidate) override;
private:
unsigned NumArgs;
bool HasExplicitTemplateArgs;
DeclContext *CurContext;
MemberExpr *MemberFn;
};
// @brief Callback class that effectively disabled typo correction
class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
public:
NoTypoCorrectionCCC() {
WantTypeSpecifiers = false;
WantExpressionKeywords = false;
WantCXXNamedCasts = false;
WantFunctionLikeCasts = false;
WantRemainingKeywords = false;
}
bool ValidateCandidate(const TypoCorrection &candidate) override {
return false;
}
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/ScopeInfo.h | //===--- ScopeInfo.h - Information about a semantic context -----*- 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 FunctionScopeInfo and its subclasses, which contain
// information about a single function, block, lambda, or method body.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SCOPEINFO_H
#define LLVM_CLANG_SEMA_SCOPEINFO_H
#include "clang/AST/Expr.h"
#include "clang/AST/Type.h"
#include "clang/Basic/CapturedStmt.h"
#include "clang/Basic/PartialDiagnostic.h"
#include "clang/Sema/Ownership.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include <algorithm>
namespace clang {
class Decl;
class BlockDecl;
class CapturedDecl;
class CXXMethodDecl;
class FieldDecl;
class ObjCPropertyDecl;
class IdentifierInfo;
class ImplicitParamDecl;
class LabelDecl;
class ReturnStmt;
class Scope;
class SwitchStmt;
class TemplateTypeParmDecl;
class TemplateParameterList;
class VarDecl;
class ObjCIvarRefExpr;
class ObjCPropertyRefExpr;
class ObjCMessageExpr;
namespace sema {
/// \brief Contains information about the compound statement currently being
/// parsed.
class CompoundScopeInfo {
public:
CompoundScopeInfo()
: HasEmptyLoopBodies(false) { }
/// \brief Whether this compound stamement contains `for' or `while' loops
/// with empty bodies.
bool HasEmptyLoopBodies;
void setHasEmptyLoopBodies() {
HasEmptyLoopBodies = true;
}
};
class PossiblyUnreachableDiag {
public:
PartialDiagnostic PD;
SourceLocation Loc;
const Stmt *stmt;
PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc,
const Stmt *stmt)
: PD(PD), Loc(Loc), stmt(stmt) {}
};
/// \brief Retains information about a function, method, or block that is
/// currently being parsed.
class FunctionScopeInfo {
protected:
enum ScopeKind {
SK_Function,
SK_Block,
SK_Lambda,
SK_CapturedRegion
};
public:
/// \brief What kind of scope we are describing.
///
ScopeKind Kind;
/// \brief Whether this function contains a VLA, \@try, try, C++
/// initializer, or anything else that can't be jumped past.
bool HasBranchProtectedScope;
/// \brief Whether this function contains any switches or direct gotos.
bool HasBranchIntoScope;
/// \brief Whether this function contains any indirect gotos.
bool HasIndirectGoto;
/// \brief Whether a statement was dropped because it was invalid.
bool HasDroppedStmt;
/// A flag that is set when parsing a method that must call super's
/// implementation, such as \c -dealloc, \c -finalize, or any method marked
/// with \c __attribute__((objc_requires_super)).
bool ObjCShouldCallSuper;
/// True when this is a method marked as a designated initializer.
bool ObjCIsDesignatedInit;
/// This starts true for a method marked as designated initializer and will
/// be set to false if there is an invocation to a designated initializer of
/// the super class.
bool ObjCWarnForNoDesignatedInitChain;
/// True when this is an initializer method not marked as a designated
/// initializer within a class that has at least one initializer marked as a
/// designated initializer.
bool ObjCIsSecondaryInit;
/// This starts true for a secondary initializer method and will be set to
/// false if there is an invocation of an initializer on 'self'.
bool ObjCWarnForNoInitDelegation;
/// First C++ 'try' statement in the current function.
SourceLocation FirstCXXTryLoc;
/// First SEH '__try' statement in the current function.
SourceLocation FirstSEHTryLoc;
/// \brief Used to determine if errors occurred in this function or block.
DiagnosticErrorTrap ErrorTrap;
/// SwitchStack - This is the current set of active switch statements in the
/// block.
SmallVector<SwitchStmt*, 8> SwitchStack;
/// \brief The list of return statements that occur within the function or
/// block, if there is any chance of applying the named return value
/// optimization, or if we need to infer a return type.
SmallVector<ReturnStmt*, 4> Returns;
/// \brief The stack of currently active compound stamement scopes in the
/// function.
SmallVector<CompoundScopeInfo, 4> CompoundScopes;
/// \brief A list of PartialDiagnostics created but delayed within the
/// current function scope. These diagnostics are vetted for reachability
/// prior to being emitted.
SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags;
/// \brief A list of parameters which have the nonnull attribute and are
/// modified in the function.
llvm::SmallPtrSet<const ParmVarDecl*, 8> ModifiedNonNullParams;
public:
/// Represents a simple identification of a weak object.
///
/// Part of the implementation of -Wrepeated-use-of-weak.
///
/// This is used to determine if two weak accesses refer to the same object.
/// Here are some examples of how various accesses are "profiled":
///
/// Access Expression | "Base" Decl | "Property" Decl
/// :---------------: | :-----------------: | :------------------------------:
/// self.property | self (VarDecl) | property (ObjCPropertyDecl)
/// self.implicitProp | self (VarDecl) | -implicitProp (ObjCMethodDecl)
/// self->ivar.prop | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl)
/// cxxObj.obj.prop | obj (FieldDecl) | prop (ObjCPropertyDecl)
/// [self foo].prop | 0 (unknown) | prop (ObjCPropertyDecl)
/// self.prop1.prop2 | prop1 (ObjCPropertyDecl) | prop2 (ObjCPropertyDecl)
/// MyClass.prop | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl)
/// weakVar | 0 (known) | weakVar (VarDecl)
/// self->weakIvar | self (VarDecl) | weakIvar (ObjCIvarDecl)
///
/// Objects are identified with only two Decls to make it reasonably fast to
/// compare them.
class WeakObjectProfileTy {
/// The base object decl, as described in the class documentation.
///
/// The extra flag is "true" if the Base and Property are enough to uniquely
/// identify the object in memory.
///
/// \sa isExactProfile()
typedef llvm::PointerIntPair<const NamedDecl *, 1, bool> BaseInfoTy;
BaseInfoTy Base;
/// The "property" decl, as described in the class documentation.
///
/// Note that this may not actually be an ObjCPropertyDecl, e.g. in the
/// case of "implicit" properties (regular methods accessed via dot syntax).
const NamedDecl *Property;
/// Used to find the proper base profile for a given base expression.
static BaseInfoTy getBaseInfo(const Expr *BaseE);
inline WeakObjectProfileTy();
static inline WeakObjectProfileTy getSentinel();
public:
WeakObjectProfileTy(const ObjCPropertyRefExpr *RE);
WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property);
WeakObjectProfileTy(const DeclRefExpr *RE);
WeakObjectProfileTy(const ObjCIvarRefExpr *RE);
const NamedDecl *getBase() const { return Base.getPointer(); }
const NamedDecl *getProperty() const { return Property; }
/// Returns true if the object base specifies a known object in memory,
/// rather than, say, an instance variable or property of another object.
///
/// Note that this ignores the effects of aliasing; that is, \c foo.bar is
/// considered an exact profile if \c foo is a local variable, even if
/// another variable \c foo2 refers to the same object as \c foo.
///
/// For increased precision, accesses with base variables that are
/// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to
/// be exact, though this is not true for arbitrary variables
/// (foo.prop1.prop2).
bool isExactProfile() const {
return Base.getInt();
}
bool operator==(const WeakObjectProfileTy &Other) const {
return Base == Other.Base && Property == Other.Property;
}
// For use in DenseMap.
// We can't specialize the usual llvm::DenseMapInfo at the end of the file
// because by that point the DenseMap in FunctionScopeInfo has already been
// instantiated.
class DenseMapInfo {
public:
static inline WeakObjectProfileTy getEmptyKey() {
return WeakObjectProfileTy();
}
static inline WeakObjectProfileTy getTombstoneKey() {
return WeakObjectProfileTy::getSentinel();
}
static unsigned getHashValue(const WeakObjectProfileTy &Val) {
typedef std::pair<BaseInfoTy, const NamedDecl *> Pair;
return llvm::DenseMapInfo<Pair>::getHashValue(Pair(Val.Base,
Val.Property));
}
static bool isEqual(const WeakObjectProfileTy &LHS,
const WeakObjectProfileTy &RHS) {
return LHS == RHS;
}
};
};
/// Represents a single use of a weak object.
///
/// Stores both the expression and whether the access is potentially unsafe
/// (i.e. it could potentially be warned about).
///
/// Part of the implementation of -Wrepeated-use-of-weak.
class WeakUseTy {
llvm::PointerIntPair<const Expr *, 1, bool> Rep;
public:
WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {}
const Expr *getUseExpr() const { return Rep.getPointer(); }
bool isUnsafe() const { return Rep.getInt(); }
void markSafe() { Rep.setInt(false); }
bool operator==(const WeakUseTy &Other) const {
return Rep == Other.Rep;
}
};
/// Used to collect uses of a particular weak object in a function body.
///
/// Part of the implementation of -Wrepeated-use-of-weak.
typedef SmallVector<WeakUseTy, 4> WeakUseVector;
/// Used to collect all uses of weak objects in a function body.
///
/// Part of the implementation of -Wrepeated-use-of-weak.
typedef llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8,
WeakObjectProfileTy::DenseMapInfo>
WeakObjectUseMap;
private:
/// Used to collect all uses of weak objects in this function body.
///
/// Part of the implementation of -Wrepeated-use-of-weak.
WeakObjectUseMap WeakObjectUses;
public:
/// Record that a weak object was accessed.
///
/// Part of the implementation of -Wrepeated-use-of-weak.
template <typename ExprT>
inline void recordUseOfWeak(const ExprT *E, bool IsRead = true);
void recordUseOfWeak(const ObjCMessageExpr *Msg,
const ObjCPropertyDecl *Prop);
/// Record that a given expression is a "safe" access of a weak object (e.g.
/// assigning it to a strong variable.)
///
/// Part of the implementation of -Wrepeated-use-of-weak.
void markSafeWeakUse(const Expr *E);
const WeakObjectUseMap &getWeakObjectUses() const {
return WeakObjectUses;
}
void setHasBranchIntoScope() {
HasBranchIntoScope = true;
}
void setHasBranchProtectedScope() {
HasBranchProtectedScope = true;
}
void setHasIndirectGoto() {
HasIndirectGoto = true;
}
void setHasDroppedStmt() {
HasDroppedStmt = true;
}
void setHasCXXTry(SourceLocation TryLoc) {
setHasBranchProtectedScope();
FirstCXXTryLoc = TryLoc;
}
void setHasSEHTry(SourceLocation TryLoc) {
setHasBranchProtectedScope();
FirstSEHTryLoc = TryLoc;
}
bool NeedsScopeChecking() const {
return !HasDroppedStmt &&
(HasIndirectGoto ||
(HasBranchProtectedScope && HasBranchIntoScope));
}
FunctionScopeInfo(DiagnosticsEngine &Diag)
: Kind(SK_Function),
HasBranchProtectedScope(false),
HasBranchIntoScope(false),
HasIndirectGoto(false),
HasDroppedStmt(false),
ObjCShouldCallSuper(false),
ObjCIsDesignatedInit(false),
ObjCWarnForNoDesignatedInitChain(false),
ObjCIsSecondaryInit(false),
ObjCWarnForNoInitDelegation(false),
ErrorTrap(Diag) { }
virtual ~FunctionScopeInfo();
/// \brief Clear out the information in this function scope, making it
/// suitable for reuse.
void Clear();
};
class CapturingScopeInfo : public FunctionScopeInfo {
public:
enum ImplicitCaptureStyle {
ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block,
ImpCap_CapturedRegion
};
ImplicitCaptureStyle ImpCaptureStyle;
class Capture {
// There are three categories of capture: capturing 'this', capturing
// local variables, and C++1y initialized captures (which can have an
// arbitrary initializer, and don't really capture in the traditional
// sense at all).
//
// There are three ways to capture a local variable:
// - capture by copy in the C++11 sense,
// - capture by reference in the C++11 sense, and
// - __block capture.
// Lambdas explicitly specify capture by copy or capture by reference.
// For blocks, __block capture applies to variables with that annotation,
// variables of reference type are captured by reference, and other
// variables are captured by copy.
enum CaptureKind {
Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_This
};
/// The variable being captured (if we are not capturing 'this') and whether
/// this is a nested capture.
llvm::PointerIntPair<VarDecl*, 1, bool> VarAndNested;
/// Expression to initialize a field of the given type, and the kind of
/// capture (if this is a capture and not an init-capture). The expression
/// is only required if we are capturing ByVal and the variable's type has
/// a non-trivial copy constructor.
llvm::PointerIntPair<void *, 2, CaptureKind> InitExprAndCaptureKind;
/// \brief The source location at which the first capture occurred.
SourceLocation Loc;
/// \brief The location of the ellipsis that expands a parameter pack.
SourceLocation EllipsisLoc;
/// \brief The type as it was captured, which is in effect the type of the
/// non-static data member that would hold the capture.
QualType CaptureType;
public:
Capture(VarDecl *Var, bool Block, bool ByRef, bool IsNested,
SourceLocation Loc, SourceLocation EllipsisLoc,
QualType CaptureType, Expr *Cpy)
: VarAndNested(Var, IsNested),
InitExprAndCaptureKind(Cpy, Block ? Cap_Block :
ByRef ? Cap_ByRef : Cap_ByCopy),
Loc(Loc), EllipsisLoc(EllipsisLoc), CaptureType(CaptureType) {}
enum IsThisCapture { ThisCapture };
Capture(IsThisCapture, bool IsNested, SourceLocation Loc,
QualType CaptureType, Expr *Cpy)
: VarAndNested(nullptr, IsNested),
InitExprAndCaptureKind(Cpy, Cap_This),
Loc(Loc), EllipsisLoc(), CaptureType(CaptureType) {}
bool isThisCapture() const {
return InitExprAndCaptureKind.getInt() == Cap_This;
}
bool isVariableCapture() const {
return InitExprAndCaptureKind.getInt() != Cap_This && !isVLATypeCapture();
}
bool isCopyCapture() const {
return InitExprAndCaptureKind.getInt() == Cap_ByCopy &&
!isVLATypeCapture();
}
bool isReferenceCapture() const {
return InitExprAndCaptureKind.getInt() == Cap_ByRef;
}
bool isBlockCapture() const {
return InitExprAndCaptureKind.getInt() == Cap_Block;
}
bool isVLATypeCapture() const {
return InitExprAndCaptureKind.getInt() == Cap_ByCopy &&
getVariable() == nullptr;
}
bool isNested() const { return VarAndNested.getInt(); }
VarDecl *getVariable() const {
return VarAndNested.getPointer();
}
/// \brief Retrieve the location at which this variable was captured.
SourceLocation getLocation() const { return Loc; }
/// \brief Retrieve the source location of the ellipsis, whose presence
/// indicates that the capture is a pack expansion.
SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
/// \brief Retrieve the capture type for this capture, which is effectively
/// the type of the non-static data member in the lambda/block structure
/// that would store this capture.
QualType getCaptureType() const { return CaptureType; }
Expr *getInitExpr() const {
assert(!isVLATypeCapture() && "no init expression for type capture");
return static_cast<Expr *>(InitExprAndCaptureKind.getPointer());
}
};
CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
: FunctionScopeInfo(Diag), ImpCaptureStyle(Style), CXXThisCaptureIndex(0),
HasImplicitReturnType(false)
{}
/// CaptureMap - A map of captured variables to (index+1) into Captures.
llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
/// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
/// zero if 'this' is not captured.
unsigned CXXThisCaptureIndex;
/// Captures - The captures.
SmallVector<Capture, 4> Captures;
/// \brief - Whether the target type of return statements in this context
/// is deduced (e.g. a lambda or block with omitted return type).
bool HasImplicitReturnType;
/// ReturnType - The target type of return statements in this context,
/// or null if unknown.
QualType ReturnType;
void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested,
SourceLocation Loc, SourceLocation EllipsisLoc,
QualType CaptureType, Expr *Cpy) {
Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc,
EllipsisLoc, CaptureType, Cpy));
CaptureMap[Var] = Captures.size();
}
void addVLATypeCapture(SourceLocation Loc, QualType CaptureType) {
Captures.push_back(Capture(/*Var*/ nullptr, /*isBlock*/ false,
/*isByref*/ false, /*isNested*/ false, Loc,
/*EllipsisLoc*/ SourceLocation(), CaptureType,
/*Cpy*/ nullptr));
}
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType,
Expr *Cpy);
/// \brief Determine whether the C++ 'this' is captured.
bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; }
/// \brief Retrieve the capture of C++ 'this', if it has been captured.
Capture &getCXXThisCapture() {
assert(isCXXThisCaptured() && "this has not been captured");
return Captures[CXXThisCaptureIndex - 1];
}
/// \brief Determine whether the given variable has been captured.
bool isCaptured(VarDecl *Var) const {
return CaptureMap.count(Var);
}
/// \brief Determine whether the given variable-array type has been captured.
bool isVLATypeCaptured(const VariableArrayType *VAT) const;
/// \brief Retrieve the capture of the given variable, if it has been
/// captured already.
Capture &getCapture(VarDecl *Var) {
assert(isCaptured(Var) && "Variable has not been captured");
return Captures[CaptureMap[Var] - 1];
}
const Capture &getCapture(VarDecl *Var) const {
llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known
= CaptureMap.find(Var);
assert(Known != CaptureMap.end() && "Variable has not been captured");
return Captures[Known->second - 1];
}
static bool classof(const FunctionScopeInfo *FSI) {
return FSI->Kind == SK_Block || FSI->Kind == SK_Lambda
|| FSI->Kind == SK_CapturedRegion;
}
};
/// \brief Retains information about a block that is currently being parsed.
class BlockScopeInfo : public CapturingScopeInfo {
public:
BlockDecl *TheDecl;
/// TheScope - This is the scope for the block itself, which contains
/// arguments etc.
Scope *TheScope;
/// BlockType - The function type of the block, if one was given.
/// Its return type may be BuiltinType::Dependent.
QualType FunctionType;
BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block)
: CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
TheScope(BlockScope)
{
Kind = SK_Block;
}
~BlockScopeInfo() override;
static bool classof(const FunctionScopeInfo *FSI) {
return FSI->Kind == SK_Block;
}
};
/// \brief Retains information about a captured region.
class CapturedRegionScopeInfo: public CapturingScopeInfo {
public:
/// \brief The CapturedDecl for this statement.
CapturedDecl *TheCapturedDecl;
/// \brief The captured record type.
RecordDecl *TheRecordDecl;
/// \brief This is the enclosing scope of the captured region.
Scope *TheScope;
/// \brief The implicit parameter for the captured variables.
ImplicitParamDecl *ContextParam;
/// \brief The kind of captured region.
CapturedRegionKind CapRegionKind;
CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD,
RecordDecl *RD, ImplicitParamDecl *Context,
CapturedRegionKind K)
: CapturingScopeInfo(Diag, ImpCap_CapturedRegion),
TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S),
ContextParam(Context), CapRegionKind(K)
{
Kind = SK_CapturedRegion;
}
~CapturedRegionScopeInfo() override;
/// \brief A descriptive name for the kind of captured region this is.
StringRef getRegionName() const {
switch (CapRegionKind) {
case CR_Default:
return "default captured statement";
case CR_OpenMP:
return "OpenMP region";
}
llvm_unreachable("Invalid captured region kind!");
}
static bool classof(const FunctionScopeInfo *FSI) {
return FSI->Kind == SK_CapturedRegion;
}
};
class LambdaScopeInfo : public CapturingScopeInfo {
public:
/// \brief The class that describes the lambda.
CXXRecordDecl *Lambda;
/// \brief The lambda's compiler-generated \c operator().
CXXMethodDecl *CallOperator;
/// \brief Source range covering the lambda introducer [...].
SourceRange IntroducerRange;
/// \brief Source location of the '&' or '=' specifying the default capture
/// type, if any.
SourceLocation CaptureDefaultLoc;
/// \brief The number of captures in the \c Captures list that are
/// explicit captures.
unsigned NumExplicitCaptures;
/// \brief Whether this is a mutable lambda.
bool Mutable;
/// \brief Whether the (empty) parameter list is explicit.
bool ExplicitParams;
/// \brief Whether any of the capture expressions requires cleanups.
bool ExprNeedsCleanups;
/// \brief Whether the lambda contains an unexpanded parameter pack.
bool ContainsUnexpandedParameterPack;
/// \brief If this is a generic lambda, use this as the depth of
/// each 'auto' parameter, during initial AST construction.
unsigned AutoTemplateParameterDepth;
/// \brief Store the list of the auto parameters for a generic lambda.
/// If this is a generic lambda, store the list of the auto
/// parameters converted into TemplateTypeParmDecls into a vector
/// that can be used to construct the generic lambda's template
/// parameter list, during initial AST construction.
SmallVector<TemplateTypeParmDecl*, 4> AutoTemplateParams;
/// If this is a generic lambda, and the template parameter
/// list has been created (from the AutoTemplateParams) then
/// store a reference to it (cache it to avoid reconstructing it).
TemplateParameterList *GLTemplateParameterList;
/// \brief Contains all variable-referring-expressions (i.e. DeclRefExprs
/// or MemberExprs) that refer to local variables in a generic lambda
/// or a lambda in a potentially-evaluated-if-used context.
///
/// Potentially capturable variables of a nested lambda that might need
/// to be captured by the lambda are housed here.
/// This is specifically useful for generic lambdas or
/// lambdas within a a potentially evaluated-if-used context.
/// If an enclosing variable is named in an expression of a lambda nested
/// within a generic lambda, we don't always know know whether the variable
/// will truly be odr-used (i.e. need to be captured) by that nested lambda,
/// until its instantiation. But we still need to capture it in the
/// enclosing lambda if all intervening lambdas can capture the variable.
llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs;
/// \brief Contains all variable-referring-expressions that refer
/// to local variables that are usable as constant expressions and
/// do not involve an odr-use (they may still need to be captured
/// if the enclosing full-expression is instantiation dependent).
llvm::SmallSet<Expr*, 8> NonODRUsedCapturingExprs;
SourceLocation PotentialThisCaptureLocation;
LambdaScopeInfo(DiagnosticsEngine &Diag)
: CapturingScopeInfo(Diag, ImpCap_None), Lambda(nullptr),
CallOperator(nullptr), NumExplicitCaptures(0), Mutable(false),
ExplicitParams(false), ExprNeedsCleanups(false),
ContainsUnexpandedParameterPack(false), AutoTemplateParameterDepth(0),
GLTemplateParameterList(nullptr) {
Kind = SK_Lambda;
}
~LambdaScopeInfo() override;
/// \brief Note when all explicit captures have been added.
void finishedExplicitCaptures() {
NumExplicitCaptures = Captures.size();
}
static bool classof(const FunctionScopeInfo *FSI) {
return FSI->Kind == SK_Lambda;
}
///
/// \brief Add a variable that might potentially be captured by the
/// lambda and therefore the enclosing lambdas.
///
/// This is also used by enclosing lambda's to speculatively capture
/// variables that nested lambda's - depending on their enclosing
/// specialization - might need to capture.
/// Consider:
/// void f(int, int); <-- don't capture
/// void f(const int&, double); <-- capture
/// void foo() {
/// const int x = 10;
/// auto L = [=](auto a) { // capture 'x'
/// return [=](auto b) {
/// f(x, a); // we may or may not need to capture 'x'
/// };
/// };
/// }
void addPotentialCapture(Expr *VarExpr) {
assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr));
PotentiallyCapturingExprs.push_back(VarExpr);
}
void addPotentialThisCapture(SourceLocation Loc) {
PotentialThisCaptureLocation = Loc;
}
bool hasPotentialThisCapture() const {
return PotentialThisCaptureLocation.isValid();
}
/// \brief Mark a variable's reference in a lambda as non-odr using.
///
/// For generic lambdas, if a variable is named in a potentially evaluated
/// expression, where the enclosing full expression is dependent then we
/// must capture the variable (given a default capture).
/// This is accomplished by recording all references to variables
/// (DeclRefExprs or MemberExprs) within said nested lambda in its array of
/// PotentialCaptures. All such variables have to be captured by that lambda,
/// except for as described below.
/// If that variable is usable as a constant expression and is named in a
/// manner that does not involve its odr-use (e.g. undergoes
/// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the
/// act of analyzing the enclosing full expression (ActOnFinishFullExpr)
/// if we can determine that the full expression is not instantiation-
/// dependent, then we can entirely avoid its capture.
///
/// const int n = 0;
/// [&] (auto x) {
/// (void)+n + x;
/// };
/// Interestingly, this strategy would involve a capture of n, even though
/// it's obviously not odr-used here, because the full-expression is
/// instantiation-dependent. It could be useful to avoid capturing such
/// variables, even when they are referred to in an instantiation-dependent
/// expression, if we can unambiguously determine that they shall never be
/// odr-used. This would involve removal of the variable-referring-expression
/// from the array of PotentialCaptures during the lvalue-to-rvalue
/// conversions. But per the working draft N3797, (post-chicago 2013) we must
/// capture such variables.
/// Before anyone is tempted to implement a strategy for not-capturing 'n',
/// consider the insightful warning in:
/// /cfe-commits/Week-of-Mon-20131104/092596.html
/// "The problem is that the set of captures for a lambda is part of the ABI
/// (since lambda layout can be made visible through inline functions and the
/// like), and there are no guarantees as to which cases we'll manage to build
/// an lvalue-to-rvalue conversion in, when parsing a template -- some
/// seemingly harmless change elsewhere in Sema could cause us to start or stop
/// building such a node. So we need a rule that anyone can implement and get
/// exactly the same result".
///
void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) {
assert(isa<DeclRefExpr>(CapturingVarExpr)
|| isa<MemberExpr>(CapturingVarExpr));
NonODRUsedCapturingExprs.insert(CapturingVarExpr);
}
bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const {
assert(isa<DeclRefExpr>(CapturingVarExpr)
|| isa<MemberExpr>(CapturingVarExpr));
return NonODRUsedCapturingExprs.count(CapturingVarExpr);
}
void removePotentialCapture(Expr *E) {
PotentiallyCapturingExprs.erase(
std::remove(PotentiallyCapturingExprs.begin(),
PotentiallyCapturingExprs.end(), E),
PotentiallyCapturingExprs.end());
}
void clearPotentialCaptures() {
PotentiallyCapturingExprs.clear();
PotentialThisCaptureLocation = SourceLocation();
}
unsigned getNumPotentialVariableCaptures() const {
return PotentiallyCapturingExprs.size();
}
bool hasPotentialCaptures() const {
return getNumPotentialVariableCaptures() ||
PotentialThisCaptureLocation.isValid();
}
// When passed the index, returns the VarDecl and Expr associated
// with the index.
void getPotentialVariableCapture(unsigned Idx, VarDecl *&VD, Expr *&E) const;
};
FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy()
: Base(nullptr, false), Property(nullptr) {}
FunctionScopeInfo::WeakObjectProfileTy
FunctionScopeInfo::WeakObjectProfileTy::getSentinel() {
FunctionScopeInfo::WeakObjectProfileTy Result;
Result.Base.setInt(true);
return Result;
}
template <typename ExprT>
void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
assert(E);
WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
Uses.push_back(WeakUseTy(E, IsRead));
}
inline void
CapturingScopeInfo::addThisCapture(bool isNested, SourceLocation Loc,
QualType CaptureType, Expr *Cpy) {
Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, CaptureType,
Cpy));
CXXThisCaptureIndex = Captures.size();
}
} // end namespace sema
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/MultiplexExternalSemaSource.h | //===--- MultiplexExternalSemaSource.h - External Sema Interface-*- 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 ExternalSemaSource interface, dispatching to all clients
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_MULTIPLEXEXTERNALSEMASOURCE_H
#define LLVM_CLANG_SEMA_MULTIPLEXEXTERNALSEMASOURCE_H
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/Weak.h"
#include "llvm/ADT/SmallVector.h"
#include <utility>
namespace clang {
class CXXConstructorDecl;
class CXXRecordDecl;
class DeclaratorDecl;
struct ExternalVTableUse;
class LookupResult;
class NamespaceDecl;
class Scope;
class Sema;
class TypedefNameDecl;
class ValueDecl;
class VarDecl;
/// \brief An abstract interface that should be implemented by
/// external AST sources that also provide information for semantic
/// analysis.
class MultiplexExternalSemaSource : public ExternalSemaSource {
private:
SmallVector<ExternalSemaSource *, 2> Sources; // doesn't own them.
public:
///\brief Constructs a new multiplexing external sema source and appends the
/// given element to it.
///
///\param[in] s1 - A non-null (old) ExternalSemaSource.
///\param[in] s2 - A non-null (new) ExternalSemaSource.
///
MultiplexExternalSemaSource(ExternalSemaSource& s1, ExternalSemaSource& s2);
~MultiplexExternalSemaSource() override;
///\brief Appends new source to the source list.
///
///\param[in] source - An ExternalSemaSource.
///
void addSource(ExternalSemaSource &source);
//===--------------------------------------------------------------------===//
// ExternalASTSource.
//===--------------------------------------------------------------------===//
/// \brief Resolve a declaration ID into a declaration, potentially
/// building a new declaration.
Decl *GetExternalDecl(uint32_t ID) override;
/// \brief Complete the redeclaration chain if it's been extended since the
/// previous generation of the AST source.
void CompleteRedeclChain(const Decl *D) override;
/// \brief Resolve a selector ID into a selector.
Selector GetExternalSelector(uint32_t ID) override;
/// \brief Returns the number of selectors known to the external AST
/// source.
uint32_t GetNumExternalSelectors() override;
/// \brief Resolve the offset of a statement in the decl stream into
/// a statement.
Stmt *GetExternalDeclStmt(uint64_t Offset) override;
/// \brief Resolve the offset of a set of C++ base specifiers in the decl
/// stream into an array of specifiers.
CXXBaseSpecifier *GetExternalCXXBaseSpecifiers(uint64_t Offset) override;
/// \brief Resolve a handle to a list of ctor initializers into the list of
/// initializers themselves.
CXXCtorInitializer **GetExternalCXXCtorInitializers(uint64_t Offset) override;
/// \brief Find all declarations with the given name in the
/// given context.
bool FindExternalVisibleDeclsByName(const DeclContext *DC,
DeclarationName Name) override;
/// \brief Ensures that the table of all visible declarations inside this
/// context is up to date.
void completeVisibleDeclsMap(const DeclContext *DC) override;
/// \brief Finds all declarations lexically contained within the given
/// DeclContext, after applying an optional filter predicate.
///
/// \param isKindWeWant a predicate function that returns true if the passed
/// declaration kind is one we are looking for. If NULL, all declarations
/// are returned.
///
/// \return an indication of whether the load succeeded or failed.
ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
bool (*isKindWeWant)(Decl::Kind),
SmallVectorImpl<Decl*> &Result) override;
/// \brief Finds all declarations lexically contained within the given
/// DeclContext.
///
/// \return true if an error occurred
ExternalLoadResult FindExternalLexicalDecls(const DeclContext *DC,
SmallVectorImpl<Decl*> &Result) {
return FindExternalLexicalDecls(DC, nullptr, Result);
}
template <typename DeclTy>
ExternalLoadResult FindExternalLexicalDeclsBy(const DeclContext *DC,
SmallVectorImpl<Decl*> &Result) {
return FindExternalLexicalDecls(DC, DeclTy::classofKind, Result);
}
/// \brief Get the decls that are contained in a file in the Offset/Length
/// range. \p Length can be 0 to indicate a point at \p Offset instead of
/// a range.
void FindFileRegionDecls(FileID File, unsigned Offset,unsigned Length,
SmallVectorImpl<Decl *> &Decls) override;
/// \brief Gives the external AST source an opportunity to complete
/// an incomplete type.
void CompleteType(TagDecl *Tag) override;
/// \brief Gives the external AST source an opportunity to complete an
/// incomplete Objective-C class.
///
/// This routine will only be invoked if the "externally completed" bit is
/// set on the ObjCInterfaceDecl via the function
/// \c ObjCInterfaceDecl::setExternallyCompleted().
void CompleteType(ObjCInterfaceDecl *Class) override;
/// \brief Loads comment ranges.
void ReadComments() override;
/// \brief Notify ExternalASTSource that we started deserialization of
/// a decl or type so until FinishedDeserializing is called there may be
/// decls that are initializing. Must be paired with FinishedDeserializing.
void StartedDeserializing() override;
/// \brief Notify ExternalASTSource that we finished the deserialization of
/// a decl or type. Must be paired with StartedDeserializing.
void FinishedDeserializing() override;
/// \brief Function that will be invoked when we begin parsing a new
/// translation unit involving this external AST source.
void StartTranslationUnit(ASTConsumer *Consumer) override;
/// \brief Print any statistics that have been gathered regarding
/// the external AST source.
void PrintStats() override;
/// \brief Perform layout on the given record.
///
/// This routine allows the external AST source to provide an specific
/// layout for a record, overriding the layout that would normally be
/// constructed. It is intended for clients who receive specific layout
/// details rather than source code (such as LLDB). The client is expected
/// to fill in the field offsets, base offsets, virtual base offsets, and
/// complete object size.
///
/// \param Record The record whose layout is being requested.
///
/// \param Size The final size of the record, in bits.
///
/// \param Alignment The final alignment of the record, in bits.
///
/// \param FieldOffsets The offset of each of the fields within the record,
/// expressed in bits. All of the fields must be provided with offsets.
///
/// \param BaseOffsets The offset of each of the direct, non-virtual base
/// classes. If any bases are not given offsets, the bases will be laid
/// out according to the ABI.
///
/// \param VirtualBaseOffsets The offset of each of the virtual base classes
/// (either direct or not). If any bases are not given offsets, the bases will
/// be laid out according to the ABI.
///
/// \returns true if the record layout was provided, false otherwise.
bool
layoutRecordType(const RecordDecl *Record,
uint64_t &Size, uint64_t &Alignment,
llvm::DenseMap<const FieldDecl *, uint64_t> &FieldOffsets,
llvm::DenseMap<const CXXRecordDecl *, CharUnits> &BaseOffsets,
llvm::DenseMap<const CXXRecordDecl *,
CharUnits> &VirtualBaseOffsets) override;
/// Return the amount of memory used by memory buffers, breaking down
/// by heap-backed versus mmap'ed memory.
void getMemoryBufferSizes(MemoryBufferSizes &sizes) const override;
//===--------------------------------------------------------------------===//
// ExternalSemaSource.
//===--------------------------------------------------------------------===//
/// \brief Initialize the semantic source with the Sema instance
/// being used to perform semantic analysis on the abstract syntax
/// tree.
void InitializeSema(Sema &S) override;
/// \brief Inform the semantic consumer that Sema is no longer available.
void ForgetSema() override;
/// \brief Load the contents of the global method pool for a given
/// selector.
void ReadMethodPool(Selector Sel) override;
/// \brief Load the set of namespaces that are known to the external source,
/// which will be used during typo correction.
void
ReadKnownNamespaces(SmallVectorImpl<NamespaceDecl*> &Namespaces) override;
/// \brief Load the set of used but not defined functions or variables with
/// internal linkage, or used but not defined inline functions.
void ReadUndefinedButUsed(
llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) override;
void ReadMismatchingDeleteExpressions(llvm::MapVector<
FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
Exprs) override;
/// \brief Do last resort, unqualified lookup on a LookupResult that
/// Sema cannot find.
///
/// \param R a LookupResult that is being recovered.
///
/// \param S the Scope of the identifier occurrence.
///
/// \return true to tell Sema to recover using the LookupResult.
bool LookupUnqualified(LookupResult &R, Scope *S) override;
/// \brief Read the set of tentative definitions known to the external Sema
/// source.
///
/// The external source should append its own tentative definitions to the
/// given vector of tentative definitions. Note that this routine may be
/// invoked multiple times; the external source should take care not to
/// introduce the same declarations repeatedly.
void ReadTentativeDefinitions(SmallVectorImpl<VarDecl*> &Defs) override;
/// \brief Read the set of unused file-scope declarations known to the
/// external Sema source.
///
/// The external source should append its own unused, filed-scope to the
/// given vector of declarations. Note that this routine may be
/// invoked multiple times; the external source should take care not to
/// introduce the same declarations repeatedly.
void ReadUnusedFileScopedDecls(
SmallVectorImpl<const DeclaratorDecl*> &Decls) override;
/// \brief Read the set of delegating constructors known to the
/// external Sema source.
///
/// The external source should append its own delegating constructors to the
/// given vector of declarations. Note that this routine may be
/// invoked multiple times; the external source should take care not to
/// introduce the same declarations repeatedly.
void ReadDelegatingConstructors(
SmallVectorImpl<CXXConstructorDecl*> &Decls) override;
/// \brief Read the set of ext_vector type declarations known to the
/// external Sema source.
///
/// The external source should append its own ext_vector type declarations to
/// the given vector of declarations. Note that this routine may be
/// invoked multiple times; the external source should take care not to
/// introduce the same declarations repeatedly.
void ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl*> &Decls) override;
/// \brief Read the set of potentially unused typedefs known to the source.
///
/// The external source should append its own potentially unused local
/// typedefs to the given vector of declarations. Note that this routine may
/// be invoked multiple times; the external source should take care not to
/// introduce the same declarations repeatedly.
void ReadUnusedLocalTypedefNameCandidates(
llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) override;
/// \brief Read the set of referenced selectors known to the
/// external Sema source.
///
/// The external source should append its own referenced selectors to the
/// given vector of selectors. Note that this routine
/// may be invoked multiple times; the external source should take care not
/// to introduce the same selectors repeatedly.
void ReadReferencedSelectors(SmallVectorImpl<std::pair<Selector,
SourceLocation> > &Sels) override;
/// \brief Read the set of weak, undeclared identifiers known to the
/// external Sema source.
///
/// The external source should append its own weak, undeclared identifiers to
/// the given vector. Note that this routine may be invoked multiple times;
/// the external source should take care not to introduce the same identifiers
/// repeatedly.
void ReadWeakUndeclaredIdentifiers(
SmallVectorImpl<std::pair<IdentifierInfo*, WeakInfo> > &WI) override;
/// \brief Read the set of used vtables known to the external Sema source.
///
/// The external source should append its own used vtables to the given
/// vector. Note that this routine may be invoked multiple times; the external
/// source should take care not to introduce the same vtables repeatedly.
void ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) override;
/// \brief Read the set of pending instantiations known to the external
/// Sema source.
///
/// The external source should append its own pending instantiations to the
/// given vector. Note that this routine may be invoked multiple times; the
/// external source should take care not to introduce the same instantiations
/// repeatedly.
void ReadPendingInstantiations(
SmallVectorImpl<std::pair<ValueDecl*, SourceLocation> >& Pending) override;
/// \brief Read the set of late parsed template functions for this source.
///
/// The external source should insert its own late parsed template functions
/// into the map. Note that this routine may be invoked multiple times; the
/// external source should take care not to introduce the same map entries
/// repeatedly.
void ReadLateParsedTemplates(
llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap)
override;
/// \copydoc ExternalSemaSource::CorrectTypo
/// \note Returns the first nonempty correction.
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
int LookupKind, Scope *S, CXXScopeSpec *SS,
CorrectionCandidateCallback &CCC,
DeclContext *MemberContext,
bool EnteringContext,
const ObjCObjectPointerType *OPT) override;
/// \brief Produces a diagnostic note if one of the attached sources
/// contains a complete definition for \p T. Queries the sources in list
/// order until the first one claims that a diagnostic was produced.
///
/// \param Loc the location at which a complete type was required but not
/// provided
///
/// \param T the \c QualType that should have been complete at \p Loc
///
/// \return true if a diagnostic was produced, false otherwise.
bool MaybeDiagnoseMissingCompleteType(SourceLocation Loc,
QualType T) override;
// isa/cast/dyn_cast support
static bool classof(const MultiplexExternalSemaSource*) { return true; }
//static bool classof(const ExternalSemaSource*) { return true; }
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/CodeCompleteOptions.h | //===---- CodeCompleteOptions.h - Code Completion Options -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_CODECOMPLETEOPTIONS_H
#define LLVM_CLANG_SEMA_CODECOMPLETEOPTIONS_H
/// Options controlling the behavior of code completion.
class CodeCompleteOptions {
public:
/// Show macros in code completion results.
unsigned IncludeMacros : 1;
/// Show code patterns in code completion results.
unsigned IncludeCodePatterns : 1;
/// Show top-level decls in code completion results.
unsigned IncludeGlobals : 1;
/// Show brief documentation comments in code completion results.
unsigned IncludeBriefComments : 1;
CodeCompleteOptions() :
IncludeMacros(0),
IncludeCodePatterns(0),
IncludeGlobals(1),
IncludeBriefComments(0)
{ }
};
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/CXXFieldCollector.h | //===- CXXFieldCollector.h - Utility class for C++ class semantic analysis ===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides CXXFieldCollector that is used during parsing & semantic
// analysis of C++ classes.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_CXXFIELDCOLLECTOR_H
#define LLVM_CLANG_SEMA_CXXFIELDCOLLECTOR_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/SmallVector.h"
namespace clang {
class FieldDecl;
/// CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of
/// C++ classes.
class CXXFieldCollector {
/// Fields - Contains all FieldDecls collected during parsing of a C++
/// class. When a nested class is entered, its fields are appended to the
/// fields of its parent class, when it is exited its fields are removed.
SmallVector<FieldDecl*, 32> Fields;
/// FieldCount - Each entry represents the number of fields collected during
/// the parsing of a C++ class. When a nested class is entered, a new field
/// count is pushed, when it is exited, the field count is popped.
SmallVector<size_t, 4> FieldCount;
// Example:
//
// class C {
// int x,y;
// class NC {
// int q;
// // At this point, Fields contains [x,y,q] decls and FieldCount contains
// // [2,1].
// };
// int z;
// // At this point, Fields contains [x,y,z] decls and FieldCount contains
// // [3].
// };
public:
/// StartClass - Called by Sema::ActOnStartCXXClassDef.
void StartClass() { FieldCount.push_back(0); }
/// Add - Called by Sema::ActOnCXXMemberDeclarator.
void Add(FieldDecl *D) {
Fields.push_back(D);
++FieldCount.back();
}
/// getCurNumField - The number of fields added to the currently parsed class.
size_t getCurNumFields() const {
assert(!FieldCount.empty() && "no currently-parsed class");
return FieldCount.back();
}
/// getCurFields - Pointer to array of fields added to the currently parsed
/// class.
FieldDecl **getCurFields() { return &*(Fields.end() - getCurNumFields()); }
/// FinishClass - Called by Sema::ActOnFinishCXXClassDef.
void FinishClass() {
Fields.resize(Fields.size() - getCurNumFields());
FieldCount.pop_back();
}
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/LocInfoType.h | //===--- LocInfoType.h - Parsed Type with Location Information---*- 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 LocInfoType class, which holds a type and its
// source-location information.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_LOCINFOTYPE_H
#define LLVM_CLANG_SEMA_LOCINFOTYPE_H
#include "clang/AST/Type.h"
namespace clang {
class TypeSourceInfo;
/// \brief Holds a QualType and a TypeSourceInfo* that came out of a declarator
/// parsing.
///
/// LocInfoType is a "transient" type, only needed for passing to/from Parser
/// and Sema, when we want to preserve type source info for a parsed type.
/// It will not participate in the type system semantics in any way.
class LocInfoType : public Type {
enum {
// The last number that can fit in Type's TC.
// Avoids conflict with an existing Type class.
LocInfo = Type::TypeLast + 1
};
TypeSourceInfo *DeclInfo;
LocInfoType(QualType ty, TypeSourceInfo *TInfo)
: Type((TypeClass)LocInfo, ty, ty->isDependentType(),
ty->isInstantiationDependentType(),
ty->isVariablyModifiedType(),
ty->containsUnexpandedParameterPack()),
DeclInfo(TInfo) {
assert(getTypeClass() == (TypeClass)LocInfo && "LocInfo didn't fit in TC?");
}
friend class Sema;
public:
QualType getType() const { return getCanonicalTypeInternal(); }
TypeSourceInfo *getTypeSourceInfo() const { return DeclInfo; }
void getAsStringInternal(std::string &Str,
const PrintingPolicy &Policy) const;
static bool classof(const Type *T) {
return T->getTypeClass() == (TypeClass)LocInfo;
}
};
} // end namespace clang
#endif // LLVM_CLANG_SEMA_LOCINFOTYPE_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/CMakeLists.txt | clang_tablegen(AttrTemplateInstantiate.inc -gen-clang-attr-template-instantiate
-I ${CMAKE_CURRENT_SOURCE_DIR}/../../
SOURCE ../Basic/Attr.td
TARGET ClangAttrTemplateInstantiate)
clang_tablegen(AttrParsedAttrList.inc -gen-clang-attr-parsed-attr-list
-I ${CMAKE_CURRENT_SOURCE_DIR}/../../
SOURCE ../Basic/Attr.td
TARGET ClangAttrParsedAttrList)
clang_tablegen(AttrParsedAttrKinds.inc -gen-clang-attr-parsed-attr-kinds
-I ${CMAKE_CURRENT_SOURCE_DIR}/../../
SOURCE ../Basic/Attr.td
TARGET ClangAttrParsedAttrKinds)
clang_tablegen(AttrSpellingListIndex.inc -gen-clang-attr-spelling-index
-I ${CMAKE_CURRENT_SOURCE_DIR}/../../
SOURCE ../Basic/Attr.td
TARGET ClangAttrSpellingListIndex)
clang_tablegen(AttrParsedAttrImpl.inc -gen-clang-attr-parsed-attr-impl
-I ${CMAKE_CURRENT_SOURCE_DIR}/../../
SOURCE ../Basic/Attr.td
TARGET ClangAttrParsedAttrImpl)
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/Ownership.h | //===--- Ownership.h - Parser ownership helpers -----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains classes for managing ownership of Stmt and Expr nodes.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_OWNERSHIP_H
#define LLVM_CLANG_SEMA_OWNERSHIP_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/PointerIntPair.h"
//===----------------------------------------------------------------------===//
// OpaquePtr
// //
///////////////////////////////////////////////////////////////////////////////
namespace clang {
class CXXCtorInitializer;
class CXXBaseSpecifier;
class Decl;
class Expr;
class ParsedTemplateArgument;
class QualType;
class Stmt;
class TemplateName;
class TemplateParameterList;
/// \brief Wrapper for void* pointer.
/// \tparam PtrTy Either a pointer type like 'T*' or a type that behaves like
/// a pointer.
///
/// This is a very simple POD type that wraps a pointer that the Parser
/// doesn't know about but that Sema or another client does. The PtrTy
/// template argument is used to make sure that "Decl" pointers are not
/// compatible with "Type" pointers for example.
template <class PtrTy>
class OpaquePtr {
void *Ptr;
explicit OpaquePtr(void *Ptr) : Ptr(Ptr) {}
typedef llvm::PointerLikeTypeTraits<PtrTy> Traits;
public:
OpaquePtr() : Ptr(nullptr) {}
static OpaquePtr make(PtrTy P) { OpaquePtr OP; OP.set(P); return OP; }
/// \brief Returns plain pointer to the entity pointed by this wrapper.
/// \tparam PointeeT Type of pointed entity.
///
/// It is identical to getPtrAs<PointeeT*>.
template <typename PointeeT> PointeeT* getPtrTo() const {
return get();
}
/// \brief Returns pointer converted to the specified type.
/// \tparam PtrT Result pointer type. There must be implicit conversion
/// from PtrTy to PtrT.
///
/// In contrast to getPtrTo, this method allows the return type to be
/// a smart pointer.
template <typename PtrT> PtrT getPtrAs() const {
return get();
}
PtrTy get() const {
return Traits::getFromVoidPointer(Ptr);
}
void set(PtrTy P) {
Ptr = Traits::getAsVoidPointer(P);
}
explicit operator bool() const { return Ptr != nullptr; }
void *getAsOpaquePtr() const { return Ptr; }
static OpaquePtr getFromOpaquePtr(void *P) { return OpaquePtr(P); }
};
/// UnionOpaquePtr - A version of OpaquePtr suitable for membership
/// in a union.
template <class T> struct UnionOpaquePtr {
void *Ptr;
static UnionOpaquePtr make(OpaquePtr<T> P) {
UnionOpaquePtr OP = { P.getAsOpaquePtr() };
return OP;
}
OpaquePtr<T> get() const { return OpaquePtr<T>::getFromOpaquePtr(Ptr); }
operator OpaquePtr<T>() const { return get(); }
UnionOpaquePtr &operator=(OpaquePtr<T> P) {
Ptr = P.getAsOpaquePtr();
return *this;
}
};
}
namespace llvm {
template <class T>
class PointerLikeTypeTraits<clang::OpaquePtr<T> > {
public:
static inline void *getAsVoidPointer(clang::OpaquePtr<T> P) {
// FIXME: Doesn't work? return P.getAs< void >();
return P.getAsOpaquePtr();
}
static inline clang::OpaquePtr<T> getFromVoidPointer(void *P) {
return clang::OpaquePtr<T>::getFromOpaquePtr(P);
}
enum { NumLowBitsAvailable = 0 };
};
template <class T>
struct isPodLike<clang::OpaquePtr<T> > { static const bool value = true; };
}
namespace clang {
// Basic
class DiagnosticBuilder;
// Determines whether the low bit of the result pointer for the
// given UID is always zero. If so, ActionResult will use that bit
// for it's "invalid" flag.
template<class Ptr>
struct IsResultPtrLowBitFree {
static const bool value = false;
};
/// ActionResult - This structure is used while parsing/acting on
/// expressions, stmts, etc. It encapsulates both the object returned by
/// the action, plus a sense of whether or not it is valid.
/// When CompressInvalid is true, the "invalid" flag will be
/// stored in the low bit of the Val pointer.
template<class PtrTy,
bool CompressInvalid = IsResultPtrLowBitFree<PtrTy>::value>
class ActionResult {
PtrTy Val;
bool Invalid;
public:
ActionResult(bool Invalid = false)
: Val(PtrTy()), Invalid(Invalid) {}
ActionResult(PtrTy val) : Val(val), Invalid(false) {}
ActionResult(const DiagnosticBuilder &) : Val(PtrTy()), Invalid(true) {}
// These two overloads prevent void* -> bool conversions.
ActionResult(const void *);
ActionResult(volatile void *);
bool isInvalid() const { return Invalid; }
bool isUsable() const { return !Invalid && Val; }
bool isUnset() const { return !Invalid && !Val; }
PtrTy get() const { return Val; }
template <typename T> T *getAs() { return static_cast<T*>(get()); }
void set(PtrTy V) { Val = V; }
const ActionResult &operator=(PtrTy RHS) {
Val = RHS;
Invalid = false;
return *this;
}
};
// This ActionResult partial specialization places the "invalid"
// flag into the low bit of the pointer.
template<typename PtrTy>
class ActionResult<PtrTy, true> {
// A pointer whose low bit is 1 if this result is invalid, 0
// otherwise.
uintptr_t PtrWithInvalid;
typedef llvm::PointerLikeTypeTraits<PtrTy> PtrTraits;
public:
ActionResult(bool Invalid = false)
: PtrWithInvalid(static_cast<uintptr_t>(Invalid)) { }
ActionResult(PtrTy V) {
void *VP = PtrTraits::getAsVoidPointer(V);
PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer");
}
ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) { }
// These two overloads prevent void* -> bool conversions.
ActionResult(const void *);
ActionResult(volatile void *);
bool isInvalid() const { return PtrWithInvalid & 0x01; }
bool isUsable() const { return PtrWithInvalid > 0x01; }
bool isUnset() const { return PtrWithInvalid == 0; }
PtrTy get() const {
void *VP = reinterpret_cast<void *>(PtrWithInvalid & ~0x01);
return PtrTraits::getFromVoidPointer(VP);
}
template <typename T> T *getAs() { return static_cast<T*>(get()); }
void set(PtrTy V) {
void *VP = PtrTraits::getAsVoidPointer(V);
PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer");
}
const ActionResult &operator=(PtrTy RHS) {
void *VP = PtrTraits::getAsVoidPointer(RHS);
PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer");
return *this;
}
// For types where we can fit a flag in with the pointer, provide
// conversions to/from pointer type.
static ActionResult getFromOpaquePointer(void *P) {
ActionResult Result;
Result.PtrWithInvalid = (uintptr_t)P;
return Result;
}
void *getAsOpaquePointer() const { return (void*)PtrWithInvalid; }
};
/// An opaque type for threading parsed type information through the
/// parser.
typedef OpaquePtr<QualType> ParsedType;
typedef UnionOpaquePtr<QualType> UnionParsedType;
// We can re-use the low bit of expression, statement, base, and
// member-initializer pointers for the "invalid" flag of
// ActionResult.
template<> struct IsResultPtrLowBitFree<Expr*> {
static const bool value = true;
};
template<> struct IsResultPtrLowBitFree<Stmt*> {
static const bool value = true;
};
template<> struct IsResultPtrLowBitFree<CXXBaseSpecifier*> {
static const bool value = true;
};
template<> struct IsResultPtrLowBitFree<CXXCtorInitializer*> {
static const bool value = true;
};
typedef ActionResult<Expr*> ExprResult;
typedef ActionResult<Stmt*> StmtResult;
typedef ActionResult<ParsedType> TypeResult;
typedef ActionResult<CXXBaseSpecifier*> BaseResult;
typedef ActionResult<CXXCtorInitializer*> MemInitResult;
typedef ActionResult<Decl*> DeclResult;
typedef OpaquePtr<TemplateName> ParsedTemplateTy;
typedef MutableArrayRef<Expr*> MultiExprArg;
typedef MutableArrayRef<Stmt*> MultiStmtArg;
typedef MutableArrayRef<ParsedTemplateArgument> ASTTemplateArgsPtr;
typedef MutableArrayRef<ParsedType> MultiTypeArg;
typedef MutableArrayRef<TemplateParameterList*> MultiTemplateParamsArg;
inline ExprResult ExprError() { return ExprResult(true); }
inline StmtResult StmtError() { return StmtResult(true); }
inline ExprResult ExprError(const DiagnosticBuilder&) { return ExprError(); }
inline StmtResult StmtError(const DiagnosticBuilder&) { return StmtError(); }
inline ExprResult ExprEmpty() { return ExprResult(false); }
inline StmtResult StmtEmpty() { return StmtResult(false); }
inline Expr *AssertSuccess(ExprResult R) {
assert(!R.isInvalid() && "operation was asserted to never fail!");
return R.get();
}
inline Stmt *AssertSuccess(StmtResult R) {
assert(!R.isInvalid() && "operation was asserted to never fail!");
return R.get();
}
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/SemaHLSL.h | //===--- SemaHLSL.h - Semantic Analysis & AST Building for HLSL --*- C++
//-*-===//
///////////////////////////////////////////////////////////////////////////////
// //
// SemaHLSL.h //
// Copyright (C) Microsoft Corporation. All rights reserved. //
// This file is distributed under the University of Illinois Open Source //
// License. See LICENSE.TXT for details. //
// //
// This file defines the semantic support for HLSL. //
//
///////////////////////////////////////////////////////////////////////////////
#ifndef LLVM_CLANG_SEMA_SEMAHLSL_H
#define LLVM_CLANG_SEMA_SEMAHLSL_H
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Overload.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"
#include "clang/Sema/Template.h"
#include "clang/Sema/TemplateDeduction.h"
// Forward declarations.
struct IDxcIntrinsicTable;
namespace clang {
class Expr;
class ExternalSemaSource;
class ImplicitConversionSequence;
} // namespace clang
namespace hlsl {
void CheckBinOpForHLSL(clang::Sema &self, clang::SourceLocation OpLoc,
clang::BinaryOperatorKind Opc, clang::ExprResult &LHS,
clang::ExprResult &RHS, clang::QualType &ResultTy,
clang::QualType &CompLHSTy,
clang::QualType &CompResultTy);
bool CheckTemplateArgumentListForHLSL(clang::Sema &self, clang::TemplateDecl *,
clang::SourceLocation,
clang::TemplateArgumentListInfo &);
clang::QualType
CheckUnaryOpForHLSL(clang::Sema &self, clang::SourceLocation OpLoc,
clang::UnaryOperatorKind Opc, clang::ExprResult &InputExpr,
clang::ExprValueKind &VK, clang::ExprObjectKind &OK);
clang::Sema::TemplateDeductionResult DeduceTemplateArgumentsForHLSL(
clang::Sema *, clang::FunctionTemplateDecl *,
clang::TemplateArgumentListInfo *, llvm::ArrayRef<clang::Expr *>,
clang::FunctionDecl *&, clang::sema::TemplateDeductionInfo &);
bool DiagnoseNodeStructArgument(clang::Sema *self,
clang::TemplateArgumentLoc ArgLoc,
clang::QualType ArgTy, bool &Empty,
const clang::FieldDecl *FD = nullptr);
void DiagnoseControlFlowConditionForHLSL(clang::Sema *self,
clang::Expr *condExpr,
llvm::StringRef StmtName);
void DiagnosePackingOffset(clang::Sema *self, clang::SourceLocation loc,
clang::QualType type, int componentOffset);
void DiagnoseRegisterType(clang::Sema *self, clang::SourceLocation loc,
clang::QualType type, char registerType);
void DiagnoseTranslationUnit(clang::Sema *self);
void DiagnoseUnusualAnnotationsForHLSL(
clang::Sema &S, std::vector<hlsl::UnusualAnnotation *> &annotations);
void DiagnosePayloadAccessQualifierAnnotations(
clang::Sema &S, clang::Declarator &D, const clang::QualType &T,
const std::vector<hlsl::UnusualAnnotation *> &annotations);
void DiagnoseRaytracingPayloadAccess(clang::Sema &S,
clang::TranslationUnitDecl *TU);
void DiagnoseCallableEntry(clang::Sema &S, clang::FunctionDecl *FD,
llvm::StringRef StageName);
void DiagnoseMissOrAnyHitEntry(clang::Sema &S, clang::FunctionDecl *FD,
llvm::StringRef StageName,
DXIL::ShaderKind Stage);
void DiagnoseRayGenerationOrIntersectionEntry(clang::Sema &S,
clang::FunctionDecl *FD,
llvm::StringRef StageName);
void DiagnoseClosestHitEntry(clang::Sema &S, clang::FunctionDecl *FD,
llvm::StringRef StageName);
void DiagnoseEntry(clang::Sema &S, clang::FunctionDecl *FD);
/// <summary>Finds the best viable function on this overload set, if it
/// exists.</summary>
clang::OverloadingResult
GetBestViableFunction(clang::Sema &S, clang::SourceLocation Loc,
clang::OverloadCandidateSet &set,
clang::OverloadCandidateSet::iterator &Best);
bool ShouldSkipNRVO(clang::Sema &sema, clang::QualType returnType,
clang::VarDecl *VD, clang::FunctionDecl *FD);
/// <summary>Processes an attribute for a declaration.</summary>
/// <param name="S">Sema with context.</param>
/// <param name="D">Annotated declaration.</param>
/// <param name="A">Single parsed attribute to process.</param>
/// <param name="Handled">After execution, whether this was recognized and
/// handled.</param>
void HandleDeclAttributeForHLSL(clang::Sema &S, clang::Decl *D,
const clang::AttributeList &Attr,
bool &Handled);
void InitializeInitSequenceForHLSL(clang::Sema *sema,
const clang::InitializedEntity &Entity,
const clang::InitializationKind &Kind,
clang::MultiExprArg Args,
bool TopLevelOfInitList,
clang::InitializationSequence *initSequence);
unsigned CaculateInitListArraySizeForHLSL(clang::Sema *sema,
const clang::InitListExpr *InitList,
const clang::QualType EltTy);
bool IsConversionToLessOrEqualElements(clang::Sema *self,
const clang::ExprResult &sourceExpr,
const clang::QualType &targetType,
bool explicitConversion);
clang::ExprResult LookupMatrixMemberExprForHLSL(
clang::Sema *self, clang::Expr &BaseExpr, clang::DeclarationName MemberName,
bool IsArrow, clang::SourceLocation OpLoc, clang::SourceLocation MemberLoc);
clang::ExprResult LookupVectorMemberExprForHLSL(
clang::Sema *self, clang::Expr &BaseExpr, clang::DeclarationName MemberName,
bool IsArrow, clang::SourceLocation OpLoc, clang::SourceLocation MemberLoc);
clang::ExprResult LookupArrayMemberExprForHLSL(
clang::Sema *self, clang::Expr &BaseExpr, clang::DeclarationName MemberName,
bool IsArrow, clang::SourceLocation OpLoc, clang::SourceLocation MemberLoc);
bool LookupRecordMemberExprForHLSL(clang::Sema *self, clang::Expr &BaseExpr,
clang::DeclarationName MemberName,
bool IsArrow, clang::SourceLocation OpLoc,
clang::SourceLocation MemberLoc,
clang::ExprResult &result);
clang::ExprResult MaybeConvertMemberAccess(clang::Sema *Self, clang::Expr *E);
/// <summary>Performs the HLSL-specific type conversion steps.</summary>
/// <param name="self">Sema with context.</param>
/// <param name="E">Expression to convert.</param>
/// <param name="targetType">Type to convert to.</param>
/// <param name="SCS">Standard conversion sequence from which Second and
/// ComponentConversion will be used.</param> <param name="CCK">Conversion
/// kind.</param> <returns>Expression result of conversion.</returns>
clang::ExprResult
PerformHLSLConversion(clang::Sema *self, clang::Expr *E,
clang::QualType targetType,
const clang::StandardConversionSequence &SCS,
clang::Sema::CheckedConversionKind CCK);
/// <summary>Processes an attribute for a statement.</summary>
/// <param name="S">Sema with context.</param>
/// <param name="St">Annotated statement.</param>
/// <param name="A">Single parsed attribute to process.</param>
/// <param name="Range">Range of all attribute lists (useful for FixIts to
/// suggest inclusions).</param> <param name="Handled">After execution, whether
/// this was recognized and handled.</param> <returns>An attribute instance if
/// processed, nullptr if not recognized or an error was found.</returns>
clang::Attr *ProcessStmtAttributeForHLSL(clang::Sema &S, clang::Stmt *St,
const clang::AttributeList &A,
clang::SourceRange Range,
bool &Handled);
bool TryStaticCastForHLSL(clang::Sema *Self, clang::ExprResult &SrcExpr,
clang::QualType DestType,
clang::Sema::CheckedConversionKind CCK,
const clang::SourceRange &OpRange, unsigned &msg,
clang::CastKind &Kind, clang::CXXCastPath &BasePath,
bool ListInitialization, bool SuppressDiagnostics,
clang::StandardConversionSequence *standard);
clang::ImplicitConversionSequence
TrySubscriptIndexInitialization(clang::Sema *Self, clang::Expr *SrcExpr,
clang::QualType DestType);
bool IsHLSLAttr(clang::attr::Kind AttrKind);
void CustomPrintHLSLAttr(const clang::Attr *A, llvm::raw_ostream &Out,
const clang::PrintingPolicy &Policy,
unsigned int Indentation);
void PrintClipPlaneIfPresent(clang::Expr *ClipPlane, llvm::raw_ostream &Out,
const clang::PrintingPolicy &Policy);
void Indent(unsigned int Indentation, llvm::raw_ostream &Out);
void GetHLSLAttributedTypes(clang::Sema *self, clang::QualType type,
const clang::AttributedType **ppMatrixOrientation,
const clang::AttributedType **ppNorm,
const clang::AttributedType **ppGLC);
bool IsMatrixType(clang::Sema *self, clang::QualType type);
bool IsVectorType(clang::Sema *self, clang::QualType type);
clang::QualType GetOriginalMatrixOrVectorElementType(clang::QualType type);
clang::QualType GetOriginalElementType(clang::Sema *self, clang::QualType type);
bool IsObjectType(clang::Sema *self, clang::QualType type,
bool *isDeprecatedEffectObject = nullptr);
bool CanConvert(clang::Sema *self, clang::SourceLocation loc,
clang::Expr *sourceExpr, clang::QualType target,
bool explicitConversion,
clang::StandardConversionSequence *standard);
// This function takes the external sema source rather than the sema object
// itself because the wire-up doesn't happen until parsing is initialized and we
// want to set this up earlier. If the HLSL constructs in the external sema move
// to Sema itself, this can be invoked on the Sema object directly.
void RegisterIntrinsicTable(clang::ExternalSemaSource *self,
IDxcIntrinsicTable *table);
clang::QualType CheckVectorConditional(clang::Sema *self,
clang::ExprResult &Cond,
clang::ExprResult &LHS,
clang::ExprResult &RHS,
clang::SourceLocation QuestionLoc);
} // namespace hlsl
bool IsTypeNumeric(clang::Sema *self, clang::QualType &type);
bool IsExprAccessingOutIndicesArray(clang::Expr *BaseExpr);
// This function reads the given declaration TSS and returns the corresponding
// parsedType with the corresponding type. Replaces the given parsed type with
// the new type
clang::QualType ApplyTypeSpecSignToParsedType(clang::Sema *self,
clang::QualType &type,
clang::TypeSpecifierSign TSS,
clang::SourceLocation Loc);
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/SemaDiagnostic.h | //===--- DiagnosticSema.h - Diagnostics for libsema -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMADIAGNOSTIC_H
#define LLVM_CLANG_SEMA_SEMADIAGNOSTIC_H
#include "clang/Basic/Diagnostic.h"
namespace clang {
namespace diag {
enum {
#define DIAG(ENUM,FLAGS,DEFAULT_MAPPING,DESC,GROUP,\
SFINAE,NOWERROR,SHOWINSYSHEADER,CATEGORY) ENUM,
#define SEMASTART
#include "clang/Basic/DiagnosticSemaKinds.inc"
#undef DIAG
NUM_BUILTIN_SEMA_DIAGNOSTICS
};
} // end namespace diag
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/Template.h | //===------- SemaTemplate.h - C++ Templates ---------------------*- C++ -*-===/
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//===----------------------------------------------------------------------===/
//
// This file provides types used in the semantic analysis of C++ templates.
//
//===----------------------------------------------------------------------===/
#ifndef LLVM_CLANG_SEMA_TEMPLATE_H
#define LLVM_CLANG_SEMA_TEMPLATE_H
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/SmallVector.h"
#include <cassert>
#include <utility>
namespace clang {
/// \brief Data structure that captures multiple levels of template argument
/// lists for use in template instantiation.
///
/// Multiple levels of template arguments occur when instantiating the
/// definitions of member templates. For example:
///
/// \code
/// template<typename T>
/// struct X {
/// template<T Value>
/// struct Y {
/// void f();
/// };
/// };
/// \endcode
///
/// When instantiating X<int>::Y<17>::f, the multi-level template argument
/// list will contain a template argument list (int) at depth 0 and a
/// template argument list (17) at depth 1.
class MultiLevelTemplateArgumentList {
/// \brief The template argument list at a certain template depth
typedef ArrayRef<TemplateArgument> ArgList;
/// \brief The template argument lists, stored from the innermost template
/// argument list (first) to the outermost template argument list (last).
SmallVector<ArgList, 4> TemplateArgumentLists;
public:
/// \brief Construct an empty set of template argument lists.
MultiLevelTemplateArgumentList() { }
/// \brief Construct a single-level template argument list.
explicit
MultiLevelTemplateArgumentList(const TemplateArgumentList &TemplateArgs) {
addOuterTemplateArguments(&TemplateArgs);
}
/// \brief Determine the number of levels in this template argument
/// list.
unsigned getNumLevels() const { return TemplateArgumentLists.size(); }
/// \brief Retrieve the template argument at a given depth and index.
const TemplateArgument &operator()(unsigned Depth, unsigned Index) const {
assert(Depth < TemplateArgumentLists.size());
assert(Index < TemplateArgumentLists[getNumLevels() - Depth - 1].size());
return TemplateArgumentLists[getNumLevels() - Depth - 1][Index];
}
/// \brief Determine whether there is a non-NULL template argument at the
/// given depth and index.
///
/// There must exist a template argument list at the given depth.
bool hasTemplateArgument(unsigned Depth, unsigned Index) const {
assert(Depth < TemplateArgumentLists.size());
if (Index >= TemplateArgumentLists[getNumLevels() - Depth - 1].size())
return false;
return !(*this)(Depth, Index).isNull();
}
/// \brief Clear out a specific template argument.
void setArgument(unsigned Depth, unsigned Index,
TemplateArgument Arg) {
assert(Depth < TemplateArgumentLists.size());
assert(Index < TemplateArgumentLists[getNumLevels() - Depth - 1].size());
const_cast<TemplateArgument&>(
TemplateArgumentLists[getNumLevels() - Depth - 1][Index])
= Arg;
}
/// \brief Add a new outermost level to the multi-level template argument
/// list.
void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs) {
addOuterTemplateArguments(ArgList(TemplateArgs->data(),
TemplateArgs->size()));
}
/// \brief Add a new outmost level to the multi-level template argument
/// list.
void addOuterTemplateArguments(ArgList Args) {
TemplateArgumentLists.push_back(Args);
}
/// \brief Retrieve the innermost template argument list.
const ArgList &getInnermost() const {
return TemplateArgumentLists.front();
}
};
/// \brief The context in which partial ordering of function templates occurs.
enum TPOC {
/// \brief Partial ordering of function templates for a function call.
TPOC_Call,
/// \brief Partial ordering of function templates for a call to a
/// conversion function.
TPOC_Conversion,
/// \brief Partial ordering of function templates in other contexts, e.g.,
/// taking the address of a function template or matching a function
/// template specialization to a function template.
TPOC_Other
};
// This is lame but unavoidable in a world without forward
// declarations of enums. The alternatives are to either pollute
// Sema.h (by including this file) or sacrifice type safety (by
// making Sema.h declare things as enums).
class TemplatePartialOrderingContext {
TPOC Value;
public:
TemplatePartialOrderingContext(TPOC Value) : Value(Value) {}
operator TPOC() const { return Value; }
};
/// \brief Captures a template argument whose value has been deduced
/// via c++ template argument deduction.
class DeducedTemplateArgument : public TemplateArgument {
/// \brief For a non-type template argument, whether the value was
/// deduced from an array bound.
bool DeducedFromArrayBound;
public:
DeducedTemplateArgument()
: TemplateArgument(), DeducedFromArrayBound(false) { }
DeducedTemplateArgument(const TemplateArgument &Arg,
bool DeducedFromArrayBound = false)
: TemplateArgument(Arg), DeducedFromArrayBound(DeducedFromArrayBound) { }
/// \brief Construct an integral non-type template argument that
/// has been deduced, possibly from an array bound.
DeducedTemplateArgument(ASTContext &Ctx,
const llvm::APSInt &Value,
QualType ValueType,
bool DeducedFromArrayBound)
: TemplateArgument(Ctx, Value, ValueType),
DeducedFromArrayBound(DeducedFromArrayBound) { }
/// \brief For a non-type template argument, determine whether the
/// template argument was deduced from an array bound.
bool wasDeducedFromArrayBound() const { return DeducedFromArrayBound; }
/// \brief Specify whether the given non-type template argument
/// was deduced from an array bound.
void setDeducedFromArrayBound(bool Deduced) {
DeducedFromArrayBound = Deduced;
}
};
/// \brief A stack-allocated class that identifies which local
/// variable declaration instantiations are present in this scope.
///
/// A new instance of this class type will be created whenever we
/// instantiate a new function declaration, which will have its own
/// set of parameter declarations.
class LocalInstantiationScope {
public:
/// \brief A set of declarations.
typedef SmallVector<Decl *, 4> DeclArgumentPack;
private:
/// \brief Reference to the semantic analysis that is performing
/// this template instantiation.
Sema &SemaRef;
typedef llvm::SmallDenseMap<
const Decl *, llvm::PointerUnion<Decl *, DeclArgumentPack *>, 4>
LocalDeclsMap;
/// \brief A mapping from local declarations that occur
/// within a template to their instantiations.
///
/// This mapping is used during instantiation to keep track of,
/// e.g., function parameter and variable declarations. For example,
/// given:
///
/// \code
/// template<typename T> T add(T x, T y) { return x + y; }
/// \endcode
///
/// when we instantiate add<int>, we will introduce a mapping from
/// the ParmVarDecl for 'x' that occurs in the template to the
/// instantiated ParmVarDecl for 'x'.
///
/// For a parameter pack, the local instantiation scope may contain a
/// set of instantiated parameters. This is stored as a DeclArgumentPack
/// pointer.
LocalDeclsMap LocalDecls;
/// \brief The set of argument packs we've allocated.
SmallVector<DeclArgumentPack *, 1> ArgumentPacks;
/// \brief The outer scope, which contains local variable
/// definitions from some other instantiation (that may not be
/// relevant to this particular scope).
LocalInstantiationScope *Outer;
/// \brief Whether we have already exited this scope.
bool Exited;
/// \brief Whether to combine this scope with the outer scope, such that
/// lookup will search our outer scope.
bool CombineWithOuterScope;
/// \brief If non-NULL, the template parameter pack that has been
/// partially substituted per C++0x [temp.arg.explicit]p9.
NamedDecl *PartiallySubstitutedPack;
/// \brief If \c PartiallySubstitutedPack is non-null, the set of
/// explicitly-specified template arguments in that pack.
const TemplateArgument *ArgsInPartiallySubstitutedPack;
/// \brief If \c PartiallySubstitutedPack, the number of
/// explicitly-specified template arguments in
/// ArgsInPartiallySubstitutedPack.
unsigned NumArgsInPartiallySubstitutedPack;
// This class is non-copyable
LocalInstantiationScope(
const LocalInstantiationScope &) = delete;
void operator=(const LocalInstantiationScope &) = delete;
public:
LocalInstantiationScope(Sema &SemaRef, bool CombineWithOuterScope = false)
: SemaRef(SemaRef), Outer(SemaRef.CurrentInstantiationScope),
Exited(false), CombineWithOuterScope(CombineWithOuterScope),
PartiallySubstitutedPack(nullptr)
{
SemaRef.CurrentInstantiationScope = this;
}
~LocalInstantiationScope() {
Exit();
}
const Sema &getSema() const { return SemaRef; }
/// \brief Exit this local instantiation scope early.
void Exit() {
if (Exited)
return;
for (unsigned I = 0, N = ArgumentPacks.size(); I != N; ++I)
delete ArgumentPacks[I];
SemaRef.CurrentInstantiationScope = Outer;
Exited = true;
}
/// \brief Clone this scope, and all outer scopes, down to the given
/// outermost scope.
LocalInstantiationScope *cloneScopes(LocalInstantiationScope *Outermost) {
if (this == Outermost) return this;
// Save the current scope from SemaRef since the LocalInstantiationScope
// will overwrite it on construction
LocalInstantiationScope *oldScope = SemaRef.CurrentInstantiationScope;
LocalInstantiationScope *newScope =
new LocalInstantiationScope(SemaRef, CombineWithOuterScope);
newScope->Outer = nullptr;
if (Outer)
newScope->Outer = Outer->cloneScopes(Outermost);
newScope->PartiallySubstitutedPack = PartiallySubstitutedPack;
newScope->ArgsInPartiallySubstitutedPack = ArgsInPartiallySubstitutedPack;
newScope->NumArgsInPartiallySubstitutedPack =
NumArgsInPartiallySubstitutedPack;
for (LocalDeclsMap::iterator I = LocalDecls.begin(), E = LocalDecls.end();
I != E; ++I) {
const Decl *D = I->first;
llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored =
newScope->LocalDecls[D];
if (I->second.is<Decl *>()) {
Stored = I->second.get<Decl *>();
} else {
DeclArgumentPack *OldPack = I->second.get<DeclArgumentPack *>();
DeclArgumentPack *NewPack = new DeclArgumentPack(*OldPack);
Stored = NewPack;
newScope->ArgumentPacks.push_back(NewPack);
}
}
// Restore the saved scope to SemaRef
SemaRef.CurrentInstantiationScope = oldScope;
return newScope;
}
/// \brief deletes the given scope, and all otuer scopes, down to the
/// given outermost scope.
static void deleteScopes(LocalInstantiationScope *Scope,
LocalInstantiationScope *Outermost) {
while (Scope && Scope != Outermost) {
LocalInstantiationScope *Out = Scope->Outer;
delete Scope;
Scope = Out;
}
}
/// \brief Find the instantiation of the declaration D within the current
/// instantiation scope.
///
/// \param D The declaration whose instantiation we are searching for.
///
/// \returns A pointer to the declaration or argument pack of declarations
/// to which the declaration \c D is instantiated, if found. Otherwise,
/// returns NULL.
llvm::PointerUnion<Decl *, DeclArgumentPack *> *
findInstantiationOf(const Decl *D);
void InstantiatedLocal(const Decl *D, Decl *Inst);
void InstantiatedLocalPackArg(const Decl *D, Decl *Inst);
void MakeInstantiatedLocalArgPack(const Decl *D);
/// \brief Note that the given parameter pack has been partially substituted
/// via explicit specification of template arguments
/// (C++0x [temp.arg.explicit]p9).
///
/// \param Pack The parameter pack, which will always be a template
/// parameter pack.
///
/// \param ExplicitArgs The explicitly-specified template arguments provided
/// for this parameter pack.
///
/// \param NumExplicitArgs The number of explicitly-specified template
/// arguments provided for this parameter pack.
void SetPartiallySubstitutedPack(NamedDecl *Pack,
const TemplateArgument *ExplicitArgs,
unsigned NumExplicitArgs);
/// \brief Reset the partially-substituted pack when it is no longer of
/// interest.
void ResetPartiallySubstitutedPack() {
assert(PartiallySubstitutedPack && "No partially-substituted pack");
PartiallySubstitutedPack = nullptr;
ArgsInPartiallySubstitutedPack = nullptr;
NumArgsInPartiallySubstitutedPack = 0;
}
/// \brief Retrieve the partially-substitued template parameter pack.
///
/// If there is no partially-substituted parameter pack, returns NULL.
NamedDecl *
getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs = nullptr,
unsigned *NumExplicitArgs = nullptr) const;
};
class TemplateDeclInstantiator
: public DeclVisitor<TemplateDeclInstantiator, Decl *>
{
Sema &SemaRef;
Sema::ArgumentPackSubstitutionIndexRAII SubstIndex;
DeclContext *Owner;
const MultiLevelTemplateArgumentList &TemplateArgs;
Sema::LateInstantiatedAttrVec* LateAttrs;
LocalInstantiationScope *StartingScope;
/// \brief A list of out-of-line class template partial
/// specializations that will need to be instantiated after the
/// enclosing class's instantiation is complete.
SmallVector<std::pair<ClassTemplateDecl *,
ClassTemplatePartialSpecializationDecl *>, 4>
OutOfLinePartialSpecs;
/// \brief A list of out-of-line variable template partial
/// specializations that will need to be instantiated after the
/// enclosing variable's instantiation is complete.
/// FIXME: Verify that this is needed.
SmallVector<
std::pair<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>, 4>
OutOfLineVarPartialSpecs;
public:
TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
const MultiLevelTemplateArgumentList &TemplateArgs)
: SemaRef(SemaRef),
SubstIndex(SemaRef, SemaRef.ArgumentPackSubstitutionIndex),
Owner(Owner), TemplateArgs(TemplateArgs), LateAttrs(nullptr),
StartingScope(nullptr) {}
// Define all the decl visitors using DeclNodes.inc
#define DECL(DERIVED, BASE) \
Decl *Visit ## DERIVED ## Decl(DERIVED ## Decl *D);
#define ABSTRACT_DECL(DECL)
// Decls which never appear inside a class or function.
#define OBJCCONTAINER(DERIVED, BASE)
#define FILESCOPEASM(DERIVED, BASE)
#define IMPORT(DERIVED, BASE)
#define LINKAGESPEC(DERIVED, BASE)
#define OBJCCOMPATIBLEALIAS(DERIVED, BASE)
#define OBJCMETHOD(DERIVED, BASE)
#define OBJCTYPEPARAM(DERIVED, BASE)
#define OBJCIVAR(DERIVED, BASE)
#define OBJCPROPERTY(DERIVED, BASE)
#define OBJCPROPERTYIMPL(DERIVED, BASE)
#define EMPTY(DERIVED, BASE)
// Decls which use special-case instantiation code.
#define BLOCK(DERIVED, BASE)
#define CAPTURED(DERIVED, BASE)
#define IMPLICITPARAM(DERIVED, BASE)
#include "clang/AST/DeclNodes.inc"
// A few supplemental visitor functions.
Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
TemplateParameterList *TemplateParams,
bool IsClassScopeSpecialization = false);
Decl *VisitFunctionDecl(FunctionDecl *D,
TemplateParameterList *TemplateParams);
Decl *VisitDecl(Decl *D);
Decl *VisitVarDecl(VarDecl *D, bool InstantiatingVarTemplate);
// Enable late instantiation of attributes. Late instantiated attributes
// will be stored in LA.
void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *LA) {
LateAttrs = LA;
StartingScope = SemaRef.CurrentInstantiationScope;
}
// Disable late instantiation of attributes.
void disableLateAttributeInstantiation() {
LateAttrs = nullptr;
StartingScope = nullptr;
}
LocalInstantiationScope *getStartingScope() const { return StartingScope; }
typedef
SmallVectorImpl<std::pair<ClassTemplateDecl *,
ClassTemplatePartialSpecializationDecl *> >
::iterator
delayed_partial_spec_iterator;
typedef SmallVectorImpl<std::pair<
VarTemplateDecl *, VarTemplatePartialSpecializationDecl *> >::iterator
delayed_var_partial_spec_iterator;
/// \brief Return an iterator to the beginning of the set of
/// "delayed" partial specializations, which must be passed to
/// InstantiateClassTemplatePartialSpecialization once the class
/// definition has been completed.
delayed_partial_spec_iterator delayed_partial_spec_begin() {
return OutOfLinePartialSpecs.begin();
}
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin() {
return OutOfLineVarPartialSpecs.begin();
}
/// \brief Return an iterator to the end of the set of
/// "delayed" partial specializations, which must be passed to
/// InstantiateClassTemplatePartialSpecialization once the class
/// definition has been completed.
delayed_partial_spec_iterator delayed_partial_spec_end() {
return OutOfLinePartialSpecs.end();
}
delayed_var_partial_spec_iterator delayed_var_partial_spec_end() {
return OutOfLineVarPartialSpecs.end();
}
// Helper functions for instantiating methods.
TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
SmallVectorImpl<ParmVarDecl *> &Params);
bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
TemplateParameterList *
SubstTemplateParams(TemplateParameterList *List);
bool SubstQualifier(const DeclaratorDecl *OldDecl,
DeclaratorDecl *NewDecl);
bool SubstQualifier(const TagDecl *OldDecl,
TagDecl *NewDecl);
Decl *VisitVarTemplateSpecializationDecl(
VarTemplateDecl *VarTemplate, VarDecl *FromVar, void *InsertPos,
const TemplateArgumentListInfo &TemplateArgsInfo,
ArrayRef<TemplateArgument> Converted);
Decl *InstantiateTypedefNameDecl(TypedefNameDecl *D, bool IsTypeAlias);
ClassTemplatePartialSpecializationDecl *
InstantiateClassTemplatePartialSpecialization(
ClassTemplateDecl *ClassTemplate,
ClassTemplatePartialSpecializationDecl *PartialSpec);
VarTemplatePartialSpecializationDecl *
InstantiateVarTemplatePartialSpecialization(
VarTemplateDecl *VarTemplate,
VarTemplatePartialSpecializationDecl *PartialSpec);
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern);
};
}
#endif // LLVM_CLANG_SEMA_TEMPLATE_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/Lookup.h | //===--- Lookup.h - Classes for name lookup ---------------------*- 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 LookupResult class, which is integral to
// Sema's name-lookup subsystem.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_LOOKUP_H
#define LLVM_CLANG_SEMA_LOOKUP_H
#include "clang/AST/DeclCXX.h"
#include "clang/Sema/Sema.h"
namespace clang {
/// @brief Represents the results of name lookup.
///
/// An instance of the LookupResult class captures the results of a
/// single name lookup, which can return no result (nothing found),
/// a single declaration, a set of overloaded functions, or an
/// ambiguity. Use the getKind() method to determine which of these
/// results occurred for a given lookup.
class LookupResult {
public:
enum LookupResultKind {
/// @brief No entity found met the criteria.
NotFound = 0,
/// @brief No entity found met the criteria within the current
/// instantiation,, but there were dependent base classes of the
/// current instantiation that could not be searched.
NotFoundInCurrentInstantiation,
/// @brief Name lookup found a single declaration that met the
/// criteria. getFoundDecl() will return this declaration.
Found,
/// @brief Name lookup found a set of overloaded functions that
/// met the criteria.
FoundOverloaded,
/// @brief Name lookup found an unresolvable value declaration
/// and cannot yet complete. This only happens in C++ dependent
/// contexts with dependent using declarations.
FoundUnresolvedValue,
/// @brief Name lookup results in an ambiguity; use
/// getAmbiguityKind to figure out what kind of ambiguity
/// we have.
Ambiguous
};
enum AmbiguityKind {
/// Name lookup results in an ambiguity because multiple
/// entities that meet the lookup criteria were found in
/// subobjects of different types. For example:
/// @code
/// struct A { void f(int); }
/// struct B { void f(double); }
/// struct C : A, B { };
/// void test(C c) {
/// c.f(0); // error: A::f and B::f come from subobjects of different
/// // types. overload resolution is not performed.
/// }
/// @endcode
AmbiguousBaseSubobjectTypes,
/// Name lookup results in an ambiguity because multiple
/// nonstatic entities that meet the lookup criteria were found
/// in different subobjects of the same type. For example:
/// @code
/// struct A { int x; };
/// struct B : A { };
/// struct C : A { };
/// struct D : B, C { };
/// int test(D d) {
/// return d.x; // error: 'x' is found in two A subobjects (of B and C)
/// }
/// @endcode
AmbiguousBaseSubobjects,
/// Name lookup results in an ambiguity because multiple definitions
/// of entity that meet the lookup criteria were found in different
/// declaration contexts.
/// @code
/// namespace A {
/// int i;
/// namespace B { int i; }
/// int test() {
/// using namespace B;
/// return i; // error 'i' is found in namespace A and A::B
/// }
/// }
/// @endcode
AmbiguousReference,
/// Name lookup results in an ambiguity because an entity with a
/// tag name was hidden by an entity with an ordinary name from
/// a different context.
/// @code
/// namespace A { struct Foo {}; }
/// namespace B { void Foo(); }
/// namespace C {
/// using namespace A;
/// using namespace B;
/// }
/// void test() {
/// C::Foo(); // error: tag 'A::Foo' is hidden by an object in a
/// // different namespace
/// }
/// @endcode
AmbiguousTagHiding
};
/// A little identifier for flagging temporary lookup results.
enum TemporaryToken {
Temporary
};
typedef UnresolvedSetImpl::iterator iterator;
LookupResult(Sema &SemaRef, const DeclarationNameInfo &NameInfo,
Sema::LookupNameKind LookupKind,
Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
: ResultKind(NotFound),
Paths(nullptr),
NamingClass(nullptr),
SemaPtr(&SemaRef),
NameInfo(NameInfo),
LookupKind(LookupKind),
IDNS(0),
Redecl(Redecl != Sema::NotForRedeclaration),
HideTags(true),
Diagnose(Redecl == Sema::NotForRedeclaration),
AllowHidden(Redecl == Sema::ForRedeclaration),
Shadowed(false)
{
configure();
}
// TODO: consider whether this constructor should be restricted to take
// as input a const IndentifierInfo* (instead of Name),
// forcing other cases towards the constructor taking a DNInfo.
LookupResult(Sema &SemaRef, DeclarationName Name,
SourceLocation NameLoc, Sema::LookupNameKind LookupKind,
Sema::RedeclarationKind Redecl = Sema::NotForRedeclaration)
: ResultKind(NotFound),
Paths(nullptr),
NamingClass(nullptr),
SemaPtr(&SemaRef),
NameInfo(Name, NameLoc),
LookupKind(LookupKind),
IDNS(0),
Redecl(Redecl != Sema::NotForRedeclaration),
HideTags(true),
Diagnose(Redecl == Sema::NotForRedeclaration),
AllowHidden(Redecl == Sema::ForRedeclaration),
Shadowed(false)
{
configure();
}
/// Creates a temporary lookup result, initializing its core data
/// using the information from another result. Diagnostics are always
/// disabled.
LookupResult(TemporaryToken _, const LookupResult &Other)
: ResultKind(NotFound),
Paths(nullptr),
NamingClass(nullptr),
SemaPtr(Other.SemaPtr),
NameInfo(Other.NameInfo),
LookupKind(Other.LookupKind),
IDNS(Other.IDNS),
Redecl(Other.Redecl),
HideTags(Other.HideTags),
Diagnose(false),
AllowHidden(Other.AllowHidden),
Shadowed(false)
{}
~LookupResult() {
if (Diagnose) diagnose();
if (Paths) deletePaths(Paths);
}
/// Gets the name info to look up.
const DeclarationNameInfo &getLookupNameInfo() const {
return NameInfo;
}
/// \brief Sets the name info to look up.
void setLookupNameInfo(const DeclarationNameInfo &NameInfo) {
this->NameInfo = NameInfo;
}
/// Gets the name to look up.
DeclarationName getLookupName() const {
return NameInfo.getName();
}
/// \brief Sets the name to look up.
void setLookupName(DeclarationName Name) {
NameInfo.setName(Name);
}
/// Gets the kind of lookup to perform.
Sema::LookupNameKind getLookupKind() const {
return LookupKind;
}
/// True if this lookup is just looking for an existing declaration.
bool isForRedeclaration() const {
return Redecl;
}
/// \brief Specify whether hidden declarations are visible, e.g.,
/// for recovery reasons.
void setAllowHidden(bool AH) {
AllowHidden = AH;
}
/// \brief Determine whether this lookup is permitted to see hidden
/// declarations, such as those in modules that have not yet been imported.
bool isHiddenDeclarationVisible() const {
return AllowHidden || LookupKind == Sema::LookupTagName;
}
/// Sets whether tag declarations should be hidden by non-tag
/// declarations during resolution. The default is true.
void setHideTags(bool Hide) {
HideTags = Hide;
}
bool isAmbiguous() const {
return getResultKind() == Ambiguous;
}
/// Determines if this names a single result which is not an
/// unresolved value using decl. If so, it is safe to call
/// getFoundDecl().
bool isSingleResult() const {
return getResultKind() == Found;
}
/// Determines if the results are overloaded.
bool isOverloadedResult() const {
return getResultKind() == FoundOverloaded;
}
bool isUnresolvableResult() const {
return getResultKind() == FoundUnresolvedValue;
}
LookupResultKind getResultKind() const {
assert(sanity());
return ResultKind;
}
AmbiguityKind getAmbiguityKind() const {
assert(isAmbiguous());
return Ambiguity;
}
const UnresolvedSetImpl &asUnresolvedSet() const {
return Decls;
}
iterator begin() const { return iterator(Decls.begin()); }
iterator end() const { return iterator(Decls.end()); }
/// \brief Return true if no decls were found
bool empty() const { return Decls.empty(); }
/// \brief Return the base paths structure that's associated with
/// these results, or null if none is.
CXXBasePaths *getBasePaths() const {
return Paths;
}
/// \brief Determine whether the given declaration is visible to the
/// program.
static bool isVisible(Sema &SemaRef, NamedDecl *D) {
// If this declaration is not hidden, it's visible.
if (!D->isHidden())
return true;
// During template instantiation, we can refer to hidden declarations, if
// they were visible in any module along the path of instantiation.
return isVisibleSlow(SemaRef, D);
}
/// \brief Retrieve the accepted (re)declaration of the given declaration,
/// if there is one.
NamedDecl *getAcceptableDecl(NamedDecl *D) const {
if (!D->isInIdentifierNamespace(IDNS))
return nullptr;
if (isHiddenDeclarationVisible() || isVisible(getSema(), D))
return D;
return getAcceptableDeclSlow(D);
}
private:
static bool isVisibleSlow(Sema &SemaRef, NamedDecl *D);
NamedDecl *getAcceptableDeclSlow(NamedDecl *D) const;
public:
/// \brief Returns the identifier namespace mask for this lookup.
unsigned getIdentifierNamespace() const {
return IDNS;
}
/// \brief Returns whether these results arose from performing a
/// lookup into a class.
bool isClassLookup() const {
return NamingClass != nullptr;
}
/// \brief Returns the 'naming class' for this lookup, i.e. the
/// class which was looked into to find these results.
///
/// C++0x [class.access.base]p5:
/// The access to a member is affected by the class in which the
/// member is named. This naming class is the class in which the
/// member name was looked up and found. [Note: this class can be
/// explicit, e.g., when a qualified-id is used, or implicit,
/// e.g., when a class member access operator (5.2.5) is used
/// (including cases where an implicit "this->" is added). If both
/// a class member access operator and a qualified-id are used to
/// name the member (as in p->T::m), the class naming the member
/// is the class named by the nested-name-specifier of the
/// qualified-id (that is, T). -- end note ]
///
/// This is set by the lookup routines when they find results in a class.
CXXRecordDecl *getNamingClass() const {
return NamingClass;
}
/// \brief Sets the 'naming class' for this lookup.
void setNamingClass(CXXRecordDecl *Record) {
NamingClass = Record;
}
/// \brief Returns the base object type associated with this lookup;
/// important for [class.protected]. Most lookups do not have an
/// associated base object.
QualType getBaseObjectType() const {
return BaseObjectType;
}
/// \brief Sets the base object type for this lookup.
void setBaseObjectType(QualType T) {
BaseObjectType = T;
}
/// \brief Add a declaration to these results with its natural access.
/// Does not test the acceptance criteria.
void addDecl(NamedDecl *D) {
addDecl(D, D->getAccess());
}
/// \brief Add a declaration to these results with the given access.
/// Does not test the acceptance criteria.
void addDecl(NamedDecl *D, AccessSpecifier AS) {
Decls.addDecl(D, AS);
ResultKind = Found;
}
/// \brief Add all the declarations from another set of lookup
/// results.
void addAllDecls(const LookupResult &Other) {
Decls.append(Other.Decls.begin(), Other.Decls.end());
ResultKind = Found;
}
/// \brief Determine whether no result was found because we could not
/// search into dependent base classes of the current instantiation.
bool wasNotFoundInCurrentInstantiation() const {
return ResultKind == NotFoundInCurrentInstantiation;
}
/// \brief Note that while no result was found in the current instantiation,
/// there were dependent base classes that could not be searched.
void setNotFoundInCurrentInstantiation() {
assert(ResultKind == NotFound && Decls.empty());
ResultKind = NotFoundInCurrentInstantiation;
}
/// \brief Determine whether the lookup result was shadowed by some other
/// declaration that lookup ignored.
bool isShadowed() const { return Shadowed; }
/// \brief Note that we found and ignored a declaration while performing
/// lookup.
void setShadowed() { Shadowed = true; }
/// \brief Resolves the result kind of the lookup, possibly hiding
/// decls.
///
/// This should be called in any environment where lookup might
/// generate multiple lookup results.
void resolveKind();
/// \brief Re-resolves the result kind of the lookup after a set of
/// removals has been performed.
void resolveKindAfterFilter() {
if (Decls.empty()) {
if (ResultKind != NotFoundInCurrentInstantiation)
ResultKind = NotFound;
if (Paths) {
deletePaths(Paths);
Paths = nullptr;
}
} else {
AmbiguityKind SavedAK;
bool WasAmbiguous = false;
if (ResultKind == Ambiguous) {
SavedAK = Ambiguity;
WasAmbiguous = true;
}
ResultKind = Found;
resolveKind();
// If we didn't make the lookup unambiguous, restore the old
// ambiguity kind.
if (ResultKind == Ambiguous) {
(void)WasAmbiguous;
assert(WasAmbiguous);
Ambiguity = SavedAK;
} else if (Paths) {
deletePaths(Paths);
Paths = nullptr;
}
}
}
template <class DeclClass>
DeclClass *getAsSingle() const {
if (getResultKind() != Found) return nullptr;
return dyn_cast<DeclClass>(getFoundDecl());
}
/// \brief Fetch the unique decl found by this lookup. Asserts
/// that one was found.
///
/// This is intended for users who have examined the result kind
/// and are certain that there is only one result.
NamedDecl *getFoundDecl() const {
assert(getResultKind() == Found
&& "getFoundDecl called on non-unique result");
return (*begin())->getUnderlyingDecl();
}
/// Fetches a representative decl. Useful for lazy diagnostics.
NamedDecl *getRepresentativeDecl() const {
assert(!Decls.empty() && "cannot get representative of empty set");
return *begin();
}
/// \brief Asks if the result is a single tag decl.
bool isSingleTagDecl() const {
return getResultKind() == Found && isa<TagDecl>(getFoundDecl());
}
/// \brief Make these results show that the name was found in
/// base classes of different types.
///
/// The given paths object is copied and invalidated.
void setAmbiguousBaseSubobjectTypes(CXXBasePaths &P);
/// \brief Make these results show that the name was found in
/// distinct base classes of the same type.
///
/// The given paths object is copied and invalidated.
void setAmbiguousBaseSubobjects(CXXBasePaths &P);
/// \brief Make these results show that the name was found in
/// different contexts and a tag decl was hidden by an ordinary
/// decl in a different context.
void setAmbiguousQualifiedTagHiding() {
setAmbiguous(AmbiguousTagHiding);
}
/// \brief Clears out any current state.
void clear() {
ResultKind = NotFound;
Decls.clear();
if (Paths) deletePaths(Paths);
Paths = nullptr;
NamingClass = nullptr;
Shadowed = false;
}
/// \brief Clears out any current state and re-initializes for a
/// different kind of lookup.
void clear(Sema::LookupNameKind Kind) {
clear();
LookupKind = Kind;
configure();
}
/// \brief Change this lookup's redeclaration kind.
void setRedeclarationKind(Sema::RedeclarationKind RK) {
Redecl = RK;
AllowHidden = (RK == Sema::ForRedeclaration);
configure();
}
void print(raw_ostream &);
/// Suppress the diagnostics that would normally fire because of this
/// lookup. This happens during (e.g.) redeclaration lookups.
void suppressDiagnostics() {
Diagnose = false;
}
/// Determines whether this lookup is suppressing diagnostics.
bool isSuppressingDiagnostics() const {
return !Diagnose;
}
/// Sets a 'context' source range.
void setContextRange(SourceRange SR) {
NameContextRange = SR;
}
/// Gets the source range of the context of this name; for C++
/// qualified lookups, this is the source range of the scope
/// specifier.
SourceRange getContextRange() const {
return NameContextRange;
}
/// Gets the location of the identifier. This isn't always defined:
/// sometimes we're doing lookups on synthesized names.
SourceLocation getNameLoc() const {
return NameInfo.getLoc();
}
/// \brief Get the Sema object that this lookup result is searching
/// with.
Sema &getSema() const { return *SemaPtr; }
/// A class for iterating through a result set and possibly
/// filtering out results. The results returned are possibly
/// sugared.
class Filter {
LookupResult &Results;
LookupResult::iterator I;
bool Changed;
bool CalledDone;
friend class LookupResult;
Filter(LookupResult &Results)
: Results(Results), I(Results.begin()), Changed(false), CalledDone(false)
{}
public:
~Filter() {
assert(CalledDone &&
"LookupResult::Filter destroyed without done() call");
}
bool hasNext() const {
return I != Results.end();
}
NamedDecl *next() {
assert(I != Results.end() && "next() called on empty filter");
return *I++;
}
/// Restart the iteration.
void restart() {
I = Results.begin();
}
/// Erase the last element returned from this iterator.
void erase() {
Results.Decls.erase(--I);
Changed = true;
}
/// Replaces the current entry with the given one, preserving the
/// access bits.
void replace(NamedDecl *D) {
Results.Decls.replace(I-1, D);
Changed = true;
}
/// Replaces the current entry with the given one.
void replace(NamedDecl *D, AccessSpecifier AS) {
Results.Decls.replace(I-1, D, AS);
Changed = true;
}
void done() {
assert(!CalledDone && "done() called twice");
CalledDone = true;
if (Changed)
Results.resolveKindAfterFilter();
}
};
/// Create a filter for this result set.
Filter makeFilter() {
return Filter(*this);
}
void setFindLocalExtern(bool FindLocalExtern) {
if (FindLocalExtern)
IDNS |= Decl::IDNS_LocalExtern;
else
IDNS &= ~Decl::IDNS_LocalExtern;
}
private:
void diagnose() {
if (isAmbiguous())
getSema().DiagnoseAmbiguousLookup(*this);
else if (isClassLookup() && getSema().getLangOpts().AccessControl)
getSema().CheckLookupAccess(*this);
}
void setAmbiguous(AmbiguityKind AK) {
ResultKind = Ambiguous;
Ambiguity = AK;
}
void addDeclsFromBasePaths(const CXXBasePaths &P);
void configure();
// Sanity checks.
bool sanity() const;
bool sanityCheckUnresolved() const {
for (iterator I = begin(), E = end(); I != E; ++I)
if (isa<UnresolvedUsingValueDecl>((*I)->getUnderlyingDecl()))
return true;
return false;
}
static void deletePaths(CXXBasePaths *);
// Results.
LookupResultKind ResultKind;
AmbiguityKind Ambiguity; // ill-defined unless ambiguous
UnresolvedSet<8> Decls;
CXXBasePaths *Paths;
CXXRecordDecl *NamingClass;
QualType BaseObjectType;
// Parameters.
Sema *SemaPtr;
DeclarationNameInfo NameInfo;
SourceRange NameContextRange;
Sema::LookupNameKind LookupKind;
unsigned IDNS; // set by configure()
bool Redecl;
/// \brief True if tag declarations should be hidden if non-tags
/// are present
bool HideTags;
bool Diagnose;
/// \brief True if we should allow hidden declarations to be 'visible'.
bool AllowHidden;
/// \brief True if the found declarations were shadowed by some other
/// declaration that we skipped. This only happens when \c LookupKind
/// is \c LookupRedeclarationWithLinkage.
bool Shadowed;
};
/// \brief Consumes visible declarations found when searching for
/// all visible names within a given scope or context.
///
/// This abstract class is meant to be subclassed by clients of \c
/// Sema::LookupVisibleDecls(), each of which should override the \c
/// FoundDecl() function to process declarations as they are found.
class VisibleDeclConsumer {
public:
/// \brief Destroys the visible declaration consumer.
virtual ~VisibleDeclConsumer();
/// \brief Determine whether hidden declarations (from unimported
/// modules) should be given to this consumer. By default, they
/// are not included.
virtual bool includeHiddenDecls() const;
/// \brief Invoked each time \p Sema::LookupVisibleDecls() finds a
/// declaration visible from the current scope or context.
///
/// \param ND the declaration found.
///
/// \param Hiding a declaration that hides the declaration \p ND,
/// or NULL if no such declaration exists.
///
/// \param Ctx the original context from which the lookup started.
///
/// \param InBaseClass whether this declaration was found in base
/// class of the context we searched.
virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
bool InBaseClass) = 0;
};
/// \brief A class for storing results from argument-dependent lookup.
class ADLResult {
private:
/// A map from canonical decls to the 'most recent' decl.
llvm::DenseMap<NamedDecl*, NamedDecl*> Decls;
public:
/// Adds a new ADL candidate to this map.
void insert(NamedDecl *D);
/// Removes any data associated with a given decl.
void erase(NamedDecl *D) {
Decls.erase(cast<NamedDecl>(D->getCanonicalDecl()));
}
class iterator
: public llvm::iterator_adaptor_base<
iterator, llvm::DenseMap<NamedDecl *, NamedDecl *>::iterator,
std::forward_iterator_tag, NamedDecl *> {
friend class ADLResult;
iterator(llvm::DenseMap<NamedDecl *, NamedDecl *>::iterator Iter)
: iterator_adaptor_base(std::move(Iter)) {}
public:
iterator() {}
value_type operator*() const { return I->second; }
};
iterator begin() { return iterator(Decls.begin()); }
iterator end() { return iterator(Decls.end()); }
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/AnalysisBasedWarnings.h | //=- AnalysisBasedWarnings.h - Sema warnings based on libAnalysis -*- 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 AnalysisBasedWarnings, a worker object used by Sema
// that issues warnings based on dataflow-analysis.
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_ANALYSISBASEDWARNINGS_H
#define LLVM_CLANG_SEMA_ANALYSISBASEDWARNINGS_H
#include "llvm/ADT/DenseMap.h"
namespace clang {
class BlockExpr;
class Decl;
class FunctionDecl;
class ObjCMethodDecl;
class QualType;
class Sema;
namespace sema {
class FunctionScopeInfo;
}
namespace sema {
class AnalysisBasedWarnings {
public:
class Policy {
friend class AnalysisBasedWarnings;
// The warnings to run.
unsigned enableCheckFallThrough : 1;
unsigned enableCheckUnreachable : 1;
unsigned enableThreadSafetyAnalysis : 1;
unsigned enableConsumedAnalysis : 1;
public:
Policy();
void disableCheckFallThrough() { enableCheckFallThrough = 0; }
};
private:
Sema &S;
Policy DefaultPolicy;
enum VisitFlag { NotVisited = 0, Visited = 1, Pending = 2 };
llvm::DenseMap<const FunctionDecl*, VisitFlag> VisitedFD;
/// \name Statistics
/// @{
/// \brief Number of function CFGs built and analyzed.
unsigned NumFunctionsAnalyzed;
/// \brief Number of functions for which the CFG could not be successfully
/// built.
unsigned NumFunctionsWithBadCFGs;
/// \brief Total number of blocks across all CFGs.
unsigned NumCFGBlocks;
/// \brief Largest number of CFG blocks for a single function analyzed.
unsigned MaxCFGBlocksPerFunction;
/// \brief Total number of CFGs with variables analyzed for uninitialized
/// uses.
unsigned NumUninitAnalysisFunctions;
/// \brief Total number of variables analyzed for uninitialized uses.
unsigned NumUninitAnalysisVariables;
/// \brief Max number of variables analyzed for uninitialized uses in a single
/// function.
unsigned MaxUninitAnalysisVariablesPerFunction;
/// \brief Total number of block visits during uninitialized use analysis.
unsigned NumUninitAnalysisBlockVisits;
/// \brief Max number of block visits during uninitialized use analysis of
/// a single function.
unsigned MaxUninitAnalysisBlockVisitsPerFunction;
/// @}
public:
AnalysisBasedWarnings(Sema &s);
void IssueWarnings(Policy P, FunctionScopeInfo *fscope,
const Decl *D, const BlockExpr *blkExpr);
Policy getDefaultPolicy() { return DefaultPolicy; }
void PrintStats() const;
};
}} // end namespace clang::sema
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/LoopHint.h | //===--- LoopHint.h - Types for LoopHint ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_LOOPHINT_H
#define LLVM_CLANG_SEMA_LOOPHINT_H
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/AttributeList.h"
#include "clang/Sema/Ownership.h"
namespace clang {
/// \brief Loop optimization hint for loop and unroll pragmas.
struct LoopHint {
// Source range of the directive.
SourceRange Range;
// Identifier corresponding to the name of the pragma. "loop" for
// "#pragma clang loop" directives and "unroll" for "#pragma unroll"
// hints.
IdentifierLoc *PragmaNameLoc;
// Name of the loop hint. Examples: "unroll", "vectorize". In the
// "#pragma unroll" and "#pragma nounroll" cases, this is identical to
// PragmaNameLoc.
IdentifierLoc *OptionLoc;
// Identifier for the hint state argument. If null, then the state is
// default value such as for "#pragma unroll".
IdentifierLoc *StateLoc;
// Expression for the hint argument if it exists, null otherwise.
Expr *ValueExpr;
LoopHint()
: PragmaNameLoc(nullptr), OptionLoc(nullptr), StateLoc(nullptr),
ValueExpr(nullptr) {}
};
} // end namespace clang
#endif // LLVM_CLANG_SEMA_LOOPHINT_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/ObjCMethodList.h | //===--- ObjCMethodList.h - A singly linked list of methods -----*- 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 ObjCMethodList, a singly-linked list of methods.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_OBJCMETHODLIST_H
#define LLVM_CLANG_SEMA_OBJCMETHODLIST_H
#include "llvm/ADT/PointerIntPair.h"
namespace clang {
class ObjCMethodDecl;
/// \brief a linked list of methods with the same selector name but different
/// signatures.
struct ObjCMethodList {
// NOTE: If you add any members to this struct, make sure to serialize them.
/// \brief If there is more than one decl with this signature.
llvm::PointerIntPair<ObjCMethodDecl *, 1> MethodAndHasMoreThanOneDecl;
/// \brief The next list object and 2 bits for extra info.
llvm::PointerIntPair<ObjCMethodList *, 2> NextAndExtraBits;
ObjCMethodList() { }
ObjCMethodList(ObjCMethodDecl *M)
: MethodAndHasMoreThanOneDecl(M, 0) {}
ObjCMethodList *getNext() const { return NextAndExtraBits.getPointer(); }
unsigned getBits() const { return NextAndExtraBits.getInt(); }
void setNext(ObjCMethodList *L) { NextAndExtraBits.setPointer(L); }
void setBits(unsigned B) { NextAndExtraBits.setInt(B); }
ObjCMethodDecl *getMethod() const {
return MethodAndHasMoreThanOneDecl.getPointer();
}
void setMethod(ObjCMethodDecl *M) {
return MethodAndHasMoreThanOneDecl.setPointer(M);
}
bool hasMoreThanOneDecl() const {
return MethodAndHasMoreThanOneDecl.getInt();
}
void setHasMoreThanOneDecl(bool B) {
return MethodAndHasMoreThanOneDecl.setInt(B);
}
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/CodeCompleteConsumer.h | //===---- CodeCompleteConsumer.h - Code Completion Interface ----*- 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 CodeCompleteConsumer class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
#define LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
#include "clang-c/Index.h"
#include "clang/AST/CanonicalType.h"
#include "clang/AST/Type.h"
#include "clang/Sema/CodeCompleteOptions.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include <string>
namespace clang {
class Decl;
/// \brief Default priority values for code-completion results based
/// on their kind.
enum {
/// \brief Priority for the next initialization in a constructor initializer
/// list.
CCP_NextInitializer = 7,
/// \brief Priority for an enumeration constant inside a switch whose
/// condition is of the enumeration type.
CCP_EnumInCase = 7,
/// \brief Priority for a send-to-super completion.
CCP_SuperCompletion = 20,
/// \brief Priority for a declaration that is in the local scope.
CCP_LocalDeclaration = 34,
/// \brief Priority for a member declaration found from the current
/// method or member function.
CCP_MemberDeclaration = 35,
/// \brief Priority for a language keyword (that isn't any of the other
/// categories).
CCP_Keyword = 40,
/// \brief Priority for a code pattern.
CCP_CodePattern = 40,
/// \brief Priority for a non-type declaration.
CCP_Declaration = 50,
/// \brief Priority for a type.
CCP_Type = CCP_Declaration,
/// \brief Priority for a constant value (e.g., enumerator).
CCP_Constant = 65,
/// \brief Priority for a preprocessor macro.
CCP_Macro = 70,
/// \brief Priority for a nested-name-specifier.
CCP_NestedNameSpecifier = 75,
/// \brief Priority for a result that isn't likely to be what the user wants,
/// but is included for completeness.
CCP_Unlikely = 80,
/// \brief Priority for the Objective-C "_cmd" implicit parameter.
CCP_ObjC_cmd = CCP_Unlikely
};
/// \brief Priority value deltas that are added to code-completion results
/// based on the context of the result.
enum {
/// \brief The result is in a base class.
CCD_InBaseClass = 2,
/// \brief The result is a C++ non-static member function whose qualifiers
/// exactly match the object type on which the member function can be called.
CCD_ObjectQualifierMatch = -1,
/// \brief The selector of the given message exactly matches the selector
/// of the current method, which might imply that some kind of delegation
/// is occurring.
CCD_SelectorMatch = -3,
/// \brief Adjustment to the "bool" type in Objective-C, where the typedef
/// "BOOL" is preferred.
CCD_bool_in_ObjC = 1,
/// \brief Adjustment for KVC code pattern priorities when it doesn't look
/// like the
CCD_ProbablyNotObjCCollection = 15,
/// \brief An Objective-C method being used as a property.
CCD_MethodAsProperty = 2
};
/// \brief Priority value factors by which we will divide or multiply the
/// priority of a code-completion result.
enum {
/// \brief Divide by this factor when a code-completion result's type exactly
/// matches the type we expect.
CCF_ExactTypeMatch = 4,
/// \brief Divide by this factor when a code-completion result's type is
/// similar to the type we expect (e.g., both arithmetic types, both
/// Objective-C object pointer types).
CCF_SimilarTypeMatch = 2
};
/// \brief A simplified classification of types used when determining
/// "similar" types for code completion.
enum SimplifiedTypeClass {
STC_Arithmetic,
STC_Array,
STC_Block,
STC_Function,
STC_ObjectiveC,
STC_Other,
STC_Pointer,
STC_Record,
STC_Void
};
/// \brief Determine the simplified type class of the given canonical type.
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
/// \brief Determine the type that this declaration will have if it is used
/// as a type or in an expression.
QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
/// \brief Determine the priority to be given to a macro code completion result
/// with the given name.
///
/// \param MacroName The name of the macro.
///
/// \param LangOpts Options describing the current language dialect.
///
/// \param PreferredTypeIsPointer Whether the preferred type for the context
/// of this macro is a pointer type.
unsigned getMacroUsagePriority(StringRef MacroName,
const LangOptions &LangOpts,
bool PreferredTypeIsPointer = false);
/// \brief Determine the libclang cursor kind associated with the given
/// declaration.
CXCursorKind getCursorKindForDecl(const Decl *D);
class FunctionDecl;
class FunctionType;
class FunctionTemplateDecl;
class IdentifierInfo;
class NamedDecl;
class NestedNameSpecifier;
class Sema;
/// \brief The context in which code completion occurred, so that the
/// code-completion consumer can process the results accordingly.
class CodeCompletionContext {
public:
enum Kind {
/// \brief An unspecified code-completion context.
CCC_Other,
/// \brief An unspecified code-completion context where we should also add
/// macro completions.
CCC_OtherWithMacros,
/// \brief Code completion occurred within a "top-level" completion context,
/// e.g., at namespace or global scope.
CCC_TopLevel,
/// \brief Code completion occurred within an Objective-C interface,
/// protocol, or category interface.
CCC_ObjCInterface,
/// \brief Code completion occurred within an Objective-C implementation
/// or category implementation.
CCC_ObjCImplementation,
/// \brief Code completion occurred within the instance variable list of
/// an Objective-C interface, implementation, or category implementation.
CCC_ObjCIvarList,
/// \brief Code completion occurred within a class, struct, or union.
CCC_ClassStructUnion,
/// \brief Code completion occurred where a statement (or declaration) is
/// expected in a function, method, or block.
CCC_Statement,
/// \brief Code completion occurred where an expression is expected.
CCC_Expression,
/// \brief Code completion occurred where an Objective-C message receiver
/// is expected.
CCC_ObjCMessageReceiver,
/// \brief Code completion occurred on the right-hand side of a member
/// access expression using the dot operator.
///
/// The results of this completion are the members of the type being
/// accessed. The type itself is available via
/// \c CodeCompletionContext::getType().
CCC_DotMemberAccess,
/// \brief Code completion occurred on the right-hand side of a member
/// access expression using the arrow operator.
///
/// The results of this completion are the members of the type being
/// accessed. The type itself is available via
/// \c CodeCompletionContext::getType().
CCC_ArrowMemberAccess,
/// \brief Code completion occurred on the right-hand side of an Objective-C
/// property access expression.
///
/// The results of this completion are the members of the type being
/// accessed. The type itself is available via
/// \c CodeCompletionContext::getType().
CCC_ObjCPropertyAccess,
/// \brief Code completion occurred after the "enum" keyword, to indicate
/// an enumeration name.
CCC_EnumTag,
/// \brief Code completion occurred after the "union" keyword, to indicate
/// a union name.
CCC_UnionTag,
/// \brief Code completion occurred after the "struct" or "class" keyword,
/// to indicate a struct or class name.
CCC_ClassOrStructTag,
/// \brief Code completion occurred where a protocol name is expected.
CCC_ObjCProtocolName,
/// \brief Code completion occurred where a namespace or namespace alias
/// is expected.
CCC_Namespace,
/// \brief Code completion occurred where a type name is expected.
CCC_Type,
/// \brief Code completion occurred where a new name is expected.
CCC_Name,
/// \brief Code completion occurred where a new name is expected and a
/// qualified name is permissible.
CCC_PotentiallyQualifiedName,
/// \brief Code completion occurred where an macro is being defined.
CCC_MacroName,
/// \brief Code completion occurred where a macro name is expected
/// (without any arguments, in the case of a function-like macro).
CCC_MacroNameUse,
/// \brief Code completion occurred within a preprocessor expression.
CCC_PreprocessorExpression,
/// \brief Code completion occurred where a preprocessor directive is
/// expected.
CCC_PreprocessorDirective,
/// \brief Code completion occurred in a context where natural language is
/// expected, e.g., a comment or string literal.
///
/// This context usually implies that no completions should be added,
/// unless they come from an appropriate natural-language dictionary.
CCC_NaturalLanguage,
/// \brief Code completion for a selector, as in an \@selector expression.
CCC_SelectorName,
/// \brief Code completion within a type-qualifier list.
CCC_TypeQualifiers,
/// \brief Code completion in a parenthesized expression, which means that
/// we may also have types here in C and Objective-C (as well as in C++).
CCC_ParenthesizedExpression,
/// \brief Code completion where an Objective-C instance message is
/// expected.
CCC_ObjCInstanceMessage,
/// \brief Code completion where an Objective-C class message is expected.
CCC_ObjCClassMessage,
/// \brief Code completion where the name of an Objective-C class is
/// expected.
CCC_ObjCInterfaceName,
/// \brief Code completion where an Objective-C category name is expected.
CCC_ObjCCategoryName,
/// \brief An unknown context, in which we are recovering from a parsing
/// error and don't know which completions we should give.
CCC_Recovery
};
private:
enum Kind Kind;
/// \brief The type that would prefer to see at this point (e.g., the type
/// of an initializer or function parameter).
QualType PreferredType;
/// \brief The type of the base object in a member access expression.
QualType BaseType;
/// \brief The identifiers for Objective-C selector parts.
ArrayRef<IdentifierInfo *> SelIdents;
public:
/// \brief Construct a new code-completion context of the given kind.
CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(None) { }
/// \brief Construct a new code-completion context of the given kind.
CodeCompletionContext(enum Kind Kind, QualType T,
ArrayRef<IdentifierInfo *> SelIdents = None)
: Kind(Kind),
SelIdents(SelIdents) {
if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
Kind == CCC_ObjCInstanceMessage)
BaseType = T;
else
PreferredType = T;
}
/// \brief Retrieve the kind of code-completion context.
enum Kind getKind() const { return Kind; }
/// \brief Retrieve the type that this expression would prefer to have, e.g.,
/// if the expression is a variable initializer or a function argument, the
/// type of the corresponding variable or function parameter.
QualType getPreferredType() const { return PreferredType; }
/// \brief Retrieve the type of the base object in a member-access
/// expression.
QualType getBaseType() const { return BaseType; }
/// \brief Retrieve the Objective-C selector identifiers.
ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
/// \brief Determines whether we want C++ constructors as results within this
/// context.
bool wantConstructorResults() const;
};
/// \brief A "string" used to describe how code completion can
/// be performed for an entity.
///
/// A code completion string typically shows how a particular entity can be
/// used. For example, the code completion string for a function would show
/// the syntax to call it, including the parentheses, placeholders for the
/// arguments, etc.
class CodeCompletionString {
public:
/// \brief The different kinds of "chunks" that can occur within a code
/// completion string.
enum ChunkKind {
/// \brief The piece of text that the user is expected to type to
/// match the code-completion string, typically a keyword or the name of a
/// declarator or macro.
CK_TypedText,
/// \brief A piece of text that should be placed in the buffer, e.g.,
/// parentheses or a comma in a function call.
CK_Text,
/// \brief A code completion string that is entirely optional. For example,
/// an optional code completion string that describes the default arguments
/// in a function call.
CK_Optional,
/// \brief A string that acts as a placeholder for, e.g., a function
/// call argument.
CK_Placeholder,
/// \brief A piece of text that describes something about the result but
/// should not be inserted into the buffer.
CK_Informative,
/// \brief A piece of text that describes the type of an entity or, for
/// functions and methods, the return type.
CK_ResultType,
/// \brief A piece of text that describes the parameter that corresponds
/// to the code-completion location within a function call, message send,
/// macro invocation, etc.
CK_CurrentParameter,
/// \brief A left parenthesis ('(').
CK_LeftParen,
/// \brief A right parenthesis (')').
CK_RightParen,
/// \brief A left bracket ('[').
CK_LeftBracket,
/// \brief A right bracket (']').
CK_RightBracket,
/// \brief A left brace ('{').
CK_LeftBrace,
/// \brief A right brace ('}').
CK_RightBrace,
/// \brief A left angle bracket ('<').
CK_LeftAngle,
/// \brief A right angle bracket ('>').
CK_RightAngle,
/// \brief A comma separator (',').
CK_Comma,
/// \brief A colon (':').
CK_Colon,
/// \brief A semicolon (';').
CK_SemiColon,
/// \brief An '=' sign.
CK_Equal,
/// \brief Horizontal whitespace (' ').
CK_HorizontalSpace,
/// \brief Vertical whitespace ('\\n' or '\\r\\n', depending on the
/// platform).
CK_VerticalSpace
};
/// \brief One piece of the code completion string.
struct Chunk {
/// \brief The kind of data stored in this piece of the code completion
/// string.
ChunkKind Kind;
union {
/// \brief The text string associated with a CK_Text, CK_Placeholder,
/// CK_Informative, or CK_Comma chunk.
/// The string is owned by the chunk and will be deallocated
/// (with delete[]) when the chunk is destroyed.
const char *Text;
/// \brief The code completion string associated with a CK_Optional chunk.
/// The optional code completion string is owned by the chunk, and will
/// be deallocated (with delete) when the chunk is destroyed.
CodeCompletionString *Optional;
};
Chunk() : Kind(CK_Text), Text(nullptr) { }
explicit Chunk(ChunkKind Kind, const char *Text = "");
/// \brief Create a new text chunk.
static Chunk CreateText(const char *Text);
/// \brief Create a new optional chunk.
static Chunk CreateOptional(CodeCompletionString *Optional);
/// \brief Create a new placeholder chunk.
static Chunk CreatePlaceholder(const char *Placeholder);
/// \brief Create a new informative chunk.
static Chunk CreateInformative(const char *Informative);
/// \brief Create a new result type chunk.
static Chunk CreateResultType(const char *ResultType);
/// \brief Create a new current-parameter chunk.
static Chunk CreateCurrentParameter(const char *CurrentParameter);
};
private:
/// \brief The number of chunks stored in this string.
unsigned NumChunks : 16;
/// \brief The number of annotations for this code-completion result.
unsigned NumAnnotations : 16;
/// \brief The priority of this code-completion string.
unsigned Priority : 16;
/// \brief The availability of this code-completion result.
unsigned Availability : 2;
/// \brief The name of the parent context.
StringRef ParentName;
/// \brief A brief documentation comment attached to the declaration of
/// entity being completed by this result.
const char *BriefComment;
CodeCompletionString(const CodeCompletionString &) = delete;
void operator=(const CodeCompletionString &) = delete;
CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
unsigned Priority, CXAvailabilityKind Availability,
const char **Annotations, unsigned NumAnnotations,
StringRef ParentName,
const char *BriefComment);
~CodeCompletionString() = default;
friend class CodeCompletionBuilder;
friend class CodeCompletionResult;
public:
typedef const Chunk *iterator;
iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
iterator end() const { return begin() + NumChunks; }
bool empty() const { return NumChunks == 0; }
unsigned size() const { return NumChunks; }
const Chunk &operator[](unsigned I) const {
assert(I < size() && "Chunk index out-of-range");
return begin()[I];
}
/// \brief Returns the text in the TypedText chunk.
const char *getTypedText() const;
/// \brief Retrieve the priority of this code completion result.
unsigned getPriority() const { return Priority; }
/// \brief Retrieve the availability of this code completion result.
unsigned getAvailability() const { return Availability; }
/// \brief Retrieve the number of annotations for this code completion result.
unsigned getAnnotationCount() const;
/// \brief Retrieve the annotation string specified by \c AnnotationNr.
const char *getAnnotation(unsigned AnnotationNr) const;
/// \brief Retrieve the name of the parent context.
StringRef getParentContextName() const {
return ParentName;
}
const char *getBriefComment() const {
return BriefComment;
}
/// \brief Retrieve a string representation of the code completion string,
/// which is mainly useful for debugging.
std::string getAsString() const;
};
/// \brief An allocator used specifically for the purpose of code completion.
class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
public:
/// \brief Copy the given string into this allocator.
const char *CopyString(const Twine &String);
};
/// \brief Allocator for a cached set of global code completions.
class GlobalCodeCompletionAllocator
: public CodeCompletionAllocator,
public RefCountedBase<GlobalCodeCompletionAllocator>
{
};
class CodeCompletionTUInfo {
llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> AllocatorRef;
public:
explicit CodeCompletionTUInfo(
IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> Allocator)
: AllocatorRef(Allocator) { }
IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
return AllocatorRef;
}
CodeCompletionAllocator &getAllocator() const {
assert(AllocatorRef);
return *AllocatorRef;
}
StringRef getParentName(const DeclContext *DC);
};
} // end namespace clang
namespace llvm {
template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
static const bool value = true;
};
}
namespace clang {
/// \brief A builder class used to construct new code-completion strings.
class CodeCompletionBuilder {
public:
typedef CodeCompletionString::Chunk Chunk;
private:
CodeCompletionAllocator &Allocator;
CodeCompletionTUInfo &CCTUInfo;
unsigned Priority;
CXAvailabilityKind Availability;
StringRef ParentName;
const char *BriefComment;
/// \brief The chunks stored in this string.
SmallVector<Chunk, 4> Chunks;
SmallVector<const char *, 2> Annotations;
public:
CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo)
: Allocator(Allocator), CCTUInfo(CCTUInfo),
Priority(0), Availability(CXAvailability_Available),
BriefComment(nullptr) { }
CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
unsigned Priority, CXAvailabilityKind Availability)
: Allocator(Allocator), CCTUInfo(CCTUInfo),
Priority(Priority), Availability(Availability),
BriefComment(nullptr) { }
/// \brief Retrieve the allocator into which the code completion
/// strings should be allocated.
CodeCompletionAllocator &getAllocator() const { return Allocator; }
CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
/// \brief Take the resulting completion string.
///
/// This operation can only be performed once.
CodeCompletionString *TakeString();
/// \brief Add a new typed-text chunk.
void AddTypedTextChunk(const char *Text);
/// \brief Add a new text chunk.
void AddTextChunk(const char *Text);
/// \brief Add a new optional chunk.
void AddOptionalChunk(CodeCompletionString *Optional);
/// \brief Add a new placeholder chunk.
void AddPlaceholderChunk(const char *Placeholder);
/// \brief Add a new informative chunk.
void AddInformativeChunk(const char *Text);
/// \brief Add a new result-type chunk.
void AddResultTypeChunk(const char *ResultType);
/// \brief Add a new current-parameter chunk.
void AddCurrentParameterChunk(const char *CurrentParameter);
/// \brief Add a new chunk.
void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
void AddAnnotation(const char *A) { Annotations.push_back(A); }
/// \brief Add the parent context information to this code completion.
void addParentContext(const DeclContext *DC);
const char *getBriefComment() const { return BriefComment; }
void addBriefComment(StringRef Comment);
StringRef getParentName() const { return ParentName; }
};
/// \brief Captures a result of code completion.
class CodeCompletionResult {
public:
/// \brief Describes the kind of result generated.
enum ResultKind {
RK_Declaration = 0, ///< Refers to a declaration
RK_Keyword, ///< Refers to a keyword or symbol.
RK_Macro, ///< Refers to a macro
RK_Pattern ///< Refers to a precomputed pattern.
};
/// \brief When Kind == RK_Declaration or RK_Pattern, the declaration we are
/// referring to. In the latter case, the declaration might be NULL.
const NamedDecl *Declaration;
union {
/// \brief When Kind == RK_Keyword, the string representing the keyword
/// or symbol's spelling.
const char *Keyword;
/// \brief When Kind == RK_Pattern, the code-completion string that
/// describes the completion text to insert.
CodeCompletionString *Pattern;
/// \brief When Kind == RK_Macro, the identifier that refers to a macro.
const IdentifierInfo *Macro;
};
/// \brief The priority of this particular code-completion result.
unsigned Priority;
/// \brief Specifies which parameter (of a function, Objective-C method,
/// macro, etc.) we should start with when formatting the result.
unsigned StartParameter;
/// \brief The kind of result stored here.
ResultKind Kind;
/// \brief The cursor kind that describes this result.
CXCursorKind CursorKind;
/// \brief The availability of this result.
CXAvailabilityKind Availability;
/// \brief Whether this result is hidden by another name.
bool Hidden : 1;
/// \brief Whether this result was found via lookup into a base class.
bool QualifierIsInformative : 1;
/// \brief Whether this declaration is the beginning of a
/// nested-name-specifier and, therefore, should be followed by '::'.
bool StartsNestedNameSpecifier : 1;
/// \brief Whether all parameters (of a function, Objective-C
/// method, etc.) should be considered "informative".
bool AllParametersAreInformative : 1;
/// \brief Whether we're completing a declaration of the given entity,
/// rather than a use of that entity.
bool DeclaringEntity : 1;
/// \brief If the result should have a nested-name-specifier, this is it.
/// When \c QualifierIsInformative, the nested-name-specifier is
/// informative rather than required.
NestedNameSpecifier *Qualifier;
/// \brief Build a result that refers to a declaration.
CodeCompletionResult(const NamedDecl *Declaration,
unsigned Priority,
NestedNameSpecifier *Qualifier = nullptr,
bool QualifierIsInformative = false,
bool Accessible = true)
: Declaration(Declaration), Priority(Priority),
StartParameter(0), Kind(RK_Declaration),
Availability(CXAvailability_Available), Hidden(false),
QualifierIsInformative(QualifierIsInformative),
StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
DeclaringEntity(false), Qualifier(Qualifier) {
computeCursorKindAndAvailability(Accessible);
}
/// \brief Build a result that refers to a keyword or symbol.
CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
: Declaration(nullptr), Keyword(Keyword), Priority(Priority),
StartParameter(0), Kind(RK_Keyword), CursorKind(CXCursor_NotImplemented),
Availability(CXAvailability_Available), Hidden(false),
QualifierIsInformative(0), StartsNestedNameSpecifier(false),
AllParametersAreInformative(false), DeclaringEntity(false),
Qualifier(nullptr) {}
/// \brief Build a result that refers to a macro.
CodeCompletionResult(const IdentifierInfo *Macro,
unsigned Priority = CCP_Macro)
: Declaration(nullptr), Macro(Macro), Priority(Priority), StartParameter(0),
Kind(RK_Macro), CursorKind(CXCursor_MacroDefinition),
Availability(CXAvailability_Available), Hidden(false),
QualifierIsInformative(0), StartsNestedNameSpecifier(false),
AllParametersAreInformative(false), DeclaringEntity(false),
Qualifier(nullptr) {}
/// \brief Build a result that refers to a pattern.
CodeCompletionResult(CodeCompletionString *Pattern,
unsigned Priority = CCP_CodePattern,
CXCursorKind CursorKind = CXCursor_NotImplemented,
CXAvailabilityKind Availability = CXAvailability_Available,
const NamedDecl *D = nullptr)
: Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
Kind(RK_Pattern), CursorKind(CursorKind), Availability(Availability),
Hidden(false), QualifierIsInformative(0),
StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
DeclaringEntity(false), Qualifier(nullptr)
{
}
/// \brief Build a result that refers to a pattern with an associated
/// declaration.
CodeCompletionResult(CodeCompletionString *Pattern, NamedDecl *D,
unsigned Priority)
: Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
Kind(RK_Pattern), Availability(CXAvailability_Available), Hidden(false),
QualifierIsInformative(false), StartsNestedNameSpecifier(false),
AllParametersAreInformative(false), DeclaringEntity(false),
Qualifier(nullptr) {
computeCursorKindAndAvailability();
}
/// \brief Retrieve the declaration stored in this result.
const NamedDecl *getDeclaration() const {
assert(Kind == RK_Declaration && "Not a declaration result");
return Declaration;
}
/// \brief Retrieve the keyword stored in this result.
const char *getKeyword() const {
assert(Kind == RK_Keyword && "Not a keyword result");
return Keyword;
}
/// \brief Create a new code-completion string that describes how to insert
/// this result into a program.
///
/// \param S The semantic analysis that created the result.
///
/// \param Allocator The allocator that will be used to allocate the
/// string itself.
CodeCompletionString *CreateCodeCompletionString(Sema &S,
const CodeCompletionContext &CCContext,
CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
bool IncludeBriefComments);
CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
Preprocessor &PP,
const CodeCompletionContext &CCContext,
CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
bool IncludeBriefComments);
private:
void computeCursorKindAndAvailability(bool Accessible = true);
};
bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
inline bool operator>(const CodeCompletionResult &X,
const CodeCompletionResult &Y) {
return Y < X;
}
inline bool operator<=(const CodeCompletionResult &X,
const CodeCompletionResult &Y) {
return !(Y < X);
}
inline bool operator>=(const CodeCompletionResult &X,
const CodeCompletionResult &Y) {
return !(X < Y);
}
raw_ostream &operator<<(raw_ostream &OS,
const CodeCompletionString &CCS);
/// \brief Abstract interface for a consumer of code-completion
/// information.
class CodeCompleteConsumer {
protected:
const CodeCompleteOptions CodeCompleteOpts;
/// \brief Whether the output format for the code-completion consumer is
/// binary.
bool OutputIsBinary;
public:
class OverloadCandidate {
public:
/// \brief Describes the type of overload candidate.
enum CandidateKind {
/// \brief The candidate is a function declaration.
CK_Function,
/// \brief The candidate is a function template.
CK_FunctionTemplate,
/// \brief The "candidate" is actually a variable, expression, or block
/// for which we only have a function prototype.
CK_FunctionType
};
private:
/// \brief The kind of overload candidate.
CandidateKind Kind;
union {
/// \brief The function overload candidate, available when
/// Kind == CK_Function.
FunctionDecl *Function;
/// \brief The function template overload candidate, available when
/// Kind == CK_FunctionTemplate.
FunctionTemplateDecl *FunctionTemplate;
/// \brief The function type that describes the entity being called,
/// when Kind == CK_FunctionType.
const FunctionType *Type;
};
public:
OverloadCandidate(FunctionDecl *Function)
: Kind(CK_Function), Function(Function) { }
OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
: Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
OverloadCandidate(const FunctionType *Type)
: Kind(CK_FunctionType), Type(Type) { }
/// \brief Determine the kind of overload candidate.
CandidateKind getKind() const { return Kind; }
/// \brief Retrieve the function overload candidate or the templated
/// function declaration for a function template.
FunctionDecl *getFunction() const;
/// \brief Retrieve the function template overload candidate.
FunctionTemplateDecl *getFunctionTemplate() const {
assert(getKind() == CK_FunctionTemplate && "Not a function template");
return FunctionTemplate;
}
/// \brief Retrieve the function type of the entity, regardless of how the
/// function is stored.
const FunctionType *getFunctionType() const;
/// \brief Create a new code-completion string that describes the function
/// signature of this overload candidate.
CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
Sema &S,
CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
bool IncludeBriefComments) const;
};
CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
bool OutputIsBinary)
: CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary)
{ }
/// \brief Whether the code-completion consumer wants to see macros.
bool includeMacros() const {
return CodeCompleteOpts.IncludeMacros;
}
/// \brief Whether the code-completion consumer wants to see code patterns.
bool includeCodePatterns() const {
return CodeCompleteOpts.IncludeCodePatterns;
}
/// \brief Whether to include global (top-level) declaration results.
bool includeGlobals() const {
return CodeCompleteOpts.IncludeGlobals;
}
/// \brief Whether to include brief documentation comments within the set of
/// code completions returned.
bool includeBriefComments() const {
return CodeCompleteOpts.IncludeBriefComments;
}
/// \brief Determine whether the output of this consumer is binary.
bool isOutputBinary() const { return OutputIsBinary; }
/// \brief Deregisters and destroys this code-completion consumer.
virtual ~CodeCompleteConsumer();
/// \name Code-completion callbacks
//@{
/// \brief Process the finalized code-completion results.
virtual void ProcessCodeCompleteResults(Sema &S,
CodeCompletionContext Context,
CodeCompletionResult *Results,
unsigned NumResults) { }
/// \param S the semantic-analyzer object for which code-completion is being
/// done.
///
/// \param CurrentArg the index of the current argument.
///
/// \param Candidates an array of overload candidates.
///
/// \param NumCandidates the number of overload candidates
virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
OverloadCandidate *Candidates,
unsigned NumCandidates) { }
//@}
/// \brief Retrieve the allocator that will be used to allocate
/// code completion strings.
virtual CodeCompletionAllocator &getAllocator() = 0;
virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
};
/// \brief A simple code-completion consumer that prints the results it
/// receives in a simple format.
class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
/// \brief The raw output stream.
raw_ostream &OS;
CodeCompletionTUInfo CCTUInfo;
public:
/// \brief Create a new printing code-completion consumer that prints its
/// results to the given raw output stream.
PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
raw_ostream &OS)
: CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
CCTUInfo(new GlobalCodeCompletionAllocator) {}
/// \brief Prints the finalized code-completion results.
void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
CodeCompletionResult *Results,
unsigned NumResults) override;
void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
OverloadCandidate *Candidates,
unsigned NumCandidates) override;
CodeCompletionAllocator &getAllocator() override {
return CCTUInfo.getAllocator();
}
CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
};
} // end namespace clang
#endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/SemaInternal.h | //===--- SemaInternal.h - Internal Sema Interfaces --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides common API and #includes for the internal
// implementation of Sema.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H
#define LLVM_CLANG_SEMA_SEMAINTERNAL_H
#include "clang/AST/ASTContext.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"
namespace clang {
inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
return PartialDiagnostic(DiagID, Context.getDiagAllocator());
}
inline bool
FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) {
return FTI.NumParams == 1 && !FTI.isVariadic &&
FTI.Params[0].Ident == nullptr && FTI.Params[0].Param &&
cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType();
}
inline bool
FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
// Assume FTI is well-formed.
return FTI.NumParams && !FTIHasSingleVoidParameter(FTI);
}
// This requires the variable to be non-dependent and the initializer
// to not be value dependent.
inline bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context) {
const VarDecl *DefVD = nullptr;
return !isa<ParmVarDecl>(Var) &&
Var->isUsableInConstantExpressions(Context) &&
Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE();
}
// Helper function to check whether D's attributes match current CUDA mode.
// Decls with mismatched attributes and related diagnostics may have to be
// ignored during this CUDA compilation pass.
inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
if (!LangOpts.CUDA || !D)
return true;
bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
D->hasAttr<CUDASharedAttr>() ||
D->hasAttr<CUDAGlobalAttr>();
return isDeviceSideDecl == LangOpts.CUDAIsDevice;
}
// Directly mark a variable odr-used. Given a choice, prefer to use
// MarkVariableReferenced since it does additional checks and then
// calls MarkVarDeclODRUsed.
// If the variable must be captured:
// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
// - else capture it in the DeclContext that maps to the
// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
inline void MarkVarDeclODRUsed(VarDecl *Var,
SourceLocation Loc, Sema &SemaRef,
const unsigned *const FunctionScopeIndexToStopAt) {
// Keep track of used but undefined variables.
// FIXME: We shouldn't suppress this warning for static data members.
if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
!Var->isExternallyVisible() &&
!(Var->isStaticDataMember() && Var->hasInit())) {
SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
if (old.isInvalid()) old = Loc;
}
QualType CaptureType, DeclRefType;
SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
/*EllipsisLoc*/ SourceLocation(),
/*BuildAndDiagnose*/ true,
CaptureType, DeclRefType,
FunctionScopeIndexToStopAt);
Var->markUsed(SemaRef.Context);
}
/// Return a DLL attribute from the declaration.
inline InheritableAttr *getDLLAttr(Decl *D) {
assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
"A declaration cannot be both dllimport and dllexport.");
if (auto *Import = D->getAttr<DLLImportAttr>())
return Import;
if (auto *Export = D->getAttr<DLLExportAttr>())
return Export;
return nullptr;
}
class TypoCorrectionConsumer : public VisibleDeclConsumer {
typedef SmallVector<TypoCorrection, 1> TypoResultList;
typedef llvm::StringMap<TypoResultList> TypoResultsMap;
typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
public:
TypoCorrectionConsumer(Sema &SemaRef,
const DeclarationNameInfo &TypoName,
Sema::LookupNameKind LookupKind,
Scope *S, CXXScopeSpec *SS,
std::unique_ptr<CorrectionCandidateCallback> CCC,
DeclContext *MemberContext,
bool EnteringContext)
: Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
SavedTCIndex(0), SemaRef(SemaRef), S(S),
SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
Result(SemaRef, TypoName, LookupKind),
Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
EnteringContext(EnteringContext), SearchNamespaces(false) {
Result.suppressDiagnostics();
// Arrange for ValidatedCorrections[0] to always be an empty correction.
ValidatedCorrections.push_back(TypoCorrection());
}
bool includeHiddenDecls() const override { return true; }
// Methods for adding potential corrections to the consumer.
void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
bool InBaseClass) override;
void FoundName(StringRef Name);
void addKeywordResult(StringRef Keyword);
void addCorrection(TypoCorrection Correction);
bool empty() const {
return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
}
/// \brief Return the list of TypoCorrections for the given identifier from
/// the set of corrections that have the closest edit distance, if any.
TypoResultList &operator[](StringRef Name) {
return CorrectionResults.begin()->second[Name];
}
/// \brief Return the edit distance of the corrections that have the
/// closest/best edit distance from the original typop.
unsigned getBestEditDistance(bool Normalized) {
if (CorrectionResults.empty())
return (std::numeric_limits<unsigned>::max)();
unsigned BestED = CorrectionResults.begin()->first;
return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
}
/// \brief Set-up method to add to the consumer the set of namespaces to use
/// in performing corrections to nested name specifiers. This method also
/// implicitly adds all of the known classes in the current AST context to the
/// to the consumer for correcting nested name specifiers.
void
addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
/// \brief Return the next typo correction that passes all internal filters
/// and is deemed valid by the consumer's CorrectionCandidateCallback,
/// starting with the corrections that have the closest edit distance. An
/// empty TypoCorrection is returned once no more viable corrections remain
/// in the consumer.
const TypoCorrection &getNextCorrection();
/// \brief Get the last correction returned by getNextCorrection().
const TypoCorrection &getCurrentCorrection() {
return CurrentTCIndex < ValidatedCorrections.size()
? ValidatedCorrections[CurrentTCIndex]
: ValidatedCorrections[0]; // The empty correction.
}
/// \brief Return the next typo correction like getNextCorrection, but keep
/// the internal state pointed to the current correction (i.e. the next time
/// getNextCorrection is called, it will return the same correction returned
/// by peekNextcorrection).
const TypoCorrection &peekNextCorrection() {
auto Current = CurrentTCIndex;
const TypoCorrection &TC = getNextCorrection();
CurrentTCIndex = Current;
return TC;
}
/// \brief Reset the consumer's position in the stream of viable corrections
/// (i.e. getNextCorrection() will return each of the previously returned
/// corrections in order before returning any new corrections).
void resetCorrectionStream() {
CurrentTCIndex = 0;
}
/// \brief Return whether the end of the stream of corrections has been
/// reached.
bool finished() {
return CorrectionResults.empty() &&
CurrentTCIndex >= ValidatedCorrections.size();
}
/// \brief Save the current position in the correction stream (overwriting any
/// previously saved position).
void saveCurrentPosition() {
SavedTCIndex = CurrentTCIndex;
}
/// \brief Restore the saved position in the correction stream.
void restoreSavedPosition() {
CurrentTCIndex = SavedTCIndex;
}
ASTContext &getContext() const { return SemaRef.Context; }
const LookupResult &getLookupResult() const { return Result; }
bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
const CXXScopeSpec *getSS() const { return SS.get(); }
Scope *getScope() const { return S; }
private:
class NamespaceSpecifierSet {
struct SpecifierInfo {
DeclContext* DeclCtx;
NestedNameSpecifier* NameSpecifier;
unsigned EditDistance;
};
typedef SmallVector<DeclContext*, 4> DeclContextList;
typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
ASTContext &Context;
DeclContextList CurContextChain;
std::string CurNameSpecifier;
SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
std::map<unsigned, SpecifierInfoList> DistanceMap;
/// \brief Helper for building the list of DeclContexts between the current
/// context and the top of the translation unit
static DeclContextList buildContextChain(DeclContext *Start);
unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
NestedNameSpecifier *&NNS);
public:
NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
CXXScopeSpec *CurScopeSpec);
/// \brief Add the DeclContext (a namespace or record) to the set, computing
/// the corresponding NestedNameSpecifier and its distance in the process.
void addNameSpecifier(DeclContext *Ctx);
/// \brief Provides flat iteration over specifiers, sorted by distance.
class iterator
: public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
SpecifierInfo> {
/// Always points to the last element in the distance map.
const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
/// Iterator on the distance map.
std::map<unsigned, SpecifierInfoList>::iterator Outer;
/// Iterator on an element in the distance map.
SpecifierInfoList::iterator Inner;
public:
iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
: OuterBack(std::prev(Set.DistanceMap.end())),
Outer(Set.DistanceMap.begin()),
Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
assert(!Set.DistanceMap.empty());
}
iterator &operator++() {
++Inner;
if (Inner == Outer->second.end() && Outer != OuterBack) {
++Outer;
Inner = Outer->second.begin();
}
return *this;
}
SpecifierInfo &operator*() { return *Inner; }
bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
};
iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
};
void addName(StringRef Name, NamedDecl *ND,
NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
/// \brief Find any visible decls for the given typo correction candidate.
/// If none are found, it to the set of candidates for which qualified lookups
/// will be performed to find possible nested name specifier changes.
bool resolveCorrection(TypoCorrection &Candidate);
/// \brief Perform qualified lookups on the queued set of typo correction
/// candidates and add the nested name specifier changes to each candidate if
/// a lookup succeeds (at which point the candidate will be returned to the
/// main pool of potential corrections).
void performQualifiedLookups();
/// \brief The name written that is a typo in the source.
IdentifierInfo *Typo;
/// \brief The results found that have the smallest edit distance
/// found (so far) with the typo name.
///
/// The pointer value being set to the current DeclContext indicates
/// whether there is a keyword with this name.
TypoEditDistanceMap CorrectionResults;
SmallVector<TypoCorrection, 4> ValidatedCorrections;
size_t CurrentTCIndex;
size_t SavedTCIndex;
Sema &SemaRef;
Scope *S;
std::unique_ptr<CXXScopeSpec> SS;
std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
DeclContext *MemberContext;
LookupResult Result;
NamespaceSpecifierSet Namespaces;
SmallVector<TypoCorrection, 2> QualifiedResults;
bool EnteringContext;
bool SearchNamespaces;
};
inline Sema::TypoExprState::TypoExprState() {}
inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) LLVM_NOEXCEPT {
*this = std::move(other);
}
inline Sema::TypoExprState &Sema::TypoExprState::operator=(
Sema::TypoExprState &&other) LLVM_NOEXCEPT {
Consumer = std::move(other.Consumer);
DiagHandler = std::move(other.DiagHandler);
RecoveryHandler = std::move(other.RecoveryHandler);
return *this;
}
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/Overload.h | //===--- Overload.h - C++ Overloading ---------------------------*- 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 data structures and types used in C++
// overload resolution.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_OVERLOAD_H
#define LLVM_CLANG_SEMA_OVERLOAD_H
#include "clang/AST/Decl.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/Type.h"
#include "clang/AST/UnresolvedSet.h"
#include "clang/Sema/SemaFixItUtils.h"
#include "clang/Sema/TemplateDeduction.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/AlignOf.h"
#include "llvm/Support/Allocator.h"
namespace clang {
class ASTContext;
class CXXConstructorDecl;
class CXXConversionDecl;
class FunctionDecl;
class Sema;
/// OverloadingResult - Capture the result of performing overload
/// resolution.
enum OverloadingResult {
OR_Success, ///< Overload resolution succeeded.
OR_No_Viable_Function, ///< No viable function found.
OR_Ambiguous, ///< Ambiguous candidates found.
OR_Deleted ///< Succeeded, but refers to a deleted function.
};
enum OverloadCandidateDisplayKind {
/// Requests that all candidates be shown. Viable candidates will
/// be printed first.
OCD_AllCandidates,
/// Requests that only viable candidates be shown.
OCD_ViableCandidates
};
/// ImplicitConversionKind - The kind of implicit conversion used to
/// convert an argument to a parameter's type. The enumerator values
/// match with Table 9 of (C++ 13.3.3.1.1) and are listed such that
/// better conversion kinds have smaller values.
enum ImplicitConversionKind {
ICK_Identity = 0, ///< Identity conversion (no conversion)
ICK_Lvalue_To_Rvalue, ///< Lvalue-to-rvalue conversion (C++ 4.1)
ICK_Array_To_Pointer, ///< Array-to-pointer conversion (C++ 4.2)
ICK_Function_To_Pointer, ///< Function-to-pointer (C++ 4.3)
ICK_NoReturn_Adjustment, ///< Removal of noreturn from a type (Clang)
ICK_Qualification, ///< Qualification conversions (C++ 4.4)
ICK_Integral_Promotion, ///< Integral promotions (C++ 4.5)
ICK_Floating_Promotion, ///< Floating point promotions (C++ 4.6)
ICK_Complex_Promotion, ///< Complex promotions (Clang extension)
ICK_Integral_Conversion, ///< Integral conversions (C++ 4.7)
ICK_Floating_Conversion, ///< Floating point conversions (C++ 4.8)
ICK_Complex_Conversion, ///< Complex conversions (C99 6.3.1.6)
ICK_Floating_Integral, ///< Floating-integral conversions (C++ 4.9)
ICK_Pointer_Conversion, ///< Pointer conversions (C++ 4.10)
ICK_Pointer_Member, ///< Pointer-to-member conversions (C++ 4.11)
ICK_Boolean_Conversion, ///< Boolean conversions (C++ 4.12)
ICK_Compatible_Conversion, ///< Conversions between compatible types in C99
ICK_Derived_To_Base, ///< Derived-to-base (C++ [over.best.ics])
ICK_Vector_Conversion, ///< Vector conversions
ICK_Vector_Splat, ///< A vector splat from an arithmetic type
ICK_Complex_Real, ///< Complex-real conversions (C99 6.3.1.7)
ICK_Block_Pointer_Conversion, ///< Block Pointer conversions
ICK_TransparentUnionConversion, ///< Transparent Union Conversions
ICK_Writeback_Conversion, ///< Objective-C ARC writeback conversion
ICK_Zero_Event_Conversion, ///< Zero constant to event (OpenCL1.2 6.12.10)
// HLSL Change Starts
// The following conversion types also imply a potential followup
// ComponentConversion.
// List is roughly ordered to preserve the property:
// "better conversion kinds have smaller values"
// Unfortunately, this property isn't really possible to preserve due
// to potential additional component conversion.
ICK_HLSLVector_Scalar, ///< HLSLVector/Matrix to scalar
ICK_HLSLVector_Conversion, ///< HLSLVector/Matrix conversion
ICK_Flat_Conversion, ///< Flat assignment conversion for HLSL (inline conversion, straddled)
ICK_HLSLVector_Splat, ///< HLSLVector/Matrix splat
ICK_HLSLVector_Truncation, ///< HLSLVector/Matrix truncation
ICK_HLSL_Derived_To_Base, ///< HLSL Derived-to-base
// HLSL Change Ends
ICK_Num_Conversion_Kinds ///< The number of conversion kinds
};
/// ImplicitConversionRank - The rank of an implicit conversion
/// kind. The enumerator values match with Table 9 of (C++
/// 13.3.3.1.1) and are listed such that better conversion ranks
/// have smaller values.
enum ImplicitConversionRank {
ICR_Exact_Match = 0, ///< Exact Match
ICR_Promotion, ///< Promotion
ICR_Conversion, ///< Conversion
ICR_Complex_Real_Conversion, ///< Complex <-> Real conversion
ICR_Writeback_Conversion ///< ObjC ARC writeback conversion
};
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind);
/// NarrowingKind - The kind of narrowing conversion being performed by a
/// standard conversion sequence according to C++11 [dcl.init.list]p7.
enum NarrowingKind {
/// Not a narrowing conversion.
NK_Not_Narrowing,
/// A narrowing conversion by virtue of the source and destination types.
NK_Type_Narrowing,
/// A narrowing conversion, because a constant expression got narrowed.
NK_Constant_Narrowing,
/// A narrowing conversion, because a non-constant-expression variable might
/// have got narrowed.
NK_Variable_Narrowing
};
/// StandardConversionSequence - represents a standard conversion
/// sequence (C++ 13.3.3.1.1). A standard conversion sequence
/// contains between zero and three conversions. If a particular
/// conversion is not needed, it will be set to the identity conversion
/// (ICK_Identity). Note that the three conversions are
/// specified as separate members (rather than in an array) so that
/// we can keep the size of a standard conversion sequence to a
/// single word.
class StandardConversionSequence {
public:
/// First -- The first conversion can be an lvalue-to-rvalue
/// conversion, array-to-pointer conversion, or
/// function-to-pointer conversion.
ImplicitConversionKind First : 8;
/// Second - The second conversion can be an integral promotion,
/// floating point promotion, integral conversion, floating point
/// conversion, floating-integral conversion, pointer conversion,
/// pointer-to-member conversion, or boolean conversion.
ImplicitConversionKind Second : 8;
// HLSL Change Starts
/// ComponentConversion - If this is not ICK_Identity, this describes
/// the type of conversion to apply to the component type of an HLSL
/// vector or matrix type. If used, Second must be one of the
/// ICK_HLSLVector_* implicit conversion kinds.
ImplicitConversionKind ComponentConversion : 8;
// HLSL Change Ends
/// Third - The third conversion can be a qualification conversion.
ImplicitConversionKind Third : 8;
/// \brief Whether this is the deprecated conversion of a
/// string literal to a pointer to non-const character data
/// (C++ 4.2p2).
unsigned DeprecatedStringLiteralToCharPtr : 1;
/// \brief Whether the qualification conversion involves a change in the
/// Objective-C lifetime (for automatic reference counting).
unsigned QualificationIncludesObjCLifetime : 1;
/// IncompatibleObjC - Whether this is an Objective-C conversion
/// that we should warn about (if we actually use it).
unsigned IncompatibleObjC : 1;
/// ReferenceBinding - True when this is a reference binding
/// (C++ [over.ics.ref]).
unsigned ReferenceBinding : 1;
/// DirectBinding - True when this is a reference binding that is a
/// direct binding (C++ [dcl.init.ref]).
unsigned DirectBinding : 1;
/// \brief Whether this is an lvalue reference binding (otherwise, it's
/// an rvalue reference binding).
unsigned IsLvalueReference : 1;
/// \brief Whether we're binding to a function lvalue.
unsigned BindsToFunctionLvalue : 1;
/// \brief Whether we're binding to an rvalue.
unsigned BindsToRvalue : 1;
/// \brief Whether this binds an implicit object argument to a
/// non-static member function without a ref-qualifier.
unsigned BindsImplicitObjectArgumentWithoutRefQualifier : 1;
/// \brief Whether this binds a reference to an object with a different
/// Objective-C lifetime qualifier.
unsigned ObjCLifetimeConversionBinding : 1;
/// FromType - The type that this conversion is converting
/// from. This is an opaque pointer that can be translated into a
/// QualType.
void *FromTypePtr;
/// ToType - The types that this conversion is converting to in
/// each step. This is an opaque pointer that can be translated
/// into a QualType.
void *ToTypePtrs[3];
/// CopyConstructor - The copy constructor that is used to perform
/// this conversion, when the conversion is actually just the
/// initialization of an object via copy constructor. Such
/// conversions are either identity conversions or derived-to-base
/// conversions.
CXXConstructorDecl *CopyConstructor;
void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
void setToType(unsigned Idx, QualType T) {
assert(Idx < 3 && "To type index is out of range");
ToTypePtrs[Idx] = T.getAsOpaquePtr();
}
void setAllToTypes(QualType T) {
ToTypePtrs[0] = T.getAsOpaquePtr();
ToTypePtrs[1] = ToTypePtrs[0];
ToTypePtrs[2] = ToTypePtrs[0];
}
QualType getFromType() const {
return QualType::getFromOpaquePtr(FromTypePtr);
}
QualType getToType(unsigned Idx) const {
assert(Idx < 3 && "To type index is out of range");
return QualType::getFromOpaquePtr(ToTypePtrs[Idx]);
}
void setAsIdentityConversion();
bool isIdentityConversion() const {
return Second == ICK_Identity && Third == ICK_Identity;
}
ImplicitConversionRank getRank() const;
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted,
APValue &ConstantValue,
QualType &ConstantType) const;
bool isPointerConversionToBool() const;
bool isPointerConversionToVoidPointer(ASTContext& Context) const;
void dump() const;
};
/// UserDefinedConversionSequence - Represents a user-defined
/// conversion sequence (C++ 13.3.3.1.2).
struct UserDefinedConversionSequence {
/// \brief Represents the standard conversion that occurs before
/// the actual user-defined conversion.
///
/// C++11 13.3.3.1.2p1:
/// If the user-defined conversion is specified by a constructor
/// (12.3.1), the initial standard conversion sequence converts
/// the source type to the type required by the argument of the
/// constructor. If the user-defined conversion is specified by
/// a conversion function (12.3.2), the initial standard
/// conversion sequence converts the source type to the implicit
/// object parameter of the conversion function.
StandardConversionSequence Before;
/// EllipsisConversion - When this is true, it means user-defined
/// conversion sequence starts with a ... (ellipsis) conversion, instead of
/// a standard conversion. In this case, 'Before' field must be ignored.
// FIXME. I much rather put this as the first field. But there seems to be
// a gcc code gen. bug which causes a crash in a test. Putting it here seems
// to work around the crash.
bool EllipsisConversion : 1;
/// HadMultipleCandidates - When this is true, it means that the
/// conversion function was resolved from an overloaded set having
/// size greater than 1.
bool HadMultipleCandidates : 1;
/// After - Represents the standard conversion that occurs after
/// the actual user-defined conversion.
StandardConversionSequence After;
/// ConversionFunction - The function that will perform the
/// user-defined conversion. Null if the conversion is an
/// aggregate initialization from an initializer list.
FunctionDecl* ConversionFunction;
/// \brief The declaration that we found via name lookup, which might be
/// the same as \c ConversionFunction or it might be a using declaration
/// that refers to \c ConversionFunction.
DeclAccessPair FoundConversionFunction;
void dump() const;
};
/// Represents an ambiguous user-defined conversion sequence.
struct AmbiguousConversionSequence {
typedef SmallVector<FunctionDecl*, 4> ConversionSet;
void *FromTypePtr;
void *ToTypePtr;
char Buffer[sizeof(ConversionSet)];
QualType getFromType() const {
return QualType::getFromOpaquePtr(FromTypePtr);
}
QualType getToType() const {
return QualType::getFromOpaquePtr(ToTypePtr);
}
void setFromType(QualType T) { FromTypePtr = T.getAsOpaquePtr(); }
void setToType(QualType T) { ToTypePtr = T.getAsOpaquePtr(); }
ConversionSet &conversions() {
return *reinterpret_cast<ConversionSet*>(Buffer);
}
const ConversionSet &conversions() const {
return *reinterpret_cast<const ConversionSet*>(Buffer);
}
void addConversion(FunctionDecl *D) {
conversions().push_back(D);
}
typedef ConversionSet::iterator iterator;
iterator begin() { return conversions().begin(); }
iterator end() { return conversions().end(); }
typedef ConversionSet::const_iterator const_iterator;
const_iterator begin() const { return conversions().begin(); }
const_iterator end() const { return conversions().end(); }
void construct();
void destruct();
void copyFrom(const AmbiguousConversionSequence &);
};
/// BadConversionSequence - Records information about an invalid
/// conversion sequence.
struct BadConversionSequence {
enum FailureKind {
no_conversion,
unrelated_class,
bad_qualifiers,
lvalue_ref_to_rvalue,
rvalue_ref_to_lvalue
};
// This can be null, e.g. for implicit object arguments.
Expr *FromExpr;
FailureKind Kind;
private:
// The type we're converting from (an opaque QualType).
void *FromTy;
// The type we're converting to (an opaque QualType).
void *ToTy;
public:
void init(FailureKind K, Expr *From, QualType To) {
init(K, From->getType(), To);
FromExpr = From;
}
void init(FailureKind K, QualType From, QualType To) {
Kind = K;
FromExpr = nullptr;
setFromType(From);
setToType(To);
}
QualType getFromType() const { return QualType::getFromOpaquePtr(FromTy); }
QualType getToType() const { return QualType::getFromOpaquePtr(ToTy); }
void setFromExpr(Expr *E) {
FromExpr = E;
setFromType(E->getType());
}
void setFromType(QualType T) { FromTy = T.getAsOpaquePtr(); }
void setToType(QualType T) { ToTy = T.getAsOpaquePtr(); }
};
/// ImplicitConversionSequence - Represents an implicit conversion
/// sequence, which may be a standard conversion sequence
/// (C++ 13.3.3.1.1), user-defined conversion sequence (C++ 13.3.3.1.2),
/// or an ellipsis conversion sequence (C++ 13.3.3.1.3).
class ImplicitConversionSequence {
public:
/// Kind - The kind of implicit conversion sequence. BadConversion
/// specifies that there is no conversion from the source type to
/// the target type. AmbiguousConversion represents the unique
/// ambiguous conversion (C++0x [over.best.ics]p10).
enum Kind {
StandardConversion = 0,
UserDefinedConversion,
AmbiguousConversion,
EllipsisConversion,
BadConversion
};
private:
enum {
Uninitialized = BadConversion + 1
};
/// ConversionKind - The kind of implicit conversion sequence.
unsigned ConversionKind : 30;
/// \brief Whether the target is really a std::initializer_list, and the
/// sequence only represents the worst element conversion.
bool StdInitializerListElement : 1;
void setKind(Kind K) {
destruct();
ConversionKind = K;
}
void destruct() {
if (ConversionKind == AmbiguousConversion) Ambiguous.destruct();
}
public:
union {
/// When ConversionKind == StandardConversion, provides the
/// details of the standard conversion sequence.
StandardConversionSequence Standard;
/// When ConversionKind == UserDefinedConversion, provides the
/// details of the user-defined conversion sequence.
UserDefinedConversionSequence UserDefined;
/// When ConversionKind == AmbiguousConversion, provides the
/// details of the ambiguous conversion.
AmbiguousConversionSequence Ambiguous;
/// When ConversionKind == BadConversion, provides the details
/// of the bad conversion.
BadConversionSequence Bad;
};
ImplicitConversionSequence()
: ConversionKind(Uninitialized), StdInitializerListElement(false)
{}
~ImplicitConversionSequence() {
destruct();
}
ImplicitConversionSequence(const ImplicitConversionSequence &Other)
: ConversionKind(Other.ConversionKind),
StdInitializerListElement(Other.StdInitializerListElement)
{
switch (ConversionKind) {
case Uninitialized: break;
case StandardConversion: Standard = Other.Standard; break;
case UserDefinedConversion: UserDefined = Other.UserDefined; break;
case AmbiguousConversion: Ambiguous.copyFrom(Other.Ambiguous); break;
case EllipsisConversion: break;
case BadConversion: Bad = Other.Bad; break;
}
}
ImplicitConversionSequence &
operator=(const ImplicitConversionSequence &Other) {
destruct();
new (this) ImplicitConversionSequence(Other);
return *this;
}
Kind getKind() const {
assert(isInitialized() && "querying uninitialized conversion");
return Kind(ConversionKind);
}
/// \brief Return a ranking of the implicit conversion sequence
/// kind, where smaller ranks represent better conversion
/// sequences.
///
/// In particular, this routine gives user-defined conversion
/// sequences and ambiguous conversion sequences the same rank,
/// per C++ [over.best.ics]p10.
unsigned getKindRank() const {
switch (getKind()) {
case StandardConversion:
return 0;
case UserDefinedConversion:
case AmbiguousConversion:
return 1;
case EllipsisConversion:
return 2;
case BadConversion:
return 3;
}
llvm_unreachable("Invalid ImplicitConversionSequence::Kind!");
}
bool isBad() const { return getKind() == BadConversion; }
bool isStandard() const { return getKind() == StandardConversion; }
bool isEllipsis() const { return getKind() == EllipsisConversion; }
bool isAmbiguous() const { return getKind() == AmbiguousConversion; }
bool isUserDefined() const { return getKind() == UserDefinedConversion; }
bool isFailure() const { return isBad() || isAmbiguous(); }
/// Determines whether this conversion sequence has been
/// initialized. Most operations should never need to query
/// uninitialized conversions and should assert as above.
bool isInitialized() const { return ConversionKind != Uninitialized; }
/// Sets this sequence as a bad conversion for an explicit argument.
void setBad(BadConversionSequence::FailureKind Failure,
Expr *FromExpr, QualType ToType) {
setKind(BadConversion);
Bad.init(Failure, FromExpr, ToType);
}
/// Sets this sequence as a bad conversion for an implicit argument.
void setBad(BadConversionSequence::FailureKind Failure,
QualType FromType, QualType ToType) {
setKind(BadConversion);
Bad.init(Failure, FromType, ToType);
}
void setStandard() { setKind(StandardConversion); }
void setEllipsis() { setKind(EllipsisConversion); }
void setUserDefined() { setKind(UserDefinedConversion); }
void setAmbiguous() {
if (ConversionKind == AmbiguousConversion) return;
ConversionKind = AmbiguousConversion;
Ambiguous.construct();
}
/// \brief Whether the target is really a std::initializer_list, and the
/// sequence only represents the worst element conversion.
bool isStdInitializerListElement() const {
return StdInitializerListElement;
}
void setStdInitializerListElement(bool V = true) {
StdInitializerListElement = V;
}
// The result of a comparison between implicit conversion
// sequences. Use Sema::CompareImplicitConversionSequences to
// actually perform the comparison.
enum CompareKind {
Better = -1,
Indistinguishable = 0,
Worse = 1
};
void DiagnoseAmbiguousConversion(Sema &S,
SourceLocation CaretLoc,
const PartialDiagnostic &PDiag) const;
void dump() const;
};
enum OverloadFailureKind {
ovl_fail_too_many_arguments,
ovl_fail_too_few_arguments,
ovl_fail_bad_conversion,
ovl_fail_bad_deduction,
/// This conversion candidate was not considered because it
/// duplicates the work of a trivial or derived-to-base
/// conversion.
ovl_fail_trivial_conversion,
/// This conversion candidate was not considered because it is
/// an illegal instantiation of a constructor temploid: it is
/// callable with one argument, we only have one argument, and
/// its first parameter type is exactly the type of the class.
///
/// Defining such a constructor directly is illegal, and
/// template-argument deduction is supposed to ignore such
/// instantiations, but we can still get one with the right
/// kind of implicit instantiation.
ovl_fail_illegal_constructor,
/// This conversion candidate is not viable because its result
/// type is not implicitly convertible to the desired type.
ovl_fail_bad_final_conversion,
/// This conversion function template specialization candidate is not
/// viable because the final conversion was not an exact match.
ovl_fail_final_conversion_not_exact,
/// (CUDA) This candidate was not viable because the callee
/// was not accessible from the caller's target (i.e. host->device,
/// global->host, device->host).
ovl_fail_bad_target,
/// This candidate function was not viable because an enable_if
/// attribute disabled it.
ovl_fail_enable_if
};
/// OverloadCandidate - A single candidate in an overload set (C++ 13.3).
struct OverloadCandidate {
/// Function - The actual function that this candidate
/// represents. When NULL, this is a built-in candidate
/// (C++ [over.oper]) or a surrogate for a conversion to a
/// function pointer or reference (C++ [over.call.object]).
FunctionDecl *Function;
/// FoundDecl - The original declaration that was looked up /
/// invented / otherwise found, together with its access.
/// Might be a UsingShadowDecl or a FunctionTemplateDecl.
DeclAccessPair FoundDecl;
// BuiltinTypes - Provides the return and parameter types of a
// built-in overload candidate. Only valid when Function is NULL.
struct {
QualType ResultTy;
QualType ParamTypes[3];
} BuiltinTypes;
/// Surrogate - The conversion function for which this candidate
/// is a surrogate, but only if IsSurrogate is true.
CXXConversionDecl *Surrogate;
/// Conversions - The conversion sequences used to convert the
/// function arguments to the function parameters, the pointer points to a
/// fixed size array with NumConversions elements. The memory is owned by
/// the OverloadCandidateSet.
ImplicitConversionSequence *Conversions;
ImplicitConversionSequence *OutConversions; // HLSL Change
/// The FixIt hints which can be used to fix the Bad candidate.
ConversionFixItGenerator Fix;
/// NumConversions - The number of elements in the Conversions array.
unsigned NumConversions;
/// Viable - True to indicate that this overload candidate is viable.
bool Viable;
/// IsSurrogate - True to indicate that this candidate is a
/// surrogate for a conversion to a function pointer or reference
/// (C++ [over.call.object]).
bool IsSurrogate;
/// IgnoreObjectArgument - True to indicate that the first
/// argument's conversion, which for this function represents the
/// implicit object argument, should be ignored. This will be true
/// when the candidate is a static member function (where the
/// implicit object argument is just a placeholder) or a
/// non-static member function when the call doesn't have an
/// object argument.
bool IgnoreObjectArgument;
/// FailureKind - The reason why this candidate is not viable.
/// Actually an OverloadFailureKind.
unsigned char FailureKind;
/// \brief The number of call arguments that were explicitly provided,
/// to be used while performing partial ordering of function templates.
unsigned ExplicitCallArguments;
union {
DeductionFailureInfo DeductionFailure;
/// FinalConversion - For a conversion function (where Function is
/// a CXXConversionDecl), the standard conversion that occurs
/// after the call to the overload candidate to convert the result
/// of calling the conversion function to the required type.
StandardConversionSequence FinalConversion;
};
/// hasAmbiguousConversion - Returns whether this overload
/// candidate requires an ambiguous conversion or not.
bool hasAmbiguousConversion() const {
for (unsigned i = 0, e = NumConversions; i != e; ++i) {
if (!Conversions[i].isInitialized()) return false;
if (Conversions[i].isAmbiguous()) return true;
}
return false;
}
bool TryToFixBadConversion(unsigned Idx, Sema &S) {
bool CanFix = Fix.tryToFixConversion(
Conversions[Idx].Bad.FromExpr,
Conversions[Idx].Bad.getFromType(),
Conversions[Idx].Bad.getToType(), S);
// If at least one conversion fails, the candidate cannot be fixed.
if (!CanFix)
Fix.clear();
return CanFix;
}
unsigned getNumParams() const {
if (IsSurrogate) {
auto STy = Surrogate->getConversionType();
while (STy->isPointerType() || STy->isReferenceType())
STy = STy->getPointeeType();
return STy->getAs<FunctionProtoType>()->getNumParams();
}
if (Function)
return Function->getNumParams();
return ExplicitCallArguments;
}
};
/// OverloadCandidateSet - A set of overload candidates, used in C++
/// overload resolution (C++ 13.3).
class OverloadCandidateSet {
public:
enum CandidateSetKind {
/// Normal lookup.
CSK_Normal,
/// Lookup for candidates for a call using operator syntax. Candidates
/// that have no parameters of class type will be skipped unless there
/// is a parameter of (reference to) enum type and the corresponding
/// argument is of the same enum type.
CSK_Operator
};
private:
static const int InlineCandidates = 4; // HLSL Change - shrink inline cost
SmallVector<OverloadCandidate, InlineCandidates> Candidates; // HLSL Change - shrink inline cost
llvm::SmallPtrSet<Decl *, InlineCandidates> Functions; // HLSL Change - shrink inline cost
// Allocator for OverloadCandidate::Conversions. We store the first few
// elements inline to avoid allocation for small sets.
llvm::BumpPtrAllocator ConversionSequenceAllocator;
SourceLocation Loc;
CandidateSetKind Kind;
unsigned NumInlineSequences;
llvm::AlignedCharArray<llvm::AlignOf<ImplicitConversionSequence>::Alignment,
InlineCandidates * sizeof(ImplicitConversionSequence)> InlineSpace; // HLSL Change - shrink inline cost
OverloadCandidateSet(const OverloadCandidateSet &) = delete;
void operator=(const OverloadCandidateSet &) = delete;
void destroyCandidates();
public:
OverloadCandidateSet(SourceLocation Loc, CandidateSetKind CSK)
: Loc(Loc), Kind(CSK), NumInlineSequences(0) {}
~OverloadCandidateSet() { destroyCandidates(); }
SourceLocation getLocation() const { return Loc; }
CandidateSetKind getKind() const { return Kind; }
/// \brief Determine when this overload candidate will be new to the
/// overload set.
bool isNewCandidate(Decl *F) {
return Functions.insert(F->getCanonicalDecl()).second;
}
/// \brief Clear out all of the candidates.
void clear();
typedef SmallVectorImpl<OverloadCandidate>::iterator iterator;
iterator begin() { return Candidates.begin(); }
iterator end() { return Candidates.end(); }
size_t size() const { return Candidates.size(); }
bool empty() const { return Candidates.empty(); }
/// \brief Add a new candidate with NumConversions conversion sequence slots
/// to the overload set.
OverloadCandidate &addCandidate(unsigned NumConversions = 0) {
Candidates.push_back(OverloadCandidate());
OverloadCandidate &C = Candidates.back();
// Assign space from the inline array if there are enough free slots
// available.
if (NumConversions + NumInlineSequences <= InlineCandidates) {
ImplicitConversionSequence *I =
(ImplicitConversionSequence *)InlineSpace.buffer;
C.Conversions = &I[NumInlineSequences];
NumInlineSequences += NumConversions;
} else {
// Otherwise get memory from the allocator.
C.Conversions = ConversionSequenceAllocator
.Allocate<ImplicitConversionSequence>(NumConversions);
}
// Construct the new objects.
for (unsigned i = 0; i != NumConversions; ++i)
new (&C.Conversions[i]) ImplicitConversionSequence();
// HLSL Change Starts - consider specifying this size separately
if (NumConversions + NumInlineSequences <= InlineCandidates) {
ImplicitConversionSequence *I =
(ImplicitConversionSequence *)InlineSpace.buffer;
C.OutConversions = &I[NumInlineSequences];
NumInlineSequences += NumConversions;
}
else {
// Otherwise get memory from the allocator.
C.OutConversions = ConversionSequenceAllocator
.Allocate<ImplicitConversionSequence>(NumConversions);
}
for (unsigned i = 0; i != NumConversions; ++i)
new (&C.OutConversions[i]) ImplicitConversionSequence();
// HLSL Change Ends
C.NumConversions = NumConversions;
return C;
}
/// Find the best viable function on this overload set, if it exists.
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc,
OverloadCandidateSet::iterator& Best,
bool UserDefinedConversion = false);
void NoteCandidates(Sema &S,
OverloadCandidateDisplayKind OCD,
ArrayRef<Expr *> Args,
StringRef Opc = "",
SourceLocation Loc = SourceLocation());
};
bool isBetterOverloadCandidate(Sema &S,
const OverloadCandidate& Cand1,
const OverloadCandidate& Cand2,
SourceLocation Loc,
bool UserDefinedConversion = false);
} // end namespace clang
#endif // LLVM_CLANG_SEMA_OVERLOAD_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/SemaFixItUtils.h | //===--- SemaFixItUtils.h - Sema FixIts -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines helper classes for generation of Sema FixItHints.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMAFIXITUTILS_H
#define LLVM_CLANG_SEMA_SEMAFIXITUTILS_H
#include "clang/AST/Expr.h"
namespace clang {
enum OverloadFixItKind {
OFIK_Undefined = 0,
OFIK_Dereference,
OFIK_TakeAddress,
OFIK_RemoveDereference,
OFIK_RemoveTakeAddress
};
class Sema;
/// The class facilities generation and storage of conversion FixIts. Hints for
/// new conversions are added using TryToFixConversion method. The default type
/// conversion checker can be reset.
struct ConversionFixItGenerator {
/// Performs a simple check to see if From type can be converted to To type.
static bool compareTypesSimple(CanQualType From,
CanQualType To,
Sema &S,
SourceLocation Loc,
ExprValueKind FromVK);
/// The list of Hints generated so far.
std::vector<FixItHint> Hints;
/// The number of Conversions fixed. This can be different from the size
/// of the Hints vector since we allow multiple FixIts per conversion.
unsigned NumConversionsFixed;
/// The type of fix applied. If multiple conversions are fixed, corresponds
/// to the kid of the very first conversion.
OverloadFixItKind Kind;
typedef bool (*TypeComparisonFuncTy) (const CanQualType FromTy,
const CanQualType ToTy,
Sema &S,
SourceLocation Loc,
ExprValueKind FromVK);
/// The type comparison function used to decide if expression FromExpr of
/// type FromTy can be converted to ToTy. For example, one could check if
/// an implicit conversion exists. Returns true if comparison exists.
TypeComparisonFuncTy CompareTypes;
ConversionFixItGenerator(TypeComparisonFuncTy Foo): NumConversionsFixed(0),
Kind(OFIK_Undefined),
CompareTypes(Foo) {}
ConversionFixItGenerator(): NumConversionsFixed(0),
Kind(OFIK_Undefined),
CompareTypes(compareTypesSimple) {}
/// Resets the default conversion checker method.
void setConversionChecker(TypeComparisonFuncTy Foo) {
CompareTypes = Foo;
}
/// If possible, generates and stores a fix for the given conversion.
bool tryToFixConversion(const Expr *FromExpr,
const QualType FromQTy, const QualType ToQTy,
Sema &S);
void clear() {
Hints.clear();
NumConversionsFixed = 0;
}
bool isNull() {
return (NumConversionsFixed == 0);
}
};
} // endof namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/AttributeList.h | //===--- AttributeList.h - Parsed attribute sets ----------------*- 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 AttributeList class, which is used to collect
// parsed attributes.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_ATTRIBUTELIST_H
#define LLVM_CLANG_SEMA_ATTRIBUTELIST_H
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/VersionTuple.h"
#include "clang/Sema/Ownership.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Allocator.h"
#include <cassert>
namespace clang {
class ASTContext;
class IdentifierInfo;
class Expr;
/// \brief Represents information about a change in availability for
/// an entity, which is part of the encoding of the 'availability'
/// attribute.
struct AvailabilityChange {
/// \brief The location of the keyword indicating the kind of change.
SourceLocation KeywordLoc;
/// \brief The version number at which the change occurred.
VersionTuple Version;
/// \brief The source range covering the version number.
SourceRange VersionRange;
/// \brief Determine whether this availability change is valid.
bool isValid() const { return !Version.empty(); }
};
/// \brief Wraps an identifier and optional source location for the identifier.
struct IdentifierLoc {
SourceLocation Loc;
IdentifierInfo *Ident;
static IdentifierLoc *create(ASTContext &Ctx, SourceLocation Loc,
IdentifierInfo *Ident);
};
/// \brief A union of the various pointer types that can be passed to an
/// AttributeList as an argument.
typedef llvm::PointerUnion<Expr*, IdentifierLoc*> ArgsUnion;
typedef llvm::SmallVector<ArgsUnion, 12U> ArgsVector;
/// AttributeList - Represents a syntactic attribute.
///
/// For a GNU attribute, there are four forms of this construct:
///
/// 1: __attribute__(( const )). ParmName/Args/NumArgs will all be unused.
/// 2: __attribute__(( mode(byte) )). ParmName used, Args/NumArgs unused.
/// 3: __attribute__(( format(printf, 1, 2) )). ParmName/Args/NumArgs all used.
/// 4: __attribute__(( aligned(16) )). ParmName is unused, Args/Num used.
///
class AttributeList { // TODO: This should really be called ParsedAttribute
public:
/// The style used to specify an attribute.
enum Syntax {
/// __attribute__((...))
AS_GNU,
/// [[...]]
AS_CXX11,
/// __declspec(...)
AS_Declspec,
/// __ptr16, alignas(...), etc.
AS_Keyword,
/// Context-sensitive version of a keyword attribute.
AS_ContextSensitiveKeyword,
/// #pragma ...
AS_Pragma
};
private:
IdentifierInfo *AttrName;
IdentifierInfo *ScopeName;
SourceRange AttrRange;
SourceLocation ScopeLoc;
SourceLocation EllipsisLoc;
/// The number of expression arguments this attribute has.
/// The expressions themselves are stored after the object.
unsigned NumArgs : 15;
/// Corresponds to the Syntax enum.
unsigned SyntaxUsed : 3;
/// True if already diagnosed as invalid.
mutable unsigned Invalid : 1;
/// True if this attribute was used as a type attribute.
mutable unsigned UsedAsTypeAttr : 1;
/// True if this has the extra information associated with an
/// availability attribute.
unsigned IsAvailability : 1;
/// True if this has extra information associated with a
/// type_tag_for_datatype attribute.
unsigned IsTypeTagForDatatype : 1;
/// True if this has extra information associated with a
/// Microsoft __delcspec(property) attribute.
unsigned IsProperty : 1;
/// True if this has a ParsedType
unsigned HasParsedType : 1;
unsigned padding : 8;
unsigned AttrKind;
/// \brief The location of the 'unavailable' keyword in an
/// availability attribute.
SourceLocation UnavailableLoc;
const Expr *MessageExpr;
/// The next attribute in the current position.
AttributeList *NextInPosition;
/// The next attribute allocated in the current Pool.
AttributeList *NextInPool;
/// Arguments, if any, are stored immediately following the object.
ArgsUnion *getArgsBuffer() {
return reinterpret_cast<ArgsUnion*>(this+1);
}
ArgsUnion const *getArgsBuffer() const {
return reinterpret_cast<ArgsUnion const *>(this+1);
}
enum AvailabilitySlot {
IntroducedSlot, DeprecatedSlot, ObsoletedSlot
};
/// Availability information is stored immediately following the arguments,
/// if any, at the end of the object.
AvailabilityChange &getAvailabilitySlot(AvailabilitySlot index) {
return reinterpret_cast<AvailabilityChange*>(getArgsBuffer()
+ NumArgs)[index];
}
const AvailabilityChange &getAvailabilitySlot(AvailabilitySlot index) const {
return reinterpret_cast<const AvailabilityChange*>(getArgsBuffer()
+ NumArgs)[index];
}
public:
struct TypeTagForDatatypeData {
ParsedType *MatchingCType;
unsigned LayoutCompatible : 1;
unsigned MustBeNull : 1;
};
struct PropertyData {
IdentifierInfo *GetterId, *SetterId;
PropertyData(IdentifierInfo *getterId, IdentifierInfo *setterId)
: GetterId(getterId), SetterId(setterId) {}
};
private:
/// Type tag information is stored immediately following the arguments, if
/// any, at the end of the object. They are mutually exlusive with
/// availability slots.
TypeTagForDatatypeData &getTypeTagForDatatypeDataSlot() {
return *reinterpret_cast<TypeTagForDatatypeData*>(getArgsBuffer()+NumArgs);
}
const TypeTagForDatatypeData &getTypeTagForDatatypeDataSlot() const {
return *reinterpret_cast<const TypeTagForDatatypeData*>(getArgsBuffer()
+ NumArgs);
}
/// The type buffer immediately follows the object and are mutually exclusive
/// with arguments.
ParsedType &getTypeBuffer() {
return *reinterpret_cast<ParsedType *>(this + 1);
}
const ParsedType &getTypeBuffer() const {
return *reinterpret_cast<const ParsedType *>(this + 1);
}
/// The property data immediately follows the object is is mutually exclusive
/// with arguments.
PropertyData &getPropertyDataBuffer() {
assert(IsProperty);
return *reinterpret_cast<PropertyData*>(this + 1);
}
const PropertyData &getPropertyDataBuffer() const {
assert(IsProperty);
return *reinterpret_cast<const PropertyData*>(this + 1);
}
AttributeList(const AttributeList &) = delete;
void operator=(const AttributeList &) = delete;
void operator delete(void *) = delete;
~AttributeList() = delete;
size_t allocated_size() const;
/// Constructor for attributes with expression arguments.
AttributeList(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
ArgsUnion *args, unsigned numArgs,
Syntax syntaxUsed, SourceLocation ellipsisLoc)
: AttrName(attrName), ScopeName(scopeName), AttrRange(attrRange),
ScopeLoc(scopeLoc), EllipsisLoc(ellipsisLoc), NumArgs(numArgs),
SyntaxUsed(syntaxUsed), Invalid(false), UsedAsTypeAttr(false),
IsAvailability(false), IsTypeTagForDatatype(false), IsProperty(false),
HasParsedType(false), NextInPosition(nullptr), NextInPool(nullptr) {
if (numArgs) memcpy(getArgsBuffer(), args, numArgs * sizeof(ArgsUnion));
AttrKind = getKind(getName(), getScopeName(), syntaxUsed);
}
/// Constructor for availability attributes.
AttributeList(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierLoc *Parm, const AvailabilityChange &introduced,
const AvailabilityChange &deprecated,
const AvailabilityChange &obsoleted,
SourceLocation unavailable,
const Expr *messageExpr,
Syntax syntaxUsed)
: AttrName(attrName), ScopeName(scopeName), AttrRange(attrRange),
ScopeLoc(scopeLoc), EllipsisLoc(), NumArgs(1), SyntaxUsed(syntaxUsed),
Invalid(false), UsedAsTypeAttr(false), IsAvailability(true),
IsTypeTagForDatatype(false), IsProperty(false), HasParsedType(false),
UnavailableLoc(unavailable), MessageExpr(messageExpr),
NextInPosition(nullptr), NextInPool(nullptr) {
ArgsUnion PVal(Parm);
memcpy(getArgsBuffer(), &PVal, sizeof(ArgsUnion));
new (&getAvailabilitySlot(IntroducedSlot)) AvailabilityChange(introduced);
new (&getAvailabilitySlot(DeprecatedSlot)) AvailabilityChange(deprecated);
new (&getAvailabilitySlot(ObsoletedSlot)) AvailabilityChange(obsoleted);
AttrKind = getKind(getName(), getScopeName(), syntaxUsed);
}
/// Constructor for objc_bridge_related attributes.
AttributeList(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierLoc *Parm1,
IdentifierLoc *Parm2,
IdentifierLoc *Parm3,
Syntax syntaxUsed)
: AttrName(attrName), ScopeName(scopeName), AttrRange(attrRange),
ScopeLoc(scopeLoc), EllipsisLoc(), NumArgs(3), SyntaxUsed(syntaxUsed),
Invalid(false), UsedAsTypeAttr(false), IsAvailability(false),
IsTypeTagForDatatype(false), IsProperty(false), HasParsedType(false),
NextInPosition(nullptr), NextInPool(nullptr) {
ArgsVector Args;
Args.push_back(Parm1);
Args.push_back(Parm2);
Args.push_back(Parm3);
memcpy(getArgsBuffer(), &Args[0], 3 * sizeof(ArgsUnion));
AttrKind = getKind(getName(), getScopeName(), syntaxUsed);
}
/// Constructor for type_tag_for_datatype attribute.
AttributeList(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierLoc *ArgKind, ParsedType matchingCType,
bool layoutCompatible, bool mustBeNull, Syntax syntaxUsed)
: AttrName(attrName), ScopeName(scopeName), AttrRange(attrRange),
ScopeLoc(scopeLoc), EllipsisLoc(), NumArgs(1), SyntaxUsed(syntaxUsed),
Invalid(false), UsedAsTypeAttr(false), IsAvailability(false),
IsTypeTagForDatatype(true), IsProperty(false), HasParsedType(false),
NextInPosition(nullptr), NextInPool(nullptr) {
ArgsUnion PVal(ArgKind);
memcpy(getArgsBuffer(), &PVal, sizeof(ArgsUnion));
TypeTagForDatatypeData &ExtraData = getTypeTagForDatatypeDataSlot();
new (&ExtraData.MatchingCType) ParsedType(matchingCType);
ExtraData.LayoutCompatible = layoutCompatible;
ExtraData.MustBeNull = mustBeNull;
AttrKind = getKind(getName(), getScopeName(), syntaxUsed);
}
/// Constructor for attributes with a single type argument.
AttributeList(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
ParsedType typeArg, Syntax syntaxUsed)
: AttrName(attrName), ScopeName(scopeName), AttrRange(attrRange),
ScopeLoc(scopeLoc), EllipsisLoc(), NumArgs(0), SyntaxUsed(syntaxUsed),
Invalid(false), UsedAsTypeAttr(false), IsAvailability(false),
IsTypeTagForDatatype(false), IsProperty(false), HasParsedType(true),
NextInPosition(nullptr), NextInPool(nullptr) {
new (&getTypeBuffer()) ParsedType(typeArg);
AttrKind = getKind(getName(), getScopeName(), syntaxUsed);
}
/// Constructor for microsoft __declspec(property) attribute.
AttributeList(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierInfo *getterId, IdentifierInfo *setterId,
Syntax syntaxUsed)
: AttrName(attrName), ScopeName(scopeName), AttrRange(attrRange),
ScopeLoc(scopeLoc), EllipsisLoc(), NumArgs(0), SyntaxUsed(syntaxUsed),
Invalid(false), UsedAsTypeAttr(false), IsAvailability(false),
IsTypeTagForDatatype(false), IsProperty(true), HasParsedType(false),
NextInPosition(nullptr), NextInPool(nullptr) {
new (&getPropertyDataBuffer()) PropertyData(getterId, setterId);
AttrKind = getKind(getName(), getScopeName(), syntaxUsed);
}
friend class AttributePool;
friend class AttributeFactory;
public:
enum Kind {
#define PARSED_ATTR(NAME) AT_##NAME,
#include "clang/Sema/AttrParsedAttrList.inc"
#undef PARSED_ATTR
IgnoredAttribute,
UnknownAttribute
};
IdentifierInfo *getName() const { return AttrName; }
SourceLocation getLoc() const { return AttrRange.getBegin(); }
SourceRange getRange() const { return AttrRange; }
bool hasScope() const { return ScopeName; }
IdentifierInfo *getScopeName() const { return ScopeName; }
SourceLocation getScopeLoc() const { return ScopeLoc; }
bool hasParsedType() const { return HasParsedType; }
/// Is this the Microsoft __declspec(property) attribute?
bool isDeclspecPropertyAttribute() const {
return IsProperty;
}
bool isAlignasAttribute() const {
// FIXME: Use a better mechanism to determine this.
return getKind() == AT_Aligned && isKeywordAttribute();
}
bool isDeclspecAttribute() const { return SyntaxUsed == AS_Declspec; }
bool isCXX11Attribute() const {
return SyntaxUsed == AS_CXX11 || isAlignasAttribute();
}
bool isKeywordAttribute() const {
return SyntaxUsed == AS_Keyword || SyntaxUsed == AS_ContextSensitiveKeyword;
}
bool isContextSensitiveKeywordAttribute() const {
return SyntaxUsed == AS_ContextSensitiveKeyword;
}
bool isInvalid() const { return Invalid; }
void setInvalid(bool b = true) const { Invalid = b; }
bool isUsedAsTypeAttr() const { return UsedAsTypeAttr; }
void setUsedAsTypeAttr() { UsedAsTypeAttr = true; }
bool isPackExpansion() const { return EllipsisLoc.isValid(); }
SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
Kind getKind() const { return Kind(AttrKind); }
static Kind getKind(const IdentifierInfo *Name, const IdentifierInfo *Scope,
Syntax SyntaxUsed);
AttributeList *getNext() const { return NextInPosition; }
void setNext(AttributeList *N) { NextInPosition = N; }
/// getNumArgs - Return the number of actual arguments to this attribute.
unsigned getNumArgs() const { return NumArgs; }
/// getArg - Return the specified argument.
ArgsUnion getArg(unsigned Arg) const {
assert(Arg < NumArgs && "Arg access out of range!");
return getArgsBuffer()[Arg];
}
bool isArgExpr(unsigned Arg) const {
return Arg < NumArgs && getArg(Arg).is<Expr*>();
}
Expr *getArgAsExpr(unsigned Arg) const {
return getArg(Arg).get<Expr*>();
}
bool isArgIdent(unsigned Arg) const {
return Arg < NumArgs && getArg(Arg).is<IdentifierLoc*>();
}
IdentifierLoc *getArgAsIdent(unsigned Arg) const {
return getArg(Arg).get<IdentifierLoc*>();
}
const AvailabilityChange &getAvailabilityIntroduced() const {
assert(getKind() == AT_Availability && "Not an availability attribute");
return getAvailabilitySlot(IntroducedSlot);
}
const AvailabilityChange &getAvailabilityDeprecated() const {
assert(getKind() == AT_Availability && "Not an availability attribute");
return getAvailabilitySlot(DeprecatedSlot);
}
const AvailabilityChange &getAvailabilityObsoleted() const {
assert(getKind() == AT_Availability && "Not an availability attribute");
return getAvailabilitySlot(ObsoletedSlot);
}
SourceLocation getUnavailableLoc() const {
assert(getKind() == AT_Availability && "Not an availability attribute");
return UnavailableLoc;
}
const Expr * getMessageExpr() const {
assert(getKind() == AT_Availability && "Not an availability attribute");
return MessageExpr;
}
const ParsedType &getMatchingCType() const {
assert(getKind() == AT_TypeTagForDatatype &&
"Not a type_tag_for_datatype attribute");
return *getTypeTagForDatatypeDataSlot().MatchingCType;
}
bool getLayoutCompatible() const {
assert(getKind() == AT_TypeTagForDatatype &&
"Not a type_tag_for_datatype attribute");
return getTypeTagForDatatypeDataSlot().LayoutCompatible;
}
bool getMustBeNull() const {
assert(getKind() == AT_TypeTagForDatatype &&
"Not a type_tag_for_datatype attribute");
return getTypeTagForDatatypeDataSlot().MustBeNull;
}
const ParsedType &getTypeArg() const {
assert(HasParsedType && "Not a type attribute");
return getTypeBuffer();
}
const PropertyData &getPropertyData() const {
assert(isDeclspecPropertyAttribute() && "Not a __delcspec(property) attribute");
return getPropertyDataBuffer();
}
/// \brief Get an index into the attribute spelling list
/// defined in Attr.td. This index is used by an attribute
/// to pretty print itself.
unsigned getAttributeSpellingListIndex() const;
bool isTargetSpecificAttr() const;
bool isTypeAttr() const;
bool hasCustomParsing() const;
unsigned getMinArgs() const;
unsigned getMaxArgs() const;
bool hasVariadicArg() const;
bool diagnoseAppertainsTo(class Sema &S, const Decl *D) const;
bool diagnoseLangOpts(class Sema &S) const;
bool existsInTarget(const llvm::Triple &T) const;
bool isKnownToGCC() const;
/// \brief If the parsed attribute has a semantic equivalent, and it would
/// have a semantic Spelling enumeration (due to having semantically-distinct
/// spelling variations), return the value of that semantic spelling. If the
/// parsed attribute does not have a semantic equivalent, or would not have
/// a Spelling enumeration, the value UINT_MAX is returned.
unsigned getSemanticSpelling() const;
};
/// A factory, from which one makes pools, from which one creates
/// individual attributes which are deallocated with the pool.
///
/// Note that it's tolerably cheap to create and destroy one of
/// these as long as you don't actually allocate anything in it.
class AttributeFactory {
public:
enum {
/// The required allocation size of an availability attribute,
/// which we want to ensure is a multiple of sizeof(void*).
AvailabilityAllocSize =
sizeof(AttributeList)
+ ((3 * sizeof(AvailabilityChange) + sizeof(void*) +
sizeof(ArgsUnion) - 1)
/ sizeof(void*) * sizeof(void*)),
TypeTagForDatatypeAllocSize =
sizeof(AttributeList)
+ (sizeof(AttributeList::TypeTagForDatatypeData) + sizeof(void *) +
sizeof(ArgsUnion) - 1)
/ sizeof(void*) * sizeof(void*),
PropertyAllocSize =
sizeof(AttributeList)
+ (sizeof(AttributeList::PropertyData) + sizeof(void *) - 1)
/ sizeof(void*) * sizeof(void*)
};
private:
enum {
/// The number of free lists we want to be sure to support
/// inline. This is just enough that availability attributes
/// don't surpass it. It's actually very unlikely we'll see an
/// attribute that needs more than that; on x86-64 you'd need 10
/// expression arguments, and on i386 you'd need 19.
InlineFreeListsCapacity =
1 + (AvailabilityAllocSize - sizeof(AttributeList)) / sizeof(void*)
};
llvm::BumpPtrAllocator Alloc;
/// Free lists. The index is determined by the following formula:
/// (size - sizeof(AttributeList)) / sizeof(void*)
SmallVector<AttributeList*, InlineFreeListsCapacity> FreeLists;
// The following are the private interface used by AttributePool.
friend class AttributePool;
/// Allocate an attribute of the given size.
void *allocate(size_t size);
/// Reclaim all the attributes in the given pool chain, which is
/// non-empty. Note that the current implementation is safe
/// against reclaiming things which were not actually allocated
/// with the allocator, although of course it's important to make
/// sure that their allocator lives at least as long as this one.
void reclaimPool(AttributeList *head);
public:
AttributeFactory();
~AttributeFactory();
};
class AttributePool {
AttributeFactory &Factory;
AttributeList *Head;
void *allocate(size_t size) {
return Factory.allocate(size);
}
AttributeList *add(AttributeList *attr) {
// We don't care about the order of the pool.
attr->NextInPool = Head;
Head = attr;
return attr;
}
void takePool(AttributeList *pool);
public:
/// Create a new pool for a factory.
AttributePool(AttributeFactory &factory) : Factory(factory), Head(nullptr) {}
/// Move the given pool's allocations to this pool.
AttributePool(AttributePool &pool) : Factory(pool.Factory), Head(pool.Head) {
pool.Head = nullptr;
}
AttributeFactory &getFactory() const { return Factory; }
void clear() {
if (Head) {
Factory.reclaimPool(Head);
Head = nullptr;
}
}
/// Take the given pool's allocations and add them to this pool.
void takeAllFrom(AttributePool &pool) {
if (pool.Head) {
takePool(pool.Head);
pool.Head = nullptr;
}
}
~AttributePool() {
if (Head) Factory.reclaimPool(Head);
}
AttributeList *create(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
ArgsUnion *args, unsigned numArgs,
AttributeList::Syntax syntax,
SourceLocation ellipsisLoc = SourceLocation()) {
void *memory = allocate(sizeof(AttributeList)
+ numArgs * sizeof(ArgsUnion));
return add(new (memory) AttributeList(attrName, attrRange,
scopeName, scopeLoc,
args, numArgs, syntax,
ellipsisLoc));
}
AttributeList *create(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierLoc *Param,
const AvailabilityChange &introduced,
const AvailabilityChange &deprecated,
const AvailabilityChange &obsoleted,
SourceLocation unavailable,
const Expr *MessageExpr,
AttributeList::Syntax syntax) {
void *memory = allocate(AttributeFactory::AvailabilityAllocSize);
return add(new (memory) AttributeList(attrName, attrRange,
scopeName, scopeLoc,
Param, introduced, deprecated,
obsoleted, unavailable, MessageExpr,
syntax));
}
AttributeList *create(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierLoc *Param1,
IdentifierLoc *Param2,
IdentifierLoc *Param3,
AttributeList::Syntax syntax) {
size_t size = sizeof(AttributeList) + 3 * sizeof(ArgsUnion);
void *memory = allocate(size);
return add(new (memory) AttributeList(attrName, attrRange,
scopeName, scopeLoc,
Param1, Param2, Param3,
syntax));
}
AttributeList *createTypeTagForDatatype(
IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierLoc *argumentKind, ParsedType matchingCType,
bool layoutCompatible, bool mustBeNull,
AttributeList::Syntax syntax) {
void *memory = allocate(AttributeFactory::TypeTagForDatatypeAllocSize);
return add(new (memory) AttributeList(attrName, attrRange,
scopeName, scopeLoc,
argumentKind, matchingCType,
layoutCompatible, mustBeNull,
syntax));
}
AttributeList *createTypeAttribute(
IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
ParsedType typeArg, AttributeList::Syntax syntaxUsed) {
void *memory = allocate(sizeof(AttributeList) + sizeof(void *));
return add(new (memory) AttributeList(attrName, attrRange,
scopeName, scopeLoc,
typeArg, syntaxUsed));
}
AttributeList *createPropertyAttribute(
IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierInfo *getterId, IdentifierInfo *setterId,
AttributeList::Syntax syntaxUsed) {
void *memory = allocate(AttributeFactory::PropertyAllocSize);
return add(new (memory) AttributeList(attrName, attrRange,
scopeName, scopeLoc,
getterId, setterId,
syntaxUsed));
}
};
/// ParsedAttributes - A collection of parsed attributes. Currently
/// we don't differentiate between the various attribute syntaxes,
/// which is basically silly.
///
/// Right now this is a very lightweight container, but the expectation
/// is that this will become significantly more serious.
class ParsedAttributes {
public:
ParsedAttributes(AttributeFactory &factory)
: pool(factory), list(nullptr) {
}
ParsedAttributes(const ParsedAttributes &) = delete;
AttributePool &getPool() const { return pool; }
bool empty() const { return list == nullptr; }
void add(AttributeList *newAttr) {
assert(newAttr);
assert(newAttr->getNext() == nullptr);
newAttr->setNext(list);
list = newAttr;
}
void addAll(AttributeList *newList) {
if (!newList) return;
AttributeList *lastInNewList = newList;
while (AttributeList *next = lastInNewList->getNext())
lastInNewList = next;
lastInNewList->setNext(list);
list = newList;
}
void set(AttributeList *newList) {
list = newList;
}
void takeAllFrom(ParsedAttributes &attrs) {
addAll(attrs.list);
attrs.list = nullptr;
pool.takeAllFrom(attrs.pool);
}
void clear() { list = nullptr; pool.clear(); }
AttributeList *getList() const { return list; }
/// Returns a reference to the attribute list. Try not to introduce
/// dependencies on this method, it may not be long-lived.
AttributeList *&getListRef() { return list; }
/// Add attribute with expression arguments.
AttributeList *addNew(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
ArgsUnion *args, unsigned numArgs,
AttributeList::Syntax syntax,
SourceLocation ellipsisLoc = SourceLocation()) {
AttributeList *attr =
pool.create(attrName, attrRange, scopeName, scopeLoc, args, numArgs,
syntax, ellipsisLoc);
add(attr);
return attr;
}
/// Add availability attribute.
AttributeList *addNew(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierLoc *Param,
const AvailabilityChange &introduced,
const AvailabilityChange &deprecated,
const AvailabilityChange &obsoleted,
SourceLocation unavailable,
const Expr *MessageExpr,
AttributeList::Syntax syntax) {
AttributeList *attr =
pool.create(attrName, attrRange, scopeName, scopeLoc, Param, introduced,
deprecated, obsoleted, unavailable, MessageExpr, syntax);
add(attr);
return attr;
}
/// Add objc_bridge_related attribute.
AttributeList *addNew(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierLoc *Param1,
IdentifierLoc *Param2,
IdentifierLoc *Param3,
AttributeList::Syntax syntax) {
AttributeList *attr =
pool.create(attrName, attrRange, scopeName, scopeLoc,
Param1, Param2, Param3, syntax);
add(attr);
return attr;
}
/// Add type_tag_for_datatype attribute.
AttributeList *addNewTypeTagForDatatype(
IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierLoc *argumentKind, ParsedType matchingCType,
bool layoutCompatible, bool mustBeNull,
AttributeList::Syntax syntax) {
AttributeList *attr =
pool.createTypeTagForDatatype(attrName, attrRange,
scopeName, scopeLoc,
argumentKind, matchingCType,
layoutCompatible, mustBeNull, syntax);
add(attr);
return attr;
}
/// Add an attribute with a single type argument.
AttributeList *
addNewTypeAttr(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
ParsedType typeArg, AttributeList::Syntax syntaxUsed) {
AttributeList *attr =
pool.createTypeAttribute(attrName, attrRange, scopeName, scopeLoc,
typeArg, syntaxUsed);
add(attr);
return attr;
}
/// Add microsoft __delspec(property) attribute.
AttributeList *
addNewPropertyAttr(IdentifierInfo *attrName, SourceRange attrRange,
IdentifierInfo *scopeName, SourceLocation scopeLoc,
IdentifierInfo *getterId, IdentifierInfo *setterId,
AttributeList::Syntax syntaxUsed) {
AttributeList *attr =
pool.createPropertyAttribute(attrName, attrRange, scopeName, scopeLoc,
getterId, setterId, syntaxUsed);
add(attr);
return attr;
}
private:
mutable AttributePool pool;
AttributeList *list;
};
/// These constants match the enumerated choices of
/// err_attribute_argument_n_type and err_attribute_argument_type.
enum AttributeArgumentNType {
AANT_ArgumentIntOrBool,
AANT_ArgumentIntegerConstant,
AANT_ArgumentString,
AANT_ArgumentIdentifier
};
/// These constants match the enumerated choices of
/// warn_attribute_wrong_decl_type and err_attribute_wrong_decl_type.
enum AttributeDeclKind {
ExpectedFunction,
ExpectedUnion,
ExpectedVariableOrFunction,
ExpectedFunctionOrMethod,
ExpectedParameter,
ExpectedFunctionMethodOrBlock,
ExpectedFunctionMethodOrClass,
ExpectedFunctionMethodOrParameter,
ExpectedClass,
ExpectedEnum,
ExpectedVariable,
ExpectedMethod,
ExpectedVariableFunctionOrLabel,
ExpectedFieldOrGlobalVar,
ExpectedStruct,
ExpectedVariableOrTypedef,
ExpectedTLSVar,
ExpectedVariableOrField,
ExpectedVariableFieldOrTag,
ExpectedTypeOrNamespace,
ExpectedObjectiveCInterface,
ExpectedMethodOrProperty,
ExpectedStructOrUnion,
ExpectedStructOrUnionOrClass,
ExpectedType,
ExpectedObjCInstanceMethod,
ExpectedObjCInterfaceDeclInitMethod,
ExpectedFunctionVariableOrClass,
ExpectedObjectiveCProtocol,
ExpectedFunctionGlobalVarMethodOrProperty,
ExpectedStructOrUnionOrTypedef,
ExpectedStructOrTypedef,
ExpectedObjectiveCInterfaceOrProtocol,
ExpectedKernelFunction,
// SPIRV Change Begins
ExpectedField,
ExpectedScalarGlobalVar,
ExpectedStructGlobalVar,
ExpectedGlobalVarOrCTBuffer,
ExpectedTextureOrSamplerState,
ExpectedRWTextureOrBuffer,
ExpectedCounterStructuredBuffer,
ExpectedSubpassInput,
ExpectedCTBuffer,
// SPIRV Change Ends
// HLSL Change Begins - add attribute decl combinations
ExpectedVariableOrParam,
ExpectedFunctionOrParamOrField,
ExpectedFunctionOrVariableOrParamOrFieldOrType
// HLSL Change Ends
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/DeclSpec.h | //===--- DeclSpec.h - Parsed declaration specifiers -------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file defines the classes used to store parsed information about
/// declaration-specifiers and declarators.
///
/// \verbatim
/// static const int volatile x, *y, *(*(*z)[10])(const void *x);
/// ------------------------- - -- ---------------------------
/// declaration-specifiers \ | /
/// declarators
/// \endverbatim
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_DECLSPEC_H
#define LLVM_CLANG_SEMA_DECLSPEC_H
#include "clang/AST/Attr.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/Basic/ExceptionSpecificationType.h"
#include "clang/Basic/Lambda.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Lex/Token.h"
#include "clang/Sema/AttributeList.h"
#include "clang/Sema/Ownership.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
// HLSL Change Starts
namespace hlsl {
struct UnusualAnnotation;
}
// HLSL Change Ends
namespace clang {
class ASTContext;
class CXXRecordDecl;
class TypeLoc;
class LangOptions;
class DiagnosticsEngine;
class IdentifierInfo;
class NamespaceAliasDecl;
class NamespaceDecl;
class NestedNameSpecifier;
class NestedNameSpecifierLoc;
class ObjCDeclSpec;
class Preprocessor;
class Sema;
class Declarator;
struct TemplateIdAnnotation;
/// \brief Represents a C++ nested-name-specifier or a global scope specifier.
///
/// These can be in 3 states:
/// 1) Not present, identified by isEmpty()
/// 2) Present, identified by isNotEmpty()
/// 2.a) Valid, identified by isValid()
/// 2.b) Invalid, identified by isInvalid().
///
/// isSet() is deprecated because it mostly corresponded to "valid" but was
/// often used as if it meant "present".
///
/// The actual scope is described by getScopeRep().
class CXXScopeSpec {
SourceRange Range;
NestedNameSpecifierLocBuilder Builder;
public:
const SourceRange &getRange() const { return Range; }
void setRange(const SourceRange &R) { Range = R; }
void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); }
void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); }
SourceLocation getBeginLoc() const { return Range.getBegin(); }
SourceLocation getEndLoc() const { return Range.getEnd(); }
/// \brief Retrieve the representation of the nested-name-specifier.
NestedNameSpecifier *getScopeRep() const {
return Builder.getRepresentation();
}
/// \brief Extend the current nested-name-specifier by another
/// nested-name-specifier component of the form 'type::'.
///
/// \param Context The AST context in which this nested-name-specifier
/// resides.
///
/// \param TemplateKWLoc The location of the 'template' keyword, if present.
///
/// \param TL The TypeLoc that describes the type preceding the '::'.
///
/// \param ColonColonLoc The location of the trailing '::'.
void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL,
SourceLocation ColonColonLoc);
/// \brief Extend the current nested-name-specifier by another
/// nested-name-specifier component of the form 'identifier::'.
///
/// \param Context The AST context in which this nested-name-specifier
/// resides.
///
/// \param Identifier The identifier.
///
/// \param IdentifierLoc The location of the identifier.
///
/// \param ColonColonLoc The location of the trailing '::'.
void Extend(ASTContext &Context, IdentifierInfo *Identifier,
SourceLocation IdentifierLoc, SourceLocation ColonColonLoc);
/// \brief Extend the current nested-name-specifier by another
/// nested-name-specifier component of the form 'namespace::'.
///
/// \param Context The AST context in which this nested-name-specifier
/// resides.
///
/// \param Namespace The namespace.
///
/// \param NamespaceLoc The location of the namespace name.
///
/// \param ColonColonLoc The location of the trailing '::'.
void Extend(ASTContext &Context, NamespaceDecl *Namespace,
SourceLocation NamespaceLoc, SourceLocation ColonColonLoc);
/// \brief Extend the current nested-name-specifier by another
/// nested-name-specifier component of the form 'namespace-alias::'.
///
/// \param Context The AST context in which this nested-name-specifier
/// resides.
///
/// \param Alias The namespace alias.
///
/// \param AliasLoc The location of the namespace alias
/// name.
///
/// \param ColonColonLoc The location of the trailing '::'.
void Extend(ASTContext &Context, NamespaceAliasDecl *Alias,
SourceLocation AliasLoc, SourceLocation ColonColonLoc);
/// \brief Turn this (empty) nested-name-specifier into the global
/// nested-name-specifier '::'.
void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc);
/// \brief Turns this (empty) nested-name-specifier into '__super'
/// nested-name-specifier.
///
/// \param Context The AST context in which this nested-name-specifier
/// resides.
///
/// \param RD The declaration of the class in which nested-name-specifier
/// appeared.
///
/// \param SuperLoc The location of the '__super' keyword.
/// name.
///
/// \param ColonColonLoc The location of the trailing '::'.
void MakeSuper(ASTContext &Context, CXXRecordDecl *RD,
SourceLocation SuperLoc, SourceLocation ColonColonLoc);
/// \brief Make a new nested-name-specifier from incomplete source-location
/// information.
///
/// FIXME: This routine should be used very, very rarely, in cases where we
/// need to synthesize a nested-name-specifier. Most code should instead use
/// \c Adopt() with a proper \c NestedNameSpecifierLoc.
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier,
SourceRange R);
/// \brief Adopt an existing nested-name-specifier (with source-range
/// information).
void Adopt(NestedNameSpecifierLoc Other);
/// \brief Retrieve a nested-name-specifier with location information, copied
/// into the given AST context.
///
/// \param Context The context into which this nested-name-specifier will be
/// copied.
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const;
/// \brief Retrieve the location of the name in the last qualifier
/// in this nested name specifier.
///
/// For example, the location of \c bar
/// in
/// \verbatim
/// \::foo::bar<0>::
/// ^~~
/// \endverbatim
SourceLocation getLastQualifierNameLoc() const;
/// No scope specifier.
bool isEmpty() const { return !Range.isValid(); }
/// A scope specifier is present, but may be valid or invalid.
bool isNotEmpty() const { return !isEmpty(); }
/// An error occurred during parsing of the scope specifier.
bool isInvalid() const { return isNotEmpty() && getScopeRep() == nullptr; }
/// A scope specifier is present, and it refers to a real scope.
bool isValid() const { return isNotEmpty() && getScopeRep() != nullptr; }
/// \brief Indicate that this nested-name-specifier is invalid.
void SetInvalid(SourceRange R) {
assert(R.isValid() && "Must have a valid source range");
if (Range.getBegin().isInvalid())
Range.setBegin(R.getBegin());
Range.setEnd(R.getEnd());
Builder.Clear();
}
/// Deprecated. Some call sites intend isNotEmpty() while others intend
/// isValid().
bool isSet() const { return getScopeRep() != nullptr; }
void clear() {
Range = SourceRange();
Builder.Clear();
}
/// \brief Retrieve the data associated with the source-location information.
char *location_data() const { return Builder.getBuffer().first; }
/// \brief Retrieve the size of the data associated with source-location
/// information.
unsigned location_size() const { return Builder.getBuffer().second; }
};
/// \brief Captures information about "declaration specifiers".
///
/// "Declaration specifiers" encompasses storage-class-specifiers,
/// type-specifiers, type-qualifiers, and function-specifiers.
class DeclSpec {
public:
/// \brief storage-class-specifier
/// \note The order of these enumerators is important for diagnostics.
enum SCS {
SCS_unspecified = 0,
SCS_typedef,
SCS_extern,
SCS_static,
SCS_auto,
SCS_register,
SCS_private_extern,
SCS_mutable
};
// Import thread storage class specifier enumeration and constants.
// These can be combined with SCS_extern and SCS_static.
typedef ThreadStorageClassSpecifier TSCS;
static const TSCS TSCS_unspecified = clang::TSCS_unspecified;
static const TSCS TSCS___thread = clang::TSCS___thread;
static const TSCS TSCS_thread_local = clang::TSCS_thread_local;
static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local;
// Import type specifier width enumeration and constants.
typedef TypeSpecifierWidth TSW;
static const TSW TSW_unspecified = clang::TSW_unspecified;
static const TSW TSW_short = clang::TSW_short;
static const TSW TSW_long = clang::TSW_long;
static const TSW TSW_longlong = clang::TSW_longlong;
enum TSC {
TSC_unspecified,
TSC_imaginary,
TSC_complex
};
// Import type specifier sign enumeration and constants.
typedef TypeSpecifierSign TSS;
static const TSS TSS_unspecified = clang::TSS_unspecified;
static const TSS TSS_signed = clang::TSS_signed;
static const TSS TSS_unsigned = clang::TSS_unsigned;
// Import type specifier type enumeration and constants.
typedef TypeSpecifierType TST;
static const TST TST_unspecified = clang::TST_unspecified;
static const TST TST_void = clang::TST_void;
static const TST TST_char = clang::TST_char;
static const TST TST_wchar = clang::TST_wchar;
static const TST TST_char16 = clang::TST_char16;
static const TST TST_char32 = clang::TST_char32;
static const TST TST_int = clang::TST_int;
static const TST TST_int128 = clang::TST_int128;
// HLSL Change Starts
static const TST TST_halffloat = clang::TST_halffloat;
static const TST TST_min16float = clang::TST_min16float;
static const TST TST_min16int = clang::TST_min16int;
static const TST TST_min16uint = clang::TST_min16uint;
static const TST TST_min10float = clang::TST_min10float;
static const TST TST_min12int = clang::TST_min12int;
static const TST TST_int8_4packed = clang::TST_int8_4packed;
static const TST TST_uint8_4packed = clang::TST_uint8_4packed;
// HLSL Change Ends
static const TST TST_half = clang::TST_half;
static const TST TST_float = clang::TST_float;
static const TST TST_double = clang::TST_double;
static const TST TST_bool = clang::TST_bool;
static const TST TST_decimal32 = clang::TST_decimal32;
static const TST TST_decimal64 = clang::TST_decimal64;
static const TST TST_decimal128 = clang::TST_decimal128;
static const TST TST_enum = clang::TST_enum;
static const TST TST_union = clang::TST_union;
static const TST TST_struct = clang::TST_struct;
static const TST TST_interface = clang::TST_interface;
static const TST TST_class = clang::TST_class;
static const TST TST_typename = clang::TST_typename;
static const TST TST_typeofType = clang::TST_typeofType;
static const TST TST_typeofExpr = clang::TST_typeofExpr;
static const TST TST_decltype = clang::TST_decltype;
static const TST TST_decltype_auto = clang::TST_decltype_auto;
static const TST TST_underlyingType = clang::TST_underlyingType;
static const TST TST_auto = clang::TST_auto;
static const TST TST_unknown_anytype = clang::TST_unknown_anytype;
static const TST TST_atomic = clang::TST_atomic;
static const TST TST_error = clang::TST_error;
// type-qualifiers
enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ.
TQ_unspecified = 0,
TQ_const = 1,
TQ_restrict = 2,
TQ_volatile = 4,
// This has no corresponding Qualifiers::TQ value, because it's not treated
// as a qualifier in our type system.
TQ_atomic = 8
};
/// ParsedSpecifiers - Flags to query which specifiers were applied. This is
/// returned by getParsedSpecifiers.
enum ParsedSpecifiers {
PQ_None = 0,
PQ_StorageClassSpecifier = 1,
PQ_TypeSpecifier = 2,
PQ_TypeQualifier = 4,
PQ_FunctionSpecifier = 8
};
private:
// storage-class-specifier
/*SCS*/unsigned StorageClassSpec : 3;
/*TSCS*/unsigned ThreadStorageClassSpec : 2;
unsigned SCS_extern_in_linkage_spec : 1;
// HLSL Change Start
// Whether the default matrix pack is defined at the point
// of the declaration. This is false when rewriting
// and no #pragma pack_matrix have been encountered yet.
unsigned HasDefaultMatrixPack : 1;
// Default matrix pack at the point of the declaration
unsigned DefaultMatrixPackRowMajor : 1;
// HLSL Change End
// type-specifier
/*TSW*/unsigned TypeSpecWidth : 2;
/*TSC*/unsigned TypeSpecComplex : 2;
/*TSS*/unsigned TypeSpecSign : 2;
/*TST*/unsigned TypeSpecType : 6;
unsigned TypeAltiVecVector : 1;
unsigned TypeAltiVecPixel : 1;
unsigned TypeAltiVecBool : 1;
unsigned TypeSpecOwned : 1;
// type-qualifiers
unsigned TypeQualifiers : 4; // Bitwise OR of TQ.
// function-specifier
unsigned FS_inline_specified : 1;
unsigned FS_forceinline_specified: 1;
unsigned FS_virtual_specified : 1;
unsigned FS_explicit_specified : 1;
unsigned FS_noreturn_specified : 1;
// friend-specifier
unsigned Friend_specified : 1;
// constexpr-specifier
unsigned Constexpr_specified : 1;
// concept-specifier
unsigned Concept_specified : 1;
union {
UnionParsedType TypeRep;
Decl *DeclRep;
Expr *ExprRep;
};
// attributes.
ParsedAttributes Attrs;
// Scope specifier for the type spec, if applicable.
CXXScopeSpec TypeScope;
// SourceLocation info. These are null if the item wasn't specified or if
// the setting was synthesized.
SourceRange Range;
SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc;
SourceLocation TSWLoc, TSCLoc, TSSLoc, TSTLoc, AltiVecLoc;
/// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union,
/// typename, then this is the location of the named type (if present);
/// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and
/// TSTNameLoc provides source range info for tag types.
SourceLocation TSTNameLoc;
SourceRange TypeofParensRange;
SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc;
SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc;
SourceLocation FS_forceinlineLoc;
SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc, ConceptLoc;
WrittenBuiltinSpecs writtenBS;
void SaveWrittenBuiltinSpecs();
ObjCDeclSpec *ObjCQualifiers;
static bool isTypeRep(TST T) {
return (T == TST_typename || T == TST_typeofType ||
T == TST_underlyingType || T == TST_atomic);
}
static bool isExprRep(TST T) {
return (T == TST_typeofExpr || T == TST_decltype);
}
DeclSpec(const DeclSpec &) = delete;
void operator=(const DeclSpec &) = delete;
public:
static bool isDeclRep(TST T) {
return (T == TST_enum || T == TST_struct ||
T == TST_interface || T == TST_union ||
T == TST_class);
}
DeclSpec(AttributeFactory &attrFactory)
: StorageClassSpec(SCS_unspecified),
ThreadStorageClassSpec(TSCS_unspecified),
SCS_extern_in_linkage_spec(false),
HasDefaultMatrixPack(false), // HLSL Change
DefaultMatrixPackRowMajor(false), // HLSL Change
TypeSpecWidth(TSW_unspecified),
TypeSpecComplex(TSC_unspecified),
TypeSpecSign(TSS_unspecified),
TypeSpecType(TST_unspecified),
TypeAltiVecVector(false),
TypeAltiVecPixel(false),
TypeAltiVecBool(false),
TypeSpecOwned(false),
TypeQualifiers(TQ_unspecified),
FS_inline_specified(false),
FS_forceinline_specified(false),
FS_virtual_specified(false),
FS_explicit_specified(false),
FS_noreturn_specified(false),
Friend_specified(false),
Constexpr_specified(false),
Concept_specified(false),
Attrs(attrFactory),
writtenBS(),
ObjCQualifiers(nullptr) {
}
// storage-class-specifier
SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; }
TSCS getThreadStorageClassSpec() const {
return (TSCS)ThreadStorageClassSpec;
}
bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; }
void setExternInLinkageSpec(bool Value) {
SCS_extern_in_linkage_spec = Value;
}
// HLSL changes begin
bool TryGetDefaultMatrixPackRowMajor(bool& rowMajor) const {
if (!HasDefaultMatrixPack) return false;
rowMajor = DefaultMatrixPackRowMajor;
return true;
}
void SetDefaultMatrixPackRowMajor(bool Value) {
HasDefaultMatrixPack = true;
DefaultMatrixPackRowMajor = Value;
}
// HLSL changes end
SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; }
SourceLocation getThreadStorageClassSpecLoc() const {
return ThreadStorageClassSpecLoc;
}
void ClearStorageClassSpecs() {
StorageClassSpec = DeclSpec::SCS_unspecified;
ThreadStorageClassSpec = DeclSpec::TSCS_unspecified;
SCS_extern_in_linkage_spec = false;
StorageClassSpecLoc = SourceLocation();
ThreadStorageClassSpecLoc = SourceLocation();
}
void ClearTypeSpecType() {
TypeSpecType = DeclSpec::TST_unspecified;
TypeSpecOwned = false;
TSTLoc = SourceLocation();
}
// type-specifier
TSW getTypeSpecWidth() const { return (TSW)TypeSpecWidth; }
TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; }
TSS getTypeSpecSign() const { return (TSS)TypeSpecSign; }
TST getTypeSpecType() const { return (TST)TypeSpecType; }
bool isTypeAltiVecVector() const { return TypeAltiVecVector; }
bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; }
bool isTypeAltiVecBool() const { return TypeAltiVecBool; }
bool isTypeSpecOwned() const { return TypeSpecOwned; }
bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); }
ParsedType getRepAsType() const {
assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type");
return TypeRep;
}
Decl *getRepAsDecl() const {
assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl");
return DeclRep;
}
Expr *getRepAsExpr() const {
assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr");
return ExprRep;
}
CXXScopeSpec &getTypeSpecScope() { return TypeScope; }
const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; }
const SourceRange &getSourceRange() const LLVM_READONLY { return Range; }
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
SourceLocation getTypeSpecWidthLoc() const { return TSWLoc; }
SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; }
SourceLocation getTypeSpecSignLoc() const { return TSSLoc; }
SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; }
SourceLocation getAltiVecLoc() const { return AltiVecLoc; }
SourceLocation getTypeSpecTypeNameLoc() const {
assert(isDeclRep((TST) TypeSpecType) || TypeSpecType == TST_typename);
return TSTNameLoc;
}
SourceRange getTypeofParensRange() const { return TypeofParensRange; }
void setTypeofParensRange(SourceRange range) { TypeofParensRange = range; }
bool containsPlaceholderType() const {
return TypeSpecType == TST_auto || TypeSpecType == TST_decltype_auto;
}
bool hasTagDefinition() const;
/// \brief Turn a type-specifier-type into a string like "_Bool" or "union".
static const char *getSpecifierName(DeclSpec::TST T,
const PrintingPolicy &Policy);
static const char *getSpecifierName(DeclSpec::TQ Q);
static const char *getSpecifierName(DeclSpec::TSS S);
static const char *getSpecifierName(DeclSpec::TSC C);
static const char *getSpecifierName(DeclSpec::TSW W);
static const char *getSpecifierName(DeclSpec::SCS S);
static const char *getSpecifierName(DeclSpec::TSCS S);
// type-qualifiers
/// getTypeQualifiers - Return a set of TQs.
unsigned getTypeQualifiers() const { return TypeQualifiers; }
SourceLocation getConstSpecLoc() const { return TQ_constLoc; }
SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; }
SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; }
SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; }
/// \brief Clear out all of the type qualifiers.
void ClearTypeQualifiers() {
TypeQualifiers = 0;
TQ_constLoc = SourceLocation();
TQ_restrictLoc = SourceLocation();
TQ_volatileLoc = SourceLocation();
TQ_atomicLoc = SourceLocation();
}
// function-specifier
bool isInlineSpecified() const {
return FS_inline_specified | FS_forceinline_specified;
}
SourceLocation getInlineSpecLoc() const {
return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc;
}
bool isVirtualSpecified() const { return FS_virtual_specified; }
SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; }
bool isExplicitSpecified() const { return FS_explicit_specified; }
SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; }
bool isNoreturnSpecified() const { return FS_noreturn_specified; }
SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; }
void ClearFunctionSpecs() {
FS_inline_specified = false;
FS_inlineLoc = SourceLocation();
FS_forceinline_specified = false;
FS_forceinlineLoc = SourceLocation();
FS_virtual_specified = false;
FS_virtualLoc = SourceLocation();
FS_explicit_specified = false;
FS_explicitLoc = SourceLocation();
FS_noreturn_specified = false;
FS_noreturnLoc = SourceLocation();
}
/// \brief Return true if any type-specifier has been found.
bool hasTypeSpecifier() const {
return getTypeSpecType() != DeclSpec::TST_unspecified ||
getTypeSpecWidth() != DeclSpec::TSW_unspecified ||
getTypeSpecComplex() != DeclSpec::TSC_unspecified;
//getTypeSpecSign() != DeclSpec::TSS_unspecified; // HLSL Change - unsigned is not a complete type specifier.
}
/// \brief Return a bitmask of which flavors of specifiers this
/// DeclSpec includes.
unsigned getParsedSpecifiers() const;
/// isEmpty - Return true if this declaration specifier is completely empty:
/// no tokens were parsed in the production of it.
bool isEmpty() const {
return getParsedSpecifiers() == DeclSpec::PQ_None;
}
void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); }
void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); }
/// These methods set the specified attribute of the DeclSpec and
/// return false if there was no error. If an error occurs (for
/// example, if we tried to set "auto" on a spec with "extern"
/// already set), they return true and set PrevSpec and DiagID
/// such that
/// Diag(Loc, DiagID) << PrevSpec;
/// will yield a useful result.
///
/// TODO: use a more general approach that still allows these
/// diagnostics to be ignored when desired.
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
const PrintingPolicy &Policy);
bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID);
bool SetTypeSpecWidth(TSW W, SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID, const PrintingPolicy &Policy);
bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool SetTypeSpecSign(TSS S, SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID, const PrintingPolicy &Policy);
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID, ParsedType Rep,
const PrintingPolicy &Policy);
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID, Decl *Rep, bool Owned,
const PrintingPolicy &Policy);
bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
SourceLocation TagNameLoc, const char *&PrevSpec,
unsigned &DiagID, ParsedType Rep,
const PrintingPolicy &Policy);
bool SetTypeSpecType(TST T, SourceLocation TagKwLoc,
SourceLocation TagNameLoc, const char *&PrevSpec,
unsigned &DiagID, Decl *Rep, bool Owned,
const PrintingPolicy &Policy);
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID, Expr *Rep,
const PrintingPolicy &policy);
bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
const PrintingPolicy &Policy);
bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
const PrintingPolicy &Policy);
bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc,
const char *&PrevSpec, unsigned &DiagID,
const PrintingPolicy &Policy);
bool SetTypeSpecError();
void UpdateDeclRep(Decl *Rep) {
assert(isDeclRep((TST) TypeSpecType));
DeclRep = Rep;
}
void UpdateTypeRep(ParsedType Rep) {
assert(isTypeRep((TST) TypeSpecType));
TypeRep = Rep;
}
void UpdateExprRep(Expr *Rep) {
assert(isExprRep((TST) TypeSpecType));
ExprRep = Rep;
}
bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID, const LangOptions &Lang);
bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool SetConstexprSpec(SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool SetConceptSpec(SourceLocation Loc, const char *&PrevSpec,
unsigned &DiagID);
bool isFriendSpecified() const { return Friend_specified; }
SourceLocation getFriendSpecLoc() const { return FriendLoc; }
bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); }
SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; }
bool isConstexprSpecified() const { return Constexpr_specified; }
SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; }
bool isConceptSpecified() const { return Concept_specified; }
SourceLocation getConceptSpecLoc() const { return ConceptLoc; }
void ClearConstexprSpec() {
Constexpr_specified = false;
ConstexprLoc = SourceLocation();
}
void ClearConceptSpec() {
Concept_specified = false;
ConceptLoc = SourceLocation();
}
AttributePool &getAttributePool() const {
return Attrs.getPool();
}
/// \brief Concatenates two attribute lists.
///
/// The GCC attribute syntax allows for the following:
///
/// \code
/// short __attribute__(( unused, deprecated ))
/// int __attribute__(( may_alias, aligned(16) )) var;
/// \endcode
///
/// This declares 4 attributes using 2 lists. The following syntax is
/// also allowed and equivalent to the previous declaration.
///
/// \code
/// short __attribute__((unused)) __attribute__((deprecated))
/// int __attribute__((may_alias)) __attribute__((aligned(16))) var;
/// \endcode
///
void addAttributes(AttributeList *AL) {
Attrs.addAll(AL);
}
bool hasAttributes() const { return !Attrs.empty(); }
ParsedAttributes &getAttributes() { return Attrs; }
const ParsedAttributes &getAttributes() const { return Attrs; }
void takeAttributesFrom(ParsedAttributes &attrs) {
Attrs.takeAllFrom(attrs);
}
/// Finish - This does final analysis of the declspec, issuing diagnostics for
/// things like "_Imaginary" (lacking an FP type). After calling this method,
/// DeclSpec is guaranteed self-consistent, even if an error occurred.
void Finish(DiagnosticsEngine &D, Preprocessor &PP,
const PrintingPolicy &Policy);
const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const {
return writtenBS;
}
ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; }
void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; }
/// \brief Checks if this DeclSpec can stand alone, without a Declarator.
///
/// Only tag declspecs can stand alone.
bool isMissingDeclaratorOk();
};
/// \brief Captures information about "declaration specifiers" specific to
/// Objective-C.
class ObjCDeclSpec {
public:
/// ObjCDeclQualifier - Qualifier used on types in method
/// declarations. Not all combinations are sensible. Parameters
/// can be one of { in, out, inout } with one of { bycopy, byref }.
/// Returns can either be { oneway } or not.
///
/// This should be kept in sync with Decl::ObjCDeclQualifier.
enum ObjCDeclQualifier {
DQ_None = 0x0,
DQ_In = 0x1,
DQ_Inout = 0x2,
DQ_Out = 0x4,
DQ_Bycopy = 0x8,
DQ_Byref = 0x10,
DQ_Oneway = 0x20,
DQ_CSNullability = 0x40
};
/// PropertyAttributeKind - list of property attributes.
enum ObjCPropertyAttributeKind {
DQ_PR_noattr = 0x0,
DQ_PR_readonly = 0x01,
DQ_PR_getter = 0x02,
DQ_PR_assign = 0x04,
DQ_PR_readwrite = 0x08,
DQ_PR_retain = 0x10,
DQ_PR_copy = 0x20,
DQ_PR_nonatomic = 0x40,
DQ_PR_setter = 0x80,
DQ_PR_atomic = 0x100,
DQ_PR_weak = 0x200,
DQ_PR_strong = 0x400,
DQ_PR_unsafe_unretained = 0x800,
DQ_PR_nullability = 0x1000,
DQ_PR_null_resettable = 0x2000
};
ObjCDeclSpec()
: objcDeclQualifier(DQ_None), PropertyAttributes(DQ_PR_noattr),
Nullability(0), GetterName(nullptr), SetterName(nullptr) { }
ObjCDeclQualifier getObjCDeclQualifier() const { return objcDeclQualifier; }
void setObjCDeclQualifier(ObjCDeclQualifier DQVal) {
objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal);
}
void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) {
objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal);
}
ObjCPropertyAttributeKind getPropertyAttributes() const {
return ObjCPropertyAttributeKind(PropertyAttributes);
}
void setPropertyAttributes(ObjCPropertyAttributeKind PRVal) {
PropertyAttributes =
(ObjCPropertyAttributeKind)(PropertyAttributes | PRVal);
}
NullabilityKind getNullability() const {
assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
(getPropertyAttributes() & DQ_PR_nullability)) &&
"Objective-C declspec doesn't have nullability");
return static_cast<NullabilityKind>(Nullability);
}
SourceLocation getNullabilityLoc() const {
assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
(getPropertyAttributes() & DQ_PR_nullability)) &&
"Objective-C declspec doesn't have nullability");
return NullabilityLoc;
}
void setNullability(SourceLocation loc, NullabilityKind kind) {
assert(((getObjCDeclQualifier() & DQ_CSNullability) ||
(getPropertyAttributes() & DQ_PR_nullability)) &&
"Set the nullability declspec or property attribute first");
Nullability = static_cast<unsigned>(kind);
NullabilityLoc = loc;
}
const IdentifierInfo *getGetterName() const { return GetterName; }
IdentifierInfo *getGetterName() { return GetterName; }
void setGetterName(IdentifierInfo *name) { GetterName = name; }
const IdentifierInfo *getSetterName() const { return SetterName; }
IdentifierInfo *getSetterName() { return SetterName; }
void setSetterName(IdentifierInfo *name) { SetterName = name; }
private:
// FIXME: These two are unrelated and mutually exclusive. So perhaps
// we can put them in a union to reflect their mutual exclusivity
// (space saving is negligible).
ObjCDeclQualifier objcDeclQualifier : 7;
// NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttributeKind
unsigned PropertyAttributes : 14;
unsigned Nullability : 2;
SourceLocation NullabilityLoc;
IdentifierInfo *GetterName; // getter name or NULL if no getter
IdentifierInfo *SetterName; // setter name or NULL if no setter
};
/// \brief Represents a C++ unqualified-id that has been parsed.
class UnqualifiedId {
private:
UnqualifiedId(const UnqualifiedId &Other) = delete;
const UnqualifiedId &operator=(const UnqualifiedId &) = delete;
public:
/// \brief Describes the kind of unqualified-id parsed.
enum IdKind {
/// \brief An identifier.
IK_Identifier,
/// \brief An overloaded operator name, e.g., operator+.
IK_OperatorFunctionId,
/// \brief A conversion function name, e.g., operator int.
IK_ConversionFunctionId,
/// \brief A user-defined literal name, e.g., operator "" _i.
IK_LiteralOperatorId,
/// \brief A constructor name.
IK_ConstructorName,
/// \brief A constructor named via a template-id.
IK_ConstructorTemplateId,
/// \brief A destructor name.
IK_DestructorName,
/// \brief A template-id, e.g., f<int>.
IK_TemplateId,
/// \brief An implicit 'self' parameter
IK_ImplicitSelfParam
} Kind;
struct OFI {
/// \brief The kind of overloaded operator.
OverloadedOperatorKind Operator;
/// \brief The source locations of the individual tokens that name
/// the operator, e.g., the "new", "[", and "]" tokens in
/// operator new [].
///
/// Different operators have different numbers of tokens in their name,
/// up to three. Any remaining source locations in this array will be
/// set to an invalid value for operators with fewer than three tokens.
unsigned SymbolLocations[3];
};
/// \brief Anonymous union that holds extra data associated with the
/// parsed unqualified-id.
union {
/// \brief When Kind == IK_Identifier, the parsed identifier, or when Kind
/// == IK_UserLiteralId, the identifier suffix.
IdentifierInfo *Identifier;
/// \brief When Kind == IK_OperatorFunctionId, the overloaded operator
/// that we parsed.
struct OFI OperatorFunctionId;
/// \brief When Kind == IK_ConversionFunctionId, the type that the
/// conversion function names.
UnionParsedType ConversionFunctionId;
/// \brief When Kind == IK_ConstructorName, the class-name of the type
/// whose constructor is being referenced.
UnionParsedType ConstructorName;
/// \brief When Kind == IK_DestructorName, the type referred to by the
/// class-name.
UnionParsedType DestructorName;
/// \brief When Kind == IK_TemplateId or IK_ConstructorTemplateId,
/// the template-id annotation that contains the template name and
/// template arguments.
TemplateIdAnnotation *TemplateId;
};
/// \brief The location of the first token that describes this unqualified-id,
/// which will be the location of the identifier, "operator" keyword,
/// tilde (for a destructor), or the template name of a template-id.
SourceLocation StartLocation;
/// \brief The location of the last token that describes this unqualified-id.
SourceLocation EndLocation;
UnqualifiedId() : Kind(IK_Identifier), Identifier(nullptr) { }
/// \brief Clear out this unqualified-id, setting it to default (invalid)
/// state.
void clear() {
Kind = IK_Identifier;
Identifier = nullptr;
StartLocation = SourceLocation();
EndLocation = SourceLocation();
}
/// \brief Determine whether this unqualified-id refers to a valid name.
bool isValid() const { return StartLocation.isValid(); }
/// \brief Determine whether this unqualified-id refers to an invalid name.
bool isInvalid() const { return !isValid(); }
/// \brief Determine what kind of name we have.
IdKind getKind() const { return Kind; }
void setKind(IdKind kind) { Kind = kind; }
/// \brief Specify that this unqualified-id was parsed as an identifier.
///
/// \param Id the parsed identifier.
/// \param IdLoc the location of the parsed identifier.
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) {
Kind = IK_Identifier;
Identifier = const_cast<IdentifierInfo *>(Id);
StartLocation = EndLocation = IdLoc;
}
/// \brief Specify that this unqualified-id was parsed as an
/// operator-function-id.
///
/// \param OperatorLoc the location of the 'operator' keyword.
///
/// \param Op the overloaded operator.
///
/// \param SymbolLocations the locations of the individual operator symbols
/// in the operator.
void setOperatorFunctionId(SourceLocation OperatorLoc,
OverloadedOperatorKind Op,
SourceLocation SymbolLocations[3]);
/// \brief Specify that this unqualified-id was parsed as a
/// conversion-function-id.
///
/// \param OperatorLoc the location of the 'operator' keyword.
///
/// \param Ty the type to which this conversion function is converting.
///
/// \param EndLoc the location of the last token that makes up the type name.
void setConversionFunctionId(SourceLocation OperatorLoc,
ParsedType Ty,
SourceLocation EndLoc) {
Kind = IK_ConversionFunctionId;
StartLocation = OperatorLoc;
EndLocation = EndLoc;
ConversionFunctionId = Ty;
}
/// \brief Specific that this unqualified-id was parsed as a
/// literal-operator-id.
///
/// \param Id the parsed identifier.
///
/// \param OpLoc the location of the 'operator' keyword.
///
/// \param IdLoc the location of the identifier.
void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc,
SourceLocation IdLoc) {
Kind = IK_LiteralOperatorId;
Identifier = const_cast<IdentifierInfo *>(Id);
StartLocation = OpLoc;
EndLocation = IdLoc;
}
/// \brief Specify that this unqualified-id was parsed as a constructor name.
///
/// \param ClassType the class type referred to by the constructor name.
///
/// \param ClassNameLoc the location of the class name.
///
/// \param EndLoc the location of the last token that makes up the type name.
void setConstructorName(ParsedType ClassType,
SourceLocation ClassNameLoc,
SourceLocation EndLoc) {
Kind = IK_ConstructorName;
StartLocation = ClassNameLoc;
EndLocation = EndLoc;
ConstructorName = ClassType;
}
/// \brief Specify that this unqualified-id was parsed as a
/// template-id that names a constructor.
///
/// \param TemplateId the template-id annotation that describes the parsed
/// template-id. This UnqualifiedId instance will take ownership of the
/// \p TemplateId and will free it on destruction.
void setConstructorTemplateId(TemplateIdAnnotation *TemplateId);
/// \brief Specify that this unqualified-id was parsed as a destructor name.
///
/// \param TildeLoc the location of the '~' that introduces the destructor
/// name.
///
/// \param ClassType the name of the class referred to by the destructor name.
void setDestructorName(SourceLocation TildeLoc,
ParsedType ClassType,
SourceLocation EndLoc) {
Kind = IK_DestructorName;
StartLocation = TildeLoc;
EndLocation = EndLoc;
DestructorName = ClassType;
}
/// \brief Specify that this unqualified-id was parsed as a template-id.
///
/// \param TemplateId the template-id annotation that describes the parsed
/// template-id. This UnqualifiedId instance will take ownership of the
/// \p TemplateId and will free it on destruction.
void setTemplateId(TemplateIdAnnotation *TemplateId);
/// \brief Return the source range that covers this unqualified-id.
SourceRange getSourceRange() const LLVM_READONLY {
return SourceRange(StartLocation, EndLocation);
}
SourceLocation getLocStart() const LLVM_READONLY { return StartLocation; }
SourceLocation getLocEnd() const LLVM_READONLY { return EndLocation; }
};
/// \brief A set of tokens that has been cached for later parsing.
typedef SmallVector<Token, 4> CachedTokens;
/// \brief One instance of this struct is used for each type in a
/// declarator that is parsed.
///
/// This is intended to be a small value object.
struct DeclaratorChunk {
enum {
Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren
} Kind;
/// Loc - The place where this type was defined.
SourceLocation Loc;
/// EndLoc - If valid, the place where this chunck ends.
SourceLocation EndLoc;
SourceRange getSourceRange() const {
if (EndLoc.isInvalid())
return SourceRange(Loc, Loc);
return SourceRange(Loc, EndLoc);
}
struct TypeInfoCommon {
AttributeList *AttrList;
};
struct PointerTypeInfo : TypeInfoCommon {
/// The type qualifiers: const/volatile/restrict/atomic.
unsigned TypeQuals : 4;
/// The location of the const-qualifier, if any.
unsigned ConstQualLoc;
/// The location of the volatile-qualifier, if any.
unsigned VolatileQualLoc;
/// The location of the restrict-qualifier, if any.
unsigned RestrictQualLoc;
/// The location of the _Atomic-qualifier, if any.
unsigned AtomicQualLoc;
void destroy() {
}
};
struct ReferenceTypeInfo : TypeInfoCommon {
/// The type qualifier: restrict. [GNU] C++ extension
bool HasRestrict : 1;
/// True if this is an lvalue reference, false if it's an rvalue reference.
bool LValueRef : 1;
void destroy() {
}
};
struct ArrayTypeInfo : TypeInfoCommon {
/// The type qualifiers for the array: const/volatile/restrict/_Atomic.
unsigned TypeQuals : 4;
/// True if this dimension included the 'static' keyword.
bool hasStatic : 1;
/// True if this dimension was [*]. In this case, NumElts is null.
bool isStar : 1;
/// This is the size of the array, or null if [] or [*] was specified.
/// Since the parser is multi-purpose, and we don't want to impose a root
/// expression class on all clients, NumElts is untyped.
Expr *NumElts;
void destroy() {}
};
/// ParamInfo - An array of paraminfo objects is allocated whenever a function
/// declarator is parsed. There are two interesting styles of parameters
/// here:
/// K&R-style identifier lists and parameter type lists. K&R-style identifier
/// lists will have information about the identifier, but no type information.
/// Parameter type lists will have type info (if the actions module provides
/// it), but may have null identifier info: e.g. for 'void foo(int X, int)'.
struct ParamInfo {
IdentifierInfo *Ident;
SourceLocation IdentLoc;
Decl *Param;
/// DefaultArgTokens - When the parameter's default argument
/// cannot be parsed immediately (because it occurs within the
/// declaration of a member function), it will be stored here as a
/// sequence of tokens to be parsed once the class definition is
/// complete. Non-NULL indicates that there is a default argument.
CachedTokens *DefaultArgTokens;
ParamInfo() {}
ParamInfo(IdentifierInfo *ident, SourceLocation iloc,
Decl *param,
CachedTokens *DefArgTokens = nullptr)
: Ident(ident), IdentLoc(iloc), Param(param),
DefaultArgTokens(DefArgTokens) {}
};
struct TypeAndRange {
ParsedType Ty;
SourceRange Range;
};
struct FunctionTypeInfo : TypeInfoCommon {
/// hasPrototype - This is true if the function had at least one typed
/// parameter. If the function is () or (a,b,c), then it has no prototype,
/// and is treated as a K&R-style function.
unsigned hasPrototype : 1;
/// isVariadic - If this function has a prototype, and if that
/// proto ends with ',...)', this is true. When true, EllipsisLoc
/// contains the location of the ellipsis.
unsigned isVariadic : 1;
/// Can this declaration be a constructor-style initializer?
unsigned isAmbiguous : 1;
/// \brief Whether the ref-qualifier (if any) is an lvalue reference.
/// Otherwise, it's an rvalue reference.
unsigned RefQualifierIsLValueRef : 1;
/// The type qualifiers: const/volatile/restrict.
/// The qualifier bitmask values are the same as in QualType.
unsigned TypeQuals : 3;
/// ExceptionSpecType - An ExceptionSpecificationType value.
unsigned ExceptionSpecType : 4;
/// DeleteParams - If this is true, we need to delete[] Params.
unsigned DeleteParams : 1;
/// HasTrailingReturnType - If this is true, a trailing return type was
/// specified.
unsigned HasTrailingReturnType : 1;
/// The location of the left parenthesis in the source.
unsigned LParenLoc;
/// When isVariadic is true, the location of the ellipsis in the source.
unsigned EllipsisLoc;
/// The location of the right parenthesis in the source.
unsigned RParenLoc;
/// NumParams - This is the number of formal parameters specified by the
/// declarator.
unsigned NumParams;
/// NumExceptions - This is the number of types in the dynamic-exception-
/// decl, if the function has one.
unsigned NumExceptions;
/// \brief The location of the ref-qualifier, if any.
///
/// If this is an invalid location, there is no ref-qualifier.
unsigned RefQualifierLoc;
/// \brief The location of the const-qualifier, if any.
///
/// If this is an invalid location, there is no const-qualifier.
unsigned ConstQualifierLoc;
/// \brief The location of the volatile-qualifier, if any.
///
/// If this is an invalid location, there is no volatile-qualifier.
unsigned VolatileQualifierLoc;
/// \brief The location of the restrict-qualifier, if any.
///
/// If this is an invalid location, there is no restrict-qualifier.
unsigned RestrictQualifierLoc;
/// \brief The location of the 'mutable' qualifer in a lambda-declarator, if
/// any.
unsigned MutableLoc;
/// \brief The location of the keyword introducing the spec, if any.
unsigned ExceptionSpecLoc;
/// Params - This is a pointer to a new[]'d array of ParamInfo objects that
/// describe the parameters specified by this function declarator. null if
/// there are no parameters specified.
ParamInfo *Params;
union {
/// \brief Pointer to a new[]'d array of TypeAndRange objects that
/// contain the types in the function's dynamic exception specification
/// and their locations, if there is one.
TypeAndRange *Exceptions;
/// \brief Pointer to the expression in the noexcept-specifier of this
/// function, if it has one.
Expr *NoexceptExpr;
/// \brief Pointer to the cached tokens for an exception-specification
/// that has not yet been parsed.
CachedTokens *ExceptionSpecTokens;
};
/// \brief If HasTrailingReturnType is true, this is the trailing return
/// type specified.
UnionParsedType TrailingReturnType;
/// \brief Reset the parameter list to having zero parameters.
///
/// This is used in various places for error recovery.
void freeParams() {
for (unsigned I = 0; I < NumParams; ++I) {
delete Params[I].DefaultArgTokens;
Params[I].DefaultArgTokens = nullptr;
}
if (DeleteParams) {
delete[] Params;
DeleteParams = false;
}
NumParams = 0;
}
void destroy() {
if (DeleteParams)
delete[] Params;
if (getExceptionSpecType() == EST_Dynamic)
delete[] Exceptions;
else if (getExceptionSpecType() == EST_Unparsed)
delete ExceptionSpecTokens;
}
/// isKNRPrototype - Return true if this is a K&R style identifier list,
/// like "void foo(a,b,c)". In a function definition, this will be followed
/// by the parameter type definitions.
bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; }
SourceLocation getLParenLoc() const {
return SourceLocation::getFromRawEncoding(LParenLoc);
}
SourceLocation getEllipsisLoc() const {
return SourceLocation::getFromRawEncoding(EllipsisLoc);
}
SourceLocation getRParenLoc() const {
return SourceLocation::getFromRawEncoding(RParenLoc);
}
SourceLocation getExceptionSpecLoc() const {
return SourceLocation::getFromRawEncoding(ExceptionSpecLoc);
}
/// \brief Retrieve the location of the ref-qualifier, if any.
SourceLocation getRefQualifierLoc() const {
return SourceLocation::getFromRawEncoding(RefQualifierLoc);
}
/// \brief Retrieve the location of the 'const' qualifier, if any.
SourceLocation getConstQualifierLoc() const {
return SourceLocation::getFromRawEncoding(ConstQualifierLoc);
}
/// \brief Retrieve the location of the 'volatile' qualifier, if any.
SourceLocation getVolatileQualifierLoc() const {
return SourceLocation::getFromRawEncoding(VolatileQualifierLoc);
}
/// \brief Retrieve the location of the 'restrict' qualifier, if any.
SourceLocation getRestrictQualifierLoc() const {
return SourceLocation::getFromRawEncoding(RestrictQualifierLoc);
}
/// \brief Retrieve the location of the 'mutable' qualifier, if any.
SourceLocation getMutableLoc() const {
return SourceLocation::getFromRawEncoding(MutableLoc);
}
/// \brief Determine whether this function declaration contains a
/// ref-qualifier.
bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); }
/// \brief Determine whether this lambda-declarator contains a 'mutable'
/// qualifier.
bool hasMutableQualifier() const { return getMutableLoc().isValid(); }
/// \brief Get the type of exception specification this function has.
ExceptionSpecificationType getExceptionSpecType() const {
return static_cast<ExceptionSpecificationType>(ExceptionSpecType);
}
/// \brief Determine whether this function declarator had a
/// trailing-return-type.
bool hasTrailingReturnType() const { return HasTrailingReturnType; }
/// \brief Get the trailing-return-type for this function declarator.
ParsedType getTrailingReturnType() const { return TrailingReturnType; }
};
struct BlockPointerTypeInfo : TypeInfoCommon {
/// For now, sema will catch these as invalid.
/// The type qualifiers: const/volatile/restrict/_Atomic.
unsigned TypeQuals : 4;
void destroy() {
}
};
struct MemberPointerTypeInfo : TypeInfoCommon {
/// The type qualifiers: const/volatile/restrict/_Atomic.
unsigned TypeQuals : 4;
// CXXScopeSpec has a constructor, so it can't be a direct member.
// So we need some pointer-aligned storage and a bit of trickery.
union {
void *Aligner;
char Mem[sizeof(CXXScopeSpec)];
} ScopeMem;
CXXScopeSpec &Scope() {
return *reinterpret_cast<CXXScopeSpec*>(ScopeMem.Mem);
}
const CXXScopeSpec &Scope() const {
return *reinterpret_cast<const CXXScopeSpec*>(ScopeMem.Mem);
}
void destroy() {
Scope().~CXXScopeSpec();
}
};
union {
TypeInfoCommon Common;
PointerTypeInfo Ptr;
ReferenceTypeInfo Ref;
ArrayTypeInfo Arr;
FunctionTypeInfo Fun;
BlockPointerTypeInfo Cls;
MemberPointerTypeInfo Mem;
};
void destroy() {
switch (Kind) {
case DeclaratorChunk::Function: return Fun.destroy();
case DeclaratorChunk::Pointer: return Ptr.destroy();
case DeclaratorChunk::BlockPointer: return Cls.destroy();
case DeclaratorChunk::Reference: return Ref.destroy();
case DeclaratorChunk::Array: return Arr.destroy();
case DeclaratorChunk::MemberPointer: return Mem.destroy();
case DeclaratorChunk::Paren: return;
}
}
/// \brief If there are attributes applied to this declaratorchunk, return
/// them.
const AttributeList *getAttrs() const {
return Common.AttrList;
}
AttributeList *&getAttrListRef() {
return Common.AttrList;
}
/// \brief Return a DeclaratorChunk for a pointer.
static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc,
SourceLocation ConstQualLoc,
SourceLocation VolatileQualLoc,
SourceLocation RestrictQualLoc,
SourceLocation AtomicQualLoc) {
DeclaratorChunk I;
I.Kind = Pointer;
I.Loc = Loc;
I.Ptr.TypeQuals = TypeQuals;
I.Ptr.ConstQualLoc = ConstQualLoc.getRawEncoding();
I.Ptr.VolatileQualLoc = VolatileQualLoc.getRawEncoding();
I.Ptr.RestrictQualLoc = RestrictQualLoc.getRawEncoding();
I.Ptr.AtomicQualLoc = AtomicQualLoc.getRawEncoding();
I.Ptr.AttrList = nullptr;
return I;
}
/// \brief Return a DeclaratorChunk for a reference.
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc,
bool lvalue) {
DeclaratorChunk I;
I.Kind = Reference;
I.Loc = Loc;
I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0;
I.Ref.LValueRef = lvalue;
I.Ref.AttrList = nullptr;
return I;
}
/// \brief Return a DeclaratorChunk for an array.
static DeclaratorChunk getArray(unsigned TypeQuals,
bool isStatic, bool isStar, Expr *NumElts,
SourceLocation LBLoc, SourceLocation RBLoc) {
DeclaratorChunk I;
I.Kind = Array;
I.Loc = LBLoc;
I.EndLoc = RBLoc;
I.Arr.AttrList = nullptr;
I.Arr.TypeQuals = TypeQuals;
I.Arr.hasStatic = isStatic;
I.Arr.isStar = isStar;
I.Arr.NumElts = NumElts;
return I;
}
/// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
/// "TheDeclarator" is the declarator that this will be added to.
static DeclaratorChunk getFunction(bool HasProto,
bool IsAmbiguous,
SourceLocation LParenLoc,
ParamInfo *Params, unsigned NumParams,
SourceLocation EllipsisLoc,
SourceLocation RParenLoc,
unsigned TypeQuals,
bool RefQualifierIsLvalueRef,
SourceLocation RefQualifierLoc,
SourceLocation ConstQualifierLoc,
SourceLocation VolatileQualifierLoc,
SourceLocation RestrictQualifierLoc,
SourceLocation MutableLoc,
ExceptionSpecificationType ESpecType,
SourceLocation ESpecLoc,
ParsedType *Exceptions,
SourceRange *ExceptionRanges,
unsigned NumExceptions,
Expr *NoexceptExpr,
CachedTokens *ExceptionSpecTokens,
SourceLocation LocalRangeBegin,
SourceLocation LocalRangeEnd,
Declarator &TheDeclarator,
TypeResult TrailingReturnType =
TypeResult());
/// \brief Return a DeclaratorChunk for a block.
static DeclaratorChunk getBlockPointer(unsigned TypeQuals,
SourceLocation Loc) {
DeclaratorChunk I;
I.Kind = BlockPointer;
I.Loc = Loc;
I.Cls.TypeQuals = TypeQuals;
I.Cls.AttrList = nullptr;
return I;
}
static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS,
unsigned TypeQuals,
SourceLocation Loc) {
DeclaratorChunk I;
I.Kind = MemberPointer;
I.Loc = SS.getBeginLoc();
I.EndLoc = Loc;
I.Mem.TypeQuals = TypeQuals;
I.Mem.AttrList = nullptr;
new (I.Mem.ScopeMem.Mem) CXXScopeSpec(SS);
return I;
}
/// \brief Return a DeclaratorChunk for a paren.
static DeclaratorChunk getParen(SourceLocation LParenLoc,
SourceLocation RParenLoc) {
DeclaratorChunk I;
I.Kind = Paren;
I.Loc = LParenLoc;
I.EndLoc = RParenLoc;
I.Common.AttrList = nullptr;
return I;
}
bool isParen() const {
return Kind == Paren;
}
};
/// \brief Described the kind of function definition (if any) provided for
/// a function.
enum FunctionDefinitionKind {
FDK_Declaration,
FDK_Definition,
FDK_Defaulted,
FDK_Deleted
};
/// \brief Information about one declarator, including the parsed type
/// information and the identifier.
///
/// When the declarator is fully formed, this is turned into the appropriate
/// Decl object.
///
/// Declarators come in two types: normal declarators and abstract declarators.
/// Abstract declarators are used when parsing types, and don't have an
/// identifier. Normal declarators do have ID's.
///
/// Instances of this class should be a transient object that lives on the
/// stack, not objects that are allocated in large quantities on the heap.
class Declarator {
public:
enum TheContext {
FileContext, // File scope declaration.
PrototypeContext, // Within a function prototype.
ObjCResultContext, // An ObjC method result type.
ObjCParameterContext,// An ObjC method parameter type.
KNRTypeListContext, // K&R type definition list for formals.
TypeNameContext, // Abstract declarator for types.
MemberContext, // Struct/Union field.
BlockContext, // Declaration within a block in a function.
ForContext, // Declaration within first part of a for loop.
ConditionContext, // Condition declaration in a C++ if/switch/while/for.
TemplateParamContext,// Within a template parameter list.
CXXNewContext, // C++ new-expression.
CXXCatchContext, // C++ catch exception-declaration
ObjCCatchContext, // Objective-C catch exception-declaration
BlockLiteralContext, // Block literal declarator.
LambdaExprContext, // Lambda-expression declarator.
LambdaExprParameterContext, // Lambda-expression parameter declarator.
ConversionIdContext, // C++ conversion-type-id.
TrailingReturnContext, // C++11 trailing-type-specifier.
TemplateTypeArgContext, // Template type argument.
AliasDeclContext, // C++11 alias-declaration.
AliasTemplateContext // C++11 alias-declaration template.
};
std::vector<InheritableAttr *> customAttributesList; // HLSL Change
std::vector<hlsl::UnusualAnnotation *> UnusualAnnotations; // HLSL Change
private:
const DeclSpec &DS;
CXXScopeSpec SS;
UnqualifiedId Name;
SourceRange Range;
/// \brief Where we are parsing this declarator.
TheContext Context;
/// DeclTypeInfo - This holds each type that the declarator includes as it is
/// parsed. This is pushed from the identifier out, which means that element
/// #0 will be the most closely bound to the identifier, and
/// DeclTypeInfo.back() will be the least closely bound.
SmallVector<DeclaratorChunk, 8> DeclTypeInfo;
/// InvalidType - Set by Sema::GetTypeForDeclarator().
bool InvalidType : 1;
/// GroupingParens - Set by Parser::ParseParenDeclarator().
bool GroupingParens : 1;
/// FunctionDefinition - Is this Declarator for a function or member
/// definition and, if so, what kind?
///
/// Actually a FunctionDefinitionKind.
unsigned FunctionDefinition : 2;
/// \brief Is this Declarator a redeclaration?
bool Redeclaration : 1;
/// Attrs - Attributes.
ParsedAttributes Attrs;
/// \brief The asm label, if specified.
Expr *AsmLabel;
/// InlineParams - This is a local array used for the first function decl
/// chunk to avoid going to the heap for the common case when we have one
/// function chunk in the declarator.
DeclaratorChunk::ParamInfo InlineParams[16];
bool InlineParamsUsed;
/// \brief true if the declaration is preceded by \c __extension__.
unsigned Extension : 1;
/// Indicates whether this is an Objective-C instance variable.
unsigned ObjCIvar : 1;
/// Indicates whether this is an Objective-C 'weak' property.
unsigned ObjCWeakProperty : 1;
/// \brief If this is the second or subsequent declarator in this declaration,
/// the location of the comma before this declarator.
SourceLocation CommaLoc;
/// \brief If provided, the source location of the ellipsis used to describe
/// this declarator as a parameter pack.
SourceLocation EllipsisLoc;
friend struct DeclaratorChunk;
public:
Declarator(const DeclSpec &ds, TheContext C)
: DS(ds), Range(ds.getSourceRange()), Context(C),
InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error),
GroupingParens(false), FunctionDefinition(FDK_Declaration),
Redeclaration(false),
Attrs(ds.getAttributePool().getFactory()), AsmLabel(nullptr),
InlineParamsUsed(false), Extension(false), ObjCIvar(false),
ObjCWeakProperty(false) {
}
~Declarator() {
clear();
}
/// getDeclSpec - Return the declaration-specifier that this declarator was
/// declared with.
const DeclSpec &getDeclSpec() const { return DS; }
/// getMutableDeclSpec - Return a non-const version of the DeclSpec. This
/// should be used with extreme care: declspecs can often be shared between
/// multiple declarators, so mutating the DeclSpec affects all of the
/// Declarators. This should only be done when the declspec is known to not
/// be shared or when in error recovery etc.
DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); }
AttributePool &getAttributePool() const {
return Attrs.getPool();
}
/// getCXXScopeSpec - Return the C++ scope specifier (global scope or
/// nested-name-specifier) that is part of the declarator-id.
const CXXScopeSpec &getCXXScopeSpec() const { return SS; }
CXXScopeSpec &getCXXScopeSpec() { return SS; }
/// \brief Retrieve the name specified by this declarator.
UnqualifiedId &getName() { return Name; }
TheContext getContext() const { return Context; }
bool isPrototypeContext() const {
return (Context == PrototypeContext ||
Context == ObjCParameterContext ||
Context == ObjCResultContext ||
Context == LambdaExprParameterContext);
}
/// \brief Get the source range that spans this declarator.
const SourceRange &getSourceRange() const LLVM_READONLY { return Range; }
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
void SetSourceRange(SourceRange R) { Range = R; }
/// SetRangeBegin - Set the start of the source range to Loc, unless it's
/// invalid.
void SetRangeBegin(SourceLocation Loc) {
if (!Loc.isInvalid())
Range.setBegin(Loc);
}
/// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid.
void SetRangeEnd(SourceLocation Loc) {
if (!Loc.isInvalid())
Range.setEnd(Loc);
}
/// ExtendWithDeclSpec - Extend the declarator source range to include the
/// given declspec, unless its location is invalid. Adopts the range start if
/// the current range start is invalid.
void ExtendWithDeclSpec(const DeclSpec &DS) {
const SourceRange &SR = DS.getSourceRange();
if (Range.getBegin().isInvalid())
Range.setBegin(SR.getBegin());
if (!SR.getEnd().isInvalid())
Range.setEnd(SR.getEnd());
}
/// \brief Reset the contents of this Declarator.
void clear() {
SS.clear();
Name.clear();
Range = DS.getSourceRange();
for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i)
DeclTypeInfo[i].destroy();
DeclTypeInfo.clear();
Attrs.clear();
AsmLabel = nullptr;
InlineParamsUsed = false;
ObjCIvar = false;
ObjCWeakProperty = false;
CommaLoc = SourceLocation();
EllipsisLoc = SourceLocation();
}
/// mayOmitIdentifier - Return true if the identifier is either optional or
/// not allowed. This is true for typenames, prototypes, and template
/// parameter lists.
bool mayOmitIdentifier() const {
switch (Context) {
case FileContext:
case KNRTypeListContext:
case MemberContext:
case BlockContext:
case ForContext:
case ConditionContext:
return false;
case TypeNameContext:
case AliasDeclContext:
case AliasTemplateContext:
case PrototypeContext:
case LambdaExprParameterContext:
case ObjCParameterContext:
case ObjCResultContext:
case TemplateParamContext:
case CXXNewContext:
case CXXCatchContext:
case ObjCCatchContext:
case BlockLiteralContext:
case LambdaExprContext:
case ConversionIdContext:
case TemplateTypeArgContext:
case TrailingReturnContext:
return true;
}
llvm_unreachable("unknown context kind!");
}
/// mayHaveIdentifier - Return true if the identifier is either optional or
/// required. This is true for normal declarators and prototypes, but not
/// typenames.
bool mayHaveIdentifier() const {
switch (Context) {
case FileContext:
case KNRTypeListContext:
case MemberContext:
case BlockContext:
case ForContext:
case ConditionContext:
case PrototypeContext:
case LambdaExprParameterContext:
case TemplateParamContext:
case CXXCatchContext:
case ObjCCatchContext:
return true;
case TypeNameContext:
case CXXNewContext:
case AliasDeclContext:
case AliasTemplateContext:
case ObjCParameterContext:
case ObjCResultContext:
case BlockLiteralContext:
case LambdaExprContext:
case ConversionIdContext:
case TemplateTypeArgContext:
case TrailingReturnContext:
return false;
}
llvm_unreachable("unknown context kind!");
}
/// diagnoseIdentifier - Return true if the identifier is prohibited and
/// should be diagnosed (because it cannot be anything else).
bool diagnoseIdentifier() const {
switch (Context) {
case FileContext:
case KNRTypeListContext:
case MemberContext:
case BlockContext:
case ForContext:
case ConditionContext:
case PrototypeContext:
case LambdaExprParameterContext:
case TemplateParamContext:
case CXXCatchContext:
case ObjCCatchContext:
case TypeNameContext:
case ConversionIdContext:
case ObjCParameterContext:
case ObjCResultContext:
case BlockLiteralContext:
case CXXNewContext:
case LambdaExprContext:
return false;
case AliasDeclContext:
case AliasTemplateContext:
case TemplateTypeArgContext:
case TrailingReturnContext:
return true;
}
llvm_unreachable("unknown context kind!");
}
/// mayBeFollowedByCXXDirectInit - Return true if the declarator can be
/// followed by a C++ direct initializer, e.g. "int x(1);".
bool mayBeFollowedByCXXDirectInit() const {
if (hasGroupingParens()) return false;
if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
return false;
if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern &&
Context != FileContext)
return false;
// Special names can't have direct initializers.
if (Name.getKind() != UnqualifiedId::IK_Identifier)
return false;
switch (Context) {
case FileContext:
case BlockContext:
case ForContext:
return true;
case ConditionContext:
// This may not be followed by a direct initializer, but it can't be a
// function declaration either, and we'd prefer to perform a tentative
// parse in order to produce the right diagnostic.
return true;
case KNRTypeListContext:
case MemberContext:
case PrototypeContext:
case LambdaExprParameterContext:
case ObjCParameterContext:
case ObjCResultContext:
case TemplateParamContext:
case CXXCatchContext:
case ObjCCatchContext:
case TypeNameContext:
case CXXNewContext:
case AliasDeclContext:
case AliasTemplateContext:
case BlockLiteralContext:
case LambdaExprContext:
case ConversionIdContext:
case TemplateTypeArgContext:
case TrailingReturnContext:
return false;
}
llvm_unreachable("unknown context kind!");
}
/// isPastIdentifier - Return true if we have parsed beyond the point where
/// the
bool isPastIdentifier() const { return Name.isValid(); }
/// hasName - Whether this declarator has a name, which might be an
/// identifier (accessible via getIdentifier()) or some kind of
/// special C++ name (constructor, destructor, etc.).
bool hasName() const {
return Name.getKind() != UnqualifiedId::IK_Identifier || Name.Identifier;
}
IdentifierInfo *getIdentifier() const {
if (Name.getKind() == UnqualifiedId::IK_Identifier)
return Name.Identifier;
return nullptr;
}
SourceLocation getIdentifierLoc() const { return Name.StartLocation; }
/// \brief Set the name of this declarator to be the given identifier.
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) {
Name.setIdentifier(Id, IdLoc);
}
/// AddTypeInfo - Add a chunk to this declarator. Also extend the range to
/// EndLoc, which should be the last token of the chunk.
void AddTypeInfo(const DeclaratorChunk &TI,
ParsedAttributes &attrs,
SourceLocation EndLoc) {
DeclTypeInfo.push_back(TI);
DeclTypeInfo.back().getAttrListRef() = attrs.getList();
getAttributePool().takeAllFrom(attrs.getPool());
if (!EndLoc.isInvalid())
SetRangeEnd(EndLoc);
}
/// \brief Add a new innermost chunk to this declarator.
void AddInnermostTypeInfo(const DeclaratorChunk &TI) {
DeclTypeInfo.insert(DeclTypeInfo.begin(), TI);
}
/// \brief Return the number of types applied to this declarator.
unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); }
/// Return the specified TypeInfo from this declarator. TypeInfo #0 is
/// closest to the identifier.
const DeclaratorChunk &getTypeObject(unsigned i) const {
assert(i < DeclTypeInfo.size() && "Invalid type chunk");
return DeclTypeInfo[i];
}
DeclaratorChunk &getTypeObject(unsigned i) {
assert(i < DeclTypeInfo.size() && "Invalid type chunk");
return DeclTypeInfo[i];
}
typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator;
typedef llvm::iterator_range<type_object_iterator> type_object_range;
/// Returns the range of type objects, from the identifier outwards.
type_object_range type_objects() const {
return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end());
}
void DropFirstTypeObject() {
assert(!DeclTypeInfo.empty() && "No type chunks to drop.");
DeclTypeInfo.front().destroy();
DeclTypeInfo.erase(DeclTypeInfo.begin());
}
/// Return the innermost (closest to the declarator) chunk of this
/// declarator that is not a parens chunk, or null if there are no
/// non-parens chunks.
const DeclaratorChunk *getInnermostNonParenChunk() const {
for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
if (!DeclTypeInfo[i].isParen())
return &DeclTypeInfo[i];
}
return nullptr;
}
/// Return the outermost (furthest from the declarator) chunk of
/// this declarator that is not a parens chunk, or null if there are
/// no non-parens chunks.
const DeclaratorChunk *getOutermostNonParenChunk() const {
for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) {
if (!DeclTypeInfo[i-1].isParen())
return &DeclTypeInfo[i-1];
}
return nullptr;
}
/// isArrayOfUnknownBound - This method returns true if the declarator
/// is a declarator for an array of unknown bound (looking through
/// parentheses).
bool isArrayOfUnknownBound() const {
const DeclaratorChunk *chunk = getInnermostNonParenChunk();
return (chunk && chunk->Kind == DeclaratorChunk::Array &&
!chunk->Arr.NumElts);
}
/// isFunctionDeclarator - This method returns true if the declarator
/// is a function declarator (looking through parentheses).
/// If true is returned, then the reference type parameter idx is
/// assigned with the index of the declaration chunk.
bool isFunctionDeclarator(unsigned& idx) const {
for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) {
switch (DeclTypeInfo[i].Kind) {
case DeclaratorChunk::Function:
idx = i;
return true;
case DeclaratorChunk::Paren:
continue;
case DeclaratorChunk::Pointer:
case DeclaratorChunk::Reference:
case DeclaratorChunk::Array:
case DeclaratorChunk::BlockPointer:
case DeclaratorChunk::MemberPointer:
return false;
}
llvm_unreachable("Invalid type chunk");
}
return false;
}
/// isFunctionDeclarator - Once this declarator is fully parsed and formed,
/// this method returns true if the identifier is a function declarator
/// (looking through parentheses).
bool isFunctionDeclarator() const {
unsigned index;
return isFunctionDeclarator(index);
}
/// getFunctionTypeInfo - Retrieves the function type info object
/// (looking through parentheses).
DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() {
assert(isFunctionDeclarator() && "Not a function declarator!");
unsigned index = 0;
isFunctionDeclarator(index);
return DeclTypeInfo[index].Fun;
}
/// getFunctionTypeInfo - Retrieves the function type info object
/// (looking through parentheses).
const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const {
return const_cast<Declarator*>(this)->getFunctionTypeInfo();
}
/// \brief Determine whether the declaration that will be produced from
/// this declaration will be a function.
///
/// A declaration can declare a function even if the declarator itself
/// isn't a function declarator, if the type specifier refers to a function
/// type. This routine checks for both cases.
bool isDeclarationOfFunction() const;
/// \brief Return true if this declaration appears in a context where a
/// function declarator would be a function declaration.
bool isFunctionDeclarationContext() const {
if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
return false;
switch (Context) {
case FileContext:
case MemberContext:
case BlockContext:
return true;
case ForContext:
case ConditionContext:
case KNRTypeListContext:
case TypeNameContext:
case AliasDeclContext:
case AliasTemplateContext:
case PrototypeContext:
case LambdaExprParameterContext:
case ObjCParameterContext:
case ObjCResultContext:
case TemplateParamContext:
case CXXNewContext:
case CXXCatchContext:
case ObjCCatchContext:
case BlockLiteralContext:
case LambdaExprContext:
case ConversionIdContext:
case TemplateTypeArgContext:
case TrailingReturnContext:
return false;
}
llvm_unreachable("unknown context kind!");
}
/// \brief Return true if a function declarator at this position would be a
/// function declaration.
bool isFunctionDeclaratorAFunctionDeclaration() const {
if (!isFunctionDeclarationContext())
return false;
for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I)
if (getTypeObject(I).Kind != DeclaratorChunk::Paren)
return false;
return true;
}
// HLSL Change Starts
// This allow appending an InheritableAttr to Decl object
void addAttribute(InheritableAttr *attr) {
customAttributesList.push_back(attr);
}
// HLSL Change Ends
/// takeAttributes - Takes attributes from the given parsed-attributes
/// set and add them to this declarator.
///
/// These examples both add 3 attributes to "var":
/// short int var __attribute__((aligned(16),common,deprecated));
/// short int x, __attribute__((aligned(16)) var
/// __attribute__((common,deprecated));
///
/// Also extends the range of the declarator.
void takeAttributes(ParsedAttributes &attrs, SourceLocation lastLoc) {
Attrs.takeAllFrom(attrs);
if (!lastLoc.isInvalid())
SetRangeEnd(lastLoc);
}
const AttributeList *getAttributes() const { return Attrs.getList(); }
AttributeList *getAttributes() { return Attrs.getList(); }
AttributeList *&getAttrListRef() { return Attrs.getListRef(); }
/// hasAttributes - do we contain any attributes?
bool hasAttributes() const {
if (getAttributes() || getDeclSpec().hasAttributes()) return true;
for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i)
if (getTypeObject(i).getAttrs())
return true;
return false;
}
/// \brief Return a source range list of C++11 attributes associated
/// with the declarator.
void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) {
AttributeList *AttrList = Attrs.getList();
while (AttrList) {
if (AttrList->isCXX11Attribute())
Ranges.push_back(AttrList->getRange());
AttrList = AttrList->getNext();
}
}
void setAsmLabel(Expr *E) { AsmLabel = E; }
Expr *getAsmLabel() const { return AsmLabel; }
void setExtension(bool Val = true) { Extension = Val; }
bool getExtension() const { return Extension; }
void setObjCIvar(bool Val = true) { ObjCIvar = Val; }
bool isObjCIvar() const { return ObjCIvar; }
void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; }
bool isObjCWeakProperty() const { return ObjCWeakProperty; }
void setInvalidType(bool Val = true) { InvalidType = Val; }
bool isInvalidType() const {
return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error;
}
void setGroupingParens(bool flag) { GroupingParens = flag; }
bool hasGroupingParens() const { return GroupingParens; }
bool isFirstDeclarator() const { return !CommaLoc.isValid(); }
SourceLocation getCommaLoc() const { return CommaLoc; }
void setCommaLoc(SourceLocation CL) { CommaLoc = CL; }
bool hasEllipsis() const { return EllipsisLoc.isValid(); }
SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; }
void setFunctionDefinitionKind(FunctionDefinitionKind Val) {
FunctionDefinition = Val;
}
bool isFunctionDefinition() const {
return getFunctionDefinitionKind() != FDK_Declaration;
}
FunctionDefinitionKind getFunctionDefinitionKind() const {
return (FunctionDefinitionKind)FunctionDefinition;
}
/// Returns true if this declares a real member and not a friend.
bool isFirstDeclarationOfMember() {
return getContext() == MemberContext && !getDeclSpec().isFriendSpecified();
}
/// Returns true if this declares a static member. This cannot be called on a
/// declarator outside of a MemberContext because we won't know until
/// redeclaration time if the decl is static.
bool isStaticMember();
void setRedeclaration(bool Val) { Redeclaration = Val; }
bool isRedeclaration() const { return Redeclaration; }
};
/// \brief This little struct is used to capture information about
/// structure field declarators, which is basically just a bitfield size.
struct FieldDeclarator {
Declarator D;
Expr *BitfieldSize;
explicit FieldDeclarator(const DeclSpec &DS)
: D(DS, Declarator::MemberContext), BitfieldSize(nullptr) { }
};
/// \brief Represents a C++11 virt-specifier-seq.
class VirtSpecifiers {
public:
enum Specifier {
VS_None = 0,
VS_Override = 1,
VS_Final = 2,
VS_Sealed = 4
};
VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { }
bool SetSpecifier(Specifier VS, SourceLocation Loc,
const char *&PrevSpec);
bool isUnset() const { return Specifiers == 0; }
bool isOverrideSpecified() const { return Specifiers & VS_Override; }
SourceLocation getOverrideLoc() const { return VS_overrideLoc; }
bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed); }
bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; }
SourceLocation getFinalLoc() const { return VS_finalLoc; }
void clear() { Specifiers = 0; }
static const char *getSpecifierName(Specifier VS);
SourceLocation getFirstLocation() const { return FirstLocation; }
SourceLocation getLastLocation() const { return LastLocation; }
Specifier getLastSpecifier() const { return LastSpecifier; }
private:
unsigned Specifiers;
Specifier LastSpecifier;
SourceLocation VS_overrideLoc, VS_finalLoc;
SourceLocation FirstLocation;
SourceLocation LastLocation;
};
/// \brief Represents a complete lambda introducer.
struct LambdaIntroducer {
/// \brief An individual capture in a lambda introducer.
struct LambdaCapture {
LambdaCaptureKind Kind;
SourceLocation Loc;
IdentifierInfo *Id;
SourceLocation EllipsisLoc;
ExprResult Init;
ParsedType InitCaptureType;
LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc,
IdentifierInfo *Id, SourceLocation EllipsisLoc,
ExprResult Init, ParsedType InitCaptureType)
: Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc), Init(Init),
InitCaptureType(InitCaptureType) {}
};
SourceRange Range;
SourceLocation DefaultLoc;
LambdaCaptureDefault Default;
SmallVector<LambdaCapture, 4> Captures;
LambdaIntroducer()
: Default(LCD_None) {}
/// \brief Append a capture in a lambda introducer.
void addCapture(LambdaCaptureKind Kind,
SourceLocation Loc,
IdentifierInfo* Id,
SourceLocation EllipsisLoc,
ExprResult Init,
ParsedType InitCaptureType) {
Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, Init,
InitCaptureType));
}
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/SemaLambda.h | //===--- SemaLambda.h - Lambda Helper Functions --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief This file provides some common utility functions for processing
/// Lambdas.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SEMALAMBDA_H
#define LLVM_CLANG_SEMA_SEMALAMBDA_H
#include "clang/AST/ASTLambda.h"
#include "clang/Sema/ScopeInfo.h"
namespace clang {
/// \brief Examines the FunctionScopeInfo stack to determine the nearest
/// enclosing lambda (to the current lambda) that is 'capture-capable' for
/// the variable referenced in the current lambda (i.e. \p VarToCapture).
/// If successful, returns the index into Sema's FunctionScopeInfo stack
/// of the capture-capable lambda's LambdaScopeInfo.
/// See Implementation for more detailed comments.
Optional<unsigned> getStackIndexOfNearestEnclosingCaptureCapableLambda(
ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
VarDecl *VarToCapture, Sema &S);
} // clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/Weak.h | //===-- UnresolvedSet.h - Unresolved sets of declarations ------*- 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 WeakInfo class, which is used to store
// information about the target of a #pragma weak directive.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_WEAK_H
#define LLVM_CLANG_SEMA_WEAK_H
#include "clang/Basic/SourceLocation.h"
namespace clang {
class IdentifierInfo;
/// \brief Captures information about a \#pragma weak directive.
class WeakInfo {
IdentifierInfo *alias; // alias (optional)
SourceLocation loc; // for diagnostics
bool used; // identifier later declared?
public:
WeakInfo()
: alias(nullptr), loc(SourceLocation()), used(false) {}
WeakInfo(IdentifierInfo *Alias, SourceLocation Loc)
: alias(Alias), loc(Loc), used(false) {}
inline IdentifierInfo * getAlias() const { return alias; }
inline SourceLocation getLocation() const { return loc; }
void setUsed(bool Used=true) { used = Used; }
inline bool getUsed() { return used; }
bool operator==(WeakInfo RHS) const {
return alias == RHS.getAlias() && loc == RHS.getLocation();
}
bool operator!=(WeakInfo RHS) const { return !(*this == RHS); }
};
} // end namespace clang
#endif // LLVM_CLANG_SEMA_WEAK_H
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/Sema/Scope.h | //===--- Scope.h - Scope interface ------------------------------*- 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 Scope interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_SCOPE_H
#define LLVM_CLANG_SEMA_SCOPE_H
#include "clang/Basic/Diagnostic.h"
#include "llvm/ADT/PointerIntPair.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
namespace llvm {
class raw_ostream;
}
namespace clang {
class Decl;
class UsingDirectiveDecl;
class VarDecl;
/// Scope - A scope is a transient data structure that is used while parsing the
/// program. It assists with resolving identifiers to the appropriate
/// declaration.
///
class Scope {
public:
/// ScopeFlags - These are bitfields that are or'd together when creating a
/// scope, which defines the sorts of things the scope contains.
enum ScopeFlags {
/// \brief This indicates that the scope corresponds to a function, which
/// means that labels are set here.
FnScope = 0x01,
/// \brief This is a while, do, switch, for, etc that can have break
/// statements embedded into it.
BreakScope = 0x02,
/// \brief This is a while, do, for, which can have continue statements
/// embedded into it.
ContinueScope = 0x04,
/// \brief This is a scope that can contain a declaration. Some scopes
/// just contain loop constructs but don't contain decls.
DeclScope = 0x08,
/// \brief The controlling scope in a if/switch/while/for statement.
ControlScope = 0x10,
/// \brief The scope of a struct/union/class definition.
ClassScope = 0x20,
/// \brief This is a scope that corresponds to a block/closure object.
/// Blocks serve as top-level scopes for some objects like labels, they
/// also prevent things like break and continue. BlockScopes always have
/// the FnScope and DeclScope flags set as well.
BlockScope = 0x40,
/// \brief This is a scope that corresponds to the
/// template parameters of a C++ template. Template parameter
/// scope starts at the 'template' keyword and ends when the
/// template declaration ends.
TemplateParamScope = 0x80,
/// \brief This is a scope that corresponds to the
/// parameters within a function prototype.
FunctionPrototypeScope = 0x100,
/// \brief This is a scope that corresponds to the parameters within
/// a function prototype for a function declaration (as opposed to any
/// other kind of function declarator). Always has FunctionPrototypeScope
/// set as well.
FunctionDeclarationScope = 0x200,
/// \brief This is a scope that corresponds to the Objective-C
/// \@catch statement.
AtCatchScope = 0x400,
// HLSL Change Starts
// Overloaded with AtCatchScope because this is HLSL-specific.
ForDeclScope = 0x400,
// HLSL Change Ends
/// \brief This scope corresponds to an Objective-C method body.
/// It always has FnScope and DeclScope set as well.
ObjCMethodScope = 0x800,
/// \brief This is a scope that corresponds to a switch statement.
SwitchScope = 0x1000,
/// \brief This is the scope of a C++ try statement.
TryScope = 0x2000,
/// \brief This is the scope for a function-level C++ try or catch scope.
FnTryCatchScope = 0x4000,
/// \brief This is the scope of OpenMP executable directive.
OpenMPDirectiveScope = 0x8000,
/// \brief This is the scope of some OpenMP loop directive.
OpenMPLoopDirectiveScope = 0x10000,
/// \brief This is the scope of some OpenMP simd directive.
/// For example, it is used for 'omp simd', 'omp for simd'.
/// This flag is propagated to children scopes.
OpenMPSimdDirectiveScope = 0x20000,
/// This scope corresponds to an enum.
EnumScope = 0x40000,
/// This scope corresponds to an SEH try.
SEHTryScope = 0x80000,
/// This scope corresponds to an SEH except.
SEHExceptScope = 0x100000,
/// We are currently in the filter expression of an SEH except block.
SEHFilterScope = 0x200000,
};
private:
/// The parent scope for this scope. This is null for the translation-unit
/// scope.
Scope *AnyParent;
/// Flags - This contains a set of ScopeFlags, which indicates how the scope
/// interrelates with other control flow statements.
unsigned Flags;
/// Depth - This is the depth of this scope. The translation-unit scope has
/// depth 0.
unsigned short Depth;
/// \brief Declarations with static linkage are mangled with the number of
/// scopes seen as a component.
unsigned short MSLastManglingNumber;
unsigned short MSCurManglingNumber;
/// PrototypeDepth - This is the number of function prototype scopes
/// enclosing this scope, including this scope.
unsigned short PrototypeDepth;
/// PrototypeIndex - This is the number of parameters currently
/// declared in this scope.
unsigned short PrototypeIndex;
/// FnParent - If this scope has a parent scope that is a function body, this
/// pointer is non-null and points to it. This is used for label processing.
Scope *FnParent;
Scope *MSLastManglingParent;
/// BreakParent/ContinueParent - This is a direct link to the innermost
/// BreakScope/ContinueScope which contains the contents of this scope
/// for control flow purposes (and might be this scope itself), or null
/// if there is no such scope.
Scope *BreakParent, *ContinueParent;
/// BlockParent - This is a direct link to the immediately containing
/// BlockScope if this scope is not one, or null if there is none.
Scope *BlockParent;
/// TemplateParamParent - This is a direct link to the
/// immediately containing template parameter scope. In the
/// case of nested templates, template parameter scopes can have
/// other template parameter scopes as parents.
Scope *TemplateParamParent;
/// DeclsInScope - This keeps track of all declarations in this scope. When
/// the declaration is added to the scope, it is set as the current
/// declaration for the identifier in the IdentifierTable. When the scope is
/// popped, these declarations are removed from the IdentifierTable's notion
/// of current declaration. It is up to the current Action implementation to
/// implement these semantics.
typedef llvm::SmallPtrSet<Decl *, 32> DeclSetTy;
DeclSetTy DeclsInScope;
/// The DeclContext with which this scope is associated. For
/// example, the entity of a class scope is the class itself, the
/// entity of a function scope is a function, etc.
DeclContext *Entity;
typedef SmallVector<UsingDirectiveDecl *, 2> UsingDirectivesTy;
UsingDirectivesTy UsingDirectives;
/// \brief Used to determine if errors occurred in this scope.
DiagnosticErrorTrap ErrorTrap;
/// A lattice consisting of undefined, a single NRVO candidate variable in
/// this scope, or over-defined. The bit is true when over-defined.
llvm::PointerIntPair<VarDecl *, 1, bool> NRVO;
public:
Scope(Scope *Parent, unsigned ScopeFlags, DiagnosticsEngine &Diag)
: ErrorTrap(Diag) {
Init(Parent, ScopeFlags);
}
/// getFlags - Return the flags for this scope.
///
unsigned getFlags() const { return Flags; }
void setFlags(unsigned F) { Flags = F; }
/// isBlockScope - Return true if this scope correspond to a closure.
bool isBlockScope() const { return Flags & BlockScope; }
bool isForDeclScope() const { return Flags & ForDeclScope; } // HLSL Change
/// getParent - Return the scope that this is nested in.
///
const Scope *getParent() const { return AnyParent; }
Scope *getParent() { return AnyParent; }
/// getFnParent - Return the closest scope that is a function body.
///
const Scope *getFnParent() const { return FnParent; }
Scope *getFnParent() { return FnParent; }
const Scope *getMSLastManglingParent() const {
return MSLastManglingParent;
}
Scope *getMSLastManglingParent() { return MSLastManglingParent; }
/// getContinueParent - Return the closest scope that a continue statement
/// would be affected by.
Scope *getContinueParent() {
return ContinueParent;
}
const Scope *getContinueParent() const {
return const_cast<Scope*>(this)->getContinueParent();
}
/// getBreakParent - Return the closest scope that a break statement
/// would be affected by.
Scope *getBreakParent() {
return BreakParent;
}
const Scope *getBreakParent() const {
return const_cast<Scope*>(this)->getBreakParent();
}
Scope *getBlockParent() { return BlockParent; }
const Scope *getBlockParent() const { return BlockParent; }
Scope *getTemplateParamParent() { return TemplateParamParent; }
const Scope *getTemplateParamParent() const { return TemplateParamParent; }
/// Returns the number of function prototype scopes in this scope
/// chain.
unsigned getFunctionPrototypeDepth() const {
return PrototypeDepth;
}
/// Return the number of parameters declared in this function
/// prototype, increasing it by one for the next call.
unsigned getNextFunctionPrototypeIndex() {
assert(isFunctionPrototypeScope());
return PrototypeIndex++;
}
typedef llvm::iterator_range<DeclSetTy::iterator> decl_range;
decl_range decls() const {
return decl_range(DeclsInScope.begin(), DeclsInScope.end());
}
bool decl_empty() const { return DeclsInScope.empty(); }
void AddDecl(Decl *D) {
DeclsInScope.insert(D);
}
void RemoveDecl(Decl *D) {
DeclsInScope.erase(D);
}
void incrementMSManglingNumber() {
if (Scope *MSLMP = getMSLastManglingParent()) {
MSLMP->MSLastManglingNumber += 1;
MSCurManglingNumber += 1;
}
}
void decrementMSManglingNumber() {
if (Scope *MSLMP = getMSLastManglingParent()) {
MSLMP->MSLastManglingNumber -= 1;
MSCurManglingNumber -= 1;
}
}
unsigned getMSLastManglingNumber() const {
if (const Scope *MSLMP = getMSLastManglingParent())
return MSLMP->MSLastManglingNumber;
return 1;
}
unsigned getMSCurManglingNumber() const {
return MSCurManglingNumber;
}
/// isDeclScope - Return true if this is the scope that the specified decl is
/// declared in.
bool isDeclScope(Decl *D) {
return DeclsInScope.count(D) != 0;
}
DeclContext *getEntity() const { return Entity; }
void setEntity(DeclContext *E) { Entity = E; }
bool hasErrorOccurred() const { return ErrorTrap.hasErrorOccurred(); }
bool hasUnrecoverableErrorOccurred() const {
return ErrorTrap.hasUnrecoverableErrorOccurred();
}
/// isFunctionScope() - Return true if this scope is a function scope.
bool isFunctionScope() const { return (getFlags() & Scope::FnScope); }
/// isClassScope - Return true if this scope is a class/struct/union scope.
bool isClassScope() const {
return (getFlags() & Scope::ClassScope);
}
/// isInCXXInlineMethodScope - Return true if this scope is a C++ inline
/// method scope or is inside one.
bool isInCXXInlineMethodScope() const {
if (const Scope *FnS = getFnParent()) {
assert(FnS->getParent() && "TUScope not created?");
return FnS->getParent()->isClassScope();
}
return false;
}
/// isInObjcMethodScope - Return true if this scope is, or is contained in, an
/// Objective-C method body. Note that this method is not constant time.
bool isInObjcMethodScope() const {
for (const Scope *S = this; S; S = S->getParent()) {
// If this scope is an objc method scope, then we succeed.
if (S->getFlags() & ObjCMethodScope)
return true;
}
return false;
}
/// isInObjcMethodOuterScope - Return true if this scope is an
/// Objective-C method outer most body.
bool isInObjcMethodOuterScope() const {
if (const Scope *S = this) {
// If this scope is an objc method scope, then we succeed.
if (S->getFlags() & ObjCMethodScope)
return true;
}
return false;
}
/// isTemplateParamScope - Return true if this scope is a C++
/// template parameter scope.
bool isTemplateParamScope() const {
return getFlags() & Scope::TemplateParamScope;
}
/// isFunctionPrototypeScope - Return true if this scope is a
/// function prototype scope.
bool isFunctionPrototypeScope() const {
return getFlags() & Scope::FunctionPrototypeScope;
}
/// isAtCatchScope - Return true if this scope is \@catch.
bool isAtCatchScope() const {
return getFlags() & Scope::AtCatchScope;
}
/// isSwitchScope - Return true if this scope is a switch scope.
bool isSwitchScope() const {
for (const Scope *S = this; S; S = S->getParent()) {
if (S->getFlags() & Scope::SwitchScope)
return true;
else if (S->getFlags() & (Scope::FnScope | Scope::ClassScope |
Scope::BlockScope | Scope::TemplateParamScope |
Scope::FunctionPrototypeScope |
Scope::AtCatchScope | Scope::ObjCMethodScope))
return false;
}
return false;
}
/// \brief Determines whether this scope is the OpenMP directive scope
bool isOpenMPDirectiveScope() const {
return (getFlags() & Scope::OpenMPDirectiveScope);
}
/// \brief Determine whether this scope is some OpenMP loop directive scope
/// (for example, 'omp for', 'omp simd').
bool isOpenMPLoopDirectiveScope() const {
if (getFlags() & Scope::OpenMPLoopDirectiveScope) {
assert(isOpenMPDirectiveScope() &&
"OpenMP loop directive scope is not a directive scope");
return true;
}
return false;
}
/// \brief Determine whether this scope is (or is nested into) some OpenMP
/// loop simd directive scope (for example, 'omp simd', 'omp for simd').
bool isOpenMPSimdDirectiveScope() const {
return getFlags() & Scope::OpenMPSimdDirectiveScope;
}
/// \brief Determine whether this scope is a loop having OpenMP loop
/// directive attached.
bool isOpenMPLoopScope() const {
const Scope *P = getParent();
return P && P->isOpenMPLoopDirectiveScope();
}
/// \brief Determine whether this scope is a C++ 'try' block.
bool isTryScope() const { return getFlags() & Scope::TryScope; }
/// \brief Determine whether this scope is a SEH '__try' block.
bool isSEHTryScope() const { return getFlags() & Scope::SEHTryScope; }
/// \brief Determine whether this scope is a SEH '__except' block.
bool isSEHExceptScope() const { return getFlags() & Scope::SEHExceptScope; }
/// \brief Returns if rhs has a higher scope depth than this.
///
/// The caller is responsible for calling this only if one of the two scopes
/// is an ancestor of the other.
bool Contains(const Scope& rhs) const { return Depth < rhs.Depth; }
/// containedInPrototypeScope - Return true if this or a parent scope
/// is a FunctionPrototypeScope.
bool containedInPrototypeScope() const;
void PushUsingDirective(UsingDirectiveDecl *UDir) {
UsingDirectives.push_back(UDir);
}
typedef llvm::iterator_range<UsingDirectivesTy::iterator>
using_directives_range;
using_directives_range using_directives() {
return using_directives_range(UsingDirectives.begin(),
UsingDirectives.end());
}
void addNRVOCandidate(VarDecl *VD) {
if (NRVO.getInt())
return;
if (NRVO.getPointer() == nullptr) {
NRVO.setPointer(VD);
return;
}
if (NRVO.getPointer() != VD)
setNoNRVO();
}
void setNoNRVO() {
NRVO.setInt(1);
NRVO.setPointer(nullptr);
}
void mergeNRVOIntoParent();
/// Init - This is used by the parser to implement scope caching.
///
void Init(Scope *parent, unsigned flags);
/// \brief Sets up the specified scope flags and adjusts the scope state
/// variables accordingly.
///
void AddFlags(unsigned Flags);
void dumpImpl(raw_ostream &OS) const;
void dump() const;
};
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/ARCMigrate/FileRemapper.h | //===-- FileRemapper.h - File Remapping Helper ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ARCMIGRATE_FILEREMAPPER_H
#define LLVM_CLANG_ARCMIGRATE_FILEREMAPPER_H
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/StringRef.h"
#include <memory>
namespace llvm {
class MemoryBuffer;
}
namespace clang {
class FileManager;
class FileEntry;
class DiagnosticsEngine;
class PreprocessorOptions;
namespace arcmt {
class FileRemapper {
// FIXME: Reuse the same FileManager for multiple ASTContexts.
std::unique_ptr<FileManager> FileMgr;
typedef llvm::PointerUnion<const FileEntry *, llvm::MemoryBuffer *> Target;
typedef llvm::DenseMap<const FileEntry *, Target> MappingsTy;
MappingsTy FromToMappings;
llvm::DenseMap<const FileEntry *, const FileEntry *> ToFromMappings;
public:
FileRemapper();
~FileRemapper();
bool initFromDisk(StringRef outputDir, DiagnosticsEngine &Diag,
bool ignoreIfFilesChanged);
bool initFromFile(StringRef filePath, DiagnosticsEngine &Diag,
bool ignoreIfFilesChanged);
bool flushToDisk(StringRef outputDir, DiagnosticsEngine &Diag);
bool flushToFile(StringRef outputPath, DiagnosticsEngine &Diag);
bool overwriteOriginal(DiagnosticsEngine &Diag,
StringRef outputDir = StringRef());
void remap(StringRef filePath, std::unique_ptr<llvm::MemoryBuffer> memBuf);
void applyMappings(PreprocessorOptions &PPOpts) const;
void clear(StringRef outputDir = StringRef());
private:
void remap(const FileEntry *file, std::unique_ptr<llvm::MemoryBuffer> memBuf);
void remap(const FileEntry *file, const FileEntry *newfile);
const FileEntry *getOriginalFile(StringRef filePath);
void resetTarget(Target &targ);
bool report(const Twine &err, DiagnosticsEngine &Diag);
std::string getRemapInfoFile(StringRef outputDir);
};
} // end namespace arcmt
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/ARCMigrate/ARCMT.h | //===-- ARCMT.h - ARC Migration Rewriter ------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ARCMIGRATE_ARCMT_H
#define LLVM_CLANG_ARCMIGRATE_ARCMT_H
#include "clang/ARCMigrate/FileRemapper.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Frontend/CompilerInvocation.h"
namespace clang {
class ASTContext;
class DiagnosticConsumer;
class PCHContainerOperations;
namespace arcmt {
class MigrationPass;
/// \brief Creates an AST with the provided CompilerInvocation but with these
/// changes:
/// -if a PCH/PTH is set, the original header is used instead
/// -Automatic Reference Counting mode is enabled
///
/// It then checks the AST and produces errors/warning for ARC migration issues
/// that the user needs to handle manually.
///
/// \param emitPremigrationARCErrors if true all ARC errors will get emitted
/// even if the migrator can fix them, but the function will still return false
/// if all ARC errors can be fixed.
///
/// \param plistOut if non-empty, it is the file path to store the plist with
/// the pre-migration ARC diagnostics.
///
/// \returns false if no error is produced, true otherwise.
bool
checkForManualIssues(CompilerInvocation &CI, const FrontendInputFile &Input,
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
DiagnosticConsumer *DiagClient,
bool emitPremigrationARCErrors = false,
StringRef plistOut = StringRef());
/// \brief Works similar to checkForManualIssues but instead of checking, it
/// applies automatic modifications to source files to conform to ARC.
///
/// \returns false if no error is produced, true otherwise.
bool
applyTransformations(CompilerInvocation &origCI,
const FrontendInputFile &Input,
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
DiagnosticConsumer *DiagClient);
/// \brief Applies automatic modifications and produces temporary files
/// and metadata into the \p outputDir path.
///
/// \param emitPremigrationARCErrors if true all ARC errors will get emitted
/// even if the migrator can fix them, but the function will still return false
/// if all ARC errors can be fixed.
///
/// \param plistOut if non-empty, it is the file path to store the plist with
/// the pre-migration ARC diagnostics.
///
/// \returns false if no error is produced, true otherwise.
bool migrateWithTemporaryFiles(
CompilerInvocation &origCI, const FrontendInputFile &Input,
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
DiagnosticConsumer *DiagClient, StringRef outputDir,
bool emitPremigrationARCErrors, StringRef plistOut);
/// \brief Get the set of file remappings from the \p outputDir path that
/// migrateWithTemporaryFiles produced.
///
/// \returns false if no error is produced, true otherwise.
bool getFileRemappings(std::vector<std::pair<std::string,std::string> > &remap,
StringRef outputDir,
DiagnosticConsumer *DiagClient);
/// \brief Get the set of file remappings from a list of files with remapping
/// info.
///
/// \returns false if no error is produced, true otherwise.
bool getFileRemappingsFromFileList(
std::vector<std::pair<std::string,std::string> > &remap,
ArrayRef<StringRef> remapFiles,
DiagnosticConsumer *DiagClient);
typedef void (*TransformFn)(MigrationPass &pass);
std::vector<TransformFn> getAllTransformations(LangOptions::GCMode OrigGCMode,
bool NoFinalizeRemoval);
class MigrationProcess {
CompilerInvocation OrigCI;
std::shared_ptr<PCHContainerOperations> PCHContainerOps;
DiagnosticConsumer *DiagClient;
FileRemapper Remapper;
public:
bool HadARCErrors;
MigrationProcess(const CompilerInvocation &CI,
std::shared_ptr<PCHContainerOperations> PCHContainerOps,
DiagnosticConsumer *diagClient,
StringRef outputDir = StringRef());
class RewriteListener {
public:
virtual ~RewriteListener();
virtual void start(ASTContext &Ctx) { }
virtual void finish() { }
virtual void insert(SourceLocation loc, StringRef text) { }
virtual void remove(CharSourceRange range) { }
};
bool applyTransform(TransformFn trans, RewriteListener *listener = nullptr);
FileRemapper &getRemapper() { return Remapper; }
};
} // end namespace arcmt
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/ARCMigrate/ARCMTActions.h | //===--- ARCMTActions.h - ARC Migrate Tool Frontend Actions -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_ARCMIGRATE_ARCMTACTIONS_H
#define LLVM_CLANG_ARCMIGRATE_ARCMTACTIONS_H
#include "clang/ARCMigrate/FileRemapper.h"
#include "clang/Frontend/FrontendAction.h"
#include <memory>
namespace clang {
namespace arcmt {
class CheckAction : public WrapperFrontendAction {
protected:
bool BeginInvocation(CompilerInstance &CI) override;
public:
CheckAction(FrontendAction *WrappedAction);
};
class ModifyAction : public WrapperFrontendAction {
protected:
bool BeginInvocation(CompilerInstance &CI) override;
public:
ModifyAction(FrontendAction *WrappedAction);
};
class MigrateSourceAction : public ASTFrontendAction {
FileRemapper Remapper;
protected:
bool BeginInvocation(CompilerInstance &CI) override;
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) override;
};
class MigrateAction : public WrapperFrontendAction {
std::string MigrateDir;
std::string PlistOut;
bool EmitPremigrationARCErros;
protected:
bool BeginInvocation(CompilerInstance &CI) override;
public:
MigrateAction(FrontendAction *WrappedAction, StringRef migrateDir,
StringRef plistOut,
bool emitPremigrationARCErrors);
};
/// \brief Migrates to modern ObjC syntax.
class ObjCMigrateAction : public WrapperFrontendAction {
std::string MigrateDir;
unsigned ObjCMigAction;
FileRemapper Remapper;
CompilerInstance *CompInst;
public:
ObjCMigrateAction(FrontendAction *WrappedAction, StringRef migrateDir,
unsigned migrateAction);
protected:
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) override;
bool BeginInvocation(CompilerInstance &CI) override;
};
}
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/CodeGen/BackendUtil.h | //===--- BackendUtil.h - LLVM Backend Utilities -----------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_BACKENDUTIL_H
#define LLVM_CLANG_CODEGEN_BACKENDUTIL_H
#include "clang/Basic/LLVM.h"
namespace llvm {
class Module;
}
namespace clang {
class DiagnosticsEngine;
class CodeGenOptions;
class TargetOptions;
class LangOptions;
enum BackendAction {
Backend_EmitAssembly, ///< Emit native assembly files
Backend_EmitBC, ///< Emit LLVM bitcode files
Backend_EmitLL, ///< Emit human-readable LLVM assembly
Backend_EmitNothing, ///< Don't emit anything (benchmarking mode)
Backend_EmitMCNull, ///< Run CodeGen, but don't emit anything
Backend_EmitObj, ///< Emit native object files
Backend_EmitPasses ///< Emit pass configuration - HLSL Change
};
void EmitBackendOutput(DiagnosticsEngine &Diags, const CodeGenOptions &CGOpts,
const TargetOptions &TOpts, const LangOptions &LOpts,
StringRef TDesc, llvm::Module *M, BackendAction Action,
raw_pwrite_stream *OS);
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/CodeGen/CGFunctionInfo.h | //==-- CGFunctionInfo.h - Representation of function argument/return types -==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Defines CGFunctionInfo and associated types used in representing the
// LLVM source types and ABI-coerced types for function arguments and
// return values.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_CGFUNCTIONINFO_H
#define LLVM_CLANG_CODEGEN_CGFUNCTIONINFO_H
#include "clang/AST/CanonicalType.h"
#include "clang/AST/Type.h"
#include "llvm/ADT/FoldingSet.h"
#include <cassert>
namespace llvm {
class Type;
class StructType;
}
namespace clang {
class Decl;
namespace CodeGen {
/// ABIArgInfo - Helper class to encapsulate information about how a
/// specific C type should be passed to or returned from a function.
class ABIArgInfo {
public:
enum Kind : uint8_t {
/// Direct - Pass the argument directly using the normal converted LLVM
/// type, or by coercing to another specified type stored in
/// 'CoerceToType'). If an offset is specified (in UIntData), then the
/// argument passed is offset by some number of bytes in the memory
/// representation. A dummy argument is emitted before the real argument
/// if the specified type stored in "PaddingType" is not zero.
Direct,
/// Extend - Valid only for integer argument types. Same as 'direct'
/// but also emit a zero/sign extension attribute.
Extend,
/// Indirect - Pass the argument indirectly via a hidden pointer
/// with the specified alignment (0 indicates default alignment).
Indirect,
/// Ignore - Ignore the argument (treat as void). Useful for void and
/// empty structs.
Ignore,
/// Expand - Only valid for aggregate argument types. The structure should
/// be expanded into consecutive arguments for its constituent fields.
/// Currently expand is only allowed on structures whose fields
/// are all scalar types or are themselves expandable types.
Expand,
/// InAlloca - Pass the argument directly using the LLVM inalloca attribute.
/// This is similar to indirect with byval, except it only applies to
/// arguments stored in memory and forbids any implicit copies. When
/// applied to a return type, it means the value is returned indirectly via
/// an implicit sret parameter stored in the argument struct.
InAlloca,
KindFirst = Direct,
KindLast = InAlloca
};
private:
llvm::Type *TypeData; // isDirect() || isExtend()
llvm::Type *PaddingType;
union {
unsigned DirectOffset; // isDirect() || isExtend()
unsigned IndirectAlign; // isIndirect()
unsigned AllocaFieldIndex; // isInAlloca()
};
Kind TheKind;
bool PaddingInReg : 1;
bool InAllocaSRet : 1; // isInAlloca()
bool IndirectByVal : 1; // isIndirect()
bool IndirectRealign : 1; // isIndirect()
bool SRetAfterThis : 1; // isIndirect()
bool InReg : 1; // isDirect() || isExtend() || isIndirect()
bool CanBeFlattened: 1; // isDirect()
ABIArgInfo(Kind K)
: PaddingType(nullptr), TheKind(K), PaddingInReg(false), InReg(false) {}
public:
ABIArgInfo()
: TypeData(nullptr), PaddingType(nullptr), DirectOffset(0),
TheKind(Direct), PaddingInReg(false), InReg(false) {}
static ABIArgInfo getDirect(llvm::Type *T = nullptr, unsigned Offset = 0,
llvm::Type *Padding = nullptr,
bool CanBeFlattened = true) {
auto AI = ABIArgInfo(Direct);
AI.setCoerceToType(T);
AI.setDirectOffset(Offset);
AI.setPaddingType(Padding);
AI.setCanBeFlattened(CanBeFlattened);
return AI;
}
static ABIArgInfo getDirectInReg(llvm::Type *T = nullptr) {
auto AI = getDirect(T);
AI.setInReg(true);
return AI;
}
static ABIArgInfo getExtend(llvm::Type *T = nullptr) {
auto AI = ABIArgInfo(Extend);
AI.setCoerceToType(T);
AI.setDirectOffset(0);
return AI;
}
static ABIArgInfo getExtendInReg(llvm::Type *T = nullptr) {
auto AI = getExtend(T);
AI.setInReg(true);
return AI;
}
static ABIArgInfo getIgnore() {
return ABIArgInfo(Ignore);
}
static ABIArgInfo getIndirect(unsigned Alignment, bool ByVal = true,
bool Realign = false,
llvm::Type *Padding = nullptr) {
auto AI = ABIArgInfo(Indirect);
AI.setIndirectAlign(Alignment);
AI.setIndirectByVal(ByVal);
AI.setIndirectRealign(Realign);
AI.setSRetAfterThis(false);
AI.setPaddingType(Padding);
return AI;
}
static ABIArgInfo getIndirectInReg(unsigned Alignment, bool ByVal = true,
bool Realign = false) {
auto AI = getIndirect(Alignment, ByVal, Realign);
AI.setInReg(true);
return AI;
}
static ABIArgInfo getInAlloca(unsigned FieldIndex) {
auto AI = ABIArgInfo(InAlloca);
AI.setInAllocaFieldIndex(FieldIndex);
return AI;
}
static ABIArgInfo getExpand() {
return ABIArgInfo(Expand);
}
static ABIArgInfo getExpandWithPadding(bool PaddingInReg,
llvm::Type *Padding) {
auto AI = getExpand();
AI.setPaddingInReg(PaddingInReg);
AI.setPaddingType(Padding);
return AI;
}
Kind getKind() const { return TheKind; }
bool isDirect() const { return TheKind == Direct; }
bool isInAlloca() const { return TheKind == InAlloca; }
bool isExtend() const { return TheKind == Extend; }
bool isIgnore() const { return TheKind == Ignore; }
bool isIndirect() const { return TheKind == Indirect; }
bool isExpand() const { return TheKind == Expand; }
bool canHaveCoerceToType() const { return isDirect() || isExtend(); }
// Direct/Extend accessors
unsigned getDirectOffset() const {
assert((isDirect() || isExtend()) && "Not a direct or extend kind");
return DirectOffset;
}
void setDirectOffset(unsigned Offset) {
assert((isDirect() || isExtend()) && "Not a direct or extend kind");
DirectOffset = Offset;
}
llvm::Type *getPaddingType() const { return PaddingType; }
void setPaddingType(llvm::Type *T) { PaddingType = T; }
bool getPaddingInReg() const {
return PaddingInReg;
}
void setPaddingInReg(bool PIR) {
PaddingInReg = PIR;
}
llvm::Type *getCoerceToType() const {
assert(canHaveCoerceToType() && "Invalid kind!");
return TypeData;
}
void setCoerceToType(llvm::Type *T) {
assert(canHaveCoerceToType() && "Invalid kind!");
TypeData = T;
}
bool getInReg() const {
assert((isDirect() || isExtend() || isIndirect()) && "Invalid kind!");
return InReg;
}
void setInReg(bool IR) {
assert((isDirect() || isExtend() || isIndirect()) && "Invalid kind!");
InReg = IR;
}
// Indirect accessors
unsigned getIndirectAlign() const {
assert(isIndirect() && "Invalid kind!");
return IndirectAlign;
}
void setIndirectAlign(unsigned IA) {
assert(isIndirect() && "Invalid kind!");
IndirectAlign = IA;
}
bool getIndirectByVal() const {
assert(isIndirect() && "Invalid kind!");
return IndirectByVal;
}
void setIndirectByVal(unsigned IBV) {
assert(isIndirect() && "Invalid kind!");
IndirectByVal = IBV;
}
bool getIndirectRealign() const {
assert(isIndirect() && "Invalid kind!");
return IndirectRealign;
}
void setIndirectRealign(bool IR) {
assert(isIndirect() && "Invalid kind!");
IndirectRealign = IR;
}
bool isSRetAfterThis() const {
assert(isIndirect() && "Invalid kind!");
return SRetAfterThis;
}
void setSRetAfterThis(bool AfterThis) {
assert(isIndirect() && "Invalid kind!");
SRetAfterThis = AfterThis;
}
unsigned getInAllocaFieldIndex() const {
assert(isInAlloca() && "Invalid kind!");
return AllocaFieldIndex;
}
void setInAllocaFieldIndex(unsigned FieldIndex) {
assert(isInAlloca() && "Invalid kind!");
AllocaFieldIndex = FieldIndex;
}
/// \brief Return true if this field of an inalloca struct should be returned
/// to implement a struct return calling convention.
bool getInAllocaSRet() const {
assert(isInAlloca() && "Invalid kind!");
return InAllocaSRet;
}
void setInAllocaSRet(bool SRet) {
assert(isInAlloca() && "Invalid kind!");
InAllocaSRet = SRet;
}
bool getCanBeFlattened() const {
assert(isDirect() && "Invalid kind!");
return CanBeFlattened;
}
void setCanBeFlattened(bool Flatten) {
assert(isDirect() && "Invalid kind!");
CanBeFlattened = Flatten;
}
void dump() const;
};
/// A class for recording the number of arguments that a function
/// signature requires.
class RequiredArgs {
/// The number of required arguments, or ~0 if the signature does
/// not permit optional arguments.
unsigned NumRequired;
public:
enum All_t { All };
RequiredArgs(All_t _) : NumRequired(~0U) {}
explicit RequiredArgs(unsigned n) : NumRequired(n) {
assert(n != ~0U);
}
/// Compute the arguments required by the given formal prototype,
/// given that there may be some additional, non-formal arguments
/// in play.
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype,
unsigned additional) {
if (!prototype->isVariadic()) return All;
return RequiredArgs(prototype->getNumParams() + additional);
}
static RequiredArgs forPrototype(const FunctionProtoType *prototype) {
return forPrototypePlus(prototype, 0);
}
static RequiredArgs forPrototype(CanQual<FunctionProtoType> prototype) {
return forPrototype(prototype.getTypePtr());
}
static RequiredArgs forPrototypePlus(CanQual<FunctionProtoType> prototype,
unsigned additional) {
return forPrototypePlus(prototype.getTypePtr(), additional);
}
bool allowsOptionalArgs() const { return NumRequired != ~0U; }
unsigned getNumRequiredArgs() const {
assert(allowsOptionalArgs());
return NumRequired;
}
unsigned getOpaqueData() const { return NumRequired; }
static RequiredArgs getFromOpaqueData(unsigned value) {
if (value == ~0U) return All;
return RequiredArgs(value);
}
};
/// CGFunctionInfo - Class to encapsulate the information about a
/// function definition.
class CGFunctionInfo : public llvm::FoldingSetNode {
struct ArgInfo {
CanQualType type;
ABIArgInfo info;
};
/// The LLVM::CallingConv to use for this function (as specified by the
/// user).
unsigned CallingConvention : 8;
/// The LLVM::CallingConv to actually use for this function, which may
/// depend on the ABI.
unsigned EffectiveCallingConvention : 8;
/// The clang::CallingConv that this was originally created with.
unsigned ASTCallingConvention : 8;
/// Whether this is an instance method.
unsigned InstanceMethod : 1;
/// Whether this is a chain call.
unsigned ChainCall : 1;
/// Whether this function is noreturn.
unsigned NoReturn : 1;
/// Whether this function is returns-retained.
unsigned ReturnsRetained : 1;
/// How many arguments to pass inreg.
unsigned HasRegParm : 1;
unsigned RegParm : 3;
RequiredArgs Required;
/// The struct representing all arguments passed in memory. Only used when
/// passing non-trivial types with inalloca. Not part of the profile.
llvm::StructType *ArgStruct;
unsigned NumArgs;
ArgInfo *getArgsBuffer() {
return reinterpret_cast<ArgInfo*>(this+1);
}
const ArgInfo *getArgsBuffer() const {
return reinterpret_cast<const ArgInfo*>(this + 1);
}
CGFunctionInfo() : Required(RequiredArgs::All) {}
public:
static CGFunctionInfo *create(unsigned llvmCC,
bool instanceMethod,
bool chainCall,
const FunctionType::ExtInfo &extInfo,
CanQualType resultType,
ArrayRef<CanQualType> argTypes,
RequiredArgs required);
typedef const ArgInfo *const_arg_iterator;
typedef ArgInfo *arg_iterator;
typedef llvm::iterator_range<arg_iterator> arg_range;
typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
arg_const_range arguments() const {
return arg_const_range(arg_begin(), arg_end());
}
const_arg_iterator arg_begin() const { return getArgsBuffer() + 1; }
const_arg_iterator arg_end() const { return getArgsBuffer() + 1 + NumArgs; }
arg_iterator arg_begin() { return getArgsBuffer() + 1; }
arg_iterator arg_end() { return getArgsBuffer() + 1 + NumArgs; }
unsigned arg_size() const { return NumArgs; }
bool isVariadic() const { return Required.allowsOptionalArgs(); }
RequiredArgs getRequiredArgs() const { return Required; }
unsigned getNumRequiredArgs() const {
return isVariadic() ? getRequiredArgs().getNumRequiredArgs() : arg_size();
}
bool isInstanceMethod() const { return InstanceMethod; }
bool isChainCall() const { return ChainCall; }
bool isNoReturn() const { return NoReturn; }
/// In ARC, whether this function retains its return value. This
/// is not always reliable for call sites.
bool isReturnsRetained() const { return ReturnsRetained; }
/// getASTCallingConvention() - Return the AST-specified calling
/// convention.
CallingConv getASTCallingConvention() const {
return CallingConv(ASTCallingConvention);
}
/// getCallingConvention - Return the user specified calling
/// convention, which has been translated into an LLVM CC.
unsigned getCallingConvention() const { return CallingConvention; }
/// getEffectiveCallingConvention - Return the actual calling convention to
/// use, which may depend on the ABI.
unsigned getEffectiveCallingConvention() const {
return EffectiveCallingConvention;
}
void setEffectiveCallingConvention(unsigned Value) {
EffectiveCallingConvention = Value;
}
bool getHasRegParm() const { return HasRegParm; }
unsigned getRegParm() const { return RegParm; }
FunctionType::ExtInfo getExtInfo() const {
return FunctionType::ExtInfo(isNoReturn(),
getHasRegParm(), getRegParm(),
getASTCallingConvention(),
isReturnsRetained());
}
CanQualType getReturnType() const { return getArgsBuffer()[0].type; }
ABIArgInfo &getReturnInfo() { return getArgsBuffer()[0].info; }
const ABIArgInfo &getReturnInfo() const { return getArgsBuffer()[0].info; }
/// \brief Return true if this function uses inalloca arguments.
bool usesInAlloca() const { return ArgStruct; }
/// \brief Get the struct type used to represent all the arguments in memory.
llvm::StructType *getArgStruct() const { return ArgStruct; }
void setArgStruct(llvm::StructType *Ty) { ArgStruct = Ty; }
void Profile(llvm::FoldingSetNodeID &ID) {
ID.AddInteger(getASTCallingConvention());
ID.AddBoolean(InstanceMethod);
ID.AddBoolean(ChainCall);
ID.AddBoolean(NoReturn);
ID.AddBoolean(ReturnsRetained);
ID.AddBoolean(HasRegParm);
ID.AddInteger(RegParm);
ID.AddInteger(Required.getOpaqueData());
getReturnType().Profile(ID);
for (const auto &I : arguments())
I.type.Profile(ID);
}
static void Profile(llvm::FoldingSetNodeID &ID,
bool InstanceMethod,
bool ChainCall,
const FunctionType::ExtInfo &info,
RequiredArgs required,
CanQualType resultType,
ArrayRef<CanQualType> argTypes) {
ID.AddInteger(info.getCC());
ID.AddBoolean(InstanceMethod);
ID.AddBoolean(ChainCall);
ID.AddBoolean(info.getNoReturn());
ID.AddBoolean(info.getProducesResult());
ID.AddBoolean(info.getHasRegParm());
ID.AddInteger(info.getRegParm());
ID.AddInteger(required.getOpaqueData());
resultType.Profile(ID);
for (ArrayRef<CanQualType>::iterator
i = argTypes.begin(), e = argTypes.end(); i != e; ++i) {
i->Profile(ID);
}
}
};
} // end namespace CodeGen
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/CodeGen/ObjectFilePCHContainerOperations.h | //===-- CodeGen/ObjectFilePCHContainerOperations.h - ------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_OBJECT_FILE_PCH_CONTAINER_OPERATIONS_H
#define LLVM_CLANG_CODEGEN_OBJECT_FILE_PCH_CONTAINER_OPERATIONS_H
#include "clang/Frontend/PCHContainerOperations.h"
namespace clang {
/// A PCHContainerWriter implementation that uses LLVM to
/// wraps Clang modules inside a COFF, ELF, or Mach-O container.
class ObjectFilePCHContainerWriter : public PCHContainerWriter {
StringRef getFormat() const override { return "obj"; }
/// Return an ASTConsumer that can be chained with a
/// PCHGenerator that produces a wrapper file format
/// that also contains full debug info for the module.
std::unique_ptr<ASTConsumer> CreatePCHContainerGenerator(
DiagnosticsEngine &Diags, const HeaderSearchOptions &HSO,
const PreprocessorOptions &PPO, const TargetOptions &TO,
const LangOptions &LO, const std::string &MainFileName,
const std::string &OutputFileName, llvm::raw_pwrite_stream *OS,
std::shared_ptr<PCHBuffer> Buffer) const override;
};
/// A PCHContainerReader implementation that uses LLVM to
/// wraps Clang modules inside a COFF, ELF, or Mach-O container.
class ObjectFilePCHContainerReader : public PCHContainerReader {
StringRef getFormat() const override { return "obj"; }
/// Initialize an llvm::BitstreamReader with the serialized
/// AST inside the PCH container Buffer.
void ExtractPCH(llvm::MemoryBufferRef Buffer,
llvm::BitstreamReader &StreamFile) const override;
};
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/CodeGen/CodeGenABITypes.h | //==---- CodeGenABITypes.h - Convert Clang types to LLVM types for ABI -----==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// CodeGenABITypes is a simple interface for getting LLVM types for
// the parameters and the return value of a function given the Clang
// types.
//
// The class is implemented as a public wrapper around the private
// CodeGenTypes class in lib/CodeGen.
//
// It allows other clients, like LLDB, to determine the LLVM types that are
// actually used in function calls, which makes it possible to then determine
// the acutal ABI locations (e.g. registers, stack locations, etc.) that
// these parameters are stored in.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_CODEGENABITYPES_H
#define LLVM_CLANG_CODEGEN_CODEGENABITYPES_H
#include "clang/AST/CanonicalType.h"
#include "clang/AST/Type.h"
#include "clang/CodeGen/CGFunctionInfo.h"
namespace llvm {
class DataLayout;
class Module;
}
namespace clang {
class ASTContext;
class CXXRecordDecl;
class CodeGenOptions;
class CoverageSourceInfo;
class DiagnosticsEngine;
class HeaderSearchOptions;
class ObjCMethodDecl;
class PreprocessorOptions;
namespace CodeGen {
class CGFunctionInfo;
class CodeGenModule;
class CodeGenABITypes
{
public:
CodeGenABITypes(ASTContext &C, llvm::Module &M, const llvm::DataLayout &TD,
CoverageSourceInfo *CoverageInfo = nullptr);
~CodeGenABITypes();
/// These methods all forward to methods in the private implementation class
/// CodeGenTypes.
const CGFunctionInfo &arrangeObjCMessageSendSignature(
const ObjCMethodDecl *MD,
QualType receiverType);
const CGFunctionInfo &arrangeFreeFunctionType(
CanQual<FunctionProtoType> Ty);
const CGFunctionInfo &arrangeFreeFunctionType(
CanQual<FunctionNoProtoType> Ty);
const CGFunctionInfo &arrangeCXXMethodType(const CXXRecordDecl *RD,
const FunctionProtoType *FTP);
const CGFunctionInfo &arrangeFreeFunctionCall(CanQualType returnType,
ArrayRef<CanQualType> argTypes,
FunctionType::ExtInfo info,
RequiredArgs args);
private:
/// Default CodeGenOptions object used to initialize the
/// CodeGenModule and otherwise not used. More specifically, it is
/// not used in ABI type generation, so none of the options matter.
CodeGenOptions *CGO;
HeaderSearchOptions *HSO;
PreprocessorOptions *PPO;
/// The CodeGenModule we use get to the CodeGenTypes object.
CodeGen::CodeGenModule *CGM;
};
} // end namespace CodeGen
} // end namespace clang
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/CodeGen/CodeGenAction.h | //===--- CodeGenAction.h - LLVM Code Generation Frontend Action -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_CODEGENACTION_H
#define LLVM_CLANG_CODEGEN_CODEGENACTION_H
#include "clang/Frontend/FrontendAction.h"
#include <memory>
namespace llvm {
class LLVMContext;
class Module;
}
namespace clang {
class BackendConsumer;
class CodeGenAction : public ASTFrontendAction {
private:
unsigned Act;
std::unique_ptr<llvm::Module> TheModule;
llvm::Module *LinkModule;
llvm::LLVMContext *VMContext;
bool OwnsVMContext;
protected:
/// Create a new code generation action. If the optional \p _VMContext
/// parameter is supplied, the action uses it without taking ownership,
/// otherwise it creates a fresh LLVM context and takes ownership.
CodeGenAction(unsigned _Act, llvm::LLVMContext *_VMContext = nullptr);
bool hasIRSupport() const override;
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
StringRef InFile) override;
void ExecuteAction() override;
void EndSourceFileAction() override;
public:
~CodeGenAction() override;
/// setLinkModule - Set the link module to be used by this action. If a link
/// module is not provided, and CodeGenOptions::LinkBitcodeFile is non-empty,
/// the action will load it from the specified file.
void setLinkModule(llvm::Module *Mod) { LinkModule = Mod; }
/// Take the generated LLVM module, for use after the action has been run.
/// The result may be null on failure.
std::unique_ptr<llvm::Module> takeModule();
/// Take the LLVM context used by this action.
llvm::LLVMContext *takeLLVMContext();
BackendConsumer *BEConsumer;
};
class EmitAssemblyAction : public CodeGenAction {
virtual void anchor();
public:
EmitAssemblyAction(llvm::LLVMContext *_VMContext = nullptr);
};
class EmitBCAction : public CodeGenAction {
virtual void anchor();
public:
EmitBCAction(llvm::LLVMContext *_VMContext = nullptr);
};
class EmitLLVMAction : public CodeGenAction {
virtual void anchor();
public:
EmitLLVMAction(llvm::LLVMContext *_VMContext = nullptr);
};
class EmitLLVMOnlyAction : public CodeGenAction {
virtual void anchor();
public:
EmitLLVMOnlyAction(llvm::LLVMContext *_VMContext = nullptr);
};
class EmitCodeGenOnlyAction : public CodeGenAction {
virtual void anchor();
public:
EmitCodeGenOnlyAction(llvm::LLVMContext *_VMContext = nullptr);
};
class EmitObjAction : public CodeGenAction {
virtual void anchor();
public:
EmitObjAction(llvm::LLVMContext *_VMContext = nullptr);
};
// HLSL Change Starts
class EmitOptDumpAction : public CodeGenAction {
virtual void anchor();
public:
EmitOptDumpAction(llvm::LLVMContext *_VMContext = nullptr);
};
// HLSL Change Ends
}
#endif
|
0 | repos/DirectXShaderCompiler/tools/clang/include/clang | repos/DirectXShaderCompiler/tools/clang/include/clang/CodeGen/ModuleBuilder.h | //===--- CodeGen/ModuleBuilder.h - Build LLVM from ASTs ---------*- 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 ModuleBuilder interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_CODEGEN_MODULEBUILDER_H
#define LLVM_CLANG_CODEGEN_MODULEBUILDER_H
#include "clang/AST/ASTConsumer.h"
#include <string>
namespace llvm {
class LLVMContext;
class Module;
}
namespace clang {
class DiagnosticsEngine;
class CoverageSourceInfo;
class LangOptions;
class HeaderSearchOptions;
class PreprocessorOptions;
class CodeGenOptions;
class Decl;
class CodeGenerator : public ASTConsumer {
virtual void anchor();
public:
virtual llvm::Module* GetModule() = 0;
virtual llvm::Module* ReleaseModule() = 0;
virtual const Decl *GetDeclForMangledName(llvm::StringRef MangledName) = 0;
};
/// CreateLLVMCodeGen - Create a CodeGenerator instance.
/// It is the responsibility of the caller to call delete on
/// the allocated CodeGenerator instance.
CodeGenerator *CreateLLVMCodeGen(DiagnosticsEngine &Diags,
const std::string &ModuleName,
const HeaderSearchOptions &HeaderSearchOpts,
const PreprocessorOptions &PreprocessorOpts,
const CodeGenOptions &CGO,
llvm::LLVMContext& C,
CoverageSourceInfo *CoverageInfo = nullptr);
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.