24#include "llvm/ADT/StringSwitch.h"
25#include "llvm/Support/Debug.h"
28#define DEBUG_TYPE "body-farm"
52 ASTMaker(ASTContext &C) : C(C) {}
55 BinaryOperator *makeAssignment(
const Expr *LHS,
const Expr *RHS, QualType Ty);
58 BinaryOperator *makeComparison(
const Expr *LHS,
const Expr *RHS,
65 DeclRefExpr *makeDeclRefExpr(
const VarDecl *D,
66 bool RefersToEnclosingVariableOrCapture =
false);
69 UnaryOperator *makeDereference(
const Expr *Arg, QualType Ty);
72 Expr *makeIntegralCast(
const Expr *Arg, QualType Ty);
75 ImplicitCastExpr *makeIntegralCastToBoolean(
const Expr *Arg);
78 ImplicitCastExpr *makeLvalueToRvalue(
const Expr *Arg, QualType Ty);
83 makeLvalueToRvalue(
const VarDecl *Decl,
84 bool RefersToEnclosingVariableOrCapture =
false);
87 ImplicitCastExpr *makeImplicitCast(
const Expr *Arg, QualType Ty,
91 CastExpr *makeReferenceCast(
const Expr *Arg, QualType Ty);
94 ObjCBoolLiteralExpr *makeObjCBool(
bool Val);
97 ObjCIvarRefExpr *makeObjCIvarRef(
const Expr *Base,
const ObjCIvarDecl *IVar);
100 ReturnStmt *makeReturn(
const Expr *RetVal);
103 IntegerLiteral *makeIntegerLiteral(
uint64_t Value, QualType Ty);
106 MemberExpr *makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
107 bool IsArrow =
false,
112 ValueDecl *findMemberField(
const RecordDecl *RD, StringRef Name);
122 C,
const_cast<Expr *
>(LHS),
const_cast<Expr *
>(RHS), BO_Assign, Ty,
126BinaryOperator *ASTMaker::makeComparison(
const Expr *LHS,
const Expr *RHS,
131 C,
const_cast<Expr *
>(LHS),
const_cast<Expr *
>(RHS), Op,
133 FPOptionsOverride());
136CompoundStmt *ASTMaker::makeCompound(ArrayRef<Stmt *> Stmts) {
141DeclRefExpr *ASTMaker::makeDeclRefExpr(
143 bool RefersToEnclosingVariableOrCapture) {
147 C, NestedNameSpecifierLoc(), SourceLocation(),
const_cast<VarDecl *
>(D),
148 RefersToEnclosingVariableOrCapture, SourceLocation(),
Type,
VK_LValue);
152UnaryOperator *ASTMaker::makeDereference(
const Expr *Arg, QualType Ty) {
155 false, FPOptionsOverride());
158ImplicitCastExpr *ASTMaker::makeLvalueToRvalue(
const Expr *Arg, QualType Ty) {
159 return makeImplicitCast(Arg, Ty, CK_LValueToRValue);
163ASTMaker::makeLvalueToRvalue(
const VarDecl *Arg,
164 bool RefersToEnclosingVariableOrCapture) {
166 return makeLvalueToRvalue(makeDeclRefExpr(Arg,
167 RefersToEnclosingVariableOrCapture),
171ImplicitCastExpr *ASTMaker::makeImplicitCast(
const Expr *Arg, QualType Ty,
175 const_cast<Expr *
>(Arg),
178 FPOptionsOverride());
181CastExpr *ASTMaker::makeReferenceCast(
const Expr *Arg, QualType Ty) {
186 const_cast<Expr *
>(Arg),
nullptr,
187 C.getTrivialTypeSourceInfo(Ty), FPOptionsOverride(),
188 SourceLocation(), SourceLocation(), SourceRange());
191Expr *ASTMaker::makeIntegralCast(
const Expr *Arg, QualType Ty) {
193 return const_cast<Expr*
>(Arg);
194 return makeImplicitCast(Arg, Ty, CK_IntegralCast);
197ImplicitCastExpr *ASTMaker::makeIntegralCastToBoolean(
const Expr *Arg) {
198 return makeImplicitCast(Arg,
C.BoolTy, CK_IntegralToBoolean);
201ObjCBoolLiteralExpr *ASTMaker::makeObjCBool(
bool Val) {
202 QualType Ty =
C.getBOOLDecl() ?
C.getBOOLType() :
C.ObjCBuiltinBoolTy;
203 return new (
C) ObjCBoolLiteralExpr(Val, Ty, SourceLocation());
206ObjCIvarRefExpr *ASTMaker::makeObjCIvarRef(
const Expr *Base,
207 const ObjCIvarDecl *IVar) {
208 return new (
C) ObjCIvarRefExpr(
const_cast<ObjCIvarDecl*
>(IVar),
209 IVar->
getType(), SourceLocation(),
210 SourceLocation(),
const_cast<Expr*
>(Base),
214ReturnStmt *ASTMaker::makeReturn(
const Expr *RetVal) {
219IntegerLiteral *ASTMaker::makeIntegerLiteral(
uint64_t Value, QualType Ty) {
224MemberExpr *ASTMaker::makeMemberExpression(Expr *base, ValueDecl *MemberDecl,
230 C, base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
231 SourceLocation(), MemberDecl, FoundDecl,
232 DeclarationNameInfo(MemberDecl->
getDeclName(), SourceLocation()),
233 nullptr, MemberDecl->
getType(), ValueKind,
237ValueDecl *ASTMaker::findMemberField(
const RecordDecl *RD, StringRef Name) {
238 const IdentifierInfo &II =
C.Idents.get(Name);
239 DeclarationName DeclName =
C.DeclarationNames.getIdentifier(&II);
241 DeclContextLookupResult Decls = RD->
lookup(DeclName);
242 for (NamedDecl *FoundDecl : Decls)
263 SubExpr = M.makeImplicitCast(
266 Call->getType()->isFunctionType()) {
268 SubExpr = M.makeImplicitCast(
Call, Ty, CK_FunctionToPointerDecay);
270 &&
Call->getType()->isPointerType()
271 &&
Call->getType()->getPointeeType()->isFunctionType()){
274 llvm_unreachable(
"Unexpected state");
285 assert(CallbackDecl !=
nullptr);
288 assert(callOperatorDecl !=
nullptr);
300 C, OO_Call, callOperatorDeclRef,
314 LLVM_DEBUG(llvm::dbgs() <<
"Generating body for std::move / std::forward\n");
320 Expr *Cast = M.makeReferenceCast(Param, ReturnType);
321 return M.makeReturn(Cast);
340 LLVM_DEBUG(llvm::dbgs() <<
"Generating body for call_once\n");
351 if (!Callback->getType()->isReferenceType()) {
352 llvm::dbgs() <<
"libcxx03 std::call_once implementation, skipping.\n";
356 llvm::dbgs() <<
"unknown std::call_once implementation, skipping.\n";
360 QualType CallbackType = Callback->getType().getNonReferenceType();
367 if (!FlagRecordDecl) {
368 LLVM_DEBUG(llvm::dbgs() <<
"Flag field is not a record: "
369 <<
"unknown std::call_once implementation, "
370 <<
"ignoring the call.\n");
376 ValueDecl *FlagFieldDecl = M.findMemberField(FlagRecordDecl,
"__state_");
380 if (!FlagFieldDecl) {
381 FlagFieldDecl = M.findMemberField(FlagRecordDecl,
"_M_once");
384 if (!FlagFieldDecl) {
385 LLVM_DEBUG(llvm::dbgs() <<
"No field _M_once or __state_ found on "
386 <<
"std::once_flag struct: unknown std::call_once "
387 <<
"implementation, ignoring the call.");
391 bool isLambdaCall = CallbackRecordDecl && CallbackRecordDecl->
isLambda();
392 if (CallbackRecordDecl && !isLambdaCall) {
393 LLVM_DEBUG(llvm::dbgs()
394 <<
"Not supported: synthesizing body for functors when "
395 <<
"body farming std::call_once, ignoring the call.");
405 M.makeDeclRefExpr(Callback,
411 CallbackFunctionType =
417 if (!CallbackFunctionType)
422 LLVM_DEBUG(llvm::dbgs() <<
"Types of params of the callback do not match "
423 <<
"params passed to std::call_once, "
424 <<
"ignoring the call\n");
438 LLVM_DEBUG(llvm::dbgs() <<
"Types of params of the callback do not match "
439 <<
"params passed to std::call_once, "
440 <<
"ignoring the call\n");
443 Expr *ParamExpr = M.makeDeclRefExpr(PDecl);
446 ParamExpr = M.makeLvalueToRvalue(ParamExpr, PTy);
448 CallArgs.push_back(ParamExpr);
455 CallbackRecordDecl, CallArgs);
463 M.makeDeclRefExpr(Flag,
467 MemberExpr *Deref = M.makeMemberExpression(FlagDecl, FlagFieldDecl);
468 assert(Deref->isLValue());
469 QualType DerefType = Deref->getType();
475 M.makeImplicitCast(M.makeLvalueToRvalue(Deref, DerefType), DerefType,
476 CK_IntegralToBoolean),
485 Deref, M.makeIntegralCast(M.makeIntegerLiteral(1,
C.IntTy), DerefType),
495 M.makeCompound({CallbackCall, FlagAssignment}));
537 M.makeLvalueToRvalue(
Block),
552 M.makeLvalueToRvalue(
553 M.makeDeclRefExpr(Predicate), PredicateQPtrTy),
555 M.makeIntegralCast(DoneValue, PredicateTy),
559 Stmt *Stmts[] = { B, CE };
564 M.makeLvalueToRvalue(
566 M.makeLvalueToRvalue(
567 M.makeDeclRefExpr(Predicate),
572 Expr *GuardCondition = M.makeComparison(LValToRval, DoneValue, BO_NE);
652 if (OldCanonical != NewCanonical || OldCanonical != PointeeCanonical)
659 M.makeLvalueToRvalue(M.makeDeclRefExpr(OldValue), OldValueTy),
660 M.makeLvalueToRvalue(
662 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
672 M.makeLvalueToRvalue(M.makeDeclRefExpr(TheValue), TheValueTy),
674 M.makeLvalueToRvalue(M.makeDeclRefExpr(NewValue), NewValueTy),
677 Expr *BoolVal = M.makeObjCBool(
true);
678 Expr *RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
679 : M.makeIntegralCast(BoolVal, ResultTy);
680 Stmts[1] = M.makeReturn(RetVal);
684 BoolVal = M.makeObjCBool(
false);
685 RetVal = isBoolean ? M.makeIntegralCastToBoolean(BoolVal)
686 : M.makeIntegralCast(BoolVal, ResultTy);
687 Stmt *Else = M.makeReturn(RetVal);
701 std::optional<Stmt *> &Val = Bodies[D];
718 case Builtin::BIas_const:
719 case Builtin::BIforward:
720 case Builtin::BIforward_like:
721 case Builtin::BImove:
722 case Builtin::BImove_if_noexcept:
729 }
else if (Name.starts_with(
"OSAtomicCompareAndSwap") ||
730 Name.starts_with(
"objc_atomicCompareAndSwap")) {
735 FF = llvm::StringSwitch<FunctionFarmer>(Name)
741 if (FF) { Val = FF(C, D); }
742 else if (Injector) { Val = Injector->getBody(D); }
763 if (
auto *InterfaceDecl = dyn_cast<ObjCInterfaceDecl>(Container)) {
764 PrimaryInterface = InterfaceDecl;
765 }
else if (
auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(Container)) {
766 PrimaryInterface = CategoryDecl->getClassInterface();
767 }
else if (
auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) {
768 PrimaryInterface = ImplDecl->getClassInterface();
778 if (ShadowingProp && ShadowingProp != Prop) {
779 IVar = ShadowingProp->getPropertyIvarDecl();
799 if (Candidate->getGetterName() == MD->
getSelector()) {
828 if (I->getPropertyDecl() != Prop)
831 if (I->getGetterCXXConstructor()) {
833 return M.makeReturn(I->getGetterCXXConstructor());
855 Expr *loadedIVar = M.makeObjCIvarRef(
856 M.makeLvalueToRvalue(M.makeDeclRefExpr(selfVar), selfVar->
getType()),
860 loadedIVar = M.makeLvalueToRvalue(loadedIVar, IVar->
getType());
862 return M.makeReturn(loadedIVar);
877 std::optional<Stmt *> &Val = Bodies[D];
897 if (dyn_cast<ObjCInterfaceDecl>(D->
getParent()) != OID)
899 auto *OMD = Ext->getInstanceMethod(D->
getSelector());
900 if (OMD && !OMD->isImplicit())
Defines the clang::ASTContext interface.
static Stmt * create_call_once(ASTContext &C, const FunctionDecl *D)
Create a fake body for std::call_once.
static Stmt * create_dispatch_once(ASTContext &C, const FunctionDecl *D)
Create a fake body for dispatch_once.
static Stmt * create_OSAtomicCompareAndSwap(ASTContext &C, const FunctionDecl *D)
static Stmt * create_dispatch_sync(ASTContext &C, const FunctionDecl *D)
Create a fake body for dispatch_sync.
static Stmt * createObjCPropertyGetter(ASTContext &Ctx, const ObjCMethodDecl *MD)
static Stmt * create_std_move_forward(ASTContext &C, const FunctionDecl *D)
Create a fake body for 'std::move' or 'std::forward'.
static CallExpr * create_call_once_lambda_call(ASTContext &C, ASTMaker M, const ParmVarDecl *Callback, CXXRecordDecl *CallbackDecl, ArrayRef< Expr * > CallArgs)
static CallExpr * create_call_once_funcptr_call(ASTContext &C, ASTMaker M, const ParmVarDecl *Callback, ArrayRef< Expr * > CallArgs)
static bool isDispatchBlock(QualType Ty)
Stmt *(* FunctionFarmer)(ASTContext &C, const FunctionDecl *D)
static const ObjCIvarDecl * findBackingIvar(const ObjCPropertyDecl *Prop)
Defines enum values for all the target-independent builtin functions.
Defines the clang::CodeInjector interface which is responsible for injecting AST of function definiti...
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines an enumeration for C++ overloaded operators.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
A builtin binary operation expression such as "x + y" or "x <= y".
bool isComparisonOp() const
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
BinaryOperatorKind Opcode
QualType getPointeeType() const
Stmt * getBody(const FunctionDecl *D)
Factory method for creating bodies for ordinary functions.
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL, bool IsReversed=false)
Represents a C++ struct/union/class.
bool isLambda() const
Determine whether this class describes a lambda function object.
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
static CXXStaticCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *Path, TypeSourceInfo *Written, FPOptionsOverride FPO, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets)
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
CompoundStmt - This represents a group of statements like { stmt stmt }.
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext * getParent()
getParent - Returns the containing DeclContext.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isStdNamespace() const
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
A reference to a declared variable, function, enum, etc.
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
DeclContext * getDeclContext()
This represents one expression.
Represents difference between two FPOptions values.
Represents a function declaration or definition.
const ParmVarDecl * getParamDecl(unsigned i) const
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
QualType getReturnType() const
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
size_t param_size() const
Represents a prototype with parameter type info, e.g.
unsigned getNumParams() const
QualType getParamType(unsigned i) const
FunctionType - C99 6.7.5.3 - Function Declarators.
QualType getReturnType() const
static IfStmt * Create(const ASTContext &Ctx, SourceLocation IL, IfStatementKind Kind, Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LPL, SourceLocation RPL, Stmt *Then, SourceLocation EL=SourceLocation(), Stmt *Else=nullptr)
Create an IfStmt.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
A C++ nested-name-specifier augmented with source location information.
propimpl_range property_impls() const
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Represents an ObjC class declaration.
ObjCPropertyDecl * FindPropertyVisibleInPrimaryClass(const IdentifierInfo *PropertyId, ObjCPropertyQueryKind QueryKind) const
FindPropertyVisibleInPrimaryClass - Finds declaration of the property with name 'PropertyId' in the p...
ObjCImplementationDecl * getImplementation() const
known_extensions_range known_extensions() const
ObjCIvarDecl - Represents an ObjC instance variable.
ObjCInterfaceDecl * getContainingInterface()
Return the class interface that this ivar is logically contained in; this is either the interface whe...
ObjCMethodDecl - Represents an instance or class method declaration.
ImplicitParamDecl * getSelfDecl() const
unsigned param_size() const
bool isPropertyAccessor() const
const ObjCPropertyDecl * findPropertyDecl(bool CheckOverrides=true) const
Returns the property associated with this method's selector.
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
bool isSynthesizedAccessorStub() const
Selector getSelector() const
QualType getReturnType() const
ObjCInterfaceDecl * getClassInterface()
Represents one property declaration in an Objective-C interface.
ObjCPropertyQueryKind getQueryKind() const
bool isReadOnly() const
isReadOnly - Return true iff the property has a setter.
ObjCIvarDecl * getPropertyIvarDecl() const
ObjCPropertyAttribute::Kind getPropertyAttributes() const
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Represents a parameter to a function.
PointerType - C99 6.7.5.1 - Pointer Declarators.
QualType getPointeeType() const
A (possibly-)qualified type.
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
bool isNull() const
Return true if this QualType doesn't point to a type yet.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
static ReturnStmt * Create(const ASTContext &Ctx, SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
Create a return statement.
Encodes a location in the source.
Stmt - This represents one statement.
bool isBooleanType() const
bool isRValueReferenceType() const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isLValueReferenceType() const
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
const T * getAs() const
Member-template getAs<specific type>'.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Represents a variable declaration or definition.
Top level wrappers for InstallAPI frontend operations.
@ Comparison
A comparison.
@ OK_Ordinary
An ordinary object is located at an address in memory.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
CastKind
CastKind - The kind of operation required for a conversion.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
U cast(CodeGen::Address addr)
@ NOUR_None
This is an odr-use.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t