1f4a2713aSLionel Sambuc //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This file implements extra semantic analysis beyond what is enforced
11f4a2713aSLionel Sambuc // by the C type system.
12f4a2713aSLionel Sambuc //
13f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
14f4a2713aSLionel Sambuc
15f4a2713aSLionel Sambuc #include "clang/Sema/SemaInternal.h"
16f4a2713aSLionel Sambuc #include "clang/AST/ASTContext.h"
17f4a2713aSLionel Sambuc #include "clang/AST/CharUnits.h"
18f4a2713aSLionel Sambuc #include "clang/AST/DeclCXX.h"
19f4a2713aSLionel Sambuc #include "clang/AST/DeclObjC.h"
20f4a2713aSLionel Sambuc #include "clang/AST/EvaluatedExprVisitor.h"
21f4a2713aSLionel Sambuc #include "clang/AST/Expr.h"
22f4a2713aSLionel Sambuc #include "clang/AST/ExprCXX.h"
23f4a2713aSLionel Sambuc #include "clang/AST/ExprObjC.h"
24f4a2713aSLionel Sambuc #include "clang/AST/StmtCXX.h"
25f4a2713aSLionel Sambuc #include "clang/AST/StmtObjC.h"
26f4a2713aSLionel Sambuc #include "clang/Analysis/Analyses/FormatString.h"
27f4a2713aSLionel Sambuc #include "clang/Basic/CharInfo.h"
28f4a2713aSLionel Sambuc #include "clang/Basic/TargetBuiltins.h"
29f4a2713aSLionel Sambuc #include "clang/Basic/TargetInfo.h"
30*0a6a1f1dSLionel Sambuc #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31f4a2713aSLionel Sambuc #include "clang/Sema/Initialization.h"
32f4a2713aSLionel Sambuc #include "clang/Sema/Lookup.h"
33f4a2713aSLionel Sambuc #include "clang/Sema/ScopeInfo.h"
34f4a2713aSLionel Sambuc #include "clang/Sema/Sema.h"
35*0a6a1f1dSLionel Sambuc #include "llvm/ADT/STLExtras.h"
36f4a2713aSLionel Sambuc #include "llvm/ADT/SmallBitVector.h"
37f4a2713aSLionel Sambuc #include "llvm/ADT/SmallString.h"
38f4a2713aSLionel Sambuc #include "llvm/Support/ConvertUTF.h"
39f4a2713aSLionel Sambuc #include "llvm/Support/raw_ostream.h"
40f4a2713aSLionel Sambuc #include <limits>
41f4a2713aSLionel Sambuc using namespace clang;
42f4a2713aSLionel Sambuc using namespace sema;
43f4a2713aSLionel Sambuc
getLocationOfStringLiteralByte(const StringLiteral * SL,unsigned ByteNo) const44f4a2713aSLionel Sambuc SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45f4a2713aSLionel Sambuc unsigned ByteNo) const {
46*0a6a1f1dSLionel Sambuc return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47*0a6a1f1dSLionel Sambuc Context.getTargetInfo());
48f4a2713aSLionel Sambuc }
49f4a2713aSLionel Sambuc
50f4a2713aSLionel Sambuc /// Checks that a call expression's argument count is the desired number.
51f4a2713aSLionel Sambuc /// This is useful when doing custom type-checking. Returns true on error.
checkArgCount(Sema & S,CallExpr * call,unsigned desiredArgCount)52f4a2713aSLionel Sambuc static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53f4a2713aSLionel Sambuc unsigned argCount = call->getNumArgs();
54f4a2713aSLionel Sambuc if (argCount == desiredArgCount) return false;
55f4a2713aSLionel Sambuc
56f4a2713aSLionel Sambuc if (argCount < desiredArgCount)
57f4a2713aSLionel Sambuc return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58f4a2713aSLionel Sambuc << 0 /*function call*/ << desiredArgCount << argCount
59f4a2713aSLionel Sambuc << call->getSourceRange();
60f4a2713aSLionel Sambuc
61f4a2713aSLionel Sambuc // Highlight all the excess arguments.
62f4a2713aSLionel Sambuc SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63f4a2713aSLionel Sambuc call->getArg(argCount - 1)->getLocEnd());
64f4a2713aSLionel Sambuc
65f4a2713aSLionel Sambuc return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66f4a2713aSLionel Sambuc << 0 /*function call*/ << desiredArgCount << argCount
67f4a2713aSLionel Sambuc << call->getArg(1)->getSourceRange();
68f4a2713aSLionel Sambuc }
69f4a2713aSLionel Sambuc
70f4a2713aSLionel Sambuc /// Check that the first argument to __builtin_annotation is an integer
71f4a2713aSLionel Sambuc /// and the second argument is a non-wide string literal.
SemaBuiltinAnnotation(Sema & S,CallExpr * TheCall)72f4a2713aSLionel Sambuc static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73f4a2713aSLionel Sambuc if (checkArgCount(S, TheCall, 2))
74f4a2713aSLionel Sambuc return true;
75f4a2713aSLionel Sambuc
76f4a2713aSLionel Sambuc // First argument should be an integer.
77f4a2713aSLionel Sambuc Expr *ValArg = TheCall->getArg(0);
78f4a2713aSLionel Sambuc QualType Ty = ValArg->getType();
79f4a2713aSLionel Sambuc if (!Ty->isIntegerType()) {
80f4a2713aSLionel Sambuc S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81f4a2713aSLionel Sambuc << ValArg->getSourceRange();
82f4a2713aSLionel Sambuc return true;
83f4a2713aSLionel Sambuc }
84f4a2713aSLionel Sambuc
85f4a2713aSLionel Sambuc // Second argument should be a constant string.
86f4a2713aSLionel Sambuc Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87f4a2713aSLionel Sambuc StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88f4a2713aSLionel Sambuc if (!Literal || !Literal->isAscii()) {
89f4a2713aSLionel Sambuc S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90f4a2713aSLionel Sambuc << StrArg->getSourceRange();
91f4a2713aSLionel Sambuc return true;
92f4a2713aSLionel Sambuc }
93f4a2713aSLionel Sambuc
94f4a2713aSLionel Sambuc TheCall->setType(Ty);
95f4a2713aSLionel Sambuc return false;
96f4a2713aSLionel Sambuc }
97f4a2713aSLionel Sambuc
98f4a2713aSLionel Sambuc /// Check that the argument to __builtin_addressof is a glvalue, and set the
99f4a2713aSLionel Sambuc /// result type to the corresponding pointer type.
SemaBuiltinAddressof(Sema & S,CallExpr * TheCall)100f4a2713aSLionel Sambuc static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101f4a2713aSLionel Sambuc if (checkArgCount(S, TheCall, 1))
102f4a2713aSLionel Sambuc return true;
103f4a2713aSLionel Sambuc
104*0a6a1f1dSLionel Sambuc ExprResult Arg(TheCall->getArg(0));
105f4a2713aSLionel Sambuc QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106f4a2713aSLionel Sambuc if (ResultType.isNull())
107f4a2713aSLionel Sambuc return true;
108f4a2713aSLionel Sambuc
109*0a6a1f1dSLionel Sambuc TheCall->setArg(0, Arg.get());
110f4a2713aSLionel Sambuc TheCall->setType(ResultType);
111f4a2713aSLionel Sambuc return false;
112f4a2713aSLionel Sambuc }
113f4a2713aSLionel Sambuc
SemaBuiltinMemChkCall(Sema & S,FunctionDecl * FDecl,CallExpr * TheCall,unsigned SizeIdx,unsigned DstSizeIdx)114*0a6a1f1dSLionel Sambuc static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115*0a6a1f1dSLionel Sambuc CallExpr *TheCall, unsigned SizeIdx,
116*0a6a1f1dSLionel Sambuc unsigned DstSizeIdx) {
117*0a6a1f1dSLionel Sambuc if (TheCall->getNumArgs() <= SizeIdx ||
118*0a6a1f1dSLionel Sambuc TheCall->getNumArgs() <= DstSizeIdx)
119*0a6a1f1dSLionel Sambuc return;
120*0a6a1f1dSLionel Sambuc
121*0a6a1f1dSLionel Sambuc const Expr *SizeArg = TheCall->getArg(SizeIdx);
122*0a6a1f1dSLionel Sambuc const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123*0a6a1f1dSLionel Sambuc
124*0a6a1f1dSLionel Sambuc llvm::APSInt Size, DstSize;
125*0a6a1f1dSLionel Sambuc
126*0a6a1f1dSLionel Sambuc // find out if both sizes are known at compile time
127*0a6a1f1dSLionel Sambuc if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128*0a6a1f1dSLionel Sambuc !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129*0a6a1f1dSLionel Sambuc return;
130*0a6a1f1dSLionel Sambuc
131*0a6a1f1dSLionel Sambuc if (Size.ule(DstSize))
132*0a6a1f1dSLionel Sambuc return;
133*0a6a1f1dSLionel Sambuc
134*0a6a1f1dSLionel Sambuc // confirmed overflow so generate the diagnostic.
135*0a6a1f1dSLionel Sambuc IdentifierInfo *FnName = FDecl->getIdentifier();
136*0a6a1f1dSLionel Sambuc SourceLocation SL = TheCall->getLocStart();
137*0a6a1f1dSLionel Sambuc SourceRange SR = TheCall->getSourceRange();
138*0a6a1f1dSLionel Sambuc
139*0a6a1f1dSLionel Sambuc S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140*0a6a1f1dSLionel Sambuc }
141*0a6a1f1dSLionel Sambuc
SemaBuiltinCallWithStaticChain(Sema & S,CallExpr * BuiltinCall)142*0a6a1f1dSLionel Sambuc static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143*0a6a1f1dSLionel Sambuc if (checkArgCount(S, BuiltinCall, 2))
144*0a6a1f1dSLionel Sambuc return true;
145*0a6a1f1dSLionel Sambuc
146*0a6a1f1dSLionel Sambuc SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147*0a6a1f1dSLionel Sambuc Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148*0a6a1f1dSLionel Sambuc Expr *Call = BuiltinCall->getArg(0);
149*0a6a1f1dSLionel Sambuc Expr *Chain = BuiltinCall->getArg(1);
150*0a6a1f1dSLionel Sambuc
151*0a6a1f1dSLionel Sambuc if (Call->getStmtClass() != Stmt::CallExprClass) {
152*0a6a1f1dSLionel Sambuc S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153*0a6a1f1dSLionel Sambuc << Call->getSourceRange();
154*0a6a1f1dSLionel Sambuc return true;
155*0a6a1f1dSLionel Sambuc }
156*0a6a1f1dSLionel Sambuc
157*0a6a1f1dSLionel Sambuc auto CE = cast<CallExpr>(Call);
158*0a6a1f1dSLionel Sambuc if (CE->getCallee()->getType()->isBlockPointerType()) {
159*0a6a1f1dSLionel Sambuc S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160*0a6a1f1dSLionel Sambuc << Call->getSourceRange();
161*0a6a1f1dSLionel Sambuc return true;
162*0a6a1f1dSLionel Sambuc }
163*0a6a1f1dSLionel Sambuc
164*0a6a1f1dSLionel Sambuc const Decl *TargetDecl = CE->getCalleeDecl();
165*0a6a1f1dSLionel Sambuc if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166*0a6a1f1dSLionel Sambuc if (FD->getBuiltinID()) {
167*0a6a1f1dSLionel Sambuc S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168*0a6a1f1dSLionel Sambuc << Call->getSourceRange();
169*0a6a1f1dSLionel Sambuc return true;
170*0a6a1f1dSLionel Sambuc }
171*0a6a1f1dSLionel Sambuc
172*0a6a1f1dSLionel Sambuc if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173*0a6a1f1dSLionel Sambuc S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174*0a6a1f1dSLionel Sambuc << Call->getSourceRange();
175*0a6a1f1dSLionel Sambuc return true;
176*0a6a1f1dSLionel Sambuc }
177*0a6a1f1dSLionel Sambuc
178*0a6a1f1dSLionel Sambuc ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179*0a6a1f1dSLionel Sambuc if (ChainResult.isInvalid())
180*0a6a1f1dSLionel Sambuc return true;
181*0a6a1f1dSLionel Sambuc if (!ChainResult.get()->getType()->isPointerType()) {
182*0a6a1f1dSLionel Sambuc S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183*0a6a1f1dSLionel Sambuc << Chain->getSourceRange();
184*0a6a1f1dSLionel Sambuc return true;
185*0a6a1f1dSLionel Sambuc }
186*0a6a1f1dSLionel Sambuc
187*0a6a1f1dSLionel Sambuc QualType ReturnTy = CE->getCallReturnType();
188*0a6a1f1dSLionel Sambuc QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189*0a6a1f1dSLionel Sambuc QualType BuiltinTy = S.Context.getFunctionType(
190*0a6a1f1dSLionel Sambuc ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191*0a6a1f1dSLionel Sambuc QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
192*0a6a1f1dSLionel Sambuc
193*0a6a1f1dSLionel Sambuc Builtin =
194*0a6a1f1dSLionel Sambuc S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
195*0a6a1f1dSLionel Sambuc
196*0a6a1f1dSLionel Sambuc BuiltinCall->setType(CE->getType());
197*0a6a1f1dSLionel Sambuc BuiltinCall->setValueKind(CE->getValueKind());
198*0a6a1f1dSLionel Sambuc BuiltinCall->setObjectKind(CE->getObjectKind());
199*0a6a1f1dSLionel Sambuc BuiltinCall->setCallee(Builtin);
200*0a6a1f1dSLionel Sambuc BuiltinCall->setArg(1, ChainResult.get());
201*0a6a1f1dSLionel Sambuc
202*0a6a1f1dSLionel Sambuc return false;
203*0a6a1f1dSLionel Sambuc }
204*0a6a1f1dSLionel Sambuc
205f4a2713aSLionel Sambuc ExprResult
CheckBuiltinFunctionCall(FunctionDecl * FDecl,unsigned BuiltinID,CallExpr * TheCall)206*0a6a1f1dSLionel Sambuc Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
207*0a6a1f1dSLionel Sambuc CallExpr *TheCall) {
208*0a6a1f1dSLionel Sambuc ExprResult TheCallResult(TheCall);
209f4a2713aSLionel Sambuc
210f4a2713aSLionel Sambuc // Find out if any arguments are required to be integer constant expressions.
211f4a2713aSLionel Sambuc unsigned ICEArguments = 0;
212f4a2713aSLionel Sambuc ASTContext::GetBuiltinTypeError Error;
213f4a2713aSLionel Sambuc Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
214f4a2713aSLionel Sambuc if (Error != ASTContext::GE_None)
215f4a2713aSLionel Sambuc ICEArguments = 0; // Don't diagnose previously diagnosed errors.
216f4a2713aSLionel Sambuc
217f4a2713aSLionel Sambuc // If any arguments are required to be ICE's, check and diagnose.
218f4a2713aSLionel Sambuc for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
219f4a2713aSLionel Sambuc // Skip arguments not required to be ICE's.
220f4a2713aSLionel Sambuc if ((ICEArguments & (1 << ArgNo)) == 0) continue;
221f4a2713aSLionel Sambuc
222f4a2713aSLionel Sambuc llvm::APSInt Result;
223f4a2713aSLionel Sambuc if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
224f4a2713aSLionel Sambuc return true;
225f4a2713aSLionel Sambuc ICEArguments &= ~(1 << ArgNo);
226f4a2713aSLionel Sambuc }
227f4a2713aSLionel Sambuc
228f4a2713aSLionel Sambuc switch (BuiltinID) {
229f4a2713aSLionel Sambuc case Builtin::BI__builtin___CFStringMakeConstantString:
230f4a2713aSLionel Sambuc assert(TheCall->getNumArgs() == 1 &&
231f4a2713aSLionel Sambuc "Wrong # arguments to builtin CFStringMakeConstantString");
232f4a2713aSLionel Sambuc if (CheckObjCString(TheCall->getArg(0)))
233f4a2713aSLionel Sambuc return ExprError();
234f4a2713aSLionel Sambuc break;
235f4a2713aSLionel Sambuc case Builtin::BI__builtin_stdarg_start:
236f4a2713aSLionel Sambuc case Builtin::BI__builtin_va_start:
237f4a2713aSLionel Sambuc if (SemaBuiltinVAStart(TheCall))
238f4a2713aSLionel Sambuc return ExprError();
239f4a2713aSLionel Sambuc break;
240*0a6a1f1dSLionel Sambuc case Builtin::BI__va_start: {
241*0a6a1f1dSLionel Sambuc switch (Context.getTargetInfo().getTriple().getArch()) {
242*0a6a1f1dSLionel Sambuc case llvm::Triple::arm:
243*0a6a1f1dSLionel Sambuc case llvm::Triple::thumb:
244*0a6a1f1dSLionel Sambuc if (SemaBuiltinVAStartARM(TheCall))
245*0a6a1f1dSLionel Sambuc return ExprError();
246*0a6a1f1dSLionel Sambuc break;
247*0a6a1f1dSLionel Sambuc default:
248*0a6a1f1dSLionel Sambuc if (SemaBuiltinVAStart(TheCall))
249*0a6a1f1dSLionel Sambuc return ExprError();
250*0a6a1f1dSLionel Sambuc break;
251*0a6a1f1dSLionel Sambuc }
252*0a6a1f1dSLionel Sambuc break;
253*0a6a1f1dSLionel Sambuc }
254f4a2713aSLionel Sambuc case Builtin::BI__builtin_isgreater:
255f4a2713aSLionel Sambuc case Builtin::BI__builtin_isgreaterequal:
256f4a2713aSLionel Sambuc case Builtin::BI__builtin_isless:
257f4a2713aSLionel Sambuc case Builtin::BI__builtin_islessequal:
258f4a2713aSLionel Sambuc case Builtin::BI__builtin_islessgreater:
259f4a2713aSLionel Sambuc case Builtin::BI__builtin_isunordered:
260f4a2713aSLionel Sambuc if (SemaBuiltinUnorderedCompare(TheCall))
261f4a2713aSLionel Sambuc return ExprError();
262f4a2713aSLionel Sambuc break;
263f4a2713aSLionel Sambuc case Builtin::BI__builtin_fpclassify:
264f4a2713aSLionel Sambuc if (SemaBuiltinFPClassification(TheCall, 6))
265f4a2713aSLionel Sambuc return ExprError();
266f4a2713aSLionel Sambuc break;
267f4a2713aSLionel Sambuc case Builtin::BI__builtin_isfinite:
268f4a2713aSLionel Sambuc case Builtin::BI__builtin_isinf:
269f4a2713aSLionel Sambuc case Builtin::BI__builtin_isinf_sign:
270f4a2713aSLionel Sambuc case Builtin::BI__builtin_isnan:
271f4a2713aSLionel Sambuc case Builtin::BI__builtin_isnormal:
272f4a2713aSLionel Sambuc if (SemaBuiltinFPClassification(TheCall, 1))
273f4a2713aSLionel Sambuc return ExprError();
274f4a2713aSLionel Sambuc break;
275f4a2713aSLionel Sambuc case Builtin::BI__builtin_shufflevector:
276f4a2713aSLionel Sambuc return SemaBuiltinShuffleVector(TheCall);
277f4a2713aSLionel Sambuc // TheCall will be freed by the smart pointer here, but that's fine, since
278f4a2713aSLionel Sambuc // SemaBuiltinShuffleVector guts it, but then doesn't release it.
279f4a2713aSLionel Sambuc case Builtin::BI__builtin_prefetch:
280f4a2713aSLionel Sambuc if (SemaBuiltinPrefetch(TheCall))
281f4a2713aSLionel Sambuc return ExprError();
282f4a2713aSLionel Sambuc break;
283*0a6a1f1dSLionel Sambuc case Builtin::BI__assume:
284*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_assume:
285*0a6a1f1dSLionel Sambuc if (SemaBuiltinAssume(TheCall))
286*0a6a1f1dSLionel Sambuc return ExprError();
287*0a6a1f1dSLionel Sambuc break;
288*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_assume_aligned:
289*0a6a1f1dSLionel Sambuc if (SemaBuiltinAssumeAligned(TheCall))
290*0a6a1f1dSLionel Sambuc return ExprError();
291*0a6a1f1dSLionel Sambuc break;
292f4a2713aSLionel Sambuc case Builtin::BI__builtin_object_size:
293*0a6a1f1dSLionel Sambuc if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
294f4a2713aSLionel Sambuc return ExprError();
295f4a2713aSLionel Sambuc break;
296f4a2713aSLionel Sambuc case Builtin::BI__builtin_longjmp:
297f4a2713aSLionel Sambuc if (SemaBuiltinLongjmp(TheCall))
298f4a2713aSLionel Sambuc return ExprError();
299f4a2713aSLionel Sambuc break;
300*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_setjmp:
301*0a6a1f1dSLionel Sambuc if (SemaBuiltinSetjmp(TheCall))
302*0a6a1f1dSLionel Sambuc return ExprError();
303*0a6a1f1dSLionel Sambuc break;
304f4a2713aSLionel Sambuc
305f4a2713aSLionel Sambuc case Builtin::BI__builtin_classify_type:
306f4a2713aSLionel Sambuc if (checkArgCount(*this, TheCall, 1)) return true;
307f4a2713aSLionel Sambuc TheCall->setType(Context.IntTy);
308f4a2713aSLionel Sambuc break;
309f4a2713aSLionel Sambuc case Builtin::BI__builtin_constant_p:
310f4a2713aSLionel Sambuc if (checkArgCount(*this, TheCall, 1)) return true;
311f4a2713aSLionel Sambuc TheCall->setType(Context.IntTy);
312f4a2713aSLionel Sambuc break;
313f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add:
314f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add_1:
315f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add_2:
316f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add_4:
317f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add_8:
318f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add_16:
319f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub:
320f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub_1:
321f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub_2:
322f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub_4:
323f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub_8:
324f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub_16:
325f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or:
326f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or_1:
327f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or_2:
328f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or_4:
329f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or_8:
330f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or_16:
331f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and:
332f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and_1:
333f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and_2:
334f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and_4:
335f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and_8:
336f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and_16:
337f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor:
338f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor_1:
339f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor_2:
340f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor_4:
341f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor_8:
342f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor_16:
343*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand:
344*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand_1:
345*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand_2:
346*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand_4:
347*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand_8:
348*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand_16:
349f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch:
350f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch_1:
351f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch_2:
352f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch_4:
353f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch_8:
354f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch_16:
355f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch:
356f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch_1:
357f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch_2:
358f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch_4:
359f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch_8:
360f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch_16:
361f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch:
362f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch_1:
363f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch_2:
364f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch_4:
365f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch_8:
366f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch_16:
367f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch:
368f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch_1:
369f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch_2:
370f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch_4:
371f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch_8:
372f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch_16:
373f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch:
374f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch_1:
375f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch_2:
376f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch_4:
377f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch_8:
378f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch_16:
379*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch:
380*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch_1:
381*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch_2:
382*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch_4:
383*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch_8:
384*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch_16:
385f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap:
386f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap_1:
387f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap_2:
388f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap_4:
389f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap_8:
390f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap_16:
391f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap:
392f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap_1:
393f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap_2:
394f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap_4:
395f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap_8:
396f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap_16:
397f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set:
398f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set_1:
399f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set_2:
400f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set_4:
401f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set_8:
402f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set_16:
403f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release:
404f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release_1:
405f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release_2:
406f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release_4:
407f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release_8:
408f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release_16:
409f4a2713aSLionel Sambuc case Builtin::BI__sync_swap:
410f4a2713aSLionel Sambuc case Builtin::BI__sync_swap_1:
411f4a2713aSLionel Sambuc case Builtin::BI__sync_swap_2:
412f4a2713aSLionel Sambuc case Builtin::BI__sync_swap_4:
413f4a2713aSLionel Sambuc case Builtin::BI__sync_swap_8:
414f4a2713aSLionel Sambuc case Builtin::BI__sync_swap_16:
415f4a2713aSLionel Sambuc return SemaBuiltinAtomicOverloaded(TheCallResult);
416f4a2713aSLionel Sambuc #define BUILTIN(ID, TYPE, ATTRS)
417f4a2713aSLionel Sambuc #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
418f4a2713aSLionel Sambuc case Builtin::BI##ID: \
419f4a2713aSLionel Sambuc return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
420f4a2713aSLionel Sambuc #include "clang/Basic/Builtins.def"
421f4a2713aSLionel Sambuc case Builtin::BI__builtin_annotation:
422f4a2713aSLionel Sambuc if (SemaBuiltinAnnotation(*this, TheCall))
423f4a2713aSLionel Sambuc return ExprError();
424f4a2713aSLionel Sambuc break;
425f4a2713aSLionel Sambuc case Builtin::BI__builtin_addressof:
426f4a2713aSLionel Sambuc if (SemaBuiltinAddressof(*this, TheCall))
427f4a2713aSLionel Sambuc return ExprError();
428f4a2713aSLionel Sambuc break;
429*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_operator_new:
430*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_operator_delete:
431*0a6a1f1dSLionel Sambuc if (!getLangOpts().CPlusPlus) {
432*0a6a1f1dSLionel Sambuc Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
433*0a6a1f1dSLionel Sambuc << (BuiltinID == Builtin::BI__builtin_operator_new
434*0a6a1f1dSLionel Sambuc ? "__builtin_operator_new"
435*0a6a1f1dSLionel Sambuc : "__builtin_operator_delete")
436*0a6a1f1dSLionel Sambuc << "C++";
437*0a6a1f1dSLionel Sambuc return ExprError();
438*0a6a1f1dSLionel Sambuc }
439*0a6a1f1dSLionel Sambuc // CodeGen assumes it can find the global new and delete to call,
440*0a6a1f1dSLionel Sambuc // so ensure that they are declared.
441*0a6a1f1dSLionel Sambuc DeclareGlobalNewDelete();
442*0a6a1f1dSLionel Sambuc break;
443*0a6a1f1dSLionel Sambuc
444*0a6a1f1dSLionel Sambuc // check secure string manipulation functions where overflows
445*0a6a1f1dSLionel Sambuc // are detectable at compile time
446*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___memcpy_chk:
447*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___memmove_chk:
448*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___memset_chk:
449*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___strlcat_chk:
450*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___strlcpy_chk:
451*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___strncat_chk:
452*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___strncpy_chk:
453*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___stpncpy_chk:
454*0a6a1f1dSLionel Sambuc SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
455*0a6a1f1dSLionel Sambuc break;
456*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___memccpy_chk:
457*0a6a1f1dSLionel Sambuc SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
458*0a6a1f1dSLionel Sambuc break;
459*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___snprintf_chk:
460*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin___vsnprintf_chk:
461*0a6a1f1dSLionel Sambuc SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
462*0a6a1f1dSLionel Sambuc break;
463*0a6a1f1dSLionel Sambuc
464*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_call_with_static_chain:
465*0a6a1f1dSLionel Sambuc if (SemaBuiltinCallWithStaticChain(*this, TheCall))
466*0a6a1f1dSLionel Sambuc return ExprError();
467*0a6a1f1dSLionel Sambuc break;
468f4a2713aSLionel Sambuc }
469f4a2713aSLionel Sambuc
470f4a2713aSLionel Sambuc // Since the target specific builtins for each arch overlap, only check those
471f4a2713aSLionel Sambuc // of the arch we are compiling for.
472f4a2713aSLionel Sambuc if (BuiltinID >= Builtin::FirstTSBuiltin) {
473f4a2713aSLionel Sambuc switch (Context.getTargetInfo().getTriple().getArch()) {
474f4a2713aSLionel Sambuc case llvm::Triple::arm:
475*0a6a1f1dSLionel Sambuc case llvm::Triple::armeb:
476f4a2713aSLionel Sambuc case llvm::Triple::thumb:
477*0a6a1f1dSLionel Sambuc case llvm::Triple::thumbeb:
478f4a2713aSLionel Sambuc if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
479f4a2713aSLionel Sambuc return ExprError();
480f4a2713aSLionel Sambuc break;
481f4a2713aSLionel Sambuc case llvm::Triple::aarch64:
482*0a6a1f1dSLionel Sambuc case llvm::Triple::aarch64_be:
483f4a2713aSLionel Sambuc if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
484f4a2713aSLionel Sambuc return ExprError();
485f4a2713aSLionel Sambuc break;
486f4a2713aSLionel Sambuc case llvm::Triple::mips:
487f4a2713aSLionel Sambuc case llvm::Triple::mipsel:
488f4a2713aSLionel Sambuc case llvm::Triple::mips64:
489f4a2713aSLionel Sambuc case llvm::Triple::mips64el:
490f4a2713aSLionel Sambuc if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
491f4a2713aSLionel Sambuc return ExprError();
492f4a2713aSLionel Sambuc break;
493*0a6a1f1dSLionel Sambuc case llvm::Triple::x86:
494*0a6a1f1dSLionel Sambuc case llvm::Triple::x86_64:
495*0a6a1f1dSLionel Sambuc if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
496*0a6a1f1dSLionel Sambuc return ExprError();
497*0a6a1f1dSLionel Sambuc break;
498f4a2713aSLionel Sambuc default:
499f4a2713aSLionel Sambuc break;
500f4a2713aSLionel Sambuc }
501f4a2713aSLionel Sambuc }
502f4a2713aSLionel Sambuc
503f4a2713aSLionel Sambuc return TheCallResult;
504f4a2713aSLionel Sambuc }
505f4a2713aSLionel Sambuc
506f4a2713aSLionel Sambuc // Get the valid immediate range for the specified NEON type code.
RFT(unsigned t,bool shift=false,bool ForceQuad=false)507*0a6a1f1dSLionel Sambuc static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
508f4a2713aSLionel Sambuc NeonTypeFlags Type(t);
509*0a6a1f1dSLionel Sambuc int IsQuad = ForceQuad ? true : Type.isQuad();
510f4a2713aSLionel Sambuc switch (Type.getEltType()) {
511f4a2713aSLionel Sambuc case NeonTypeFlags::Int8:
512f4a2713aSLionel Sambuc case NeonTypeFlags::Poly8:
513f4a2713aSLionel Sambuc return shift ? 7 : (8 << IsQuad) - 1;
514f4a2713aSLionel Sambuc case NeonTypeFlags::Int16:
515f4a2713aSLionel Sambuc case NeonTypeFlags::Poly16:
516f4a2713aSLionel Sambuc return shift ? 15 : (4 << IsQuad) - 1;
517f4a2713aSLionel Sambuc case NeonTypeFlags::Int32:
518f4a2713aSLionel Sambuc return shift ? 31 : (2 << IsQuad) - 1;
519f4a2713aSLionel Sambuc case NeonTypeFlags::Int64:
520f4a2713aSLionel Sambuc case NeonTypeFlags::Poly64:
521f4a2713aSLionel Sambuc return shift ? 63 : (1 << IsQuad) - 1;
522*0a6a1f1dSLionel Sambuc case NeonTypeFlags::Poly128:
523*0a6a1f1dSLionel Sambuc return shift ? 127 : (1 << IsQuad) - 1;
524f4a2713aSLionel Sambuc case NeonTypeFlags::Float16:
525f4a2713aSLionel Sambuc assert(!shift && "cannot shift float types!");
526f4a2713aSLionel Sambuc return (4 << IsQuad) - 1;
527f4a2713aSLionel Sambuc case NeonTypeFlags::Float32:
528f4a2713aSLionel Sambuc assert(!shift && "cannot shift float types!");
529f4a2713aSLionel Sambuc return (2 << IsQuad) - 1;
530f4a2713aSLionel Sambuc case NeonTypeFlags::Float64:
531f4a2713aSLionel Sambuc assert(!shift && "cannot shift float types!");
532f4a2713aSLionel Sambuc return (1 << IsQuad) - 1;
533f4a2713aSLionel Sambuc }
534f4a2713aSLionel Sambuc llvm_unreachable("Invalid NeonTypeFlag!");
535f4a2713aSLionel Sambuc }
536f4a2713aSLionel Sambuc
537f4a2713aSLionel Sambuc /// getNeonEltType - Return the QualType corresponding to the elements of
538f4a2713aSLionel Sambuc /// the vector type specified by the NeonTypeFlags. This is used to check
539f4a2713aSLionel Sambuc /// the pointer arguments for Neon load/store intrinsics.
getNeonEltType(NeonTypeFlags Flags,ASTContext & Context,bool IsPolyUnsigned,bool IsInt64Long)540f4a2713aSLionel Sambuc static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
541*0a6a1f1dSLionel Sambuc bool IsPolyUnsigned, bool IsInt64Long) {
542f4a2713aSLionel Sambuc switch (Flags.getEltType()) {
543f4a2713aSLionel Sambuc case NeonTypeFlags::Int8:
544f4a2713aSLionel Sambuc return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
545f4a2713aSLionel Sambuc case NeonTypeFlags::Int16:
546f4a2713aSLionel Sambuc return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
547f4a2713aSLionel Sambuc case NeonTypeFlags::Int32:
548f4a2713aSLionel Sambuc return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
549f4a2713aSLionel Sambuc case NeonTypeFlags::Int64:
550*0a6a1f1dSLionel Sambuc if (IsInt64Long)
551*0a6a1f1dSLionel Sambuc return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
552*0a6a1f1dSLionel Sambuc else
553*0a6a1f1dSLionel Sambuc return Flags.isUnsigned() ? Context.UnsignedLongLongTy
554*0a6a1f1dSLionel Sambuc : Context.LongLongTy;
555f4a2713aSLionel Sambuc case NeonTypeFlags::Poly8:
556*0a6a1f1dSLionel Sambuc return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
557f4a2713aSLionel Sambuc case NeonTypeFlags::Poly16:
558*0a6a1f1dSLionel Sambuc return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
559f4a2713aSLionel Sambuc case NeonTypeFlags::Poly64:
560*0a6a1f1dSLionel Sambuc return Context.UnsignedLongTy;
561*0a6a1f1dSLionel Sambuc case NeonTypeFlags::Poly128:
562*0a6a1f1dSLionel Sambuc break;
563f4a2713aSLionel Sambuc case NeonTypeFlags::Float16:
564f4a2713aSLionel Sambuc return Context.HalfTy;
565f4a2713aSLionel Sambuc case NeonTypeFlags::Float32:
566f4a2713aSLionel Sambuc return Context.FloatTy;
567f4a2713aSLionel Sambuc case NeonTypeFlags::Float64:
568f4a2713aSLionel Sambuc return Context.DoubleTy;
569f4a2713aSLionel Sambuc }
570f4a2713aSLionel Sambuc llvm_unreachable("Invalid NeonTypeFlag!");
571f4a2713aSLionel Sambuc }
572f4a2713aSLionel Sambuc
CheckNeonBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)573*0a6a1f1dSLionel Sambuc bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
574f4a2713aSLionel Sambuc llvm::APSInt Result;
575f4a2713aSLionel Sambuc uint64_t mask = 0;
576f4a2713aSLionel Sambuc unsigned TV = 0;
577f4a2713aSLionel Sambuc int PtrArgNum = -1;
578f4a2713aSLionel Sambuc bool HasConstPtr = false;
579f4a2713aSLionel Sambuc switch (BuiltinID) {
580*0a6a1f1dSLionel Sambuc #define GET_NEON_OVERLOAD_CHECK
581f4a2713aSLionel Sambuc #include "clang/Basic/arm_neon.inc"
582*0a6a1f1dSLionel Sambuc #undef GET_NEON_OVERLOAD_CHECK
583f4a2713aSLionel Sambuc }
584f4a2713aSLionel Sambuc
585f4a2713aSLionel Sambuc // For NEON intrinsics which are overloaded on vector element type, validate
586f4a2713aSLionel Sambuc // the immediate which specifies which variant to emit.
587f4a2713aSLionel Sambuc unsigned ImmArg = TheCall->getNumArgs()-1;
588f4a2713aSLionel Sambuc if (mask) {
589f4a2713aSLionel Sambuc if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
590f4a2713aSLionel Sambuc return true;
591f4a2713aSLionel Sambuc
592f4a2713aSLionel Sambuc TV = Result.getLimitedValue(64);
593f4a2713aSLionel Sambuc if ((TV > 63) || (mask & (1ULL << TV)) == 0)
594f4a2713aSLionel Sambuc return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
595f4a2713aSLionel Sambuc << TheCall->getArg(ImmArg)->getSourceRange();
596f4a2713aSLionel Sambuc }
597f4a2713aSLionel Sambuc
598f4a2713aSLionel Sambuc if (PtrArgNum >= 0) {
599f4a2713aSLionel Sambuc // Check that pointer arguments have the specified type.
600f4a2713aSLionel Sambuc Expr *Arg = TheCall->getArg(PtrArgNum);
601f4a2713aSLionel Sambuc if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
602f4a2713aSLionel Sambuc Arg = ICE->getSubExpr();
603f4a2713aSLionel Sambuc ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
604f4a2713aSLionel Sambuc QualType RHSTy = RHS.get()->getType();
605*0a6a1f1dSLionel Sambuc
606*0a6a1f1dSLionel Sambuc llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
607*0a6a1f1dSLionel Sambuc bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
608*0a6a1f1dSLionel Sambuc bool IsInt64Long =
609*0a6a1f1dSLionel Sambuc Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
610*0a6a1f1dSLionel Sambuc QualType EltTy =
611*0a6a1f1dSLionel Sambuc getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
612f4a2713aSLionel Sambuc if (HasConstPtr)
613f4a2713aSLionel Sambuc EltTy = EltTy.withConst();
614f4a2713aSLionel Sambuc QualType LHSTy = Context.getPointerType(EltTy);
615f4a2713aSLionel Sambuc AssignConvertType ConvTy;
616f4a2713aSLionel Sambuc ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
617f4a2713aSLionel Sambuc if (RHS.isInvalid())
618f4a2713aSLionel Sambuc return true;
619f4a2713aSLionel Sambuc if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
620f4a2713aSLionel Sambuc RHS.get(), AA_Assigning))
621f4a2713aSLionel Sambuc return true;
622f4a2713aSLionel Sambuc }
623f4a2713aSLionel Sambuc
624f4a2713aSLionel Sambuc // For NEON intrinsics which take an immediate value as part of the
625f4a2713aSLionel Sambuc // instruction, range check them here.
626f4a2713aSLionel Sambuc unsigned i = 0, l = 0, u = 0;
627f4a2713aSLionel Sambuc switch (BuiltinID) {
628f4a2713aSLionel Sambuc default:
629f4a2713aSLionel Sambuc return false;
630*0a6a1f1dSLionel Sambuc #define GET_NEON_IMMEDIATE_CHECK
631f4a2713aSLionel Sambuc #include "clang/Basic/arm_neon.inc"
632*0a6a1f1dSLionel Sambuc #undef GET_NEON_IMMEDIATE_CHECK
633f4a2713aSLionel Sambuc }
634f4a2713aSLionel Sambuc
635*0a6a1f1dSLionel Sambuc return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
636*0a6a1f1dSLionel Sambuc }
637*0a6a1f1dSLionel Sambuc
CheckARMBuiltinExclusiveCall(unsigned BuiltinID,CallExpr * TheCall,unsigned MaxWidth)638*0a6a1f1dSLionel Sambuc bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
639*0a6a1f1dSLionel Sambuc unsigned MaxWidth) {
640f4a2713aSLionel Sambuc assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
641*0a6a1f1dSLionel Sambuc BuiltinID == ARM::BI__builtin_arm_ldaex ||
642*0a6a1f1dSLionel Sambuc BuiltinID == ARM::BI__builtin_arm_strex ||
643*0a6a1f1dSLionel Sambuc BuiltinID == ARM::BI__builtin_arm_stlex ||
644*0a6a1f1dSLionel Sambuc BuiltinID == AArch64::BI__builtin_arm_ldrex ||
645*0a6a1f1dSLionel Sambuc BuiltinID == AArch64::BI__builtin_arm_ldaex ||
646*0a6a1f1dSLionel Sambuc BuiltinID == AArch64::BI__builtin_arm_strex ||
647*0a6a1f1dSLionel Sambuc BuiltinID == AArch64::BI__builtin_arm_stlex) &&
648f4a2713aSLionel Sambuc "unexpected ARM builtin");
649*0a6a1f1dSLionel Sambuc bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
650*0a6a1f1dSLionel Sambuc BuiltinID == ARM::BI__builtin_arm_ldaex ||
651*0a6a1f1dSLionel Sambuc BuiltinID == AArch64::BI__builtin_arm_ldrex ||
652*0a6a1f1dSLionel Sambuc BuiltinID == AArch64::BI__builtin_arm_ldaex;
653f4a2713aSLionel Sambuc
654f4a2713aSLionel Sambuc DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
655f4a2713aSLionel Sambuc
656f4a2713aSLionel Sambuc // Ensure that we have the proper number of arguments.
657f4a2713aSLionel Sambuc if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
658f4a2713aSLionel Sambuc return true;
659f4a2713aSLionel Sambuc
660f4a2713aSLionel Sambuc // Inspect the pointer argument of the atomic builtin. This should always be
661f4a2713aSLionel Sambuc // a pointer type, whose element is an integral scalar or pointer type.
662f4a2713aSLionel Sambuc // Because it is a pointer type, we don't have to worry about any implicit
663f4a2713aSLionel Sambuc // casts here.
664f4a2713aSLionel Sambuc Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
665f4a2713aSLionel Sambuc ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
666f4a2713aSLionel Sambuc if (PointerArgRes.isInvalid())
667f4a2713aSLionel Sambuc return true;
668*0a6a1f1dSLionel Sambuc PointerArg = PointerArgRes.get();
669f4a2713aSLionel Sambuc
670f4a2713aSLionel Sambuc const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
671f4a2713aSLionel Sambuc if (!pointerType) {
672f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
673f4a2713aSLionel Sambuc << PointerArg->getType() << PointerArg->getSourceRange();
674f4a2713aSLionel Sambuc return true;
675f4a2713aSLionel Sambuc }
676f4a2713aSLionel Sambuc
677f4a2713aSLionel Sambuc // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
678f4a2713aSLionel Sambuc // task is to insert the appropriate casts into the AST. First work out just
679f4a2713aSLionel Sambuc // what the appropriate type is.
680f4a2713aSLionel Sambuc QualType ValType = pointerType->getPointeeType();
681f4a2713aSLionel Sambuc QualType AddrType = ValType.getUnqualifiedType().withVolatile();
682f4a2713aSLionel Sambuc if (IsLdrex)
683f4a2713aSLionel Sambuc AddrType.addConst();
684f4a2713aSLionel Sambuc
685f4a2713aSLionel Sambuc // Issue a warning if the cast is dodgy.
686f4a2713aSLionel Sambuc CastKind CastNeeded = CK_NoOp;
687f4a2713aSLionel Sambuc if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
688f4a2713aSLionel Sambuc CastNeeded = CK_BitCast;
689f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
690f4a2713aSLionel Sambuc << PointerArg->getType()
691f4a2713aSLionel Sambuc << Context.getPointerType(AddrType)
692f4a2713aSLionel Sambuc << AA_Passing << PointerArg->getSourceRange();
693f4a2713aSLionel Sambuc }
694f4a2713aSLionel Sambuc
695f4a2713aSLionel Sambuc // Finally, do the cast and replace the argument with the corrected version.
696f4a2713aSLionel Sambuc AddrType = Context.getPointerType(AddrType);
697f4a2713aSLionel Sambuc PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
698f4a2713aSLionel Sambuc if (PointerArgRes.isInvalid())
699f4a2713aSLionel Sambuc return true;
700*0a6a1f1dSLionel Sambuc PointerArg = PointerArgRes.get();
701f4a2713aSLionel Sambuc
702f4a2713aSLionel Sambuc TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
703f4a2713aSLionel Sambuc
704f4a2713aSLionel Sambuc // In general, we allow ints, floats and pointers to be loaded and stored.
705f4a2713aSLionel Sambuc if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
706f4a2713aSLionel Sambuc !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
707f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
708f4a2713aSLionel Sambuc << PointerArg->getType() << PointerArg->getSourceRange();
709f4a2713aSLionel Sambuc return true;
710f4a2713aSLionel Sambuc }
711f4a2713aSLionel Sambuc
712f4a2713aSLionel Sambuc // But ARM doesn't have instructions to deal with 128-bit versions.
713*0a6a1f1dSLionel Sambuc if (Context.getTypeSize(ValType) > MaxWidth) {
714*0a6a1f1dSLionel Sambuc assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
715f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
716f4a2713aSLionel Sambuc << PointerArg->getType() << PointerArg->getSourceRange();
717f4a2713aSLionel Sambuc return true;
718f4a2713aSLionel Sambuc }
719f4a2713aSLionel Sambuc
720f4a2713aSLionel Sambuc switch (ValType.getObjCLifetime()) {
721f4a2713aSLionel Sambuc case Qualifiers::OCL_None:
722f4a2713aSLionel Sambuc case Qualifiers::OCL_ExplicitNone:
723f4a2713aSLionel Sambuc // okay
724f4a2713aSLionel Sambuc break;
725f4a2713aSLionel Sambuc
726f4a2713aSLionel Sambuc case Qualifiers::OCL_Weak:
727f4a2713aSLionel Sambuc case Qualifiers::OCL_Strong:
728f4a2713aSLionel Sambuc case Qualifiers::OCL_Autoreleasing:
729f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
730f4a2713aSLionel Sambuc << ValType << PointerArg->getSourceRange();
731f4a2713aSLionel Sambuc return true;
732f4a2713aSLionel Sambuc }
733f4a2713aSLionel Sambuc
734f4a2713aSLionel Sambuc
735f4a2713aSLionel Sambuc if (IsLdrex) {
736f4a2713aSLionel Sambuc TheCall->setType(ValType);
737f4a2713aSLionel Sambuc return false;
738f4a2713aSLionel Sambuc }
739f4a2713aSLionel Sambuc
740f4a2713aSLionel Sambuc // Initialize the argument to be stored.
741f4a2713aSLionel Sambuc ExprResult ValArg = TheCall->getArg(0);
742f4a2713aSLionel Sambuc InitializedEntity Entity = InitializedEntity::InitializeParameter(
743f4a2713aSLionel Sambuc Context, ValType, /*consume*/ false);
744f4a2713aSLionel Sambuc ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
745f4a2713aSLionel Sambuc if (ValArg.isInvalid())
746f4a2713aSLionel Sambuc return true;
747f4a2713aSLionel Sambuc TheCall->setArg(0, ValArg.get());
748f4a2713aSLionel Sambuc
749f4a2713aSLionel Sambuc // __builtin_arm_strex always returns an int. It's marked as such in the .def,
750f4a2713aSLionel Sambuc // but the custom checker bypasses all default analysis.
751f4a2713aSLionel Sambuc TheCall->setType(Context.IntTy);
752f4a2713aSLionel Sambuc return false;
753f4a2713aSLionel Sambuc }
754f4a2713aSLionel Sambuc
CheckARMBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)755f4a2713aSLionel Sambuc bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
756f4a2713aSLionel Sambuc llvm::APSInt Result;
757f4a2713aSLionel Sambuc
758f4a2713aSLionel Sambuc if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
759*0a6a1f1dSLionel Sambuc BuiltinID == ARM::BI__builtin_arm_ldaex ||
760*0a6a1f1dSLionel Sambuc BuiltinID == ARM::BI__builtin_arm_strex ||
761*0a6a1f1dSLionel Sambuc BuiltinID == ARM::BI__builtin_arm_stlex) {
762*0a6a1f1dSLionel Sambuc return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
763f4a2713aSLionel Sambuc }
764f4a2713aSLionel Sambuc
765*0a6a1f1dSLionel Sambuc if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
766*0a6a1f1dSLionel Sambuc return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
767*0a6a1f1dSLionel Sambuc SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
768f4a2713aSLionel Sambuc }
769f4a2713aSLionel Sambuc
770*0a6a1f1dSLionel Sambuc if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
771f4a2713aSLionel Sambuc return true;
772f4a2713aSLionel Sambuc
773*0a6a1f1dSLionel Sambuc // For intrinsics which take an immediate value as part of the instruction,
774*0a6a1f1dSLionel Sambuc // range check them here.
775f4a2713aSLionel Sambuc unsigned i = 0, l = 0, u = 0;
776f4a2713aSLionel Sambuc switch (BuiltinID) {
777f4a2713aSLionel Sambuc default: return false;
778f4a2713aSLionel Sambuc case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
779f4a2713aSLionel Sambuc case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
780f4a2713aSLionel Sambuc case ARM::BI__builtin_arm_vcvtr_f:
781f4a2713aSLionel Sambuc case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
782f4a2713aSLionel Sambuc case ARM::BI__builtin_arm_dmb:
783*0a6a1f1dSLionel Sambuc case ARM::BI__builtin_arm_dsb:
784*0a6a1f1dSLionel Sambuc case ARM::BI__builtin_arm_isb:
785*0a6a1f1dSLionel Sambuc case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
786*0a6a1f1dSLionel Sambuc }
787f4a2713aSLionel Sambuc
788f4a2713aSLionel Sambuc // FIXME: VFP Intrinsics should error if VFP not present.
789*0a6a1f1dSLionel Sambuc return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
790*0a6a1f1dSLionel Sambuc }
791*0a6a1f1dSLionel Sambuc
CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)792*0a6a1f1dSLionel Sambuc bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
793*0a6a1f1dSLionel Sambuc CallExpr *TheCall) {
794*0a6a1f1dSLionel Sambuc llvm::APSInt Result;
795*0a6a1f1dSLionel Sambuc
796*0a6a1f1dSLionel Sambuc if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
797*0a6a1f1dSLionel Sambuc BuiltinID == AArch64::BI__builtin_arm_ldaex ||
798*0a6a1f1dSLionel Sambuc BuiltinID == AArch64::BI__builtin_arm_strex ||
799*0a6a1f1dSLionel Sambuc BuiltinID == AArch64::BI__builtin_arm_stlex) {
800*0a6a1f1dSLionel Sambuc return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
801*0a6a1f1dSLionel Sambuc }
802*0a6a1f1dSLionel Sambuc
803*0a6a1f1dSLionel Sambuc if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
804*0a6a1f1dSLionel Sambuc return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
805*0a6a1f1dSLionel Sambuc SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
806*0a6a1f1dSLionel Sambuc SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
807*0a6a1f1dSLionel Sambuc SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
808*0a6a1f1dSLionel Sambuc }
809*0a6a1f1dSLionel Sambuc
810*0a6a1f1dSLionel Sambuc if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
811*0a6a1f1dSLionel Sambuc return true;
812*0a6a1f1dSLionel Sambuc
813*0a6a1f1dSLionel Sambuc // For intrinsics which take an immediate value as part of the instruction,
814*0a6a1f1dSLionel Sambuc // range check them here.
815*0a6a1f1dSLionel Sambuc unsigned i = 0, l = 0, u = 0;
816*0a6a1f1dSLionel Sambuc switch (BuiltinID) {
817*0a6a1f1dSLionel Sambuc default: return false;
818*0a6a1f1dSLionel Sambuc case AArch64::BI__builtin_arm_dmb:
819*0a6a1f1dSLionel Sambuc case AArch64::BI__builtin_arm_dsb:
820*0a6a1f1dSLionel Sambuc case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
821*0a6a1f1dSLionel Sambuc }
822*0a6a1f1dSLionel Sambuc
823*0a6a1f1dSLionel Sambuc return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
824f4a2713aSLionel Sambuc }
825f4a2713aSLionel Sambuc
CheckMipsBuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)826f4a2713aSLionel Sambuc bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
827f4a2713aSLionel Sambuc unsigned i = 0, l = 0, u = 0;
828f4a2713aSLionel Sambuc switch (BuiltinID) {
829f4a2713aSLionel Sambuc default: return false;
830f4a2713aSLionel Sambuc case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
831f4a2713aSLionel Sambuc case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
832f4a2713aSLionel Sambuc case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
833f4a2713aSLionel Sambuc case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
834f4a2713aSLionel Sambuc case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
835f4a2713aSLionel Sambuc case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
836f4a2713aSLionel Sambuc case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
837*0a6a1f1dSLionel Sambuc }
838f4a2713aSLionel Sambuc
839*0a6a1f1dSLionel Sambuc return SemaBuiltinConstantArgRange(TheCall, i, l, u);
840*0a6a1f1dSLionel Sambuc }
841f4a2713aSLionel Sambuc
CheckX86BuiltinFunctionCall(unsigned BuiltinID,CallExpr * TheCall)842*0a6a1f1dSLionel Sambuc bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
843*0a6a1f1dSLionel Sambuc unsigned i = 0, l = 0, u = 0;
844*0a6a1f1dSLionel Sambuc switch (BuiltinID) {
845*0a6a1f1dSLionel Sambuc default: return false;
846*0a6a1f1dSLionel Sambuc case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
847*0a6a1f1dSLionel Sambuc case X86::BI__builtin_ia32_cmpps:
848*0a6a1f1dSLionel Sambuc case X86::BI__builtin_ia32_cmpss:
849*0a6a1f1dSLionel Sambuc case X86::BI__builtin_ia32_cmppd:
850*0a6a1f1dSLionel Sambuc case X86::BI__builtin_ia32_cmpsd: i = 2; l = 0; u = 31; break;
851*0a6a1f1dSLionel Sambuc }
852*0a6a1f1dSLionel Sambuc return SemaBuiltinConstantArgRange(TheCall, i, l, u);
853f4a2713aSLionel Sambuc }
854f4a2713aSLionel Sambuc
855f4a2713aSLionel Sambuc /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
856f4a2713aSLionel Sambuc /// parameter with the FormatAttr's correct format_idx and firstDataArg.
857f4a2713aSLionel Sambuc /// Returns true when the format fits the function and the FormatStringInfo has
858f4a2713aSLionel Sambuc /// been populated.
getFormatStringInfo(const FormatAttr * Format,bool IsCXXMember,FormatStringInfo * FSI)859f4a2713aSLionel Sambuc bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
860f4a2713aSLionel Sambuc FormatStringInfo *FSI) {
861f4a2713aSLionel Sambuc FSI->HasVAListArg = Format->getFirstArg() == 0;
862f4a2713aSLionel Sambuc FSI->FormatIdx = Format->getFormatIdx() - 1;
863f4a2713aSLionel Sambuc FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
864f4a2713aSLionel Sambuc
865f4a2713aSLionel Sambuc // The way the format attribute works in GCC, the implicit this argument
866f4a2713aSLionel Sambuc // of member functions is counted. However, it doesn't appear in our own
867f4a2713aSLionel Sambuc // lists, so decrement format_idx in that case.
868f4a2713aSLionel Sambuc if (IsCXXMember) {
869f4a2713aSLionel Sambuc if(FSI->FormatIdx == 0)
870f4a2713aSLionel Sambuc return false;
871f4a2713aSLionel Sambuc --FSI->FormatIdx;
872f4a2713aSLionel Sambuc if (FSI->FirstDataArg != 0)
873f4a2713aSLionel Sambuc --FSI->FirstDataArg;
874f4a2713aSLionel Sambuc }
875f4a2713aSLionel Sambuc return true;
876f4a2713aSLionel Sambuc }
877f4a2713aSLionel Sambuc
878*0a6a1f1dSLionel Sambuc /// Checks if a the given expression evaluates to null.
879*0a6a1f1dSLionel Sambuc ///
880*0a6a1f1dSLionel Sambuc /// \brief Returns true if the value evaluates to null.
CheckNonNullExpr(Sema & S,const Expr * Expr)881*0a6a1f1dSLionel Sambuc static bool CheckNonNullExpr(Sema &S,
882*0a6a1f1dSLionel Sambuc const Expr *Expr) {
883*0a6a1f1dSLionel Sambuc // As a special case, transparent unions initialized with zero are
884*0a6a1f1dSLionel Sambuc // considered null for the purposes of the nonnull attribute.
885*0a6a1f1dSLionel Sambuc if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
886*0a6a1f1dSLionel Sambuc if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
887*0a6a1f1dSLionel Sambuc if (const CompoundLiteralExpr *CLE =
888*0a6a1f1dSLionel Sambuc dyn_cast<CompoundLiteralExpr>(Expr))
889*0a6a1f1dSLionel Sambuc if (const InitListExpr *ILE =
890*0a6a1f1dSLionel Sambuc dyn_cast<InitListExpr>(CLE->getInitializer()))
891*0a6a1f1dSLionel Sambuc Expr = ILE->getInit(0);
892*0a6a1f1dSLionel Sambuc }
893*0a6a1f1dSLionel Sambuc
894*0a6a1f1dSLionel Sambuc bool Result;
895*0a6a1f1dSLionel Sambuc return (!Expr->isValueDependent() &&
896*0a6a1f1dSLionel Sambuc Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
897*0a6a1f1dSLionel Sambuc !Result);
898*0a6a1f1dSLionel Sambuc }
899*0a6a1f1dSLionel Sambuc
CheckNonNullArgument(Sema & S,const Expr * ArgExpr,SourceLocation CallSiteLoc)900*0a6a1f1dSLionel Sambuc static void CheckNonNullArgument(Sema &S,
901*0a6a1f1dSLionel Sambuc const Expr *ArgExpr,
902*0a6a1f1dSLionel Sambuc SourceLocation CallSiteLoc) {
903*0a6a1f1dSLionel Sambuc if (CheckNonNullExpr(S, ArgExpr))
904*0a6a1f1dSLionel Sambuc S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
905*0a6a1f1dSLionel Sambuc }
906*0a6a1f1dSLionel Sambuc
GetFormatNSStringIdx(const FormatAttr * Format,unsigned & Idx)907*0a6a1f1dSLionel Sambuc bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
908*0a6a1f1dSLionel Sambuc FormatStringInfo FSI;
909*0a6a1f1dSLionel Sambuc if ((GetFormatStringType(Format) == FST_NSString) &&
910*0a6a1f1dSLionel Sambuc getFormatStringInfo(Format, false, &FSI)) {
911*0a6a1f1dSLionel Sambuc Idx = FSI.FormatIdx;
912*0a6a1f1dSLionel Sambuc return true;
913*0a6a1f1dSLionel Sambuc }
914*0a6a1f1dSLionel Sambuc return false;
915*0a6a1f1dSLionel Sambuc }
916*0a6a1f1dSLionel Sambuc /// \brief Diagnose use of %s directive in an NSString which is being passed
917*0a6a1f1dSLionel Sambuc /// as formatting string to formatting method.
918*0a6a1f1dSLionel Sambuc static void
DiagnoseCStringFormatDirectiveInCFAPI(Sema & S,const NamedDecl * FDecl,Expr ** Args,unsigned NumArgs)919*0a6a1f1dSLionel Sambuc DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
920*0a6a1f1dSLionel Sambuc const NamedDecl *FDecl,
921*0a6a1f1dSLionel Sambuc Expr **Args,
922*0a6a1f1dSLionel Sambuc unsigned NumArgs) {
923*0a6a1f1dSLionel Sambuc unsigned Idx = 0;
924*0a6a1f1dSLionel Sambuc bool Format = false;
925*0a6a1f1dSLionel Sambuc ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
926*0a6a1f1dSLionel Sambuc if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
927*0a6a1f1dSLionel Sambuc Idx = 2;
928*0a6a1f1dSLionel Sambuc Format = true;
929*0a6a1f1dSLionel Sambuc }
930*0a6a1f1dSLionel Sambuc else
931*0a6a1f1dSLionel Sambuc for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
932*0a6a1f1dSLionel Sambuc if (S.GetFormatNSStringIdx(I, Idx)) {
933*0a6a1f1dSLionel Sambuc Format = true;
934*0a6a1f1dSLionel Sambuc break;
935*0a6a1f1dSLionel Sambuc }
936*0a6a1f1dSLionel Sambuc }
937*0a6a1f1dSLionel Sambuc if (!Format || NumArgs <= Idx)
938*0a6a1f1dSLionel Sambuc return;
939*0a6a1f1dSLionel Sambuc const Expr *FormatExpr = Args[Idx];
940*0a6a1f1dSLionel Sambuc if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
941*0a6a1f1dSLionel Sambuc FormatExpr = CSCE->getSubExpr();
942*0a6a1f1dSLionel Sambuc const StringLiteral *FormatString;
943*0a6a1f1dSLionel Sambuc if (const ObjCStringLiteral *OSL =
944*0a6a1f1dSLionel Sambuc dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
945*0a6a1f1dSLionel Sambuc FormatString = OSL->getString();
946*0a6a1f1dSLionel Sambuc else
947*0a6a1f1dSLionel Sambuc FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
948*0a6a1f1dSLionel Sambuc if (!FormatString)
949*0a6a1f1dSLionel Sambuc return;
950*0a6a1f1dSLionel Sambuc if (S.FormatStringHasSArg(FormatString)) {
951*0a6a1f1dSLionel Sambuc S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
952*0a6a1f1dSLionel Sambuc << "%s" << 1 << 1;
953*0a6a1f1dSLionel Sambuc S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
954*0a6a1f1dSLionel Sambuc << FDecl->getDeclName();
955*0a6a1f1dSLionel Sambuc }
956*0a6a1f1dSLionel Sambuc }
957*0a6a1f1dSLionel Sambuc
CheckNonNullArguments(Sema & S,const NamedDecl * FDecl,ArrayRef<const Expr * > Args,SourceLocation CallSiteLoc)958*0a6a1f1dSLionel Sambuc static void CheckNonNullArguments(Sema &S,
959*0a6a1f1dSLionel Sambuc const NamedDecl *FDecl,
960*0a6a1f1dSLionel Sambuc ArrayRef<const Expr *> Args,
961*0a6a1f1dSLionel Sambuc SourceLocation CallSiteLoc) {
962*0a6a1f1dSLionel Sambuc // Check the attributes attached to the method/function itself.
963*0a6a1f1dSLionel Sambuc llvm::SmallBitVector NonNullArgs;
964*0a6a1f1dSLionel Sambuc for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
965*0a6a1f1dSLionel Sambuc if (!NonNull->args_size()) {
966*0a6a1f1dSLionel Sambuc // Easy case: all pointer arguments are nonnull.
967*0a6a1f1dSLionel Sambuc for (const auto *Arg : Args)
968*0a6a1f1dSLionel Sambuc if (S.isValidPointerAttrType(Arg->getType()))
969*0a6a1f1dSLionel Sambuc CheckNonNullArgument(S, Arg, CallSiteLoc);
970*0a6a1f1dSLionel Sambuc return;
971*0a6a1f1dSLionel Sambuc }
972*0a6a1f1dSLionel Sambuc
973*0a6a1f1dSLionel Sambuc for (unsigned Val : NonNull->args()) {
974*0a6a1f1dSLionel Sambuc if (Val >= Args.size())
975*0a6a1f1dSLionel Sambuc continue;
976*0a6a1f1dSLionel Sambuc if (NonNullArgs.empty())
977*0a6a1f1dSLionel Sambuc NonNullArgs.resize(Args.size());
978*0a6a1f1dSLionel Sambuc NonNullArgs.set(Val);
979*0a6a1f1dSLionel Sambuc }
980*0a6a1f1dSLionel Sambuc }
981*0a6a1f1dSLionel Sambuc
982*0a6a1f1dSLionel Sambuc // Check the attributes on the parameters.
983*0a6a1f1dSLionel Sambuc ArrayRef<ParmVarDecl*> parms;
984*0a6a1f1dSLionel Sambuc if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
985*0a6a1f1dSLionel Sambuc parms = FD->parameters();
986*0a6a1f1dSLionel Sambuc else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
987*0a6a1f1dSLionel Sambuc parms = MD->parameters();
988*0a6a1f1dSLionel Sambuc
989*0a6a1f1dSLionel Sambuc unsigned ArgIndex = 0;
990*0a6a1f1dSLionel Sambuc for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
991*0a6a1f1dSLionel Sambuc I != E; ++I, ++ArgIndex) {
992*0a6a1f1dSLionel Sambuc const ParmVarDecl *PVD = *I;
993*0a6a1f1dSLionel Sambuc if (PVD->hasAttr<NonNullAttr>() ||
994*0a6a1f1dSLionel Sambuc (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
995*0a6a1f1dSLionel Sambuc CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
996*0a6a1f1dSLionel Sambuc }
997*0a6a1f1dSLionel Sambuc
998*0a6a1f1dSLionel Sambuc // In case this is a variadic call, check any remaining arguments.
999*0a6a1f1dSLionel Sambuc for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1000*0a6a1f1dSLionel Sambuc if (NonNullArgs[ArgIndex])
1001*0a6a1f1dSLionel Sambuc CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1002*0a6a1f1dSLionel Sambuc }
1003*0a6a1f1dSLionel Sambuc
1004f4a2713aSLionel Sambuc /// Handles the checks for format strings, non-POD arguments to vararg
1005f4a2713aSLionel Sambuc /// functions, and NULL arguments passed to non-NULL parameters.
checkCall(NamedDecl * FDecl,ArrayRef<const Expr * > Args,unsigned NumParams,bool IsMemberFunction,SourceLocation Loc,SourceRange Range,VariadicCallType CallType)1006*0a6a1f1dSLionel Sambuc void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1007*0a6a1f1dSLionel Sambuc unsigned NumParams, bool IsMemberFunction,
1008*0a6a1f1dSLionel Sambuc SourceLocation Loc, SourceRange Range,
1009f4a2713aSLionel Sambuc VariadicCallType CallType) {
1010f4a2713aSLionel Sambuc // FIXME: We should check as much as we can in the template definition.
1011f4a2713aSLionel Sambuc if (CurContext->isDependentContext())
1012f4a2713aSLionel Sambuc return;
1013f4a2713aSLionel Sambuc
1014f4a2713aSLionel Sambuc // Printf and scanf checking.
1015f4a2713aSLionel Sambuc llvm::SmallBitVector CheckedVarArgs;
1016f4a2713aSLionel Sambuc if (FDecl) {
1017*0a6a1f1dSLionel Sambuc for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1018f4a2713aSLionel Sambuc // Only create vector if there are format attributes.
1019f4a2713aSLionel Sambuc CheckedVarArgs.resize(Args.size());
1020f4a2713aSLionel Sambuc
1021*0a6a1f1dSLionel Sambuc CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1022f4a2713aSLionel Sambuc CheckedVarArgs);
1023f4a2713aSLionel Sambuc }
1024f4a2713aSLionel Sambuc }
1025f4a2713aSLionel Sambuc
1026f4a2713aSLionel Sambuc // Refuse POD arguments that weren't caught by the format string
1027f4a2713aSLionel Sambuc // checks above.
1028f4a2713aSLionel Sambuc if (CallType != VariadicDoesNotApply) {
1029*0a6a1f1dSLionel Sambuc for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1030f4a2713aSLionel Sambuc // Args[ArgIdx] can be null in malformed code.
1031f4a2713aSLionel Sambuc if (const Expr *Arg = Args[ArgIdx]) {
1032f4a2713aSLionel Sambuc if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1033f4a2713aSLionel Sambuc checkVariadicArgument(Arg, CallType);
1034f4a2713aSLionel Sambuc }
1035f4a2713aSLionel Sambuc }
1036f4a2713aSLionel Sambuc }
1037f4a2713aSLionel Sambuc
1038f4a2713aSLionel Sambuc if (FDecl) {
1039*0a6a1f1dSLionel Sambuc CheckNonNullArguments(*this, FDecl, Args, Loc);
1040f4a2713aSLionel Sambuc
1041f4a2713aSLionel Sambuc // Type safety checking.
1042*0a6a1f1dSLionel Sambuc for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1043*0a6a1f1dSLionel Sambuc CheckArgumentWithTypeTag(I, Args.data());
1044f4a2713aSLionel Sambuc }
1045f4a2713aSLionel Sambuc }
1046f4a2713aSLionel Sambuc
1047f4a2713aSLionel Sambuc /// CheckConstructorCall - Check a constructor call for correctness and safety
1048f4a2713aSLionel Sambuc /// properties not enforced by the C type system.
CheckConstructorCall(FunctionDecl * FDecl,ArrayRef<const Expr * > Args,const FunctionProtoType * Proto,SourceLocation Loc)1049f4a2713aSLionel Sambuc void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1050f4a2713aSLionel Sambuc ArrayRef<const Expr *> Args,
1051f4a2713aSLionel Sambuc const FunctionProtoType *Proto,
1052f4a2713aSLionel Sambuc SourceLocation Loc) {
1053f4a2713aSLionel Sambuc VariadicCallType CallType =
1054f4a2713aSLionel Sambuc Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1055*0a6a1f1dSLionel Sambuc checkCall(FDecl, Args, Proto->getNumParams(),
1056f4a2713aSLionel Sambuc /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1057f4a2713aSLionel Sambuc }
1058f4a2713aSLionel Sambuc
1059f4a2713aSLionel Sambuc /// CheckFunctionCall - Check a direct function call for various correctness
1060f4a2713aSLionel Sambuc /// and safety properties not strictly enforced by the C type system.
CheckFunctionCall(FunctionDecl * FDecl,CallExpr * TheCall,const FunctionProtoType * Proto)1061f4a2713aSLionel Sambuc bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1062f4a2713aSLionel Sambuc const FunctionProtoType *Proto) {
1063f4a2713aSLionel Sambuc bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1064f4a2713aSLionel Sambuc isa<CXXMethodDecl>(FDecl);
1065f4a2713aSLionel Sambuc bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1066f4a2713aSLionel Sambuc IsMemberOperatorCall;
1067f4a2713aSLionel Sambuc VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1068f4a2713aSLionel Sambuc TheCall->getCallee());
1069*0a6a1f1dSLionel Sambuc unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1070f4a2713aSLionel Sambuc Expr** Args = TheCall->getArgs();
1071f4a2713aSLionel Sambuc unsigned NumArgs = TheCall->getNumArgs();
1072f4a2713aSLionel Sambuc if (IsMemberOperatorCall) {
1073f4a2713aSLionel Sambuc // If this is a call to a member operator, hide the first argument
1074f4a2713aSLionel Sambuc // from checkCall.
1075f4a2713aSLionel Sambuc // FIXME: Our choice of AST representation here is less than ideal.
1076f4a2713aSLionel Sambuc ++Args;
1077f4a2713aSLionel Sambuc --NumArgs;
1078f4a2713aSLionel Sambuc }
1079*0a6a1f1dSLionel Sambuc checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
1080f4a2713aSLionel Sambuc IsMemberFunction, TheCall->getRParenLoc(),
1081f4a2713aSLionel Sambuc TheCall->getCallee()->getSourceRange(), CallType);
1082f4a2713aSLionel Sambuc
1083f4a2713aSLionel Sambuc IdentifierInfo *FnInfo = FDecl->getIdentifier();
1084f4a2713aSLionel Sambuc // None of the checks below are needed for functions that don't have
1085f4a2713aSLionel Sambuc // simple names (e.g., C++ conversion functions).
1086f4a2713aSLionel Sambuc if (!FnInfo)
1087f4a2713aSLionel Sambuc return false;
1088f4a2713aSLionel Sambuc
1089*0a6a1f1dSLionel Sambuc CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1090*0a6a1f1dSLionel Sambuc if (getLangOpts().ObjC1)
1091*0a6a1f1dSLionel Sambuc DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
1092*0a6a1f1dSLionel Sambuc
1093f4a2713aSLionel Sambuc unsigned CMId = FDecl->getMemoryFunctionKind();
1094f4a2713aSLionel Sambuc if (CMId == 0)
1095f4a2713aSLionel Sambuc return false;
1096f4a2713aSLionel Sambuc
1097f4a2713aSLionel Sambuc // Handle memory setting and copying functions.
1098f4a2713aSLionel Sambuc if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1099f4a2713aSLionel Sambuc CheckStrlcpycatArguments(TheCall, FnInfo);
1100f4a2713aSLionel Sambuc else if (CMId == Builtin::BIstrncat)
1101f4a2713aSLionel Sambuc CheckStrncatArguments(TheCall, FnInfo);
1102f4a2713aSLionel Sambuc else
1103f4a2713aSLionel Sambuc CheckMemaccessArguments(TheCall, CMId, FnInfo);
1104f4a2713aSLionel Sambuc
1105f4a2713aSLionel Sambuc return false;
1106f4a2713aSLionel Sambuc }
1107f4a2713aSLionel Sambuc
CheckObjCMethodCall(ObjCMethodDecl * Method,SourceLocation lbrac,ArrayRef<const Expr * > Args)1108f4a2713aSLionel Sambuc bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
1109f4a2713aSLionel Sambuc ArrayRef<const Expr *> Args) {
1110f4a2713aSLionel Sambuc VariadicCallType CallType =
1111f4a2713aSLionel Sambuc Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1112f4a2713aSLionel Sambuc
1113f4a2713aSLionel Sambuc checkCall(Method, Args, Method->param_size(),
1114f4a2713aSLionel Sambuc /*IsMemberFunction=*/false,
1115f4a2713aSLionel Sambuc lbrac, Method->getSourceRange(), CallType);
1116f4a2713aSLionel Sambuc
1117f4a2713aSLionel Sambuc return false;
1118f4a2713aSLionel Sambuc }
1119f4a2713aSLionel Sambuc
CheckPointerCall(NamedDecl * NDecl,CallExpr * TheCall,const FunctionProtoType * Proto)1120f4a2713aSLionel Sambuc bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1121f4a2713aSLionel Sambuc const FunctionProtoType *Proto) {
1122f4a2713aSLionel Sambuc const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1123f4a2713aSLionel Sambuc if (!V)
1124f4a2713aSLionel Sambuc return false;
1125f4a2713aSLionel Sambuc
1126f4a2713aSLionel Sambuc QualType Ty = V->getType();
1127f4a2713aSLionel Sambuc if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
1128f4a2713aSLionel Sambuc return false;
1129f4a2713aSLionel Sambuc
1130f4a2713aSLionel Sambuc VariadicCallType CallType;
1131f4a2713aSLionel Sambuc if (!Proto || !Proto->isVariadic()) {
1132f4a2713aSLionel Sambuc CallType = VariadicDoesNotApply;
1133f4a2713aSLionel Sambuc } else if (Ty->isBlockPointerType()) {
1134f4a2713aSLionel Sambuc CallType = VariadicBlock;
1135f4a2713aSLionel Sambuc } else { // Ty->isFunctionPointerType()
1136f4a2713aSLionel Sambuc CallType = VariadicFunction;
1137f4a2713aSLionel Sambuc }
1138*0a6a1f1dSLionel Sambuc unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1139f4a2713aSLionel Sambuc
1140*0a6a1f1dSLionel Sambuc checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1141f4a2713aSLionel Sambuc TheCall->getNumArgs()),
1142*0a6a1f1dSLionel Sambuc NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1143f4a2713aSLionel Sambuc TheCall->getCallee()->getSourceRange(), CallType);
1144f4a2713aSLionel Sambuc
1145f4a2713aSLionel Sambuc return false;
1146f4a2713aSLionel Sambuc }
1147f4a2713aSLionel Sambuc
1148f4a2713aSLionel Sambuc /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1149f4a2713aSLionel Sambuc /// such as function pointers returned from functions.
CheckOtherCall(CallExpr * TheCall,const FunctionProtoType * Proto)1150f4a2713aSLionel Sambuc bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
1151*0a6a1f1dSLionel Sambuc VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
1152f4a2713aSLionel Sambuc TheCall->getCallee());
1153*0a6a1f1dSLionel Sambuc unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1154f4a2713aSLionel Sambuc
1155*0a6a1f1dSLionel Sambuc checkCall(/*FDecl=*/nullptr,
1156*0a6a1f1dSLionel Sambuc llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1157*0a6a1f1dSLionel Sambuc NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1158f4a2713aSLionel Sambuc TheCall->getCallee()->getSourceRange(), CallType);
1159f4a2713aSLionel Sambuc
1160f4a2713aSLionel Sambuc return false;
1161f4a2713aSLionel Sambuc }
1162f4a2713aSLionel Sambuc
isValidOrderingForOp(int64_t Ordering,AtomicExpr::AtomicOp Op)1163*0a6a1f1dSLionel Sambuc static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1164*0a6a1f1dSLionel Sambuc if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1165*0a6a1f1dSLionel Sambuc Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1166*0a6a1f1dSLionel Sambuc return false;
1167*0a6a1f1dSLionel Sambuc
1168*0a6a1f1dSLionel Sambuc switch (Op) {
1169*0a6a1f1dSLionel Sambuc case AtomicExpr::AO__c11_atomic_init:
1170*0a6a1f1dSLionel Sambuc llvm_unreachable("There is no ordering argument for an init");
1171*0a6a1f1dSLionel Sambuc
1172*0a6a1f1dSLionel Sambuc case AtomicExpr::AO__c11_atomic_load:
1173*0a6a1f1dSLionel Sambuc case AtomicExpr::AO__atomic_load_n:
1174*0a6a1f1dSLionel Sambuc case AtomicExpr::AO__atomic_load:
1175*0a6a1f1dSLionel Sambuc return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1176*0a6a1f1dSLionel Sambuc Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1177*0a6a1f1dSLionel Sambuc
1178*0a6a1f1dSLionel Sambuc case AtomicExpr::AO__c11_atomic_store:
1179*0a6a1f1dSLionel Sambuc case AtomicExpr::AO__atomic_store:
1180*0a6a1f1dSLionel Sambuc case AtomicExpr::AO__atomic_store_n:
1181*0a6a1f1dSLionel Sambuc return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1182*0a6a1f1dSLionel Sambuc Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1183*0a6a1f1dSLionel Sambuc Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1184*0a6a1f1dSLionel Sambuc
1185*0a6a1f1dSLionel Sambuc default:
1186*0a6a1f1dSLionel Sambuc return true;
1187*0a6a1f1dSLionel Sambuc }
1188*0a6a1f1dSLionel Sambuc }
1189*0a6a1f1dSLionel Sambuc
SemaAtomicOpsOverloaded(ExprResult TheCallResult,AtomicExpr::AtomicOp Op)1190f4a2713aSLionel Sambuc ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1191f4a2713aSLionel Sambuc AtomicExpr::AtomicOp Op) {
1192f4a2713aSLionel Sambuc CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1193f4a2713aSLionel Sambuc DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1194f4a2713aSLionel Sambuc
1195f4a2713aSLionel Sambuc // All these operations take one of the following forms:
1196f4a2713aSLionel Sambuc enum {
1197f4a2713aSLionel Sambuc // C __c11_atomic_init(A *, C)
1198f4a2713aSLionel Sambuc Init,
1199f4a2713aSLionel Sambuc // C __c11_atomic_load(A *, int)
1200f4a2713aSLionel Sambuc Load,
1201f4a2713aSLionel Sambuc // void __atomic_load(A *, CP, int)
1202f4a2713aSLionel Sambuc Copy,
1203f4a2713aSLionel Sambuc // C __c11_atomic_add(A *, M, int)
1204f4a2713aSLionel Sambuc Arithmetic,
1205f4a2713aSLionel Sambuc // C __atomic_exchange_n(A *, CP, int)
1206f4a2713aSLionel Sambuc Xchg,
1207f4a2713aSLionel Sambuc // void __atomic_exchange(A *, C *, CP, int)
1208f4a2713aSLionel Sambuc GNUXchg,
1209f4a2713aSLionel Sambuc // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1210f4a2713aSLionel Sambuc C11CmpXchg,
1211f4a2713aSLionel Sambuc // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1212f4a2713aSLionel Sambuc GNUCmpXchg
1213f4a2713aSLionel Sambuc } Form = Init;
1214f4a2713aSLionel Sambuc const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1215f4a2713aSLionel Sambuc const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1216f4a2713aSLionel Sambuc // where:
1217f4a2713aSLionel Sambuc // C is an appropriate type,
1218f4a2713aSLionel Sambuc // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1219f4a2713aSLionel Sambuc // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1220f4a2713aSLionel Sambuc // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1221f4a2713aSLionel Sambuc // the int parameters are for orderings.
1222f4a2713aSLionel Sambuc
1223f4a2713aSLionel Sambuc assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1224f4a2713aSLionel Sambuc AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1225f4a2713aSLionel Sambuc && "need to update code for modified C11 atomics");
1226f4a2713aSLionel Sambuc bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1227f4a2713aSLionel Sambuc Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1228f4a2713aSLionel Sambuc bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1229f4a2713aSLionel Sambuc Op == AtomicExpr::AO__atomic_store_n ||
1230f4a2713aSLionel Sambuc Op == AtomicExpr::AO__atomic_exchange_n ||
1231f4a2713aSLionel Sambuc Op == AtomicExpr::AO__atomic_compare_exchange_n;
1232f4a2713aSLionel Sambuc bool IsAddSub = false;
1233f4a2713aSLionel Sambuc
1234f4a2713aSLionel Sambuc switch (Op) {
1235f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_init:
1236f4a2713aSLionel Sambuc Form = Init;
1237f4a2713aSLionel Sambuc break;
1238f4a2713aSLionel Sambuc
1239f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_load:
1240f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_load_n:
1241f4a2713aSLionel Sambuc Form = Load;
1242f4a2713aSLionel Sambuc break;
1243f4a2713aSLionel Sambuc
1244f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_store:
1245f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_load:
1246f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_store:
1247f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_store_n:
1248f4a2713aSLionel Sambuc Form = Copy;
1249f4a2713aSLionel Sambuc break;
1250f4a2713aSLionel Sambuc
1251f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_fetch_add:
1252f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_fetch_sub:
1253f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_fetch_add:
1254f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_fetch_sub:
1255f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_add_fetch:
1256f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_sub_fetch:
1257f4a2713aSLionel Sambuc IsAddSub = true;
1258f4a2713aSLionel Sambuc // Fall through.
1259f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_fetch_and:
1260f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_fetch_or:
1261f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_fetch_xor:
1262f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_fetch_and:
1263f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_fetch_or:
1264f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_fetch_xor:
1265f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_fetch_nand:
1266f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_and_fetch:
1267f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_or_fetch:
1268f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_xor_fetch:
1269f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_nand_fetch:
1270f4a2713aSLionel Sambuc Form = Arithmetic;
1271f4a2713aSLionel Sambuc break;
1272f4a2713aSLionel Sambuc
1273f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_exchange:
1274f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_exchange_n:
1275f4a2713aSLionel Sambuc Form = Xchg;
1276f4a2713aSLionel Sambuc break;
1277f4a2713aSLionel Sambuc
1278f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_exchange:
1279f4a2713aSLionel Sambuc Form = GNUXchg;
1280f4a2713aSLionel Sambuc break;
1281f4a2713aSLionel Sambuc
1282f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1283f4a2713aSLionel Sambuc case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1284f4a2713aSLionel Sambuc Form = C11CmpXchg;
1285f4a2713aSLionel Sambuc break;
1286f4a2713aSLionel Sambuc
1287f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_compare_exchange:
1288f4a2713aSLionel Sambuc case AtomicExpr::AO__atomic_compare_exchange_n:
1289f4a2713aSLionel Sambuc Form = GNUCmpXchg;
1290f4a2713aSLionel Sambuc break;
1291f4a2713aSLionel Sambuc }
1292f4a2713aSLionel Sambuc
1293f4a2713aSLionel Sambuc // Check we have the right number of arguments.
1294f4a2713aSLionel Sambuc if (TheCall->getNumArgs() < NumArgs[Form]) {
1295f4a2713aSLionel Sambuc Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1296f4a2713aSLionel Sambuc << 0 << NumArgs[Form] << TheCall->getNumArgs()
1297f4a2713aSLionel Sambuc << TheCall->getCallee()->getSourceRange();
1298f4a2713aSLionel Sambuc return ExprError();
1299f4a2713aSLionel Sambuc } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1300f4a2713aSLionel Sambuc Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1301f4a2713aSLionel Sambuc diag::err_typecheck_call_too_many_args)
1302f4a2713aSLionel Sambuc << 0 << NumArgs[Form] << TheCall->getNumArgs()
1303f4a2713aSLionel Sambuc << TheCall->getCallee()->getSourceRange();
1304f4a2713aSLionel Sambuc return ExprError();
1305f4a2713aSLionel Sambuc }
1306f4a2713aSLionel Sambuc
1307f4a2713aSLionel Sambuc // Inspect the first argument of the atomic operation.
1308f4a2713aSLionel Sambuc Expr *Ptr = TheCall->getArg(0);
1309f4a2713aSLionel Sambuc Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1310f4a2713aSLionel Sambuc const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1311f4a2713aSLionel Sambuc if (!pointerType) {
1312f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1313f4a2713aSLionel Sambuc << Ptr->getType() << Ptr->getSourceRange();
1314f4a2713aSLionel Sambuc return ExprError();
1315f4a2713aSLionel Sambuc }
1316f4a2713aSLionel Sambuc
1317f4a2713aSLionel Sambuc // For a __c11 builtin, this should be a pointer to an _Atomic type.
1318f4a2713aSLionel Sambuc QualType AtomTy = pointerType->getPointeeType(); // 'A'
1319f4a2713aSLionel Sambuc QualType ValType = AtomTy; // 'C'
1320f4a2713aSLionel Sambuc if (IsC11) {
1321f4a2713aSLionel Sambuc if (!AtomTy->isAtomicType()) {
1322f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1323f4a2713aSLionel Sambuc << Ptr->getType() << Ptr->getSourceRange();
1324f4a2713aSLionel Sambuc return ExprError();
1325f4a2713aSLionel Sambuc }
1326f4a2713aSLionel Sambuc if (AtomTy.isConstQualified()) {
1327f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1328f4a2713aSLionel Sambuc << Ptr->getType() << Ptr->getSourceRange();
1329f4a2713aSLionel Sambuc return ExprError();
1330f4a2713aSLionel Sambuc }
1331f4a2713aSLionel Sambuc ValType = AtomTy->getAs<AtomicType>()->getValueType();
1332f4a2713aSLionel Sambuc }
1333f4a2713aSLionel Sambuc
1334f4a2713aSLionel Sambuc // For an arithmetic operation, the implied arithmetic must be well-formed.
1335f4a2713aSLionel Sambuc if (Form == Arithmetic) {
1336f4a2713aSLionel Sambuc // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1337f4a2713aSLionel Sambuc if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1338f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1339f4a2713aSLionel Sambuc << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1340f4a2713aSLionel Sambuc return ExprError();
1341f4a2713aSLionel Sambuc }
1342f4a2713aSLionel Sambuc if (!IsAddSub && !ValType->isIntegerType()) {
1343f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1344f4a2713aSLionel Sambuc << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1345f4a2713aSLionel Sambuc return ExprError();
1346f4a2713aSLionel Sambuc }
1347*0a6a1f1dSLionel Sambuc if (IsC11 && ValType->isPointerType() &&
1348*0a6a1f1dSLionel Sambuc RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1349*0a6a1f1dSLionel Sambuc diag::err_incomplete_type)) {
1350*0a6a1f1dSLionel Sambuc return ExprError();
1351*0a6a1f1dSLionel Sambuc }
1352f4a2713aSLionel Sambuc } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1353f4a2713aSLionel Sambuc // For __atomic_*_n operations, the value type must be a scalar integral or
1354f4a2713aSLionel Sambuc // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1355f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1356f4a2713aSLionel Sambuc << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1357f4a2713aSLionel Sambuc return ExprError();
1358f4a2713aSLionel Sambuc }
1359f4a2713aSLionel Sambuc
1360f4a2713aSLionel Sambuc if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1361f4a2713aSLionel Sambuc !AtomTy->isScalarType()) {
1362f4a2713aSLionel Sambuc // For GNU atomics, require a trivially-copyable type. This is not part of
1363f4a2713aSLionel Sambuc // the GNU atomics specification, but we enforce it for sanity.
1364f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1365f4a2713aSLionel Sambuc << Ptr->getType() << Ptr->getSourceRange();
1366f4a2713aSLionel Sambuc return ExprError();
1367f4a2713aSLionel Sambuc }
1368f4a2713aSLionel Sambuc
1369f4a2713aSLionel Sambuc // FIXME: For any builtin other than a load, the ValType must not be
1370f4a2713aSLionel Sambuc // const-qualified.
1371f4a2713aSLionel Sambuc
1372f4a2713aSLionel Sambuc switch (ValType.getObjCLifetime()) {
1373f4a2713aSLionel Sambuc case Qualifiers::OCL_None:
1374f4a2713aSLionel Sambuc case Qualifiers::OCL_ExplicitNone:
1375f4a2713aSLionel Sambuc // okay
1376f4a2713aSLionel Sambuc break;
1377f4a2713aSLionel Sambuc
1378f4a2713aSLionel Sambuc case Qualifiers::OCL_Weak:
1379f4a2713aSLionel Sambuc case Qualifiers::OCL_Strong:
1380f4a2713aSLionel Sambuc case Qualifiers::OCL_Autoreleasing:
1381f4a2713aSLionel Sambuc // FIXME: Can this happen? By this point, ValType should be known
1382f4a2713aSLionel Sambuc // to be trivially copyable.
1383f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1384f4a2713aSLionel Sambuc << ValType << Ptr->getSourceRange();
1385f4a2713aSLionel Sambuc return ExprError();
1386f4a2713aSLionel Sambuc }
1387f4a2713aSLionel Sambuc
1388f4a2713aSLionel Sambuc QualType ResultType = ValType;
1389f4a2713aSLionel Sambuc if (Form == Copy || Form == GNUXchg || Form == Init)
1390f4a2713aSLionel Sambuc ResultType = Context.VoidTy;
1391f4a2713aSLionel Sambuc else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1392f4a2713aSLionel Sambuc ResultType = Context.BoolTy;
1393f4a2713aSLionel Sambuc
1394f4a2713aSLionel Sambuc // The type of a parameter passed 'by value'. In the GNU atomics, such
1395f4a2713aSLionel Sambuc // arguments are actually passed as pointers.
1396f4a2713aSLionel Sambuc QualType ByValType = ValType; // 'CP'
1397f4a2713aSLionel Sambuc if (!IsC11 && !IsN)
1398f4a2713aSLionel Sambuc ByValType = Ptr->getType();
1399f4a2713aSLionel Sambuc
1400f4a2713aSLionel Sambuc // The first argument --- the pointer --- has a fixed type; we
1401f4a2713aSLionel Sambuc // deduce the types of the rest of the arguments accordingly. Walk
1402f4a2713aSLionel Sambuc // the remaining arguments, converting them to the deduced value type.
1403f4a2713aSLionel Sambuc for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1404f4a2713aSLionel Sambuc QualType Ty;
1405f4a2713aSLionel Sambuc if (i < NumVals[Form] + 1) {
1406f4a2713aSLionel Sambuc switch (i) {
1407f4a2713aSLionel Sambuc case 1:
1408f4a2713aSLionel Sambuc // The second argument is the non-atomic operand. For arithmetic, this
1409f4a2713aSLionel Sambuc // is always passed by value, and for a compare_exchange it is always
1410f4a2713aSLionel Sambuc // passed by address. For the rest, GNU uses by-address and C11 uses
1411f4a2713aSLionel Sambuc // by-value.
1412f4a2713aSLionel Sambuc assert(Form != Load);
1413f4a2713aSLionel Sambuc if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1414f4a2713aSLionel Sambuc Ty = ValType;
1415f4a2713aSLionel Sambuc else if (Form == Copy || Form == Xchg)
1416f4a2713aSLionel Sambuc Ty = ByValType;
1417f4a2713aSLionel Sambuc else if (Form == Arithmetic)
1418f4a2713aSLionel Sambuc Ty = Context.getPointerDiffType();
1419f4a2713aSLionel Sambuc else
1420f4a2713aSLionel Sambuc Ty = Context.getPointerType(ValType.getUnqualifiedType());
1421f4a2713aSLionel Sambuc break;
1422f4a2713aSLionel Sambuc case 2:
1423f4a2713aSLionel Sambuc // The third argument to compare_exchange / GNU exchange is a
1424f4a2713aSLionel Sambuc // (pointer to a) desired value.
1425f4a2713aSLionel Sambuc Ty = ByValType;
1426f4a2713aSLionel Sambuc break;
1427f4a2713aSLionel Sambuc case 3:
1428f4a2713aSLionel Sambuc // The fourth argument to GNU compare_exchange is a 'weak' flag.
1429f4a2713aSLionel Sambuc Ty = Context.BoolTy;
1430f4a2713aSLionel Sambuc break;
1431f4a2713aSLionel Sambuc }
1432f4a2713aSLionel Sambuc } else {
1433f4a2713aSLionel Sambuc // The order(s) are always converted to int.
1434f4a2713aSLionel Sambuc Ty = Context.IntTy;
1435f4a2713aSLionel Sambuc }
1436f4a2713aSLionel Sambuc
1437f4a2713aSLionel Sambuc InitializedEntity Entity =
1438f4a2713aSLionel Sambuc InitializedEntity::InitializeParameter(Context, Ty, false);
1439f4a2713aSLionel Sambuc ExprResult Arg = TheCall->getArg(i);
1440f4a2713aSLionel Sambuc Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1441f4a2713aSLionel Sambuc if (Arg.isInvalid())
1442f4a2713aSLionel Sambuc return true;
1443f4a2713aSLionel Sambuc TheCall->setArg(i, Arg.get());
1444f4a2713aSLionel Sambuc }
1445f4a2713aSLionel Sambuc
1446f4a2713aSLionel Sambuc // Permute the arguments into a 'consistent' order.
1447f4a2713aSLionel Sambuc SmallVector<Expr*, 5> SubExprs;
1448f4a2713aSLionel Sambuc SubExprs.push_back(Ptr);
1449f4a2713aSLionel Sambuc switch (Form) {
1450f4a2713aSLionel Sambuc case Init:
1451f4a2713aSLionel Sambuc // Note, AtomicExpr::getVal1() has a special case for this atomic.
1452f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(1)); // Val1
1453f4a2713aSLionel Sambuc break;
1454f4a2713aSLionel Sambuc case Load:
1455f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(1)); // Order
1456f4a2713aSLionel Sambuc break;
1457f4a2713aSLionel Sambuc case Copy:
1458f4a2713aSLionel Sambuc case Arithmetic:
1459f4a2713aSLionel Sambuc case Xchg:
1460f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(2)); // Order
1461f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(1)); // Val1
1462f4a2713aSLionel Sambuc break;
1463f4a2713aSLionel Sambuc case GNUXchg:
1464f4a2713aSLionel Sambuc // Note, AtomicExpr::getVal2() has a special case for this atomic.
1465f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(3)); // Order
1466f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(1)); // Val1
1467f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(2)); // Val2
1468f4a2713aSLionel Sambuc break;
1469f4a2713aSLionel Sambuc case C11CmpXchg:
1470f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(3)); // Order
1471f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(1)); // Val1
1472f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1473f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(2)); // Val2
1474f4a2713aSLionel Sambuc break;
1475f4a2713aSLionel Sambuc case GNUCmpXchg:
1476f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(4)); // Order
1477f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(1)); // Val1
1478f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1479f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(2)); // Val2
1480f4a2713aSLionel Sambuc SubExprs.push_back(TheCall->getArg(3)); // Weak
1481f4a2713aSLionel Sambuc break;
1482f4a2713aSLionel Sambuc }
1483f4a2713aSLionel Sambuc
1484*0a6a1f1dSLionel Sambuc if (SubExprs.size() >= 2 && Form != Init) {
1485*0a6a1f1dSLionel Sambuc llvm::APSInt Result(32);
1486*0a6a1f1dSLionel Sambuc if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1487*0a6a1f1dSLionel Sambuc !isValidOrderingForOp(Result.getSExtValue(), Op))
1488*0a6a1f1dSLionel Sambuc Diag(SubExprs[1]->getLocStart(),
1489*0a6a1f1dSLionel Sambuc diag::warn_atomic_op_has_invalid_memory_order)
1490*0a6a1f1dSLionel Sambuc << SubExprs[1]->getSourceRange();
1491*0a6a1f1dSLionel Sambuc }
1492*0a6a1f1dSLionel Sambuc
1493f4a2713aSLionel Sambuc AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1494f4a2713aSLionel Sambuc SubExprs, ResultType, Op,
1495f4a2713aSLionel Sambuc TheCall->getRParenLoc());
1496f4a2713aSLionel Sambuc
1497f4a2713aSLionel Sambuc if ((Op == AtomicExpr::AO__c11_atomic_load ||
1498f4a2713aSLionel Sambuc (Op == AtomicExpr::AO__c11_atomic_store)) &&
1499f4a2713aSLionel Sambuc Context.AtomicUsesUnsupportedLibcall(AE))
1500f4a2713aSLionel Sambuc Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1501f4a2713aSLionel Sambuc ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1502f4a2713aSLionel Sambuc
1503*0a6a1f1dSLionel Sambuc return AE;
1504f4a2713aSLionel Sambuc }
1505f4a2713aSLionel Sambuc
1506f4a2713aSLionel Sambuc
1507f4a2713aSLionel Sambuc /// checkBuiltinArgument - Given a call to a builtin function, perform
1508f4a2713aSLionel Sambuc /// normal type-checking on the given argument, updating the call in
1509f4a2713aSLionel Sambuc /// place. This is useful when a builtin function requires custom
1510f4a2713aSLionel Sambuc /// type-checking for some of its arguments but not necessarily all of
1511f4a2713aSLionel Sambuc /// them.
1512f4a2713aSLionel Sambuc ///
1513f4a2713aSLionel Sambuc /// Returns true on error.
checkBuiltinArgument(Sema & S,CallExpr * E,unsigned ArgIndex)1514f4a2713aSLionel Sambuc static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1515f4a2713aSLionel Sambuc FunctionDecl *Fn = E->getDirectCallee();
1516f4a2713aSLionel Sambuc assert(Fn && "builtin call without direct callee!");
1517f4a2713aSLionel Sambuc
1518f4a2713aSLionel Sambuc ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1519f4a2713aSLionel Sambuc InitializedEntity Entity =
1520f4a2713aSLionel Sambuc InitializedEntity::InitializeParameter(S.Context, Param);
1521f4a2713aSLionel Sambuc
1522f4a2713aSLionel Sambuc ExprResult Arg = E->getArg(0);
1523f4a2713aSLionel Sambuc Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1524f4a2713aSLionel Sambuc if (Arg.isInvalid())
1525f4a2713aSLionel Sambuc return true;
1526f4a2713aSLionel Sambuc
1527*0a6a1f1dSLionel Sambuc E->setArg(ArgIndex, Arg.get());
1528f4a2713aSLionel Sambuc return false;
1529f4a2713aSLionel Sambuc }
1530f4a2713aSLionel Sambuc
1531f4a2713aSLionel Sambuc /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1532f4a2713aSLionel Sambuc /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1533f4a2713aSLionel Sambuc /// type of its first argument. The main ActOnCallExpr routines have already
1534f4a2713aSLionel Sambuc /// promoted the types of arguments because all of these calls are prototyped as
1535f4a2713aSLionel Sambuc /// void(...).
1536f4a2713aSLionel Sambuc ///
1537f4a2713aSLionel Sambuc /// This function goes through and does final semantic checking for these
1538f4a2713aSLionel Sambuc /// builtins,
1539f4a2713aSLionel Sambuc ExprResult
SemaBuiltinAtomicOverloaded(ExprResult TheCallResult)1540f4a2713aSLionel Sambuc Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1541f4a2713aSLionel Sambuc CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1542f4a2713aSLionel Sambuc DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1543f4a2713aSLionel Sambuc FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1544f4a2713aSLionel Sambuc
1545f4a2713aSLionel Sambuc // Ensure that we have at least one argument to do type inference from.
1546f4a2713aSLionel Sambuc if (TheCall->getNumArgs() < 1) {
1547f4a2713aSLionel Sambuc Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1548f4a2713aSLionel Sambuc << 0 << 1 << TheCall->getNumArgs()
1549f4a2713aSLionel Sambuc << TheCall->getCallee()->getSourceRange();
1550f4a2713aSLionel Sambuc return ExprError();
1551f4a2713aSLionel Sambuc }
1552f4a2713aSLionel Sambuc
1553f4a2713aSLionel Sambuc // Inspect the first argument of the atomic builtin. This should always be
1554f4a2713aSLionel Sambuc // a pointer type, whose element is an integral scalar or pointer type.
1555f4a2713aSLionel Sambuc // Because it is a pointer type, we don't have to worry about any implicit
1556f4a2713aSLionel Sambuc // casts here.
1557f4a2713aSLionel Sambuc // FIXME: We don't allow floating point scalars as input.
1558f4a2713aSLionel Sambuc Expr *FirstArg = TheCall->getArg(0);
1559f4a2713aSLionel Sambuc ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1560f4a2713aSLionel Sambuc if (FirstArgResult.isInvalid())
1561f4a2713aSLionel Sambuc return ExprError();
1562*0a6a1f1dSLionel Sambuc FirstArg = FirstArgResult.get();
1563f4a2713aSLionel Sambuc TheCall->setArg(0, FirstArg);
1564f4a2713aSLionel Sambuc
1565f4a2713aSLionel Sambuc const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1566f4a2713aSLionel Sambuc if (!pointerType) {
1567f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1568f4a2713aSLionel Sambuc << FirstArg->getType() << FirstArg->getSourceRange();
1569f4a2713aSLionel Sambuc return ExprError();
1570f4a2713aSLionel Sambuc }
1571f4a2713aSLionel Sambuc
1572f4a2713aSLionel Sambuc QualType ValType = pointerType->getPointeeType();
1573f4a2713aSLionel Sambuc if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1574f4a2713aSLionel Sambuc !ValType->isBlockPointerType()) {
1575f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1576f4a2713aSLionel Sambuc << FirstArg->getType() << FirstArg->getSourceRange();
1577f4a2713aSLionel Sambuc return ExprError();
1578f4a2713aSLionel Sambuc }
1579f4a2713aSLionel Sambuc
1580f4a2713aSLionel Sambuc switch (ValType.getObjCLifetime()) {
1581f4a2713aSLionel Sambuc case Qualifiers::OCL_None:
1582f4a2713aSLionel Sambuc case Qualifiers::OCL_ExplicitNone:
1583f4a2713aSLionel Sambuc // okay
1584f4a2713aSLionel Sambuc break;
1585f4a2713aSLionel Sambuc
1586f4a2713aSLionel Sambuc case Qualifiers::OCL_Weak:
1587f4a2713aSLionel Sambuc case Qualifiers::OCL_Strong:
1588f4a2713aSLionel Sambuc case Qualifiers::OCL_Autoreleasing:
1589f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1590f4a2713aSLionel Sambuc << ValType << FirstArg->getSourceRange();
1591f4a2713aSLionel Sambuc return ExprError();
1592f4a2713aSLionel Sambuc }
1593f4a2713aSLionel Sambuc
1594f4a2713aSLionel Sambuc // Strip any qualifiers off ValType.
1595f4a2713aSLionel Sambuc ValType = ValType.getUnqualifiedType();
1596f4a2713aSLionel Sambuc
1597f4a2713aSLionel Sambuc // The majority of builtins return a value, but a few have special return
1598f4a2713aSLionel Sambuc // types, so allow them to override appropriately below.
1599f4a2713aSLionel Sambuc QualType ResultType = ValType;
1600f4a2713aSLionel Sambuc
1601f4a2713aSLionel Sambuc // We need to figure out which concrete builtin this maps onto. For example,
1602f4a2713aSLionel Sambuc // __sync_fetch_and_add with a 2 byte object turns into
1603f4a2713aSLionel Sambuc // __sync_fetch_and_add_2.
1604f4a2713aSLionel Sambuc #define BUILTIN_ROW(x) \
1605f4a2713aSLionel Sambuc { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1606f4a2713aSLionel Sambuc Builtin::BI##x##_8, Builtin::BI##x##_16 }
1607f4a2713aSLionel Sambuc
1608f4a2713aSLionel Sambuc static const unsigned BuiltinIndices[][5] = {
1609f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_fetch_and_add),
1610f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_fetch_and_sub),
1611f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_fetch_and_or),
1612f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_fetch_and_and),
1613f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_fetch_and_xor),
1614*0a6a1f1dSLionel Sambuc BUILTIN_ROW(__sync_fetch_and_nand),
1615f4a2713aSLionel Sambuc
1616f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_add_and_fetch),
1617f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_sub_and_fetch),
1618f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_and_and_fetch),
1619f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_or_and_fetch),
1620f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_xor_and_fetch),
1621*0a6a1f1dSLionel Sambuc BUILTIN_ROW(__sync_nand_and_fetch),
1622f4a2713aSLionel Sambuc
1623f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_val_compare_and_swap),
1624f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_bool_compare_and_swap),
1625f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_lock_test_and_set),
1626f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_lock_release),
1627f4a2713aSLionel Sambuc BUILTIN_ROW(__sync_swap)
1628f4a2713aSLionel Sambuc };
1629f4a2713aSLionel Sambuc #undef BUILTIN_ROW
1630f4a2713aSLionel Sambuc
1631f4a2713aSLionel Sambuc // Determine the index of the size.
1632f4a2713aSLionel Sambuc unsigned SizeIndex;
1633f4a2713aSLionel Sambuc switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1634f4a2713aSLionel Sambuc case 1: SizeIndex = 0; break;
1635f4a2713aSLionel Sambuc case 2: SizeIndex = 1; break;
1636f4a2713aSLionel Sambuc case 4: SizeIndex = 2; break;
1637f4a2713aSLionel Sambuc case 8: SizeIndex = 3; break;
1638f4a2713aSLionel Sambuc case 16: SizeIndex = 4; break;
1639f4a2713aSLionel Sambuc default:
1640f4a2713aSLionel Sambuc Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1641f4a2713aSLionel Sambuc << FirstArg->getType() << FirstArg->getSourceRange();
1642f4a2713aSLionel Sambuc return ExprError();
1643f4a2713aSLionel Sambuc }
1644f4a2713aSLionel Sambuc
1645f4a2713aSLionel Sambuc // Each of these builtins has one pointer argument, followed by some number of
1646f4a2713aSLionel Sambuc // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1647f4a2713aSLionel Sambuc // that we ignore. Find out which row of BuiltinIndices to read from as well
1648f4a2713aSLionel Sambuc // as the number of fixed args.
1649f4a2713aSLionel Sambuc unsigned BuiltinID = FDecl->getBuiltinID();
1650f4a2713aSLionel Sambuc unsigned BuiltinIndex, NumFixed = 1;
1651*0a6a1f1dSLionel Sambuc bool WarnAboutSemanticsChange = false;
1652f4a2713aSLionel Sambuc switch (BuiltinID) {
1653f4a2713aSLionel Sambuc default: llvm_unreachable("Unknown overloaded atomic builtin!");
1654f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add:
1655f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add_1:
1656f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add_2:
1657f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add_4:
1658f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add_8:
1659f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_add_16:
1660f4a2713aSLionel Sambuc BuiltinIndex = 0;
1661f4a2713aSLionel Sambuc break;
1662f4a2713aSLionel Sambuc
1663f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub:
1664f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub_1:
1665f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub_2:
1666f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub_4:
1667f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub_8:
1668f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_sub_16:
1669f4a2713aSLionel Sambuc BuiltinIndex = 1;
1670f4a2713aSLionel Sambuc break;
1671f4a2713aSLionel Sambuc
1672f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or:
1673f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or_1:
1674f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or_2:
1675f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or_4:
1676f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or_8:
1677f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_or_16:
1678f4a2713aSLionel Sambuc BuiltinIndex = 2;
1679f4a2713aSLionel Sambuc break;
1680f4a2713aSLionel Sambuc
1681f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and:
1682f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and_1:
1683f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and_2:
1684f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and_4:
1685f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and_8:
1686f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_and_16:
1687f4a2713aSLionel Sambuc BuiltinIndex = 3;
1688f4a2713aSLionel Sambuc break;
1689f4a2713aSLionel Sambuc
1690f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor:
1691f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor_1:
1692f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor_2:
1693f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor_4:
1694f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor_8:
1695f4a2713aSLionel Sambuc case Builtin::BI__sync_fetch_and_xor_16:
1696f4a2713aSLionel Sambuc BuiltinIndex = 4;
1697f4a2713aSLionel Sambuc break;
1698f4a2713aSLionel Sambuc
1699*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand:
1700*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand_1:
1701*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand_2:
1702*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand_4:
1703*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand_8:
1704*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_fetch_and_nand_16:
1705*0a6a1f1dSLionel Sambuc BuiltinIndex = 5;
1706*0a6a1f1dSLionel Sambuc WarnAboutSemanticsChange = true;
1707*0a6a1f1dSLionel Sambuc break;
1708*0a6a1f1dSLionel Sambuc
1709f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch:
1710f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch_1:
1711f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch_2:
1712f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch_4:
1713f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch_8:
1714f4a2713aSLionel Sambuc case Builtin::BI__sync_add_and_fetch_16:
1715*0a6a1f1dSLionel Sambuc BuiltinIndex = 6;
1716f4a2713aSLionel Sambuc break;
1717f4a2713aSLionel Sambuc
1718f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch:
1719f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch_1:
1720f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch_2:
1721f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch_4:
1722f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch_8:
1723f4a2713aSLionel Sambuc case Builtin::BI__sync_sub_and_fetch_16:
1724*0a6a1f1dSLionel Sambuc BuiltinIndex = 7;
1725f4a2713aSLionel Sambuc break;
1726f4a2713aSLionel Sambuc
1727f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch:
1728f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch_1:
1729f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch_2:
1730f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch_4:
1731f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch_8:
1732f4a2713aSLionel Sambuc case Builtin::BI__sync_and_and_fetch_16:
1733*0a6a1f1dSLionel Sambuc BuiltinIndex = 8;
1734f4a2713aSLionel Sambuc break;
1735f4a2713aSLionel Sambuc
1736f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch:
1737f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch_1:
1738f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch_2:
1739f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch_4:
1740f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch_8:
1741f4a2713aSLionel Sambuc case Builtin::BI__sync_or_and_fetch_16:
1742*0a6a1f1dSLionel Sambuc BuiltinIndex = 9;
1743f4a2713aSLionel Sambuc break;
1744f4a2713aSLionel Sambuc
1745f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch:
1746f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch_1:
1747f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch_2:
1748f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch_4:
1749f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch_8:
1750f4a2713aSLionel Sambuc case Builtin::BI__sync_xor_and_fetch_16:
1751*0a6a1f1dSLionel Sambuc BuiltinIndex = 10;
1752*0a6a1f1dSLionel Sambuc break;
1753*0a6a1f1dSLionel Sambuc
1754*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch:
1755*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch_1:
1756*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch_2:
1757*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch_4:
1758*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch_8:
1759*0a6a1f1dSLionel Sambuc case Builtin::BI__sync_nand_and_fetch_16:
1760*0a6a1f1dSLionel Sambuc BuiltinIndex = 11;
1761*0a6a1f1dSLionel Sambuc WarnAboutSemanticsChange = true;
1762f4a2713aSLionel Sambuc break;
1763f4a2713aSLionel Sambuc
1764f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap:
1765f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap_1:
1766f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap_2:
1767f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap_4:
1768f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap_8:
1769f4a2713aSLionel Sambuc case Builtin::BI__sync_val_compare_and_swap_16:
1770*0a6a1f1dSLionel Sambuc BuiltinIndex = 12;
1771f4a2713aSLionel Sambuc NumFixed = 2;
1772f4a2713aSLionel Sambuc break;
1773f4a2713aSLionel Sambuc
1774f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap:
1775f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap_1:
1776f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap_2:
1777f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap_4:
1778f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap_8:
1779f4a2713aSLionel Sambuc case Builtin::BI__sync_bool_compare_and_swap_16:
1780*0a6a1f1dSLionel Sambuc BuiltinIndex = 13;
1781f4a2713aSLionel Sambuc NumFixed = 2;
1782f4a2713aSLionel Sambuc ResultType = Context.BoolTy;
1783f4a2713aSLionel Sambuc break;
1784f4a2713aSLionel Sambuc
1785f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set:
1786f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set_1:
1787f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set_2:
1788f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set_4:
1789f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set_8:
1790f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_test_and_set_16:
1791*0a6a1f1dSLionel Sambuc BuiltinIndex = 14;
1792f4a2713aSLionel Sambuc break;
1793f4a2713aSLionel Sambuc
1794f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release:
1795f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release_1:
1796f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release_2:
1797f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release_4:
1798f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release_8:
1799f4a2713aSLionel Sambuc case Builtin::BI__sync_lock_release_16:
1800*0a6a1f1dSLionel Sambuc BuiltinIndex = 15;
1801f4a2713aSLionel Sambuc NumFixed = 0;
1802f4a2713aSLionel Sambuc ResultType = Context.VoidTy;
1803f4a2713aSLionel Sambuc break;
1804f4a2713aSLionel Sambuc
1805f4a2713aSLionel Sambuc case Builtin::BI__sync_swap:
1806f4a2713aSLionel Sambuc case Builtin::BI__sync_swap_1:
1807f4a2713aSLionel Sambuc case Builtin::BI__sync_swap_2:
1808f4a2713aSLionel Sambuc case Builtin::BI__sync_swap_4:
1809f4a2713aSLionel Sambuc case Builtin::BI__sync_swap_8:
1810f4a2713aSLionel Sambuc case Builtin::BI__sync_swap_16:
1811*0a6a1f1dSLionel Sambuc BuiltinIndex = 16;
1812f4a2713aSLionel Sambuc break;
1813f4a2713aSLionel Sambuc }
1814f4a2713aSLionel Sambuc
1815f4a2713aSLionel Sambuc // Now that we know how many fixed arguments we expect, first check that we
1816f4a2713aSLionel Sambuc // have at least that many.
1817f4a2713aSLionel Sambuc if (TheCall->getNumArgs() < 1+NumFixed) {
1818f4a2713aSLionel Sambuc Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1819f4a2713aSLionel Sambuc << 0 << 1+NumFixed << TheCall->getNumArgs()
1820f4a2713aSLionel Sambuc << TheCall->getCallee()->getSourceRange();
1821f4a2713aSLionel Sambuc return ExprError();
1822f4a2713aSLionel Sambuc }
1823f4a2713aSLionel Sambuc
1824*0a6a1f1dSLionel Sambuc if (WarnAboutSemanticsChange) {
1825*0a6a1f1dSLionel Sambuc Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1826*0a6a1f1dSLionel Sambuc << TheCall->getCallee()->getSourceRange();
1827*0a6a1f1dSLionel Sambuc }
1828*0a6a1f1dSLionel Sambuc
1829f4a2713aSLionel Sambuc // Get the decl for the concrete builtin from this, we can tell what the
1830f4a2713aSLionel Sambuc // concrete integer type we should convert to is.
1831f4a2713aSLionel Sambuc unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1832f4a2713aSLionel Sambuc const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1833f4a2713aSLionel Sambuc FunctionDecl *NewBuiltinDecl;
1834f4a2713aSLionel Sambuc if (NewBuiltinID == BuiltinID)
1835f4a2713aSLionel Sambuc NewBuiltinDecl = FDecl;
1836f4a2713aSLionel Sambuc else {
1837f4a2713aSLionel Sambuc // Perform builtin lookup to avoid redeclaring it.
1838f4a2713aSLionel Sambuc DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1839f4a2713aSLionel Sambuc LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1840f4a2713aSLionel Sambuc LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1841f4a2713aSLionel Sambuc assert(Res.getFoundDecl());
1842f4a2713aSLionel Sambuc NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1843*0a6a1f1dSLionel Sambuc if (!NewBuiltinDecl)
1844f4a2713aSLionel Sambuc return ExprError();
1845f4a2713aSLionel Sambuc }
1846f4a2713aSLionel Sambuc
1847f4a2713aSLionel Sambuc // The first argument --- the pointer --- has a fixed type; we
1848f4a2713aSLionel Sambuc // deduce the types of the rest of the arguments accordingly. Walk
1849f4a2713aSLionel Sambuc // the remaining arguments, converting them to the deduced value type.
1850f4a2713aSLionel Sambuc for (unsigned i = 0; i != NumFixed; ++i) {
1851f4a2713aSLionel Sambuc ExprResult Arg = TheCall->getArg(i+1);
1852f4a2713aSLionel Sambuc
1853f4a2713aSLionel Sambuc // GCC does an implicit conversion to the pointer or integer ValType. This
1854f4a2713aSLionel Sambuc // can fail in some cases (1i -> int**), check for this error case now.
1855f4a2713aSLionel Sambuc // Initialize the argument.
1856f4a2713aSLionel Sambuc InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1857f4a2713aSLionel Sambuc ValType, /*consume*/ false);
1858f4a2713aSLionel Sambuc Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1859f4a2713aSLionel Sambuc if (Arg.isInvalid())
1860f4a2713aSLionel Sambuc return ExprError();
1861f4a2713aSLionel Sambuc
1862f4a2713aSLionel Sambuc // Okay, we have something that *can* be converted to the right type. Check
1863f4a2713aSLionel Sambuc // to see if there is a potentially weird extension going on here. This can
1864f4a2713aSLionel Sambuc // happen when you do an atomic operation on something like an char* and
1865f4a2713aSLionel Sambuc // pass in 42. The 42 gets converted to char. This is even more strange
1866f4a2713aSLionel Sambuc // for things like 45.123 -> char, etc.
1867f4a2713aSLionel Sambuc // FIXME: Do this check.
1868*0a6a1f1dSLionel Sambuc TheCall->setArg(i+1, Arg.get());
1869f4a2713aSLionel Sambuc }
1870f4a2713aSLionel Sambuc
1871f4a2713aSLionel Sambuc ASTContext& Context = this->getASTContext();
1872f4a2713aSLionel Sambuc
1873f4a2713aSLionel Sambuc // Create a new DeclRefExpr to refer to the new decl.
1874f4a2713aSLionel Sambuc DeclRefExpr* NewDRE = DeclRefExpr::Create(
1875f4a2713aSLionel Sambuc Context,
1876f4a2713aSLionel Sambuc DRE->getQualifierLoc(),
1877f4a2713aSLionel Sambuc SourceLocation(),
1878f4a2713aSLionel Sambuc NewBuiltinDecl,
1879f4a2713aSLionel Sambuc /*enclosing*/ false,
1880f4a2713aSLionel Sambuc DRE->getLocation(),
1881f4a2713aSLionel Sambuc Context.BuiltinFnTy,
1882f4a2713aSLionel Sambuc DRE->getValueKind());
1883f4a2713aSLionel Sambuc
1884f4a2713aSLionel Sambuc // Set the callee in the CallExpr.
1885f4a2713aSLionel Sambuc // FIXME: This loses syntactic information.
1886f4a2713aSLionel Sambuc QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1887f4a2713aSLionel Sambuc ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1888f4a2713aSLionel Sambuc CK_BuiltinFnToFnPtr);
1889*0a6a1f1dSLionel Sambuc TheCall->setCallee(PromotedCall.get());
1890f4a2713aSLionel Sambuc
1891f4a2713aSLionel Sambuc // Change the result type of the call to match the original value type. This
1892f4a2713aSLionel Sambuc // is arbitrary, but the codegen for these builtins ins design to handle it
1893f4a2713aSLionel Sambuc // gracefully.
1894f4a2713aSLionel Sambuc TheCall->setType(ResultType);
1895f4a2713aSLionel Sambuc
1896f4a2713aSLionel Sambuc return TheCallResult;
1897f4a2713aSLionel Sambuc }
1898f4a2713aSLionel Sambuc
1899f4a2713aSLionel Sambuc /// CheckObjCString - Checks that the argument to the builtin
1900f4a2713aSLionel Sambuc /// CFString constructor is correct
1901f4a2713aSLionel Sambuc /// Note: It might also make sense to do the UTF-16 conversion here (would
1902f4a2713aSLionel Sambuc /// simplify the backend).
CheckObjCString(Expr * Arg)1903f4a2713aSLionel Sambuc bool Sema::CheckObjCString(Expr *Arg) {
1904f4a2713aSLionel Sambuc Arg = Arg->IgnoreParenCasts();
1905f4a2713aSLionel Sambuc StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1906f4a2713aSLionel Sambuc
1907f4a2713aSLionel Sambuc if (!Literal || !Literal->isAscii()) {
1908f4a2713aSLionel Sambuc Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1909f4a2713aSLionel Sambuc << Arg->getSourceRange();
1910f4a2713aSLionel Sambuc return true;
1911f4a2713aSLionel Sambuc }
1912f4a2713aSLionel Sambuc
1913f4a2713aSLionel Sambuc if (Literal->containsNonAsciiOrNull()) {
1914f4a2713aSLionel Sambuc StringRef String = Literal->getString();
1915f4a2713aSLionel Sambuc unsigned NumBytes = String.size();
1916f4a2713aSLionel Sambuc SmallVector<UTF16, 128> ToBuf(NumBytes);
1917f4a2713aSLionel Sambuc const UTF8 *FromPtr = (const UTF8 *)String.data();
1918f4a2713aSLionel Sambuc UTF16 *ToPtr = &ToBuf[0];
1919f4a2713aSLionel Sambuc
1920f4a2713aSLionel Sambuc ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1921f4a2713aSLionel Sambuc &ToPtr, ToPtr + NumBytes,
1922f4a2713aSLionel Sambuc strictConversion);
1923f4a2713aSLionel Sambuc // Check for conversion failure.
1924f4a2713aSLionel Sambuc if (Result != conversionOK)
1925f4a2713aSLionel Sambuc Diag(Arg->getLocStart(),
1926f4a2713aSLionel Sambuc diag::warn_cfstring_truncated) << Arg->getSourceRange();
1927f4a2713aSLionel Sambuc }
1928f4a2713aSLionel Sambuc return false;
1929f4a2713aSLionel Sambuc }
1930f4a2713aSLionel Sambuc
1931f4a2713aSLionel Sambuc /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1932f4a2713aSLionel Sambuc /// Emit an error and return true on failure, return false on success.
SemaBuiltinVAStart(CallExpr * TheCall)1933f4a2713aSLionel Sambuc bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1934f4a2713aSLionel Sambuc Expr *Fn = TheCall->getCallee();
1935f4a2713aSLionel Sambuc if (TheCall->getNumArgs() > 2) {
1936f4a2713aSLionel Sambuc Diag(TheCall->getArg(2)->getLocStart(),
1937f4a2713aSLionel Sambuc diag::err_typecheck_call_too_many_args)
1938f4a2713aSLionel Sambuc << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1939f4a2713aSLionel Sambuc << Fn->getSourceRange()
1940f4a2713aSLionel Sambuc << SourceRange(TheCall->getArg(2)->getLocStart(),
1941f4a2713aSLionel Sambuc (*(TheCall->arg_end()-1))->getLocEnd());
1942f4a2713aSLionel Sambuc return true;
1943f4a2713aSLionel Sambuc }
1944f4a2713aSLionel Sambuc
1945f4a2713aSLionel Sambuc if (TheCall->getNumArgs() < 2) {
1946f4a2713aSLionel Sambuc return Diag(TheCall->getLocEnd(),
1947f4a2713aSLionel Sambuc diag::err_typecheck_call_too_few_args_at_least)
1948f4a2713aSLionel Sambuc << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1949f4a2713aSLionel Sambuc }
1950f4a2713aSLionel Sambuc
1951f4a2713aSLionel Sambuc // Type-check the first argument normally.
1952f4a2713aSLionel Sambuc if (checkBuiltinArgument(*this, TheCall, 0))
1953f4a2713aSLionel Sambuc return true;
1954f4a2713aSLionel Sambuc
1955f4a2713aSLionel Sambuc // Determine whether the current function is variadic or not.
1956f4a2713aSLionel Sambuc BlockScopeInfo *CurBlock = getCurBlock();
1957f4a2713aSLionel Sambuc bool isVariadic;
1958f4a2713aSLionel Sambuc if (CurBlock)
1959f4a2713aSLionel Sambuc isVariadic = CurBlock->TheDecl->isVariadic();
1960f4a2713aSLionel Sambuc else if (FunctionDecl *FD = getCurFunctionDecl())
1961f4a2713aSLionel Sambuc isVariadic = FD->isVariadic();
1962f4a2713aSLionel Sambuc else
1963f4a2713aSLionel Sambuc isVariadic = getCurMethodDecl()->isVariadic();
1964f4a2713aSLionel Sambuc
1965f4a2713aSLionel Sambuc if (!isVariadic) {
1966f4a2713aSLionel Sambuc Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1967f4a2713aSLionel Sambuc return true;
1968f4a2713aSLionel Sambuc }
1969f4a2713aSLionel Sambuc
1970f4a2713aSLionel Sambuc // Verify that the second argument to the builtin is the last argument of the
1971f4a2713aSLionel Sambuc // current function or method.
1972f4a2713aSLionel Sambuc bool SecondArgIsLastNamedArgument = false;
1973f4a2713aSLionel Sambuc const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1974f4a2713aSLionel Sambuc
1975f4a2713aSLionel Sambuc // These are valid if SecondArgIsLastNamedArgument is false after the next
1976f4a2713aSLionel Sambuc // block.
1977f4a2713aSLionel Sambuc QualType Type;
1978f4a2713aSLionel Sambuc SourceLocation ParamLoc;
1979f4a2713aSLionel Sambuc
1980f4a2713aSLionel Sambuc if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1981f4a2713aSLionel Sambuc if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1982f4a2713aSLionel Sambuc // FIXME: This isn't correct for methods (results in bogus warning).
1983f4a2713aSLionel Sambuc // Get the last formal in the current function.
1984f4a2713aSLionel Sambuc const ParmVarDecl *LastArg;
1985f4a2713aSLionel Sambuc if (CurBlock)
1986f4a2713aSLionel Sambuc LastArg = *(CurBlock->TheDecl->param_end()-1);
1987f4a2713aSLionel Sambuc else if (FunctionDecl *FD = getCurFunctionDecl())
1988f4a2713aSLionel Sambuc LastArg = *(FD->param_end()-1);
1989f4a2713aSLionel Sambuc else
1990f4a2713aSLionel Sambuc LastArg = *(getCurMethodDecl()->param_end()-1);
1991f4a2713aSLionel Sambuc SecondArgIsLastNamedArgument = PV == LastArg;
1992f4a2713aSLionel Sambuc
1993f4a2713aSLionel Sambuc Type = PV->getType();
1994f4a2713aSLionel Sambuc ParamLoc = PV->getLocation();
1995f4a2713aSLionel Sambuc }
1996f4a2713aSLionel Sambuc }
1997f4a2713aSLionel Sambuc
1998f4a2713aSLionel Sambuc if (!SecondArgIsLastNamedArgument)
1999f4a2713aSLionel Sambuc Diag(TheCall->getArg(1)->getLocStart(),
2000f4a2713aSLionel Sambuc diag::warn_second_parameter_of_va_start_not_last_named_argument);
2001f4a2713aSLionel Sambuc else if (Type->isReferenceType()) {
2002f4a2713aSLionel Sambuc Diag(Arg->getLocStart(),
2003f4a2713aSLionel Sambuc diag::warn_va_start_of_reference_type_is_undefined);
2004f4a2713aSLionel Sambuc Diag(ParamLoc, diag::note_parameter_type) << Type;
2005f4a2713aSLionel Sambuc }
2006f4a2713aSLionel Sambuc
2007f4a2713aSLionel Sambuc TheCall->setType(Context.VoidTy);
2008f4a2713aSLionel Sambuc return false;
2009f4a2713aSLionel Sambuc }
2010f4a2713aSLionel Sambuc
SemaBuiltinVAStartARM(CallExpr * Call)2011*0a6a1f1dSLionel Sambuc bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2012*0a6a1f1dSLionel Sambuc // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2013*0a6a1f1dSLionel Sambuc // const char *named_addr);
2014*0a6a1f1dSLionel Sambuc
2015*0a6a1f1dSLionel Sambuc Expr *Func = Call->getCallee();
2016*0a6a1f1dSLionel Sambuc
2017*0a6a1f1dSLionel Sambuc if (Call->getNumArgs() < 3)
2018*0a6a1f1dSLionel Sambuc return Diag(Call->getLocEnd(),
2019*0a6a1f1dSLionel Sambuc diag::err_typecheck_call_too_few_args_at_least)
2020*0a6a1f1dSLionel Sambuc << 0 /*function call*/ << 3 << Call->getNumArgs();
2021*0a6a1f1dSLionel Sambuc
2022*0a6a1f1dSLionel Sambuc // Determine whether the current function is variadic or not.
2023*0a6a1f1dSLionel Sambuc bool IsVariadic;
2024*0a6a1f1dSLionel Sambuc if (BlockScopeInfo *CurBlock = getCurBlock())
2025*0a6a1f1dSLionel Sambuc IsVariadic = CurBlock->TheDecl->isVariadic();
2026*0a6a1f1dSLionel Sambuc else if (FunctionDecl *FD = getCurFunctionDecl())
2027*0a6a1f1dSLionel Sambuc IsVariadic = FD->isVariadic();
2028*0a6a1f1dSLionel Sambuc else if (ObjCMethodDecl *MD = getCurMethodDecl())
2029*0a6a1f1dSLionel Sambuc IsVariadic = MD->isVariadic();
2030*0a6a1f1dSLionel Sambuc else
2031*0a6a1f1dSLionel Sambuc llvm_unreachable("unexpected statement type");
2032*0a6a1f1dSLionel Sambuc
2033*0a6a1f1dSLionel Sambuc if (!IsVariadic) {
2034*0a6a1f1dSLionel Sambuc Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2035*0a6a1f1dSLionel Sambuc return true;
2036*0a6a1f1dSLionel Sambuc }
2037*0a6a1f1dSLionel Sambuc
2038*0a6a1f1dSLionel Sambuc // Type-check the first argument normally.
2039*0a6a1f1dSLionel Sambuc if (checkBuiltinArgument(*this, Call, 0))
2040*0a6a1f1dSLionel Sambuc return true;
2041*0a6a1f1dSLionel Sambuc
2042*0a6a1f1dSLionel Sambuc static const struct {
2043*0a6a1f1dSLionel Sambuc unsigned ArgNo;
2044*0a6a1f1dSLionel Sambuc QualType Type;
2045*0a6a1f1dSLionel Sambuc } ArgumentTypes[] = {
2046*0a6a1f1dSLionel Sambuc { 1, Context.getPointerType(Context.CharTy.withConst()) },
2047*0a6a1f1dSLionel Sambuc { 2, Context.getSizeType() },
2048*0a6a1f1dSLionel Sambuc };
2049*0a6a1f1dSLionel Sambuc
2050*0a6a1f1dSLionel Sambuc for (const auto &AT : ArgumentTypes) {
2051*0a6a1f1dSLionel Sambuc const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2052*0a6a1f1dSLionel Sambuc if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2053*0a6a1f1dSLionel Sambuc continue;
2054*0a6a1f1dSLionel Sambuc Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2055*0a6a1f1dSLionel Sambuc << Arg->getType() << AT.Type << 1 /* different class */
2056*0a6a1f1dSLionel Sambuc << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2057*0a6a1f1dSLionel Sambuc << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2058*0a6a1f1dSLionel Sambuc }
2059*0a6a1f1dSLionel Sambuc
2060*0a6a1f1dSLionel Sambuc return false;
2061*0a6a1f1dSLionel Sambuc }
2062*0a6a1f1dSLionel Sambuc
2063f4a2713aSLionel Sambuc /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2064f4a2713aSLionel Sambuc /// friends. This is declared to take (...), so we have to check everything.
SemaBuiltinUnorderedCompare(CallExpr * TheCall)2065f4a2713aSLionel Sambuc bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2066f4a2713aSLionel Sambuc if (TheCall->getNumArgs() < 2)
2067f4a2713aSLionel Sambuc return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2068f4a2713aSLionel Sambuc << 0 << 2 << TheCall->getNumArgs()/*function call*/;
2069f4a2713aSLionel Sambuc if (TheCall->getNumArgs() > 2)
2070f4a2713aSLionel Sambuc return Diag(TheCall->getArg(2)->getLocStart(),
2071f4a2713aSLionel Sambuc diag::err_typecheck_call_too_many_args)
2072f4a2713aSLionel Sambuc << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2073f4a2713aSLionel Sambuc << SourceRange(TheCall->getArg(2)->getLocStart(),
2074f4a2713aSLionel Sambuc (*(TheCall->arg_end()-1))->getLocEnd());
2075f4a2713aSLionel Sambuc
2076f4a2713aSLionel Sambuc ExprResult OrigArg0 = TheCall->getArg(0);
2077f4a2713aSLionel Sambuc ExprResult OrigArg1 = TheCall->getArg(1);
2078f4a2713aSLionel Sambuc
2079f4a2713aSLionel Sambuc // Do standard promotions between the two arguments, returning their common
2080f4a2713aSLionel Sambuc // type.
2081f4a2713aSLionel Sambuc QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
2082f4a2713aSLionel Sambuc if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2083f4a2713aSLionel Sambuc return true;
2084f4a2713aSLionel Sambuc
2085f4a2713aSLionel Sambuc // Make sure any conversions are pushed back into the call; this is
2086f4a2713aSLionel Sambuc // type safe since unordered compare builtins are declared as "_Bool
2087f4a2713aSLionel Sambuc // foo(...)".
2088f4a2713aSLionel Sambuc TheCall->setArg(0, OrigArg0.get());
2089f4a2713aSLionel Sambuc TheCall->setArg(1, OrigArg1.get());
2090f4a2713aSLionel Sambuc
2091f4a2713aSLionel Sambuc if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
2092f4a2713aSLionel Sambuc return false;
2093f4a2713aSLionel Sambuc
2094f4a2713aSLionel Sambuc // If the common type isn't a real floating type, then the arguments were
2095f4a2713aSLionel Sambuc // invalid for this operation.
2096f4a2713aSLionel Sambuc if (Res.isNull() || !Res->isRealFloatingType())
2097f4a2713aSLionel Sambuc return Diag(OrigArg0.get()->getLocStart(),
2098f4a2713aSLionel Sambuc diag::err_typecheck_call_invalid_ordered_compare)
2099f4a2713aSLionel Sambuc << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2100f4a2713aSLionel Sambuc << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
2101f4a2713aSLionel Sambuc
2102f4a2713aSLionel Sambuc return false;
2103f4a2713aSLionel Sambuc }
2104f4a2713aSLionel Sambuc
2105f4a2713aSLionel Sambuc /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2106f4a2713aSLionel Sambuc /// __builtin_isnan and friends. This is declared to take (...), so we have
2107f4a2713aSLionel Sambuc /// to check everything. We expect the last argument to be a floating point
2108f4a2713aSLionel Sambuc /// value.
SemaBuiltinFPClassification(CallExpr * TheCall,unsigned NumArgs)2109f4a2713aSLionel Sambuc bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2110f4a2713aSLionel Sambuc if (TheCall->getNumArgs() < NumArgs)
2111f4a2713aSLionel Sambuc return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2112f4a2713aSLionel Sambuc << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
2113f4a2713aSLionel Sambuc if (TheCall->getNumArgs() > NumArgs)
2114f4a2713aSLionel Sambuc return Diag(TheCall->getArg(NumArgs)->getLocStart(),
2115f4a2713aSLionel Sambuc diag::err_typecheck_call_too_many_args)
2116f4a2713aSLionel Sambuc << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
2117f4a2713aSLionel Sambuc << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
2118f4a2713aSLionel Sambuc (*(TheCall->arg_end()-1))->getLocEnd());
2119f4a2713aSLionel Sambuc
2120f4a2713aSLionel Sambuc Expr *OrigArg = TheCall->getArg(NumArgs-1);
2121f4a2713aSLionel Sambuc
2122f4a2713aSLionel Sambuc if (OrigArg->isTypeDependent())
2123f4a2713aSLionel Sambuc return false;
2124f4a2713aSLionel Sambuc
2125f4a2713aSLionel Sambuc // This operation requires a non-_Complex floating-point number.
2126f4a2713aSLionel Sambuc if (!OrigArg->getType()->isRealFloatingType())
2127f4a2713aSLionel Sambuc return Diag(OrigArg->getLocStart(),
2128f4a2713aSLionel Sambuc diag::err_typecheck_call_invalid_unary_fp)
2129f4a2713aSLionel Sambuc << OrigArg->getType() << OrigArg->getSourceRange();
2130f4a2713aSLionel Sambuc
2131f4a2713aSLionel Sambuc // If this is an implicit conversion from float -> double, remove it.
2132f4a2713aSLionel Sambuc if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2133f4a2713aSLionel Sambuc Expr *CastArg = Cast->getSubExpr();
2134f4a2713aSLionel Sambuc if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2135f4a2713aSLionel Sambuc assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2136f4a2713aSLionel Sambuc "promotion from float to double is the only expected cast here");
2137*0a6a1f1dSLionel Sambuc Cast->setSubExpr(nullptr);
2138f4a2713aSLionel Sambuc TheCall->setArg(NumArgs-1, CastArg);
2139f4a2713aSLionel Sambuc }
2140f4a2713aSLionel Sambuc }
2141f4a2713aSLionel Sambuc
2142f4a2713aSLionel Sambuc return false;
2143f4a2713aSLionel Sambuc }
2144f4a2713aSLionel Sambuc
2145f4a2713aSLionel Sambuc /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2146f4a2713aSLionel Sambuc // This is declared to take (...), so we have to check everything.
SemaBuiltinShuffleVector(CallExpr * TheCall)2147f4a2713aSLionel Sambuc ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
2148f4a2713aSLionel Sambuc if (TheCall->getNumArgs() < 2)
2149f4a2713aSLionel Sambuc return ExprError(Diag(TheCall->getLocEnd(),
2150f4a2713aSLionel Sambuc diag::err_typecheck_call_too_few_args_at_least)
2151f4a2713aSLionel Sambuc << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2152f4a2713aSLionel Sambuc << TheCall->getSourceRange());
2153f4a2713aSLionel Sambuc
2154f4a2713aSLionel Sambuc // Determine which of the following types of shufflevector we're checking:
2155f4a2713aSLionel Sambuc // 1) unary, vector mask: (lhs, mask)
2156f4a2713aSLionel Sambuc // 2) binary, vector mask: (lhs, rhs, mask)
2157f4a2713aSLionel Sambuc // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2158f4a2713aSLionel Sambuc QualType resType = TheCall->getArg(0)->getType();
2159f4a2713aSLionel Sambuc unsigned numElements = 0;
2160f4a2713aSLionel Sambuc
2161f4a2713aSLionel Sambuc if (!TheCall->getArg(0)->isTypeDependent() &&
2162f4a2713aSLionel Sambuc !TheCall->getArg(1)->isTypeDependent()) {
2163f4a2713aSLionel Sambuc QualType LHSType = TheCall->getArg(0)->getType();
2164f4a2713aSLionel Sambuc QualType RHSType = TheCall->getArg(1)->getType();
2165f4a2713aSLionel Sambuc
2166f4a2713aSLionel Sambuc if (!LHSType->isVectorType() || !RHSType->isVectorType())
2167f4a2713aSLionel Sambuc return ExprError(Diag(TheCall->getLocStart(),
2168f4a2713aSLionel Sambuc diag::err_shufflevector_non_vector)
2169f4a2713aSLionel Sambuc << SourceRange(TheCall->getArg(0)->getLocStart(),
2170f4a2713aSLionel Sambuc TheCall->getArg(1)->getLocEnd()));
2171f4a2713aSLionel Sambuc
2172f4a2713aSLionel Sambuc numElements = LHSType->getAs<VectorType>()->getNumElements();
2173f4a2713aSLionel Sambuc unsigned numResElements = TheCall->getNumArgs() - 2;
2174f4a2713aSLionel Sambuc
2175f4a2713aSLionel Sambuc // Check to see if we have a call with 2 vector arguments, the unary shuffle
2176f4a2713aSLionel Sambuc // with mask. If so, verify that RHS is an integer vector type with the
2177f4a2713aSLionel Sambuc // same number of elts as lhs.
2178f4a2713aSLionel Sambuc if (TheCall->getNumArgs() == 2) {
2179f4a2713aSLionel Sambuc if (!RHSType->hasIntegerRepresentation() ||
2180f4a2713aSLionel Sambuc RHSType->getAs<VectorType>()->getNumElements() != numElements)
2181f4a2713aSLionel Sambuc return ExprError(Diag(TheCall->getLocStart(),
2182f4a2713aSLionel Sambuc diag::err_shufflevector_incompatible_vector)
2183f4a2713aSLionel Sambuc << SourceRange(TheCall->getArg(1)->getLocStart(),
2184f4a2713aSLionel Sambuc TheCall->getArg(1)->getLocEnd()));
2185f4a2713aSLionel Sambuc } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
2186f4a2713aSLionel Sambuc return ExprError(Diag(TheCall->getLocStart(),
2187f4a2713aSLionel Sambuc diag::err_shufflevector_incompatible_vector)
2188f4a2713aSLionel Sambuc << SourceRange(TheCall->getArg(0)->getLocStart(),
2189f4a2713aSLionel Sambuc TheCall->getArg(1)->getLocEnd()));
2190f4a2713aSLionel Sambuc } else if (numElements != numResElements) {
2191f4a2713aSLionel Sambuc QualType eltType = LHSType->getAs<VectorType>()->getElementType();
2192f4a2713aSLionel Sambuc resType = Context.getVectorType(eltType, numResElements,
2193f4a2713aSLionel Sambuc VectorType::GenericVector);
2194f4a2713aSLionel Sambuc }
2195f4a2713aSLionel Sambuc }
2196f4a2713aSLionel Sambuc
2197f4a2713aSLionel Sambuc for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
2198f4a2713aSLionel Sambuc if (TheCall->getArg(i)->isTypeDependent() ||
2199f4a2713aSLionel Sambuc TheCall->getArg(i)->isValueDependent())
2200f4a2713aSLionel Sambuc continue;
2201f4a2713aSLionel Sambuc
2202f4a2713aSLionel Sambuc llvm::APSInt Result(32);
2203f4a2713aSLionel Sambuc if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2204f4a2713aSLionel Sambuc return ExprError(Diag(TheCall->getLocStart(),
2205f4a2713aSLionel Sambuc diag::err_shufflevector_nonconstant_argument)
2206f4a2713aSLionel Sambuc << TheCall->getArg(i)->getSourceRange());
2207f4a2713aSLionel Sambuc
2208f4a2713aSLionel Sambuc // Allow -1 which will be translated to undef in the IR.
2209f4a2713aSLionel Sambuc if (Result.isSigned() && Result.isAllOnesValue())
2210f4a2713aSLionel Sambuc continue;
2211f4a2713aSLionel Sambuc
2212f4a2713aSLionel Sambuc if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2213f4a2713aSLionel Sambuc return ExprError(Diag(TheCall->getLocStart(),
2214f4a2713aSLionel Sambuc diag::err_shufflevector_argument_too_large)
2215f4a2713aSLionel Sambuc << TheCall->getArg(i)->getSourceRange());
2216f4a2713aSLionel Sambuc }
2217f4a2713aSLionel Sambuc
2218f4a2713aSLionel Sambuc SmallVector<Expr*, 32> exprs;
2219f4a2713aSLionel Sambuc
2220f4a2713aSLionel Sambuc for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
2221f4a2713aSLionel Sambuc exprs.push_back(TheCall->getArg(i));
2222*0a6a1f1dSLionel Sambuc TheCall->setArg(i, nullptr);
2223f4a2713aSLionel Sambuc }
2224f4a2713aSLionel Sambuc
2225*0a6a1f1dSLionel Sambuc return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2226f4a2713aSLionel Sambuc TheCall->getCallee()->getLocStart(),
2227*0a6a1f1dSLionel Sambuc TheCall->getRParenLoc());
2228f4a2713aSLionel Sambuc }
2229f4a2713aSLionel Sambuc
2230f4a2713aSLionel Sambuc /// SemaConvertVectorExpr - Handle __builtin_convertvector
SemaConvertVectorExpr(Expr * E,TypeSourceInfo * TInfo,SourceLocation BuiltinLoc,SourceLocation RParenLoc)2231f4a2713aSLionel Sambuc ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2232f4a2713aSLionel Sambuc SourceLocation BuiltinLoc,
2233f4a2713aSLionel Sambuc SourceLocation RParenLoc) {
2234f4a2713aSLionel Sambuc ExprValueKind VK = VK_RValue;
2235f4a2713aSLionel Sambuc ExprObjectKind OK = OK_Ordinary;
2236f4a2713aSLionel Sambuc QualType DstTy = TInfo->getType();
2237f4a2713aSLionel Sambuc QualType SrcTy = E->getType();
2238f4a2713aSLionel Sambuc
2239f4a2713aSLionel Sambuc if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2240f4a2713aSLionel Sambuc return ExprError(Diag(BuiltinLoc,
2241f4a2713aSLionel Sambuc diag::err_convertvector_non_vector)
2242f4a2713aSLionel Sambuc << E->getSourceRange());
2243f4a2713aSLionel Sambuc if (!DstTy->isVectorType() && !DstTy->isDependentType())
2244f4a2713aSLionel Sambuc return ExprError(Diag(BuiltinLoc,
2245f4a2713aSLionel Sambuc diag::err_convertvector_non_vector_type));
2246f4a2713aSLionel Sambuc
2247f4a2713aSLionel Sambuc if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2248f4a2713aSLionel Sambuc unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2249f4a2713aSLionel Sambuc unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2250f4a2713aSLionel Sambuc if (SrcElts != DstElts)
2251f4a2713aSLionel Sambuc return ExprError(Diag(BuiltinLoc,
2252f4a2713aSLionel Sambuc diag::err_convertvector_incompatible_vector)
2253f4a2713aSLionel Sambuc << E->getSourceRange());
2254f4a2713aSLionel Sambuc }
2255f4a2713aSLionel Sambuc
2256*0a6a1f1dSLionel Sambuc return new (Context)
2257*0a6a1f1dSLionel Sambuc ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
2258f4a2713aSLionel Sambuc }
2259f4a2713aSLionel Sambuc
2260f4a2713aSLionel Sambuc /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2261f4a2713aSLionel Sambuc // This is declared to take (const void*, ...) and can take two
2262f4a2713aSLionel Sambuc // optional constant int args.
SemaBuiltinPrefetch(CallExpr * TheCall)2263f4a2713aSLionel Sambuc bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
2264f4a2713aSLionel Sambuc unsigned NumArgs = TheCall->getNumArgs();
2265f4a2713aSLionel Sambuc
2266f4a2713aSLionel Sambuc if (NumArgs > 3)
2267f4a2713aSLionel Sambuc return Diag(TheCall->getLocEnd(),
2268f4a2713aSLionel Sambuc diag::err_typecheck_call_too_many_args_at_most)
2269f4a2713aSLionel Sambuc << 0 /*function call*/ << 3 << NumArgs
2270f4a2713aSLionel Sambuc << TheCall->getSourceRange();
2271f4a2713aSLionel Sambuc
2272f4a2713aSLionel Sambuc // Argument 0 is checked for us and the remaining arguments must be
2273f4a2713aSLionel Sambuc // constant integers.
2274*0a6a1f1dSLionel Sambuc for (unsigned i = 1; i != NumArgs; ++i)
2275*0a6a1f1dSLionel Sambuc if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
2276f4a2713aSLionel Sambuc return true;
2277f4a2713aSLionel Sambuc
2278*0a6a1f1dSLionel Sambuc return false;
2279f4a2713aSLionel Sambuc }
2280*0a6a1f1dSLionel Sambuc
2281*0a6a1f1dSLionel Sambuc /// SemaBuiltinAssume - Handle __assume (MS Extension).
2282*0a6a1f1dSLionel Sambuc // __assume does not evaluate its arguments, and should warn if its argument
2283*0a6a1f1dSLionel Sambuc // has side effects.
SemaBuiltinAssume(CallExpr * TheCall)2284*0a6a1f1dSLionel Sambuc bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2285*0a6a1f1dSLionel Sambuc Expr *Arg = TheCall->getArg(0);
2286*0a6a1f1dSLionel Sambuc if (Arg->isInstantiationDependent()) return false;
2287*0a6a1f1dSLionel Sambuc
2288*0a6a1f1dSLionel Sambuc if (Arg->HasSideEffects(Context))
2289*0a6a1f1dSLionel Sambuc return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2290*0a6a1f1dSLionel Sambuc << Arg->getSourceRange()
2291*0a6a1f1dSLionel Sambuc << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2292*0a6a1f1dSLionel Sambuc
2293*0a6a1f1dSLionel Sambuc return false;
2294*0a6a1f1dSLionel Sambuc }
2295*0a6a1f1dSLionel Sambuc
2296*0a6a1f1dSLionel Sambuc /// Handle __builtin_assume_aligned. This is declared
2297*0a6a1f1dSLionel Sambuc /// as (const void*, size_t, ...) and can take one optional constant int arg.
SemaBuiltinAssumeAligned(CallExpr * TheCall)2298*0a6a1f1dSLionel Sambuc bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2299*0a6a1f1dSLionel Sambuc unsigned NumArgs = TheCall->getNumArgs();
2300*0a6a1f1dSLionel Sambuc
2301*0a6a1f1dSLionel Sambuc if (NumArgs > 3)
2302*0a6a1f1dSLionel Sambuc return Diag(TheCall->getLocEnd(),
2303*0a6a1f1dSLionel Sambuc diag::err_typecheck_call_too_many_args_at_most)
2304*0a6a1f1dSLionel Sambuc << 0 /*function call*/ << 3 << NumArgs
2305*0a6a1f1dSLionel Sambuc << TheCall->getSourceRange();
2306*0a6a1f1dSLionel Sambuc
2307*0a6a1f1dSLionel Sambuc // The alignment must be a constant integer.
2308*0a6a1f1dSLionel Sambuc Expr *Arg = TheCall->getArg(1);
2309*0a6a1f1dSLionel Sambuc
2310*0a6a1f1dSLionel Sambuc // We can't check the value of a dependent argument.
2311*0a6a1f1dSLionel Sambuc if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2312*0a6a1f1dSLionel Sambuc llvm::APSInt Result;
2313*0a6a1f1dSLionel Sambuc if (SemaBuiltinConstantArg(TheCall, 1, Result))
2314*0a6a1f1dSLionel Sambuc return true;
2315*0a6a1f1dSLionel Sambuc
2316*0a6a1f1dSLionel Sambuc if (!Result.isPowerOf2())
2317*0a6a1f1dSLionel Sambuc return Diag(TheCall->getLocStart(),
2318*0a6a1f1dSLionel Sambuc diag::err_alignment_not_power_of_two)
2319*0a6a1f1dSLionel Sambuc << Arg->getSourceRange();
2320*0a6a1f1dSLionel Sambuc }
2321*0a6a1f1dSLionel Sambuc
2322*0a6a1f1dSLionel Sambuc if (NumArgs > 2) {
2323*0a6a1f1dSLionel Sambuc ExprResult Arg(TheCall->getArg(2));
2324*0a6a1f1dSLionel Sambuc InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2325*0a6a1f1dSLionel Sambuc Context.getSizeType(), false);
2326*0a6a1f1dSLionel Sambuc Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2327*0a6a1f1dSLionel Sambuc if (Arg.isInvalid()) return true;
2328*0a6a1f1dSLionel Sambuc TheCall->setArg(2, Arg.get());
2329f4a2713aSLionel Sambuc }
2330f4a2713aSLionel Sambuc
2331f4a2713aSLionel Sambuc return false;
2332f4a2713aSLionel Sambuc }
2333f4a2713aSLionel Sambuc
2334f4a2713aSLionel Sambuc /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2335f4a2713aSLionel Sambuc /// TheCall is a constant expression.
SemaBuiltinConstantArg(CallExpr * TheCall,int ArgNum,llvm::APSInt & Result)2336f4a2713aSLionel Sambuc bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2337f4a2713aSLionel Sambuc llvm::APSInt &Result) {
2338f4a2713aSLionel Sambuc Expr *Arg = TheCall->getArg(ArgNum);
2339f4a2713aSLionel Sambuc DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2340f4a2713aSLionel Sambuc FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2341f4a2713aSLionel Sambuc
2342f4a2713aSLionel Sambuc if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2343f4a2713aSLionel Sambuc
2344f4a2713aSLionel Sambuc if (!Arg->isIntegerConstantExpr(Result, Context))
2345f4a2713aSLionel Sambuc return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
2346f4a2713aSLionel Sambuc << FDecl->getDeclName() << Arg->getSourceRange();
2347f4a2713aSLionel Sambuc
2348f4a2713aSLionel Sambuc return false;
2349f4a2713aSLionel Sambuc }
2350f4a2713aSLionel Sambuc
2351*0a6a1f1dSLionel Sambuc /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2352*0a6a1f1dSLionel Sambuc /// TheCall is a constant expression in the range [Low, High].
SemaBuiltinConstantArgRange(CallExpr * TheCall,int ArgNum,int Low,int High)2353*0a6a1f1dSLionel Sambuc bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2354*0a6a1f1dSLionel Sambuc int Low, int High) {
2355f4a2713aSLionel Sambuc llvm::APSInt Result;
2356f4a2713aSLionel Sambuc
2357f4a2713aSLionel Sambuc // We can't check the value of a dependent argument.
2358*0a6a1f1dSLionel Sambuc Expr *Arg = TheCall->getArg(ArgNum);
2359*0a6a1f1dSLionel Sambuc if (Arg->isTypeDependent() || Arg->isValueDependent())
2360f4a2713aSLionel Sambuc return false;
2361f4a2713aSLionel Sambuc
2362f4a2713aSLionel Sambuc // Check constant-ness first.
2363*0a6a1f1dSLionel Sambuc if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2364f4a2713aSLionel Sambuc return true;
2365f4a2713aSLionel Sambuc
2366*0a6a1f1dSLionel Sambuc if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
2367f4a2713aSLionel Sambuc return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2368*0a6a1f1dSLionel Sambuc << Low << High << Arg->getSourceRange();
2369f4a2713aSLionel Sambuc
2370f4a2713aSLionel Sambuc return false;
2371f4a2713aSLionel Sambuc }
2372f4a2713aSLionel Sambuc
2373f4a2713aSLionel Sambuc /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2374*0a6a1f1dSLionel Sambuc /// This checks that the target supports __builtin_longjmp and
2375*0a6a1f1dSLionel Sambuc /// that val is a constant 1.
SemaBuiltinLongjmp(CallExpr * TheCall)2376f4a2713aSLionel Sambuc bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2377*0a6a1f1dSLionel Sambuc if (!Context.getTargetInfo().hasSjLjLowering())
2378*0a6a1f1dSLionel Sambuc return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2379*0a6a1f1dSLionel Sambuc << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2380*0a6a1f1dSLionel Sambuc
2381f4a2713aSLionel Sambuc Expr *Arg = TheCall->getArg(1);
2382f4a2713aSLionel Sambuc llvm::APSInt Result;
2383f4a2713aSLionel Sambuc
2384f4a2713aSLionel Sambuc // TODO: This is less than ideal. Overload this to take a value.
2385f4a2713aSLionel Sambuc if (SemaBuiltinConstantArg(TheCall, 1, Result))
2386f4a2713aSLionel Sambuc return true;
2387f4a2713aSLionel Sambuc
2388f4a2713aSLionel Sambuc if (Result != 1)
2389f4a2713aSLionel Sambuc return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2390f4a2713aSLionel Sambuc << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2391f4a2713aSLionel Sambuc
2392f4a2713aSLionel Sambuc return false;
2393f4a2713aSLionel Sambuc }
2394f4a2713aSLionel Sambuc
2395*0a6a1f1dSLionel Sambuc
2396*0a6a1f1dSLionel Sambuc /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2397*0a6a1f1dSLionel Sambuc /// This checks that the target supports __builtin_setjmp.
SemaBuiltinSetjmp(CallExpr * TheCall)2398*0a6a1f1dSLionel Sambuc bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2399*0a6a1f1dSLionel Sambuc if (!Context.getTargetInfo().hasSjLjLowering())
2400*0a6a1f1dSLionel Sambuc return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2401*0a6a1f1dSLionel Sambuc << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2402*0a6a1f1dSLionel Sambuc return false;
2403*0a6a1f1dSLionel Sambuc }
2404*0a6a1f1dSLionel Sambuc
2405f4a2713aSLionel Sambuc namespace {
2406f4a2713aSLionel Sambuc enum StringLiteralCheckType {
2407f4a2713aSLionel Sambuc SLCT_NotALiteral,
2408f4a2713aSLionel Sambuc SLCT_UncheckedLiteral,
2409f4a2713aSLionel Sambuc SLCT_CheckedLiteral
2410f4a2713aSLionel Sambuc };
2411f4a2713aSLionel Sambuc }
2412f4a2713aSLionel Sambuc
2413f4a2713aSLionel Sambuc // Determine if an expression is a string literal or constant string.
2414f4a2713aSLionel Sambuc // If this function returns false on the arguments to a function expecting a
2415f4a2713aSLionel Sambuc // format string, we will usually need to emit a warning.
2416f4a2713aSLionel Sambuc // True string literals are then checked by CheckFormatString.
2417f4a2713aSLionel Sambuc static StringLiteralCheckType
checkFormatStringExpr(Sema & S,const Expr * E,ArrayRef<const Expr * > Args,bool HasVAListArg,unsigned format_idx,unsigned firstDataArg,Sema::FormatStringType Type,Sema::VariadicCallType CallType,bool InFunctionCall,llvm::SmallBitVector & CheckedVarArgs)2418f4a2713aSLionel Sambuc checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2419f4a2713aSLionel Sambuc bool HasVAListArg, unsigned format_idx,
2420f4a2713aSLionel Sambuc unsigned firstDataArg, Sema::FormatStringType Type,
2421f4a2713aSLionel Sambuc Sema::VariadicCallType CallType, bool InFunctionCall,
2422f4a2713aSLionel Sambuc llvm::SmallBitVector &CheckedVarArgs) {
2423f4a2713aSLionel Sambuc tryAgain:
2424f4a2713aSLionel Sambuc if (E->isTypeDependent() || E->isValueDependent())
2425f4a2713aSLionel Sambuc return SLCT_NotALiteral;
2426f4a2713aSLionel Sambuc
2427f4a2713aSLionel Sambuc E = E->IgnoreParenCasts();
2428f4a2713aSLionel Sambuc
2429f4a2713aSLionel Sambuc if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
2430f4a2713aSLionel Sambuc // Technically -Wformat-nonliteral does not warn about this case.
2431f4a2713aSLionel Sambuc // The behavior of printf and friends in this case is implementation
2432f4a2713aSLionel Sambuc // dependent. Ideally if the format string cannot be null then
2433f4a2713aSLionel Sambuc // it should have a 'nonnull' attribute in the function prototype.
2434f4a2713aSLionel Sambuc return SLCT_UncheckedLiteral;
2435f4a2713aSLionel Sambuc
2436f4a2713aSLionel Sambuc switch (E->getStmtClass()) {
2437f4a2713aSLionel Sambuc case Stmt::BinaryConditionalOperatorClass:
2438f4a2713aSLionel Sambuc case Stmt::ConditionalOperatorClass: {
2439f4a2713aSLionel Sambuc // The expression is a literal if both sub-expressions were, and it was
2440f4a2713aSLionel Sambuc // completely checked only if both sub-expressions were checked.
2441f4a2713aSLionel Sambuc const AbstractConditionalOperator *C =
2442f4a2713aSLionel Sambuc cast<AbstractConditionalOperator>(E);
2443f4a2713aSLionel Sambuc StringLiteralCheckType Left =
2444f4a2713aSLionel Sambuc checkFormatStringExpr(S, C->getTrueExpr(), Args,
2445f4a2713aSLionel Sambuc HasVAListArg, format_idx, firstDataArg,
2446f4a2713aSLionel Sambuc Type, CallType, InFunctionCall, CheckedVarArgs);
2447f4a2713aSLionel Sambuc if (Left == SLCT_NotALiteral)
2448f4a2713aSLionel Sambuc return SLCT_NotALiteral;
2449f4a2713aSLionel Sambuc StringLiteralCheckType Right =
2450f4a2713aSLionel Sambuc checkFormatStringExpr(S, C->getFalseExpr(), Args,
2451f4a2713aSLionel Sambuc HasVAListArg, format_idx, firstDataArg,
2452f4a2713aSLionel Sambuc Type, CallType, InFunctionCall, CheckedVarArgs);
2453f4a2713aSLionel Sambuc return Left < Right ? Left : Right;
2454f4a2713aSLionel Sambuc }
2455f4a2713aSLionel Sambuc
2456f4a2713aSLionel Sambuc case Stmt::ImplicitCastExprClass: {
2457f4a2713aSLionel Sambuc E = cast<ImplicitCastExpr>(E)->getSubExpr();
2458f4a2713aSLionel Sambuc goto tryAgain;
2459f4a2713aSLionel Sambuc }
2460f4a2713aSLionel Sambuc
2461f4a2713aSLionel Sambuc case Stmt::OpaqueValueExprClass:
2462f4a2713aSLionel Sambuc if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2463f4a2713aSLionel Sambuc E = src;
2464f4a2713aSLionel Sambuc goto tryAgain;
2465f4a2713aSLionel Sambuc }
2466f4a2713aSLionel Sambuc return SLCT_NotALiteral;
2467f4a2713aSLionel Sambuc
2468f4a2713aSLionel Sambuc case Stmt::PredefinedExprClass:
2469f4a2713aSLionel Sambuc // While __func__, etc., are technically not string literals, they
2470f4a2713aSLionel Sambuc // cannot contain format specifiers and thus are not a security
2471f4a2713aSLionel Sambuc // liability.
2472f4a2713aSLionel Sambuc return SLCT_UncheckedLiteral;
2473f4a2713aSLionel Sambuc
2474f4a2713aSLionel Sambuc case Stmt::DeclRefExprClass: {
2475f4a2713aSLionel Sambuc const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2476f4a2713aSLionel Sambuc
2477f4a2713aSLionel Sambuc // As an exception, do not flag errors for variables binding to
2478f4a2713aSLionel Sambuc // const string literals.
2479f4a2713aSLionel Sambuc if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2480f4a2713aSLionel Sambuc bool isConstant = false;
2481f4a2713aSLionel Sambuc QualType T = DR->getType();
2482f4a2713aSLionel Sambuc
2483f4a2713aSLionel Sambuc if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2484f4a2713aSLionel Sambuc isConstant = AT->getElementType().isConstant(S.Context);
2485f4a2713aSLionel Sambuc } else if (const PointerType *PT = T->getAs<PointerType>()) {
2486f4a2713aSLionel Sambuc isConstant = T.isConstant(S.Context) &&
2487f4a2713aSLionel Sambuc PT->getPointeeType().isConstant(S.Context);
2488f4a2713aSLionel Sambuc } else if (T->isObjCObjectPointerType()) {
2489f4a2713aSLionel Sambuc // In ObjC, there is usually no "const ObjectPointer" type,
2490f4a2713aSLionel Sambuc // so don't check if the pointee type is constant.
2491f4a2713aSLionel Sambuc isConstant = T.isConstant(S.Context);
2492f4a2713aSLionel Sambuc }
2493f4a2713aSLionel Sambuc
2494f4a2713aSLionel Sambuc if (isConstant) {
2495f4a2713aSLionel Sambuc if (const Expr *Init = VD->getAnyInitializer()) {
2496f4a2713aSLionel Sambuc // Look through initializers like const char c[] = { "foo" }
2497f4a2713aSLionel Sambuc if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2498f4a2713aSLionel Sambuc if (InitList->isStringLiteralInit())
2499f4a2713aSLionel Sambuc Init = InitList->getInit(0)->IgnoreParenImpCasts();
2500f4a2713aSLionel Sambuc }
2501f4a2713aSLionel Sambuc return checkFormatStringExpr(S, Init, Args,
2502f4a2713aSLionel Sambuc HasVAListArg, format_idx,
2503f4a2713aSLionel Sambuc firstDataArg, Type, CallType,
2504f4a2713aSLionel Sambuc /*InFunctionCall*/false, CheckedVarArgs);
2505f4a2713aSLionel Sambuc }
2506f4a2713aSLionel Sambuc }
2507f4a2713aSLionel Sambuc
2508f4a2713aSLionel Sambuc // For vprintf* functions (i.e., HasVAListArg==true), we add a
2509f4a2713aSLionel Sambuc // special check to see if the format string is a function parameter
2510f4a2713aSLionel Sambuc // of the function calling the printf function. If the function
2511f4a2713aSLionel Sambuc // has an attribute indicating it is a printf-like function, then we
2512f4a2713aSLionel Sambuc // should suppress warnings concerning non-literals being used in a call
2513f4a2713aSLionel Sambuc // to a vprintf function. For example:
2514f4a2713aSLionel Sambuc //
2515f4a2713aSLionel Sambuc // void
2516f4a2713aSLionel Sambuc // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2517f4a2713aSLionel Sambuc // va_list ap;
2518f4a2713aSLionel Sambuc // va_start(ap, fmt);
2519f4a2713aSLionel Sambuc // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2520f4a2713aSLionel Sambuc // ...
2521f4a2713aSLionel Sambuc // }
2522f4a2713aSLionel Sambuc if (HasVAListArg) {
2523f4a2713aSLionel Sambuc if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2524f4a2713aSLionel Sambuc if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2525f4a2713aSLionel Sambuc int PVIndex = PV->getFunctionScopeIndex() + 1;
2526*0a6a1f1dSLionel Sambuc for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
2527f4a2713aSLionel Sambuc // adjust for implicit parameter
2528f4a2713aSLionel Sambuc if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2529f4a2713aSLionel Sambuc if (MD->isInstance())
2530f4a2713aSLionel Sambuc ++PVIndex;
2531f4a2713aSLionel Sambuc // We also check if the formats are compatible.
2532f4a2713aSLionel Sambuc // We can't pass a 'scanf' string to a 'printf' function.
2533f4a2713aSLionel Sambuc if (PVIndex == PVFormat->getFormatIdx() &&
2534f4a2713aSLionel Sambuc Type == S.GetFormatStringType(PVFormat))
2535f4a2713aSLionel Sambuc return SLCT_UncheckedLiteral;
2536f4a2713aSLionel Sambuc }
2537f4a2713aSLionel Sambuc }
2538f4a2713aSLionel Sambuc }
2539f4a2713aSLionel Sambuc }
2540f4a2713aSLionel Sambuc }
2541f4a2713aSLionel Sambuc
2542f4a2713aSLionel Sambuc return SLCT_NotALiteral;
2543f4a2713aSLionel Sambuc }
2544f4a2713aSLionel Sambuc
2545f4a2713aSLionel Sambuc case Stmt::CallExprClass:
2546f4a2713aSLionel Sambuc case Stmt::CXXMemberCallExprClass: {
2547f4a2713aSLionel Sambuc const CallExpr *CE = cast<CallExpr>(E);
2548f4a2713aSLionel Sambuc if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2549f4a2713aSLionel Sambuc if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2550f4a2713aSLionel Sambuc unsigned ArgIndex = FA->getFormatIdx();
2551f4a2713aSLionel Sambuc if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2552f4a2713aSLionel Sambuc if (MD->isInstance())
2553f4a2713aSLionel Sambuc --ArgIndex;
2554f4a2713aSLionel Sambuc const Expr *Arg = CE->getArg(ArgIndex - 1);
2555f4a2713aSLionel Sambuc
2556f4a2713aSLionel Sambuc return checkFormatStringExpr(S, Arg, Args,
2557f4a2713aSLionel Sambuc HasVAListArg, format_idx, firstDataArg,
2558f4a2713aSLionel Sambuc Type, CallType, InFunctionCall,
2559f4a2713aSLionel Sambuc CheckedVarArgs);
2560f4a2713aSLionel Sambuc } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2561f4a2713aSLionel Sambuc unsigned BuiltinID = FD->getBuiltinID();
2562f4a2713aSLionel Sambuc if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2563f4a2713aSLionel Sambuc BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2564f4a2713aSLionel Sambuc const Expr *Arg = CE->getArg(0);
2565f4a2713aSLionel Sambuc return checkFormatStringExpr(S, Arg, Args,
2566f4a2713aSLionel Sambuc HasVAListArg, format_idx,
2567f4a2713aSLionel Sambuc firstDataArg, Type, CallType,
2568f4a2713aSLionel Sambuc InFunctionCall, CheckedVarArgs);
2569f4a2713aSLionel Sambuc }
2570f4a2713aSLionel Sambuc }
2571f4a2713aSLionel Sambuc }
2572f4a2713aSLionel Sambuc
2573f4a2713aSLionel Sambuc return SLCT_NotALiteral;
2574f4a2713aSLionel Sambuc }
2575f4a2713aSLionel Sambuc case Stmt::ObjCStringLiteralClass:
2576f4a2713aSLionel Sambuc case Stmt::StringLiteralClass: {
2577*0a6a1f1dSLionel Sambuc const StringLiteral *StrE = nullptr;
2578f4a2713aSLionel Sambuc
2579f4a2713aSLionel Sambuc if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2580f4a2713aSLionel Sambuc StrE = ObjCFExpr->getString();
2581f4a2713aSLionel Sambuc else
2582f4a2713aSLionel Sambuc StrE = cast<StringLiteral>(E);
2583f4a2713aSLionel Sambuc
2584f4a2713aSLionel Sambuc if (StrE) {
2585f4a2713aSLionel Sambuc S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2586f4a2713aSLionel Sambuc Type, InFunctionCall, CallType, CheckedVarArgs);
2587f4a2713aSLionel Sambuc return SLCT_CheckedLiteral;
2588f4a2713aSLionel Sambuc }
2589f4a2713aSLionel Sambuc
2590f4a2713aSLionel Sambuc return SLCT_NotALiteral;
2591f4a2713aSLionel Sambuc }
2592f4a2713aSLionel Sambuc
2593f4a2713aSLionel Sambuc default:
2594f4a2713aSLionel Sambuc return SLCT_NotALiteral;
2595f4a2713aSLionel Sambuc }
2596f4a2713aSLionel Sambuc }
2597f4a2713aSLionel Sambuc
GetFormatStringType(const FormatAttr * Format)2598f4a2713aSLionel Sambuc Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2599f4a2713aSLionel Sambuc return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2600f4a2713aSLionel Sambuc .Case("scanf", FST_Scanf)
2601f4a2713aSLionel Sambuc .Cases("printf", "printf0", FST_Printf)
2602f4a2713aSLionel Sambuc .Cases("NSString", "CFString", FST_NSString)
2603f4a2713aSLionel Sambuc .Case("strftime", FST_Strftime)
2604f4a2713aSLionel Sambuc .Case("strfmon", FST_Strfmon)
2605f4a2713aSLionel Sambuc .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2606f4a2713aSLionel Sambuc .Default(FST_Unknown);
2607f4a2713aSLionel Sambuc }
2608f4a2713aSLionel Sambuc
2609f4a2713aSLionel Sambuc /// CheckFormatArguments - Check calls to printf and scanf (and similar
2610f4a2713aSLionel Sambuc /// functions) for correct use of format strings.
2611f4a2713aSLionel Sambuc /// Returns true if a format string has been fully checked.
CheckFormatArguments(const FormatAttr * Format,ArrayRef<const Expr * > Args,bool IsCXXMember,VariadicCallType CallType,SourceLocation Loc,SourceRange Range,llvm::SmallBitVector & CheckedVarArgs)2612f4a2713aSLionel Sambuc bool Sema::CheckFormatArguments(const FormatAttr *Format,
2613f4a2713aSLionel Sambuc ArrayRef<const Expr *> Args,
2614f4a2713aSLionel Sambuc bool IsCXXMember,
2615f4a2713aSLionel Sambuc VariadicCallType CallType,
2616f4a2713aSLionel Sambuc SourceLocation Loc, SourceRange Range,
2617f4a2713aSLionel Sambuc llvm::SmallBitVector &CheckedVarArgs) {
2618f4a2713aSLionel Sambuc FormatStringInfo FSI;
2619f4a2713aSLionel Sambuc if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2620f4a2713aSLionel Sambuc return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2621f4a2713aSLionel Sambuc FSI.FirstDataArg, GetFormatStringType(Format),
2622f4a2713aSLionel Sambuc CallType, Loc, Range, CheckedVarArgs);
2623f4a2713aSLionel Sambuc return false;
2624f4a2713aSLionel Sambuc }
2625f4a2713aSLionel Sambuc
CheckFormatArguments(ArrayRef<const Expr * > Args,bool HasVAListArg,unsigned format_idx,unsigned firstDataArg,FormatStringType Type,VariadicCallType CallType,SourceLocation Loc,SourceRange Range,llvm::SmallBitVector & CheckedVarArgs)2626f4a2713aSLionel Sambuc bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2627f4a2713aSLionel Sambuc bool HasVAListArg, unsigned format_idx,
2628f4a2713aSLionel Sambuc unsigned firstDataArg, FormatStringType Type,
2629f4a2713aSLionel Sambuc VariadicCallType CallType,
2630f4a2713aSLionel Sambuc SourceLocation Loc, SourceRange Range,
2631f4a2713aSLionel Sambuc llvm::SmallBitVector &CheckedVarArgs) {
2632f4a2713aSLionel Sambuc // CHECK: printf/scanf-like function is called with no format string.
2633f4a2713aSLionel Sambuc if (format_idx >= Args.size()) {
2634f4a2713aSLionel Sambuc Diag(Loc, diag::warn_missing_format_string) << Range;
2635f4a2713aSLionel Sambuc return false;
2636f4a2713aSLionel Sambuc }
2637f4a2713aSLionel Sambuc
2638f4a2713aSLionel Sambuc const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2639f4a2713aSLionel Sambuc
2640f4a2713aSLionel Sambuc // CHECK: format string is not a string literal.
2641f4a2713aSLionel Sambuc //
2642f4a2713aSLionel Sambuc // Dynamically generated format strings are difficult to
2643f4a2713aSLionel Sambuc // automatically vet at compile time. Requiring that format strings
2644f4a2713aSLionel Sambuc // are string literals: (1) permits the checking of format strings by
2645f4a2713aSLionel Sambuc // the compiler and thereby (2) can practically remove the source of
2646f4a2713aSLionel Sambuc // many format string exploits.
2647f4a2713aSLionel Sambuc
2648f4a2713aSLionel Sambuc // Format string can be either ObjC string (e.g. @"%d") or
2649f4a2713aSLionel Sambuc // C string (e.g. "%d")
2650f4a2713aSLionel Sambuc // ObjC string uses the same format specifiers as C string, so we can use
2651f4a2713aSLionel Sambuc // the same format string checking logic for both ObjC and C strings.
2652f4a2713aSLionel Sambuc StringLiteralCheckType CT =
2653f4a2713aSLionel Sambuc checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2654f4a2713aSLionel Sambuc format_idx, firstDataArg, Type, CallType,
2655f4a2713aSLionel Sambuc /*IsFunctionCall*/true, CheckedVarArgs);
2656f4a2713aSLionel Sambuc if (CT != SLCT_NotALiteral)
2657f4a2713aSLionel Sambuc // Literal format string found, check done!
2658f4a2713aSLionel Sambuc return CT == SLCT_CheckedLiteral;
2659f4a2713aSLionel Sambuc
2660f4a2713aSLionel Sambuc // Strftime is particular as it always uses a single 'time' argument,
2661f4a2713aSLionel Sambuc // so it is safe to pass a non-literal string.
2662f4a2713aSLionel Sambuc if (Type == FST_Strftime)
2663f4a2713aSLionel Sambuc return false;
2664f4a2713aSLionel Sambuc
2665f4a2713aSLionel Sambuc // Do not emit diag when the string param is a macro expansion and the
2666f4a2713aSLionel Sambuc // format is either NSString or CFString. This is a hack to prevent
2667f4a2713aSLionel Sambuc // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2668f4a2713aSLionel Sambuc // which are usually used in place of NS and CF string literals.
2669f4a2713aSLionel Sambuc if (Type == FST_NSString &&
2670f4a2713aSLionel Sambuc SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2671f4a2713aSLionel Sambuc return false;
2672f4a2713aSLionel Sambuc
2673f4a2713aSLionel Sambuc // If there are no arguments specified, warn with -Wformat-security, otherwise
2674f4a2713aSLionel Sambuc // warn only with -Wformat-nonliteral.
2675f4a2713aSLionel Sambuc if (Args.size() == firstDataArg)
2676f4a2713aSLionel Sambuc Diag(Args[format_idx]->getLocStart(),
2677f4a2713aSLionel Sambuc diag::warn_format_nonliteral_noargs)
2678f4a2713aSLionel Sambuc << OrigFormatExpr->getSourceRange();
2679f4a2713aSLionel Sambuc else
2680f4a2713aSLionel Sambuc Diag(Args[format_idx]->getLocStart(),
2681f4a2713aSLionel Sambuc diag::warn_format_nonliteral)
2682f4a2713aSLionel Sambuc << OrigFormatExpr->getSourceRange();
2683f4a2713aSLionel Sambuc return false;
2684f4a2713aSLionel Sambuc }
2685f4a2713aSLionel Sambuc
2686f4a2713aSLionel Sambuc namespace {
2687f4a2713aSLionel Sambuc class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2688f4a2713aSLionel Sambuc protected:
2689f4a2713aSLionel Sambuc Sema &S;
2690f4a2713aSLionel Sambuc const StringLiteral *FExpr;
2691f4a2713aSLionel Sambuc const Expr *OrigFormatExpr;
2692f4a2713aSLionel Sambuc const unsigned FirstDataArg;
2693f4a2713aSLionel Sambuc const unsigned NumDataArgs;
2694f4a2713aSLionel Sambuc const char *Beg; // Start of format string.
2695f4a2713aSLionel Sambuc const bool HasVAListArg;
2696f4a2713aSLionel Sambuc ArrayRef<const Expr *> Args;
2697f4a2713aSLionel Sambuc unsigned FormatIdx;
2698f4a2713aSLionel Sambuc llvm::SmallBitVector CoveredArgs;
2699f4a2713aSLionel Sambuc bool usesPositionalArgs;
2700f4a2713aSLionel Sambuc bool atFirstArg;
2701f4a2713aSLionel Sambuc bool inFunctionCall;
2702f4a2713aSLionel Sambuc Sema::VariadicCallType CallType;
2703f4a2713aSLionel Sambuc llvm::SmallBitVector &CheckedVarArgs;
2704f4a2713aSLionel Sambuc public:
CheckFormatHandler(Sema & s,const StringLiteral * fexpr,const Expr * origFormatExpr,unsigned firstDataArg,unsigned numDataArgs,const char * beg,bool hasVAListArg,ArrayRef<const Expr * > Args,unsigned formatIdx,bool inFunctionCall,Sema::VariadicCallType callType,llvm::SmallBitVector & CheckedVarArgs)2705f4a2713aSLionel Sambuc CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2706f4a2713aSLionel Sambuc const Expr *origFormatExpr, unsigned firstDataArg,
2707f4a2713aSLionel Sambuc unsigned numDataArgs, const char *beg, bool hasVAListArg,
2708f4a2713aSLionel Sambuc ArrayRef<const Expr *> Args,
2709f4a2713aSLionel Sambuc unsigned formatIdx, bool inFunctionCall,
2710f4a2713aSLionel Sambuc Sema::VariadicCallType callType,
2711f4a2713aSLionel Sambuc llvm::SmallBitVector &CheckedVarArgs)
2712f4a2713aSLionel Sambuc : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2713f4a2713aSLionel Sambuc FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2714f4a2713aSLionel Sambuc Beg(beg), HasVAListArg(hasVAListArg),
2715f4a2713aSLionel Sambuc Args(Args), FormatIdx(formatIdx),
2716f4a2713aSLionel Sambuc usesPositionalArgs(false), atFirstArg(true),
2717f4a2713aSLionel Sambuc inFunctionCall(inFunctionCall), CallType(callType),
2718f4a2713aSLionel Sambuc CheckedVarArgs(CheckedVarArgs) {
2719f4a2713aSLionel Sambuc CoveredArgs.resize(numDataArgs);
2720f4a2713aSLionel Sambuc CoveredArgs.reset();
2721f4a2713aSLionel Sambuc }
2722f4a2713aSLionel Sambuc
2723f4a2713aSLionel Sambuc void DoneProcessing();
2724f4a2713aSLionel Sambuc
2725f4a2713aSLionel Sambuc void HandleIncompleteSpecifier(const char *startSpecifier,
2726*0a6a1f1dSLionel Sambuc unsigned specifierLen) override;
2727f4a2713aSLionel Sambuc
2728f4a2713aSLionel Sambuc void HandleInvalidLengthModifier(
2729f4a2713aSLionel Sambuc const analyze_format_string::FormatSpecifier &FS,
2730f4a2713aSLionel Sambuc const analyze_format_string::ConversionSpecifier &CS,
2731*0a6a1f1dSLionel Sambuc const char *startSpecifier, unsigned specifierLen,
2732*0a6a1f1dSLionel Sambuc unsigned DiagID);
2733f4a2713aSLionel Sambuc
2734f4a2713aSLionel Sambuc void HandleNonStandardLengthModifier(
2735f4a2713aSLionel Sambuc const analyze_format_string::FormatSpecifier &FS,
2736f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen);
2737f4a2713aSLionel Sambuc
2738f4a2713aSLionel Sambuc void HandleNonStandardConversionSpecifier(
2739f4a2713aSLionel Sambuc const analyze_format_string::ConversionSpecifier &CS,
2740f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen);
2741f4a2713aSLionel Sambuc
2742*0a6a1f1dSLionel Sambuc void HandlePosition(const char *startPos, unsigned posLen) override;
2743f4a2713aSLionel Sambuc
2744*0a6a1f1dSLionel Sambuc void HandleInvalidPosition(const char *startSpecifier,
2745f4a2713aSLionel Sambuc unsigned specifierLen,
2746*0a6a1f1dSLionel Sambuc analyze_format_string::PositionContext p) override;
2747f4a2713aSLionel Sambuc
2748*0a6a1f1dSLionel Sambuc void HandleZeroPosition(const char *startPos, unsigned posLen) override;
2749f4a2713aSLionel Sambuc
2750*0a6a1f1dSLionel Sambuc void HandleNullChar(const char *nullCharacter) override;
2751f4a2713aSLionel Sambuc
2752f4a2713aSLionel Sambuc template <typename Range>
2753f4a2713aSLionel Sambuc static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2754f4a2713aSLionel Sambuc const Expr *ArgumentExpr,
2755f4a2713aSLionel Sambuc PartialDiagnostic PDiag,
2756f4a2713aSLionel Sambuc SourceLocation StringLoc,
2757f4a2713aSLionel Sambuc bool IsStringLocation, Range StringRange,
2758f4a2713aSLionel Sambuc ArrayRef<FixItHint> Fixit = None);
2759f4a2713aSLionel Sambuc
2760f4a2713aSLionel Sambuc protected:
2761f4a2713aSLionel Sambuc bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2762f4a2713aSLionel Sambuc const char *startSpec,
2763f4a2713aSLionel Sambuc unsigned specifierLen,
2764f4a2713aSLionel Sambuc const char *csStart, unsigned csLen);
2765f4a2713aSLionel Sambuc
2766f4a2713aSLionel Sambuc void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2767f4a2713aSLionel Sambuc const char *startSpec,
2768f4a2713aSLionel Sambuc unsigned specifierLen);
2769f4a2713aSLionel Sambuc
2770f4a2713aSLionel Sambuc SourceRange getFormatStringRange();
2771f4a2713aSLionel Sambuc CharSourceRange getSpecifierRange(const char *startSpecifier,
2772f4a2713aSLionel Sambuc unsigned specifierLen);
2773f4a2713aSLionel Sambuc SourceLocation getLocationOfByte(const char *x);
2774f4a2713aSLionel Sambuc
2775f4a2713aSLionel Sambuc const Expr *getDataArg(unsigned i) const;
2776f4a2713aSLionel Sambuc
2777f4a2713aSLionel Sambuc bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2778f4a2713aSLionel Sambuc const analyze_format_string::ConversionSpecifier &CS,
2779f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen,
2780f4a2713aSLionel Sambuc unsigned argIndex);
2781f4a2713aSLionel Sambuc
2782f4a2713aSLionel Sambuc template <typename Range>
2783f4a2713aSLionel Sambuc void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2784f4a2713aSLionel Sambuc bool IsStringLocation, Range StringRange,
2785f4a2713aSLionel Sambuc ArrayRef<FixItHint> Fixit = None);
2786f4a2713aSLionel Sambuc };
2787f4a2713aSLionel Sambuc }
2788f4a2713aSLionel Sambuc
getFormatStringRange()2789f4a2713aSLionel Sambuc SourceRange CheckFormatHandler::getFormatStringRange() {
2790f4a2713aSLionel Sambuc return OrigFormatExpr->getSourceRange();
2791f4a2713aSLionel Sambuc }
2792f4a2713aSLionel Sambuc
2793f4a2713aSLionel Sambuc CharSourceRange CheckFormatHandler::
getSpecifierRange(const char * startSpecifier,unsigned specifierLen)2794f4a2713aSLionel Sambuc getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2795f4a2713aSLionel Sambuc SourceLocation Start = getLocationOfByte(startSpecifier);
2796f4a2713aSLionel Sambuc SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2797f4a2713aSLionel Sambuc
2798f4a2713aSLionel Sambuc // Advance the end SourceLocation by one due to half-open ranges.
2799f4a2713aSLionel Sambuc End = End.getLocWithOffset(1);
2800f4a2713aSLionel Sambuc
2801f4a2713aSLionel Sambuc return CharSourceRange::getCharRange(Start, End);
2802f4a2713aSLionel Sambuc }
2803f4a2713aSLionel Sambuc
getLocationOfByte(const char * x)2804f4a2713aSLionel Sambuc SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2805f4a2713aSLionel Sambuc return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2806f4a2713aSLionel Sambuc }
2807f4a2713aSLionel Sambuc
HandleIncompleteSpecifier(const char * startSpecifier,unsigned specifierLen)2808f4a2713aSLionel Sambuc void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2809f4a2713aSLionel Sambuc unsigned specifierLen){
2810f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2811f4a2713aSLionel Sambuc getLocationOfByte(startSpecifier),
2812f4a2713aSLionel Sambuc /*IsStringLocation*/true,
2813f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen));
2814f4a2713aSLionel Sambuc }
2815f4a2713aSLionel Sambuc
HandleInvalidLengthModifier(const analyze_format_string::FormatSpecifier & FS,const analyze_format_string::ConversionSpecifier & CS,const char * startSpecifier,unsigned specifierLen,unsigned DiagID)2816f4a2713aSLionel Sambuc void CheckFormatHandler::HandleInvalidLengthModifier(
2817f4a2713aSLionel Sambuc const analyze_format_string::FormatSpecifier &FS,
2818f4a2713aSLionel Sambuc const analyze_format_string::ConversionSpecifier &CS,
2819f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2820f4a2713aSLionel Sambuc using namespace analyze_format_string;
2821f4a2713aSLionel Sambuc
2822f4a2713aSLionel Sambuc const LengthModifier &LM = FS.getLengthModifier();
2823f4a2713aSLionel Sambuc CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2824f4a2713aSLionel Sambuc
2825f4a2713aSLionel Sambuc // See if we know how to fix this length modifier.
2826f4a2713aSLionel Sambuc Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2827f4a2713aSLionel Sambuc if (FixedLM) {
2828f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2829f4a2713aSLionel Sambuc getLocationOfByte(LM.getStart()),
2830f4a2713aSLionel Sambuc /*IsStringLocation*/true,
2831f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen));
2832f4a2713aSLionel Sambuc
2833f4a2713aSLionel Sambuc S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2834f4a2713aSLionel Sambuc << FixedLM->toString()
2835f4a2713aSLionel Sambuc << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2836f4a2713aSLionel Sambuc
2837f4a2713aSLionel Sambuc } else {
2838f4a2713aSLionel Sambuc FixItHint Hint;
2839f4a2713aSLionel Sambuc if (DiagID == diag::warn_format_nonsensical_length)
2840f4a2713aSLionel Sambuc Hint = FixItHint::CreateRemoval(LMRange);
2841f4a2713aSLionel Sambuc
2842f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2843f4a2713aSLionel Sambuc getLocationOfByte(LM.getStart()),
2844f4a2713aSLionel Sambuc /*IsStringLocation*/true,
2845f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen),
2846f4a2713aSLionel Sambuc Hint);
2847f4a2713aSLionel Sambuc }
2848f4a2713aSLionel Sambuc }
2849f4a2713aSLionel Sambuc
HandleNonStandardLengthModifier(const analyze_format_string::FormatSpecifier & FS,const char * startSpecifier,unsigned specifierLen)2850f4a2713aSLionel Sambuc void CheckFormatHandler::HandleNonStandardLengthModifier(
2851f4a2713aSLionel Sambuc const analyze_format_string::FormatSpecifier &FS,
2852f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen) {
2853f4a2713aSLionel Sambuc using namespace analyze_format_string;
2854f4a2713aSLionel Sambuc
2855f4a2713aSLionel Sambuc const LengthModifier &LM = FS.getLengthModifier();
2856f4a2713aSLionel Sambuc CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2857f4a2713aSLionel Sambuc
2858f4a2713aSLionel Sambuc // See if we know how to fix this length modifier.
2859f4a2713aSLionel Sambuc Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2860f4a2713aSLionel Sambuc if (FixedLM) {
2861f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2862f4a2713aSLionel Sambuc << LM.toString() << 0,
2863f4a2713aSLionel Sambuc getLocationOfByte(LM.getStart()),
2864f4a2713aSLionel Sambuc /*IsStringLocation*/true,
2865f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen));
2866f4a2713aSLionel Sambuc
2867f4a2713aSLionel Sambuc S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2868f4a2713aSLionel Sambuc << FixedLM->toString()
2869f4a2713aSLionel Sambuc << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2870f4a2713aSLionel Sambuc
2871f4a2713aSLionel Sambuc } else {
2872f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2873f4a2713aSLionel Sambuc << LM.toString() << 0,
2874f4a2713aSLionel Sambuc getLocationOfByte(LM.getStart()),
2875f4a2713aSLionel Sambuc /*IsStringLocation*/true,
2876f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen));
2877f4a2713aSLionel Sambuc }
2878f4a2713aSLionel Sambuc }
2879f4a2713aSLionel Sambuc
HandleNonStandardConversionSpecifier(const analyze_format_string::ConversionSpecifier & CS,const char * startSpecifier,unsigned specifierLen)2880f4a2713aSLionel Sambuc void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2881f4a2713aSLionel Sambuc const analyze_format_string::ConversionSpecifier &CS,
2882f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen) {
2883f4a2713aSLionel Sambuc using namespace analyze_format_string;
2884f4a2713aSLionel Sambuc
2885f4a2713aSLionel Sambuc // See if we know how to fix this conversion specifier.
2886f4a2713aSLionel Sambuc Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2887f4a2713aSLionel Sambuc if (FixedCS) {
2888f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2889f4a2713aSLionel Sambuc << CS.toString() << /*conversion specifier*/1,
2890f4a2713aSLionel Sambuc getLocationOfByte(CS.getStart()),
2891f4a2713aSLionel Sambuc /*IsStringLocation*/true,
2892f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen));
2893f4a2713aSLionel Sambuc
2894f4a2713aSLionel Sambuc CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2895f4a2713aSLionel Sambuc S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2896f4a2713aSLionel Sambuc << FixedCS->toString()
2897f4a2713aSLionel Sambuc << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2898f4a2713aSLionel Sambuc } else {
2899f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2900f4a2713aSLionel Sambuc << CS.toString() << /*conversion specifier*/1,
2901f4a2713aSLionel Sambuc getLocationOfByte(CS.getStart()),
2902f4a2713aSLionel Sambuc /*IsStringLocation*/true,
2903f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen));
2904f4a2713aSLionel Sambuc }
2905f4a2713aSLionel Sambuc }
2906f4a2713aSLionel Sambuc
HandlePosition(const char * startPos,unsigned posLen)2907f4a2713aSLionel Sambuc void CheckFormatHandler::HandlePosition(const char *startPos,
2908f4a2713aSLionel Sambuc unsigned posLen) {
2909f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2910f4a2713aSLionel Sambuc getLocationOfByte(startPos),
2911f4a2713aSLionel Sambuc /*IsStringLocation*/true,
2912f4a2713aSLionel Sambuc getSpecifierRange(startPos, posLen));
2913f4a2713aSLionel Sambuc }
2914f4a2713aSLionel Sambuc
2915f4a2713aSLionel Sambuc void
HandleInvalidPosition(const char * startPos,unsigned posLen,analyze_format_string::PositionContext p)2916f4a2713aSLionel Sambuc CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2917f4a2713aSLionel Sambuc analyze_format_string::PositionContext p) {
2918f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2919f4a2713aSLionel Sambuc << (unsigned) p,
2920f4a2713aSLionel Sambuc getLocationOfByte(startPos), /*IsStringLocation*/true,
2921f4a2713aSLionel Sambuc getSpecifierRange(startPos, posLen));
2922f4a2713aSLionel Sambuc }
2923f4a2713aSLionel Sambuc
HandleZeroPosition(const char * startPos,unsigned posLen)2924f4a2713aSLionel Sambuc void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2925f4a2713aSLionel Sambuc unsigned posLen) {
2926f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2927f4a2713aSLionel Sambuc getLocationOfByte(startPos),
2928f4a2713aSLionel Sambuc /*IsStringLocation*/true,
2929f4a2713aSLionel Sambuc getSpecifierRange(startPos, posLen));
2930f4a2713aSLionel Sambuc }
2931f4a2713aSLionel Sambuc
HandleNullChar(const char * nullCharacter)2932f4a2713aSLionel Sambuc void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2933f4a2713aSLionel Sambuc if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2934f4a2713aSLionel Sambuc // The presence of a null character is likely an error.
2935f4a2713aSLionel Sambuc EmitFormatDiagnostic(
2936f4a2713aSLionel Sambuc S.PDiag(diag::warn_printf_format_string_contains_null_char),
2937f4a2713aSLionel Sambuc getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2938f4a2713aSLionel Sambuc getFormatStringRange());
2939f4a2713aSLionel Sambuc }
2940f4a2713aSLionel Sambuc }
2941f4a2713aSLionel Sambuc
2942f4a2713aSLionel Sambuc // Note that this may return NULL if there was an error parsing or building
2943f4a2713aSLionel Sambuc // one of the argument expressions.
getDataArg(unsigned i) const2944f4a2713aSLionel Sambuc const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2945f4a2713aSLionel Sambuc return Args[FirstDataArg + i];
2946f4a2713aSLionel Sambuc }
2947f4a2713aSLionel Sambuc
DoneProcessing()2948f4a2713aSLionel Sambuc void CheckFormatHandler::DoneProcessing() {
2949f4a2713aSLionel Sambuc // Does the number of data arguments exceed the number of
2950f4a2713aSLionel Sambuc // format conversions in the format string?
2951f4a2713aSLionel Sambuc if (!HasVAListArg) {
2952f4a2713aSLionel Sambuc // Find any arguments that weren't covered.
2953f4a2713aSLionel Sambuc CoveredArgs.flip();
2954f4a2713aSLionel Sambuc signed notCoveredArg = CoveredArgs.find_first();
2955f4a2713aSLionel Sambuc if (notCoveredArg >= 0) {
2956f4a2713aSLionel Sambuc assert((unsigned)notCoveredArg < NumDataArgs);
2957f4a2713aSLionel Sambuc if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2958f4a2713aSLionel Sambuc SourceLocation Loc = E->getLocStart();
2959f4a2713aSLionel Sambuc if (!S.getSourceManager().isInSystemMacro(Loc)) {
2960f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2961f4a2713aSLionel Sambuc Loc, /*IsStringLocation*/false,
2962f4a2713aSLionel Sambuc getFormatStringRange());
2963f4a2713aSLionel Sambuc }
2964f4a2713aSLionel Sambuc }
2965f4a2713aSLionel Sambuc }
2966f4a2713aSLionel Sambuc }
2967f4a2713aSLionel Sambuc }
2968f4a2713aSLionel Sambuc
2969f4a2713aSLionel Sambuc bool
HandleInvalidConversionSpecifier(unsigned argIndex,SourceLocation Loc,const char * startSpec,unsigned specifierLen,const char * csStart,unsigned csLen)2970f4a2713aSLionel Sambuc CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2971f4a2713aSLionel Sambuc SourceLocation Loc,
2972f4a2713aSLionel Sambuc const char *startSpec,
2973f4a2713aSLionel Sambuc unsigned specifierLen,
2974f4a2713aSLionel Sambuc const char *csStart,
2975f4a2713aSLionel Sambuc unsigned csLen) {
2976f4a2713aSLionel Sambuc
2977f4a2713aSLionel Sambuc bool keepGoing = true;
2978f4a2713aSLionel Sambuc if (argIndex < NumDataArgs) {
2979f4a2713aSLionel Sambuc // Consider the argument coverered, even though the specifier doesn't
2980f4a2713aSLionel Sambuc // make sense.
2981f4a2713aSLionel Sambuc CoveredArgs.set(argIndex);
2982f4a2713aSLionel Sambuc }
2983f4a2713aSLionel Sambuc else {
2984f4a2713aSLionel Sambuc // If argIndex exceeds the number of data arguments we
2985f4a2713aSLionel Sambuc // don't issue a warning because that is just a cascade of warnings (and
2986f4a2713aSLionel Sambuc // they may have intended '%%' anyway). We don't want to continue processing
2987f4a2713aSLionel Sambuc // the format string after this point, however, as we will like just get
2988f4a2713aSLionel Sambuc // gibberish when trying to match arguments.
2989f4a2713aSLionel Sambuc keepGoing = false;
2990f4a2713aSLionel Sambuc }
2991f4a2713aSLionel Sambuc
2992f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2993f4a2713aSLionel Sambuc << StringRef(csStart, csLen),
2994f4a2713aSLionel Sambuc Loc, /*IsStringLocation*/true,
2995f4a2713aSLionel Sambuc getSpecifierRange(startSpec, specifierLen));
2996f4a2713aSLionel Sambuc
2997f4a2713aSLionel Sambuc return keepGoing;
2998f4a2713aSLionel Sambuc }
2999f4a2713aSLionel Sambuc
3000f4a2713aSLionel Sambuc void
HandlePositionalNonpositionalArgs(SourceLocation Loc,const char * startSpec,unsigned specifierLen)3001f4a2713aSLionel Sambuc CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3002f4a2713aSLionel Sambuc const char *startSpec,
3003f4a2713aSLionel Sambuc unsigned specifierLen) {
3004f4a2713aSLionel Sambuc EmitFormatDiagnostic(
3005f4a2713aSLionel Sambuc S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3006f4a2713aSLionel Sambuc Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3007f4a2713aSLionel Sambuc }
3008f4a2713aSLionel Sambuc
3009f4a2713aSLionel Sambuc bool
CheckNumArgs(const analyze_format_string::FormatSpecifier & FS,const analyze_format_string::ConversionSpecifier & CS,const char * startSpecifier,unsigned specifierLen,unsigned argIndex)3010f4a2713aSLionel Sambuc CheckFormatHandler::CheckNumArgs(
3011f4a2713aSLionel Sambuc const analyze_format_string::FormatSpecifier &FS,
3012f4a2713aSLionel Sambuc const analyze_format_string::ConversionSpecifier &CS,
3013f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3014f4a2713aSLionel Sambuc
3015f4a2713aSLionel Sambuc if (argIndex >= NumDataArgs) {
3016f4a2713aSLionel Sambuc PartialDiagnostic PDiag = FS.usesPositionalArg()
3017f4a2713aSLionel Sambuc ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3018f4a2713aSLionel Sambuc << (argIndex+1) << NumDataArgs)
3019f4a2713aSLionel Sambuc : S.PDiag(diag::warn_printf_insufficient_data_args);
3020f4a2713aSLionel Sambuc EmitFormatDiagnostic(
3021f4a2713aSLionel Sambuc PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3022f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen));
3023f4a2713aSLionel Sambuc return false;
3024f4a2713aSLionel Sambuc }
3025f4a2713aSLionel Sambuc return true;
3026f4a2713aSLionel Sambuc }
3027f4a2713aSLionel Sambuc
3028f4a2713aSLionel Sambuc template<typename Range>
EmitFormatDiagnostic(PartialDiagnostic PDiag,SourceLocation Loc,bool IsStringLocation,Range StringRange,ArrayRef<FixItHint> FixIt)3029f4a2713aSLionel Sambuc void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3030f4a2713aSLionel Sambuc SourceLocation Loc,
3031f4a2713aSLionel Sambuc bool IsStringLocation,
3032f4a2713aSLionel Sambuc Range StringRange,
3033f4a2713aSLionel Sambuc ArrayRef<FixItHint> FixIt) {
3034f4a2713aSLionel Sambuc EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
3035f4a2713aSLionel Sambuc Loc, IsStringLocation, StringRange, FixIt);
3036f4a2713aSLionel Sambuc }
3037f4a2713aSLionel Sambuc
3038f4a2713aSLionel Sambuc /// \brief If the format string is not within the funcion call, emit a note
3039f4a2713aSLionel Sambuc /// so that the function call and string are in diagnostic messages.
3040f4a2713aSLionel Sambuc ///
3041f4a2713aSLionel Sambuc /// \param InFunctionCall if true, the format string is within the function
3042f4a2713aSLionel Sambuc /// call and only one diagnostic message will be produced. Otherwise, an
3043f4a2713aSLionel Sambuc /// extra note will be emitted pointing to location of the format string.
3044f4a2713aSLionel Sambuc ///
3045f4a2713aSLionel Sambuc /// \param ArgumentExpr the expression that is passed as the format string
3046f4a2713aSLionel Sambuc /// argument in the function call. Used for getting locations when two
3047f4a2713aSLionel Sambuc /// diagnostics are emitted.
3048f4a2713aSLionel Sambuc ///
3049f4a2713aSLionel Sambuc /// \param PDiag the callee should already have provided any strings for the
3050f4a2713aSLionel Sambuc /// diagnostic message. This function only adds locations and fixits
3051f4a2713aSLionel Sambuc /// to diagnostics.
3052f4a2713aSLionel Sambuc ///
3053f4a2713aSLionel Sambuc /// \param Loc primary location for diagnostic. If two diagnostics are
3054f4a2713aSLionel Sambuc /// required, one will be at Loc and a new SourceLocation will be created for
3055f4a2713aSLionel Sambuc /// the other one.
3056f4a2713aSLionel Sambuc ///
3057f4a2713aSLionel Sambuc /// \param IsStringLocation if true, Loc points to the format string should be
3058f4a2713aSLionel Sambuc /// used for the note. Otherwise, Loc points to the argument list and will
3059f4a2713aSLionel Sambuc /// be used with PDiag.
3060f4a2713aSLionel Sambuc ///
3061f4a2713aSLionel Sambuc /// \param StringRange some or all of the string to highlight. This is
3062f4a2713aSLionel Sambuc /// templated so it can accept either a CharSourceRange or a SourceRange.
3063f4a2713aSLionel Sambuc ///
3064f4a2713aSLionel Sambuc /// \param FixIt optional fix it hint for the format string.
3065f4a2713aSLionel Sambuc template<typename Range>
EmitFormatDiagnostic(Sema & S,bool InFunctionCall,const Expr * ArgumentExpr,PartialDiagnostic PDiag,SourceLocation Loc,bool IsStringLocation,Range StringRange,ArrayRef<FixItHint> FixIt)3066f4a2713aSLionel Sambuc void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3067f4a2713aSLionel Sambuc const Expr *ArgumentExpr,
3068f4a2713aSLionel Sambuc PartialDiagnostic PDiag,
3069f4a2713aSLionel Sambuc SourceLocation Loc,
3070f4a2713aSLionel Sambuc bool IsStringLocation,
3071f4a2713aSLionel Sambuc Range StringRange,
3072f4a2713aSLionel Sambuc ArrayRef<FixItHint> FixIt) {
3073f4a2713aSLionel Sambuc if (InFunctionCall) {
3074f4a2713aSLionel Sambuc const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3075f4a2713aSLionel Sambuc D << StringRange;
3076f4a2713aSLionel Sambuc for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3077f4a2713aSLionel Sambuc I != E; ++I) {
3078f4a2713aSLionel Sambuc D << *I;
3079f4a2713aSLionel Sambuc }
3080f4a2713aSLionel Sambuc } else {
3081f4a2713aSLionel Sambuc S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3082f4a2713aSLionel Sambuc << ArgumentExpr->getSourceRange();
3083f4a2713aSLionel Sambuc
3084f4a2713aSLionel Sambuc const Sema::SemaDiagnosticBuilder &Note =
3085f4a2713aSLionel Sambuc S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3086f4a2713aSLionel Sambuc diag::note_format_string_defined);
3087f4a2713aSLionel Sambuc
3088f4a2713aSLionel Sambuc Note << StringRange;
3089f4a2713aSLionel Sambuc for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3090f4a2713aSLionel Sambuc I != E; ++I) {
3091f4a2713aSLionel Sambuc Note << *I;
3092f4a2713aSLionel Sambuc }
3093f4a2713aSLionel Sambuc }
3094f4a2713aSLionel Sambuc }
3095f4a2713aSLionel Sambuc
3096f4a2713aSLionel Sambuc //===--- CHECK: Printf format string checking ------------------------------===//
3097f4a2713aSLionel Sambuc
3098f4a2713aSLionel Sambuc namespace {
3099f4a2713aSLionel Sambuc class CheckPrintfHandler : public CheckFormatHandler {
3100f4a2713aSLionel Sambuc bool ObjCContext;
3101f4a2713aSLionel Sambuc public:
CheckPrintfHandler(Sema & s,const StringLiteral * fexpr,const Expr * origFormatExpr,unsigned firstDataArg,unsigned numDataArgs,bool isObjC,const char * beg,bool hasVAListArg,ArrayRef<const Expr * > Args,unsigned formatIdx,bool inFunctionCall,Sema::VariadicCallType CallType,llvm::SmallBitVector & CheckedVarArgs)3102f4a2713aSLionel Sambuc CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3103f4a2713aSLionel Sambuc const Expr *origFormatExpr, unsigned firstDataArg,
3104f4a2713aSLionel Sambuc unsigned numDataArgs, bool isObjC,
3105f4a2713aSLionel Sambuc const char *beg, bool hasVAListArg,
3106f4a2713aSLionel Sambuc ArrayRef<const Expr *> Args,
3107f4a2713aSLionel Sambuc unsigned formatIdx, bool inFunctionCall,
3108f4a2713aSLionel Sambuc Sema::VariadicCallType CallType,
3109f4a2713aSLionel Sambuc llvm::SmallBitVector &CheckedVarArgs)
3110f4a2713aSLionel Sambuc : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3111f4a2713aSLionel Sambuc numDataArgs, beg, hasVAListArg, Args,
3112f4a2713aSLionel Sambuc formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3113f4a2713aSLionel Sambuc ObjCContext(isObjC)
3114f4a2713aSLionel Sambuc {}
3115f4a2713aSLionel Sambuc
3116f4a2713aSLionel Sambuc
3117f4a2713aSLionel Sambuc bool HandleInvalidPrintfConversionSpecifier(
3118f4a2713aSLionel Sambuc const analyze_printf::PrintfSpecifier &FS,
3119f4a2713aSLionel Sambuc const char *startSpecifier,
3120*0a6a1f1dSLionel Sambuc unsigned specifierLen) override;
3121f4a2713aSLionel Sambuc
3122f4a2713aSLionel Sambuc bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3123f4a2713aSLionel Sambuc const char *startSpecifier,
3124*0a6a1f1dSLionel Sambuc unsigned specifierLen) override;
3125f4a2713aSLionel Sambuc bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3126f4a2713aSLionel Sambuc const char *StartSpecifier,
3127f4a2713aSLionel Sambuc unsigned SpecifierLen,
3128f4a2713aSLionel Sambuc const Expr *E);
3129f4a2713aSLionel Sambuc
3130f4a2713aSLionel Sambuc bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3131f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen);
3132f4a2713aSLionel Sambuc void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3133f4a2713aSLionel Sambuc const analyze_printf::OptionalAmount &Amt,
3134f4a2713aSLionel Sambuc unsigned type,
3135f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen);
3136f4a2713aSLionel Sambuc void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3137f4a2713aSLionel Sambuc const analyze_printf::OptionalFlag &flag,
3138f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen);
3139f4a2713aSLionel Sambuc void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3140f4a2713aSLionel Sambuc const analyze_printf::OptionalFlag &ignoredFlag,
3141f4a2713aSLionel Sambuc const analyze_printf::OptionalFlag &flag,
3142f4a2713aSLionel Sambuc const char *startSpecifier, unsigned specifierLen);
3143f4a2713aSLionel Sambuc bool checkForCStrMembers(const analyze_printf::ArgType &AT,
3144*0a6a1f1dSLionel Sambuc const Expr *E);
3145f4a2713aSLionel Sambuc
3146f4a2713aSLionel Sambuc };
3147f4a2713aSLionel Sambuc }
3148f4a2713aSLionel Sambuc
HandleInvalidPrintfConversionSpecifier(const analyze_printf::PrintfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)3149f4a2713aSLionel Sambuc bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3150f4a2713aSLionel Sambuc const analyze_printf::PrintfSpecifier &FS,
3151f4a2713aSLionel Sambuc const char *startSpecifier,
3152f4a2713aSLionel Sambuc unsigned specifierLen) {
3153f4a2713aSLionel Sambuc const analyze_printf::PrintfConversionSpecifier &CS =
3154f4a2713aSLionel Sambuc FS.getConversionSpecifier();
3155f4a2713aSLionel Sambuc
3156f4a2713aSLionel Sambuc return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3157f4a2713aSLionel Sambuc getLocationOfByte(CS.getStart()),
3158f4a2713aSLionel Sambuc startSpecifier, specifierLen,
3159f4a2713aSLionel Sambuc CS.getStart(), CS.getLength());
3160f4a2713aSLionel Sambuc }
3161f4a2713aSLionel Sambuc
HandleAmount(const analyze_format_string::OptionalAmount & Amt,unsigned k,const char * startSpecifier,unsigned specifierLen)3162f4a2713aSLionel Sambuc bool CheckPrintfHandler::HandleAmount(
3163f4a2713aSLionel Sambuc const analyze_format_string::OptionalAmount &Amt,
3164f4a2713aSLionel Sambuc unsigned k, const char *startSpecifier,
3165f4a2713aSLionel Sambuc unsigned specifierLen) {
3166f4a2713aSLionel Sambuc
3167f4a2713aSLionel Sambuc if (Amt.hasDataArgument()) {
3168f4a2713aSLionel Sambuc if (!HasVAListArg) {
3169f4a2713aSLionel Sambuc unsigned argIndex = Amt.getArgIndex();
3170f4a2713aSLionel Sambuc if (argIndex >= NumDataArgs) {
3171f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3172f4a2713aSLionel Sambuc << k,
3173f4a2713aSLionel Sambuc getLocationOfByte(Amt.getStart()),
3174f4a2713aSLionel Sambuc /*IsStringLocation*/true,
3175f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen));
3176f4a2713aSLionel Sambuc // Don't do any more checking. We will just emit
3177f4a2713aSLionel Sambuc // spurious errors.
3178f4a2713aSLionel Sambuc return false;
3179f4a2713aSLionel Sambuc }
3180f4a2713aSLionel Sambuc
3181f4a2713aSLionel Sambuc // Type check the data argument. It should be an 'int'.
3182f4a2713aSLionel Sambuc // Although not in conformance with C99, we also allow the argument to be
3183f4a2713aSLionel Sambuc // an 'unsigned int' as that is a reasonably safe case. GCC also
3184f4a2713aSLionel Sambuc // doesn't emit a warning for that case.
3185f4a2713aSLionel Sambuc CoveredArgs.set(argIndex);
3186f4a2713aSLionel Sambuc const Expr *Arg = getDataArg(argIndex);
3187f4a2713aSLionel Sambuc if (!Arg)
3188f4a2713aSLionel Sambuc return false;
3189f4a2713aSLionel Sambuc
3190f4a2713aSLionel Sambuc QualType T = Arg->getType();
3191f4a2713aSLionel Sambuc
3192f4a2713aSLionel Sambuc const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3193f4a2713aSLionel Sambuc assert(AT.isValid());
3194f4a2713aSLionel Sambuc
3195f4a2713aSLionel Sambuc if (!AT.matchesType(S.Context, T)) {
3196f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
3197f4a2713aSLionel Sambuc << k << AT.getRepresentativeTypeName(S.Context)
3198f4a2713aSLionel Sambuc << T << Arg->getSourceRange(),
3199f4a2713aSLionel Sambuc getLocationOfByte(Amt.getStart()),
3200f4a2713aSLionel Sambuc /*IsStringLocation*/true,
3201f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen));
3202f4a2713aSLionel Sambuc // Don't do any more checking. We will just emit
3203f4a2713aSLionel Sambuc // spurious errors.
3204f4a2713aSLionel Sambuc return false;
3205f4a2713aSLionel Sambuc }
3206f4a2713aSLionel Sambuc }
3207f4a2713aSLionel Sambuc }
3208f4a2713aSLionel Sambuc return true;
3209f4a2713aSLionel Sambuc }
3210f4a2713aSLionel Sambuc
HandleInvalidAmount(const analyze_printf::PrintfSpecifier & FS,const analyze_printf::OptionalAmount & Amt,unsigned type,const char * startSpecifier,unsigned specifierLen)3211f4a2713aSLionel Sambuc void CheckPrintfHandler::HandleInvalidAmount(
3212f4a2713aSLionel Sambuc const analyze_printf::PrintfSpecifier &FS,
3213f4a2713aSLionel Sambuc const analyze_printf::OptionalAmount &Amt,
3214f4a2713aSLionel Sambuc unsigned type,
3215f4a2713aSLionel Sambuc const char *startSpecifier,
3216f4a2713aSLionel Sambuc unsigned specifierLen) {
3217f4a2713aSLionel Sambuc const analyze_printf::PrintfConversionSpecifier &CS =
3218f4a2713aSLionel Sambuc FS.getConversionSpecifier();
3219f4a2713aSLionel Sambuc
3220f4a2713aSLionel Sambuc FixItHint fixit =
3221f4a2713aSLionel Sambuc Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3222f4a2713aSLionel Sambuc ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3223f4a2713aSLionel Sambuc Amt.getConstantLength()))
3224f4a2713aSLionel Sambuc : FixItHint();
3225f4a2713aSLionel Sambuc
3226f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3227f4a2713aSLionel Sambuc << type << CS.toString(),
3228f4a2713aSLionel Sambuc getLocationOfByte(Amt.getStart()),
3229f4a2713aSLionel Sambuc /*IsStringLocation*/true,
3230f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen),
3231f4a2713aSLionel Sambuc fixit);
3232f4a2713aSLionel Sambuc }
3233f4a2713aSLionel Sambuc
HandleFlag(const analyze_printf::PrintfSpecifier & FS,const analyze_printf::OptionalFlag & flag,const char * startSpecifier,unsigned specifierLen)3234f4a2713aSLionel Sambuc void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3235f4a2713aSLionel Sambuc const analyze_printf::OptionalFlag &flag,
3236f4a2713aSLionel Sambuc const char *startSpecifier,
3237f4a2713aSLionel Sambuc unsigned specifierLen) {
3238f4a2713aSLionel Sambuc // Warn about pointless flag with a fixit removal.
3239f4a2713aSLionel Sambuc const analyze_printf::PrintfConversionSpecifier &CS =
3240f4a2713aSLionel Sambuc FS.getConversionSpecifier();
3241f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3242f4a2713aSLionel Sambuc << flag.toString() << CS.toString(),
3243f4a2713aSLionel Sambuc getLocationOfByte(flag.getPosition()),
3244f4a2713aSLionel Sambuc /*IsStringLocation*/true,
3245f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen),
3246f4a2713aSLionel Sambuc FixItHint::CreateRemoval(
3247f4a2713aSLionel Sambuc getSpecifierRange(flag.getPosition(), 1)));
3248f4a2713aSLionel Sambuc }
3249f4a2713aSLionel Sambuc
HandleIgnoredFlag(const analyze_printf::PrintfSpecifier & FS,const analyze_printf::OptionalFlag & ignoredFlag,const analyze_printf::OptionalFlag & flag,const char * startSpecifier,unsigned specifierLen)3250f4a2713aSLionel Sambuc void CheckPrintfHandler::HandleIgnoredFlag(
3251f4a2713aSLionel Sambuc const analyze_printf::PrintfSpecifier &FS,
3252f4a2713aSLionel Sambuc const analyze_printf::OptionalFlag &ignoredFlag,
3253f4a2713aSLionel Sambuc const analyze_printf::OptionalFlag &flag,
3254f4a2713aSLionel Sambuc const char *startSpecifier,
3255f4a2713aSLionel Sambuc unsigned specifierLen) {
3256f4a2713aSLionel Sambuc // Warn about ignored flag with a fixit removal.
3257f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3258f4a2713aSLionel Sambuc << ignoredFlag.toString() << flag.toString(),
3259f4a2713aSLionel Sambuc getLocationOfByte(ignoredFlag.getPosition()),
3260f4a2713aSLionel Sambuc /*IsStringLocation*/true,
3261f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen),
3262f4a2713aSLionel Sambuc FixItHint::CreateRemoval(
3263f4a2713aSLionel Sambuc getSpecifierRange(ignoredFlag.getPosition(), 1)));
3264f4a2713aSLionel Sambuc }
3265f4a2713aSLionel Sambuc
3266f4a2713aSLionel Sambuc // Determines if the specified is a C++ class or struct containing
3267f4a2713aSLionel Sambuc // a member with the specified name and kind (e.g. a CXXMethodDecl named
3268f4a2713aSLionel Sambuc // "c_str()").
3269f4a2713aSLionel Sambuc template<typename MemberKind>
3270f4a2713aSLionel Sambuc static llvm::SmallPtrSet<MemberKind*, 1>
CXXRecordMembersNamed(StringRef Name,Sema & S,QualType Ty)3271f4a2713aSLionel Sambuc CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3272f4a2713aSLionel Sambuc const RecordType *RT = Ty->getAs<RecordType>();
3273f4a2713aSLionel Sambuc llvm::SmallPtrSet<MemberKind*, 1> Results;
3274f4a2713aSLionel Sambuc
3275f4a2713aSLionel Sambuc if (!RT)
3276f4a2713aSLionel Sambuc return Results;
3277f4a2713aSLionel Sambuc const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3278*0a6a1f1dSLionel Sambuc if (!RD || !RD->getDefinition())
3279f4a2713aSLionel Sambuc return Results;
3280f4a2713aSLionel Sambuc
3281*0a6a1f1dSLionel Sambuc LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
3282f4a2713aSLionel Sambuc Sema::LookupMemberName);
3283*0a6a1f1dSLionel Sambuc R.suppressDiagnostics();
3284f4a2713aSLionel Sambuc
3285f4a2713aSLionel Sambuc // We just need to include all members of the right kind turned up by the
3286f4a2713aSLionel Sambuc // filter, at this point.
3287f4a2713aSLionel Sambuc if (S.LookupQualifiedName(R, RT->getDecl()))
3288f4a2713aSLionel Sambuc for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3289f4a2713aSLionel Sambuc NamedDecl *decl = (*I)->getUnderlyingDecl();
3290f4a2713aSLionel Sambuc if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3291f4a2713aSLionel Sambuc Results.insert(FK);
3292f4a2713aSLionel Sambuc }
3293f4a2713aSLionel Sambuc return Results;
3294f4a2713aSLionel Sambuc }
3295f4a2713aSLionel Sambuc
3296*0a6a1f1dSLionel Sambuc /// Check if we could call '.c_str()' on an object.
3297*0a6a1f1dSLionel Sambuc ///
3298*0a6a1f1dSLionel Sambuc /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3299*0a6a1f1dSLionel Sambuc /// allow the call, or if it would be ambiguous).
hasCStrMethod(const Expr * E)3300*0a6a1f1dSLionel Sambuc bool Sema::hasCStrMethod(const Expr *E) {
3301*0a6a1f1dSLionel Sambuc typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3302*0a6a1f1dSLionel Sambuc MethodSet Results =
3303*0a6a1f1dSLionel Sambuc CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3304*0a6a1f1dSLionel Sambuc for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3305*0a6a1f1dSLionel Sambuc MI != ME; ++MI)
3306*0a6a1f1dSLionel Sambuc if ((*MI)->getMinRequiredArguments() == 0)
3307*0a6a1f1dSLionel Sambuc return true;
3308*0a6a1f1dSLionel Sambuc return false;
3309*0a6a1f1dSLionel Sambuc }
3310*0a6a1f1dSLionel Sambuc
3311f4a2713aSLionel Sambuc // Check if a (w)string was passed when a (w)char* was needed, and offer a
3312f4a2713aSLionel Sambuc // better diagnostic if so. AT is assumed to be valid.
3313f4a2713aSLionel Sambuc // Returns true when a c_str() conversion method is found.
checkForCStrMembers(const analyze_printf::ArgType & AT,const Expr * E)3314f4a2713aSLionel Sambuc bool CheckPrintfHandler::checkForCStrMembers(
3315*0a6a1f1dSLionel Sambuc const analyze_printf::ArgType &AT, const Expr *E) {
3316f4a2713aSLionel Sambuc typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3317f4a2713aSLionel Sambuc
3318f4a2713aSLionel Sambuc MethodSet Results =
3319f4a2713aSLionel Sambuc CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3320f4a2713aSLionel Sambuc
3321f4a2713aSLionel Sambuc for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3322f4a2713aSLionel Sambuc MI != ME; ++MI) {
3323f4a2713aSLionel Sambuc const CXXMethodDecl *Method = *MI;
3324*0a6a1f1dSLionel Sambuc if (Method->getMinRequiredArguments() == 0 &&
3325*0a6a1f1dSLionel Sambuc AT.matchesType(S.Context, Method->getReturnType())) {
3326f4a2713aSLionel Sambuc // FIXME: Suggest parens if the expression needs them.
3327*0a6a1f1dSLionel Sambuc SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
3328f4a2713aSLionel Sambuc S.Diag(E->getLocStart(), diag::note_printf_c_str)
3329f4a2713aSLionel Sambuc << "c_str()"
3330f4a2713aSLionel Sambuc << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3331f4a2713aSLionel Sambuc return true;
3332f4a2713aSLionel Sambuc }
3333f4a2713aSLionel Sambuc }
3334f4a2713aSLionel Sambuc
3335f4a2713aSLionel Sambuc return false;
3336f4a2713aSLionel Sambuc }
3337f4a2713aSLionel Sambuc
3338f4a2713aSLionel Sambuc bool
HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)3339f4a2713aSLionel Sambuc CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
3340f4a2713aSLionel Sambuc &FS,
3341f4a2713aSLionel Sambuc const char *startSpecifier,
3342f4a2713aSLionel Sambuc unsigned specifierLen) {
3343f4a2713aSLionel Sambuc
3344f4a2713aSLionel Sambuc using namespace analyze_format_string;
3345f4a2713aSLionel Sambuc using namespace analyze_printf;
3346f4a2713aSLionel Sambuc const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
3347f4a2713aSLionel Sambuc
3348f4a2713aSLionel Sambuc if (FS.consumesDataArgument()) {
3349f4a2713aSLionel Sambuc if (atFirstArg) {
3350f4a2713aSLionel Sambuc atFirstArg = false;
3351f4a2713aSLionel Sambuc usesPositionalArgs = FS.usesPositionalArg();
3352f4a2713aSLionel Sambuc }
3353f4a2713aSLionel Sambuc else if (usesPositionalArgs != FS.usesPositionalArg()) {
3354f4a2713aSLionel Sambuc HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3355f4a2713aSLionel Sambuc startSpecifier, specifierLen);
3356f4a2713aSLionel Sambuc return false;
3357f4a2713aSLionel Sambuc }
3358f4a2713aSLionel Sambuc }
3359f4a2713aSLionel Sambuc
3360f4a2713aSLionel Sambuc // First check if the field width, precision, and conversion specifier
3361f4a2713aSLionel Sambuc // have matching data arguments.
3362f4a2713aSLionel Sambuc if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3363f4a2713aSLionel Sambuc startSpecifier, specifierLen)) {
3364f4a2713aSLionel Sambuc return false;
3365f4a2713aSLionel Sambuc }
3366f4a2713aSLionel Sambuc
3367f4a2713aSLionel Sambuc if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3368f4a2713aSLionel Sambuc startSpecifier, specifierLen)) {
3369f4a2713aSLionel Sambuc return false;
3370f4a2713aSLionel Sambuc }
3371f4a2713aSLionel Sambuc
3372f4a2713aSLionel Sambuc if (!CS.consumesDataArgument()) {
3373f4a2713aSLionel Sambuc // FIXME: Technically specifying a precision or field width here
3374f4a2713aSLionel Sambuc // makes no sense. Worth issuing a warning at some point.
3375f4a2713aSLionel Sambuc return true;
3376f4a2713aSLionel Sambuc }
3377f4a2713aSLionel Sambuc
3378f4a2713aSLionel Sambuc // Consume the argument.
3379f4a2713aSLionel Sambuc unsigned argIndex = FS.getArgIndex();
3380f4a2713aSLionel Sambuc if (argIndex < NumDataArgs) {
3381f4a2713aSLionel Sambuc // The check to see if the argIndex is valid will come later.
3382f4a2713aSLionel Sambuc // We set the bit here because we may exit early from this
3383f4a2713aSLionel Sambuc // function if we encounter some other error.
3384f4a2713aSLionel Sambuc CoveredArgs.set(argIndex);
3385f4a2713aSLionel Sambuc }
3386f4a2713aSLionel Sambuc
3387f4a2713aSLionel Sambuc // Check for using an Objective-C specific conversion specifier
3388f4a2713aSLionel Sambuc // in a non-ObjC literal.
3389f4a2713aSLionel Sambuc if (!ObjCContext && CS.isObjCArg()) {
3390f4a2713aSLionel Sambuc return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3391f4a2713aSLionel Sambuc specifierLen);
3392f4a2713aSLionel Sambuc }
3393f4a2713aSLionel Sambuc
3394f4a2713aSLionel Sambuc // Check for invalid use of field width
3395f4a2713aSLionel Sambuc if (!FS.hasValidFieldWidth()) {
3396f4a2713aSLionel Sambuc HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3397f4a2713aSLionel Sambuc startSpecifier, specifierLen);
3398f4a2713aSLionel Sambuc }
3399f4a2713aSLionel Sambuc
3400f4a2713aSLionel Sambuc // Check for invalid use of precision
3401f4a2713aSLionel Sambuc if (!FS.hasValidPrecision()) {
3402f4a2713aSLionel Sambuc HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3403f4a2713aSLionel Sambuc startSpecifier, specifierLen);
3404f4a2713aSLionel Sambuc }
3405f4a2713aSLionel Sambuc
3406f4a2713aSLionel Sambuc // Check each flag does not conflict with any other component.
3407f4a2713aSLionel Sambuc if (!FS.hasValidThousandsGroupingPrefix())
3408f4a2713aSLionel Sambuc HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3409f4a2713aSLionel Sambuc if (!FS.hasValidLeadingZeros())
3410f4a2713aSLionel Sambuc HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3411f4a2713aSLionel Sambuc if (!FS.hasValidPlusPrefix())
3412f4a2713aSLionel Sambuc HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3413f4a2713aSLionel Sambuc if (!FS.hasValidSpacePrefix())
3414f4a2713aSLionel Sambuc HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3415f4a2713aSLionel Sambuc if (!FS.hasValidAlternativeForm())
3416f4a2713aSLionel Sambuc HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3417f4a2713aSLionel Sambuc if (!FS.hasValidLeftJustified())
3418f4a2713aSLionel Sambuc HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3419f4a2713aSLionel Sambuc
3420f4a2713aSLionel Sambuc // Check that flags are not ignored by another flag
3421f4a2713aSLionel Sambuc if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3422f4a2713aSLionel Sambuc HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3423f4a2713aSLionel Sambuc startSpecifier, specifierLen);
3424f4a2713aSLionel Sambuc if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3425f4a2713aSLionel Sambuc HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3426f4a2713aSLionel Sambuc startSpecifier, specifierLen);
3427f4a2713aSLionel Sambuc
3428f4a2713aSLionel Sambuc // Check the length modifier is valid with the given conversion specifier.
3429f4a2713aSLionel Sambuc if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3430f4a2713aSLionel Sambuc HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3431f4a2713aSLionel Sambuc diag::warn_format_nonsensical_length);
3432f4a2713aSLionel Sambuc else if (!FS.hasStandardLengthModifier())
3433f4a2713aSLionel Sambuc HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3434f4a2713aSLionel Sambuc else if (!FS.hasStandardLengthConversionCombination())
3435f4a2713aSLionel Sambuc HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3436f4a2713aSLionel Sambuc diag::warn_format_non_standard_conversion_spec);
3437f4a2713aSLionel Sambuc
3438f4a2713aSLionel Sambuc if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3439f4a2713aSLionel Sambuc HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3440f4a2713aSLionel Sambuc
3441f4a2713aSLionel Sambuc // The remaining checks depend on the data arguments.
3442f4a2713aSLionel Sambuc if (HasVAListArg)
3443f4a2713aSLionel Sambuc return true;
3444f4a2713aSLionel Sambuc
3445f4a2713aSLionel Sambuc if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3446f4a2713aSLionel Sambuc return false;
3447f4a2713aSLionel Sambuc
3448f4a2713aSLionel Sambuc const Expr *Arg = getDataArg(argIndex);
3449f4a2713aSLionel Sambuc if (!Arg)
3450f4a2713aSLionel Sambuc return true;
3451f4a2713aSLionel Sambuc
3452f4a2713aSLionel Sambuc return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3453f4a2713aSLionel Sambuc }
3454f4a2713aSLionel Sambuc
requiresParensToAddCast(const Expr * E)3455f4a2713aSLionel Sambuc static bool requiresParensToAddCast(const Expr *E) {
3456f4a2713aSLionel Sambuc // FIXME: We should have a general way to reason about operator
3457f4a2713aSLionel Sambuc // precedence and whether parens are actually needed here.
3458f4a2713aSLionel Sambuc // Take care of a few common cases where they aren't.
3459f4a2713aSLionel Sambuc const Expr *Inside = E->IgnoreImpCasts();
3460f4a2713aSLionel Sambuc if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3461f4a2713aSLionel Sambuc Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3462f4a2713aSLionel Sambuc
3463f4a2713aSLionel Sambuc switch (Inside->getStmtClass()) {
3464f4a2713aSLionel Sambuc case Stmt::ArraySubscriptExprClass:
3465f4a2713aSLionel Sambuc case Stmt::CallExprClass:
3466f4a2713aSLionel Sambuc case Stmt::CharacterLiteralClass:
3467f4a2713aSLionel Sambuc case Stmt::CXXBoolLiteralExprClass:
3468f4a2713aSLionel Sambuc case Stmt::DeclRefExprClass:
3469f4a2713aSLionel Sambuc case Stmt::FloatingLiteralClass:
3470f4a2713aSLionel Sambuc case Stmt::IntegerLiteralClass:
3471f4a2713aSLionel Sambuc case Stmt::MemberExprClass:
3472f4a2713aSLionel Sambuc case Stmt::ObjCArrayLiteralClass:
3473f4a2713aSLionel Sambuc case Stmt::ObjCBoolLiteralExprClass:
3474f4a2713aSLionel Sambuc case Stmt::ObjCBoxedExprClass:
3475f4a2713aSLionel Sambuc case Stmt::ObjCDictionaryLiteralClass:
3476f4a2713aSLionel Sambuc case Stmt::ObjCEncodeExprClass:
3477f4a2713aSLionel Sambuc case Stmt::ObjCIvarRefExprClass:
3478f4a2713aSLionel Sambuc case Stmt::ObjCMessageExprClass:
3479f4a2713aSLionel Sambuc case Stmt::ObjCPropertyRefExprClass:
3480f4a2713aSLionel Sambuc case Stmt::ObjCStringLiteralClass:
3481f4a2713aSLionel Sambuc case Stmt::ObjCSubscriptRefExprClass:
3482f4a2713aSLionel Sambuc case Stmt::ParenExprClass:
3483f4a2713aSLionel Sambuc case Stmt::StringLiteralClass:
3484f4a2713aSLionel Sambuc case Stmt::UnaryOperatorClass:
3485f4a2713aSLionel Sambuc return false;
3486f4a2713aSLionel Sambuc default:
3487f4a2713aSLionel Sambuc return true;
3488f4a2713aSLionel Sambuc }
3489f4a2713aSLionel Sambuc }
3490f4a2713aSLionel Sambuc
3491*0a6a1f1dSLionel Sambuc static std::pair<QualType, StringRef>
shouldNotPrintDirectly(const ASTContext & Context,QualType IntendedTy,const Expr * E)3492*0a6a1f1dSLionel Sambuc shouldNotPrintDirectly(const ASTContext &Context,
3493*0a6a1f1dSLionel Sambuc QualType IntendedTy,
3494*0a6a1f1dSLionel Sambuc const Expr *E) {
3495*0a6a1f1dSLionel Sambuc // Use a 'while' to peel off layers of typedefs.
3496*0a6a1f1dSLionel Sambuc QualType TyTy = IntendedTy;
3497*0a6a1f1dSLionel Sambuc while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3498*0a6a1f1dSLionel Sambuc StringRef Name = UserTy->getDecl()->getName();
3499*0a6a1f1dSLionel Sambuc QualType CastTy = llvm::StringSwitch<QualType>(Name)
3500*0a6a1f1dSLionel Sambuc .Case("NSInteger", Context.LongTy)
3501*0a6a1f1dSLionel Sambuc .Case("NSUInteger", Context.UnsignedLongTy)
3502*0a6a1f1dSLionel Sambuc .Case("SInt32", Context.IntTy)
3503*0a6a1f1dSLionel Sambuc .Case("UInt32", Context.UnsignedIntTy)
3504*0a6a1f1dSLionel Sambuc .Default(QualType());
3505*0a6a1f1dSLionel Sambuc
3506*0a6a1f1dSLionel Sambuc if (!CastTy.isNull())
3507*0a6a1f1dSLionel Sambuc return std::make_pair(CastTy, Name);
3508*0a6a1f1dSLionel Sambuc
3509*0a6a1f1dSLionel Sambuc TyTy = UserTy->desugar();
3510*0a6a1f1dSLionel Sambuc }
3511*0a6a1f1dSLionel Sambuc
3512*0a6a1f1dSLionel Sambuc // Strip parens if necessary.
3513*0a6a1f1dSLionel Sambuc if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3514*0a6a1f1dSLionel Sambuc return shouldNotPrintDirectly(Context,
3515*0a6a1f1dSLionel Sambuc PE->getSubExpr()->getType(),
3516*0a6a1f1dSLionel Sambuc PE->getSubExpr());
3517*0a6a1f1dSLionel Sambuc
3518*0a6a1f1dSLionel Sambuc // If this is a conditional expression, then its result type is constructed
3519*0a6a1f1dSLionel Sambuc // via usual arithmetic conversions and thus there might be no necessary
3520*0a6a1f1dSLionel Sambuc // typedef sugar there. Recurse to operands to check for NSInteger &
3521*0a6a1f1dSLionel Sambuc // Co. usage condition.
3522*0a6a1f1dSLionel Sambuc if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3523*0a6a1f1dSLionel Sambuc QualType TrueTy, FalseTy;
3524*0a6a1f1dSLionel Sambuc StringRef TrueName, FalseName;
3525*0a6a1f1dSLionel Sambuc
3526*0a6a1f1dSLionel Sambuc std::tie(TrueTy, TrueName) =
3527*0a6a1f1dSLionel Sambuc shouldNotPrintDirectly(Context,
3528*0a6a1f1dSLionel Sambuc CO->getTrueExpr()->getType(),
3529*0a6a1f1dSLionel Sambuc CO->getTrueExpr());
3530*0a6a1f1dSLionel Sambuc std::tie(FalseTy, FalseName) =
3531*0a6a1f1dSLionel Sambuc shouldNotPrintDirectly(Context,
3532*0a6a1f1dSLionel Sambuc CO->getFalseExpr()->getType(),
3533*0a6a1f1dSLionel Sambuc CO->getFalseExpr());
3534*0a6a1f1dSLionel Sambuc
3535*0a6a1f1dSLionel Sambuc if (TrueTy == FalseTy)
3536*0a6a1f1dSLionel Sambuc return std::make_pair(TrueTy, TrueName);
3537*0a6a1f1dSLionel Sambuc else if (TrueTy.isNull())
3538*0a6a1f1dSLionel Sambuc return std::make_pair(FalseTy, FalseName);
3539*0a6a1f1dSLionel Sambuc else if (FalseTy.isNull())
3540*0a6a1f1dSLionel Sambuc return std::make_pair(TrueTy, TrueName);
3541*0a6a1f1dSLionel Sambuc }
3542*0a6a1f1dSLionel Sambuc
3543*0a6a1f1dSLionel Sambuc return std::make_pair(QualType(), StringRef());
3544*0a6a1f1dSLionel Sambuc }
3545*0a6a1f1dSLionel Sambuc
3546f4a2713aSLionel Sambuc bool
checkFormatExpr(const analyze_printf::PrintfSpecifier & FS,const char * StartSpecifier,unsigned SpecifierLen,const Expr * E)3547f4a2713aSLionel Sambuc CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3548f4a2713aSLionel Sambuc const char *StartSpecifier,
3549f4a2713aSLionel Sambuc unsigned SpecifierLen,
3550f4a2713aSLionel Sambuc const Expr *E) {
3551f4a2713aSLionel Sambuc using namespace analyze_format_string;
3552f4a2713aSLionel Sambuc using namespace analyze_printf;
3553f4a2713aSLionel Sambuc // Now type check the data expression that matches the
3554f4a2713aSLionel Sambuc // format specifier.
3555f4a2713aSLionel Sambuc const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3556f4a2713aSLionel Sambuc ObjCContext);
3557f4a2713aSLionel Sambuc if (!AT.isValid())
3558f4a2713aSLionel Sambuc return true;
3559f4a2713aSLionel Sambuc
3560f4a2713aSLionel Sambuc QualType ExprTy = E->getType();
3561f4a2713aSLionel Sambuc while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3562f4a2713aSLionel Sambuc ExprTy = TET->getUnderlyingExpr()->getType();
3563f4a2713aSLionel Sambuc }
3564f4a2713aSLionel Sambuc
3565f4a2713aSLionel Sambuc if (AT.matchesType(S.Context, ExprTy))
3566f4a2713aSLionel Sambuc return true;
3567f4a2713aSLionel Sambuc
3568f4a2713aSLionel Sambuc // Look through argument promotions for our error message's reported type.
3569f4a2713aSLionel Sambuc // This includes the integral and floating promotions, but excludes array
3570f4a2713aSLionel Sambuc // and function pointer decay; seeing that an argument intended to be a
3571f4a2713aSLionel Sambuc // string has type 'char [6]' is probably more confusing than 'char *'.
3572f4a2713aSLionel Sambuc if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3573f4a2713aSLionel Sambuc if (ICE->getCastKind() == CK_IntegralCast ||
3574f4a2713aSLionel Sambuc ICE->getCastKind() == CK_FloatingCast) {
3575f4a2713aSLionel Sambuc E = ICE->getSubExpr();
3576f4a2713aSLionel Sambuc ExprTy = E->getType();
3577f4a2713aSLionel Sambuc
3578f4a2713aSLionel Sambuc // Check if we didn't match because of an implicit cast from a 'char'
3579f4a2713aSLionel Sambuc // or 'short' to an 'int'. This is done because printf is a varargs
3580f4a2713aSLionel Sambuc // function.
3581f4a2713aSLionel Sambuc if (ICE->getType() == S.Context.IntTy ||
3582f4a2713aSLionel Sambuc ICE->getType() == S.Context.UnsignedIntTy) {
3583f4a2713aSLionel Sambuc // All further checking is done on the subexpression.
3584f4a2713aSLionel Sambuc if (AT.matchesType(S.Context, ExprTy))
3585f4a2713aSLionel Sambuc return true;
3586f4a2713aSLionel Sambuc }
3587f4a2713aSLionel Sambuc }
3588f4a2713aSLionel Sambuc } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3589f4a2713aSLionel Sambuc // Special case for 'a', which has type 'int' in C.
3590f4a2713aSLionel Sambuc // Note, however, that we do /not/ want to treat multibyte constants like
3591f4a2713aSLionel Sambuc // 'MooV' as characters! This form is deprecated but still exists.
3592f4a2713aSLionel Sambuc if (ExprTy == S.Context.IntTy)
3593f4a2713aSLionel Sambuc if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3594f4a2713aSLionel Sambuc ExprTy = S.Context.CharTy;
3595f4a2713aSLionel Sambuc }
3596f4a2713aSLionel Sambuc
3597*0a6a1f1dSLionel Sambuc // Look through enums to their underlying type.
3598*0a6a1f1dSLionel Sambuc bool IsEnum = false;
3599*0a6a1f1dSLionel Sambuc if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3600*0a6a1f1dSLionel Sambuc ExprTy = EnumTy->getDecl()->getIntegerType();
3601*0a6a1f1dSLionel Sambuc IsEnum = true;
3602*0a6a1f1dSLionel Sambuc }
3603*0a6a1f1dSLionel Sambuc
3604f4a2713aSLionel Sambuc // %C in an Objective-C context prints a unichar, not a wchar_t.
3605f4a2713aSLionel Sambuc // If the argument is an integer of some kind, believe the %C and suggest
3606f4a2713aSLionel Sambuc // a cast instead of changing the conversion specifier.
3607f4a2713aSLionel Sambuc QualType IntendedTy = ExprTy;
3608f4a2713aSLionel Sambuc if (ObjCContext &&
3609f4a2713aSLionel Sambuc FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3610f4a2713aSLionel Sambuc if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3611f4a2713aSLionel Sambuc !ExprTy->isCharType()) {
3612f4a2713aSLionel Sambuc // 'unichar' is defined as a typedef of unsigned short, but we should
3613f4a2713aSLionel Sambuc // prefer using the typedef if it is visible.
3614f4a2713aSLionel Sambuc IntendedTy = S.Context.UnsignedShortTy;
3615f4a2713aSLionel Sambuc
3616f4a2713aSLionel Sambuc // While we are here, check if the value is an IntegerLiteral that happens
3617f4a2713aSLionel Sambuc // to be within the valid range.
3618f4a2713aSLionel Sambuc if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3619f4a2713aSLionel Sambuc const llvm::APInt &V = IL->getValue();
3620f4a2713aSLionel Sambuc if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3621f4a2713aSLionel Sambuc return true;
3622f4a2713aSLionel Sambuc }
3623f4a2713aSLionel Sambuc
3624f4a2713aSLionel Sambuc LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3625f4a2713aSLionel Sambuc Sema::LookupOrdinaryName);
3626f4a2713aSLionel Sambuc if (S.LookupName(Result, S.getCurScope())) {
3627f4a2713aSLionel Sambuc NamedDecl *ND = Result.getFoundDecl();
3628f4a2713aSLionel Sambuc if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3629f4a2713aSLionel Sambuc if (TD->getUnderlyingType() == IntendedTy)
3630f4a2713aSLionel Sambuc IntendedTy = S.Context.getTypedefType(TD);
3631f4a2713aSLionel Sambuc }
3632f4a2713aSLionel Sambuc }
3633f4a2713aSLionel Sambuc }
3634f4a2713aSLionel Sambuc
3635f4a2713aSLionel Sambuc // Special-case some of Darwin's platform-independence types by suggesting
3636f4a2713aSLionel Sambuc // casts to primitive types that are known to be large enough.
3637*0a6a1f1dSLionel Sambuc bool ShouldNotPrintDirectly = false; StringRef CastTyName;
3638f4a2713aSLionel Sambuc if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3639*0a6a1f1dSLionel Sambuc QualType CastTy;
3640*0a6a1f1dSLionel Sambuc std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3641f4a2713aSLionel Sambuc if (!CastTy.isNull()) {
3642f4a2713aSLionel Sambuc IntendedTy = CastTy;
3643*0a6a1f1dSLionel Sambuc ShouldNotPrintDirectly = true;
3644f4a2713aSLionel Sambuc }
3645f4a2713aSLionel Sambuc }
3646f4a2713aSLionel Sambuc
3647f4a2713aSLionel Sambuc // We may be able to offer a FixItHint if it is a supported type.
3648f4a2713aSLionel Sambuc PrintfSpecifier fixedFS = FS;
3649f4a2713aSLionel Sambuc bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3650f4a2713aSLionel Sambuc S.Context, ObjCContext);
3651f4a2713aSLionel Sambuc
3652f4a2713aSLionel Sambuc if (success) {
3653f4a2713aSLionel Sambuc // Get the fix string from the fixed format specifier
3654f4a2713aSLionel Sambuc SmallString<16> buf;
3655f4a2713aSLionel Sambuc llvm::raw_svector_ostream os(buf);
3656f4a2713aSLionel Sambuc fixedFS.toString(os);
3657f4a2713aSLionel Sambuc
3658f4a2713aSLionel Sambuc CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3659f4a2713aSLionel Sambuc
3660*0a6a1f1dSLionel Sambuc if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
3661f4a2713aSLionel Sambuc // In this case, the specifier is wrong and should be changed to match
3662f4a2713aSLionel Sambuc // the argument.
3663f4a2713aSLionel Sambuc EmitFormatDiagnostic(
3664*0a6a1f1dSLionel Sambuc S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3665*0a6a1f1dSLionel Sambuc << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
3666f4a2713aSLionel Sambuc << E->getSourceRange(),
3667f4a2713aSLionel Sambuc E->getLocStart(),
3668f4a2713aSLionel Sambuc /*IsStringLocation*/false,
3669f4a2713aSLionel Sambuc SpecRange,
3670f4a2713aSLionel Sambuc FixItHint::CreateReplacement(SpecRange, os.str()));
3671f4a2713aSLionel Sambuc
3672f4a2713aSLionel Sambuc } else {
3673f4a2713aSLionel Sambuc // The canonical type for formatting this value is different from the
3674f4a2713aSLionel Sambuc // actual type of the expression. (This occurs, for example, with Darwin's
3675f4a2713aSLionel Sambuc // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3676f4a2713aSLionel Sambuc // should be printed as 'long' for 64-bit compatibility.)
3677f4a2713aSLionel Sambuc // Rather than emitting a normal format/argument mismatch, we want to
3678f4a2713aSLionel Sambuc // add a cast to the recommended type (and correct the format string
3679f4a2713aSLionel Sambuc // if necessary).
3680f4a2713aSLionel Sambuc SmallString<16> CastBuf;
3681f4a2713aSLionel Sambuc llvm::raw_svector_ostream CastFix(CastBuf);
3682f4a2713aSLionel Sambuc CastFix << "(";
3683f4a2713aSLionel Sambuc IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3684f4a2713aSLionel Sambuc CastFix << ")";
3685f4a2713aSLionel Sambuc
3686f4a2713aSLionel Sambuc SmallVector<FixItHint,4> Hints;
3687f4a2713aSLionel Sambuc if (!AT.matchesType(S.Context, IntendedTy))
3688f4a2713aSLionel Sambuc Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3689f4a2713aSLionel Sambuc
3690f4a2713aSLionel Sambuc if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3691f4a2713aSLionel Sambuc // If there's already a cast present, just replace it.
3692f4a2713aSLionel Sambuc SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3693f4a2713aSLionel Sambuc Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3694f4a2713aSLionel Sambuc
3695f4a2713aSLionel Sambuc } else if (!requiresParensToAddCast(E)) {
3696f4a2713aSLionel Sambuc // If the expression has high enough precedence,
3697f4a2713aSLionel Sambuc // just write the C-style cast.
3698f4a2713aSLionel Sambuc Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3699f4a2713aSLionel Sambuc CastFix.str()));
3700f4a2713aSLionel Sambuc } else {
3701f4a2713aSLionel Sambuc // Otherwise, add parens around the expression as well as the cast.
3702f4a2713aSLionel Sambuc CastFix << "(";
3703f4a2713aSLionel Sambuc Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3704f4a2713aSLionel Sambuc CastFix.str()));
3705f4a2713aSLionel Sambuc
3706*0a6a1f1dSLionel Sambuc SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
3707f4a2713aSLionel Sambuc Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3708f4a2713aSLionel Sambuc }
3709f4a2713aSLionel Sambuc
3710f4a2713aSLionel Sambuc if (ShouldNotPrintDirectly) {
3711f4a2713aSLionel Sambuc // The expression has a type that should not be printed directly.
3712f4a2713aSLionel Sambuc // We extract the name from the typedef because we don't want to show
3713f4a2713aSLionel Sambuc // the underlying type in the diagnostic.
3714*0a6a1f1dSLionel Sambuc StringRef Name;
3715*0a6a1f1dSLionel Sambuc if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3716*0a6a1f1dSLionel Sambuc Name = TypedefTy->getDecl()->getName();
3717*0a6a1f1dSLionel Sambuc else
3718*0a6a1f1dSLionel Sambuc Name = CastTyName;
3719f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3720*0a6a1f1dSLionel Sambuc << Name << IntendedTy << IsEnum
3721f4a2713aSLionel Sambuc << E->getSourceRange(),
3722f4a2713aSLionel Sambuc E->getLocStart(), /*IsStringLocation=*/false,
3723f4a2713aSLionel Sambuc SpecRange, Hints);
3724f4a2713aSLionel Sambuc } else {
3725f4a2713aSLionel Sambuc // In this case, the expression could be printed using a different
3726f4a2713aSLionel Sambuc // specifier, but we've decided that the specifier is probably correct
3727f4a2713aSLionel Sambuc // and we should cast instead. Just use the normal warning message.
3728f4a2713aSLionel Sambuc EmitFormatDiagnostic(
3729*0a6a1f1dSLionel Sambuc S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3730*0a6a1f1dSLionel Sambuc << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3731f4a2713aSLionel Sambuc << E->getSourceRange(),
3732f4a2713aSLionel Sambuc E->getLocStart(), /*IsStringLocation*/false,
3733f4a2713aSLionel Sambuc SpecRange, Hints);
3734f4a2713aSLionel Sambuc }
3735f4a2713aSLionel Sambuc }
3736f4a2713aSLionel Sambuc } else {
3737f4a2713aSLionel Sambuc const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3738f4a2713aSLionel Sambuc SpecifierLen);
3739f4a2713aSLionel Sambuc // Since the warning for passing non-POD types to variadic functions
3740f4a2713aSLionel Sambuc // was deferred until now, we emit a warning for non-POD
3741f4a2713aSLionel Sambuc // arguments here.
3742f4a2713aSLionel Sambuc switch (S.isValidVarArgType(ExprTy)) {
3743f4a2713aSLionel Sambuc case Sema::VAK_Valid:
3744f4a2713aSLionel Sambuc case Sema::VAK_ValidInCXX11:
3745f4a2713aSLionel Sambuc EmitFormatDiagnostic(
3746*0a6a1f1dSLionel Sambuc S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3747*0a6a1f1dSLionel Sambuc << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3748f4a2713aSLionel Sambuc << CSR
3749f4a2713aSLionel Sambuc << E->getSourceRange(),
3750f4a2713aSLionel Sambuc E->getLocStart(), /*IsStringLocation*/false, CSR);
3751f4a2713aSLionel Sambuc break;
3752f4a2713aSLionel Sambuc
3753f4a2713aSLionel Sambuc case Sema::VAK_Undefined:
3754*0a6a1f1dSLionel Sambuc case Sema::VAK_MSVCUndefined:
3755f4a2713aSLionel Sambuc EmitFormatDiagnostic(
3756f4a2713aSLionel Sambuc S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3757f4a2713aSLionel Sambuc << S.getLangOpts().CPlusPlus11
3758f4a2713aSLionel Sambuc << ExprTy
3759f4a2713aSLionel Sambuc << CallType
3760f4a2713aSLionel Sambuc << AT.getRepresentativeTypeName(S.Context)
3761f4a2713aSLionel Sambuc << CSR
3762f4a2713aSLionel Sambuc << E->getSourceRange(),
3763f4a2713aSLionel Sambuc E->getLocStart(), /*IsStringLocation*/false, CSR);
3764*0a6a1f1dSLionel Sambuc checkForCStrMembers(AT, E);
3765f4a2713aSLionel Sambuc break;
3766f4a2713aSLionel Sambuc
3767f4a2713aSLionel Sambuc case Sema::VAK_Invalid:
3768f4a2713aSLionel Sambuc if (ExprTy->isObjCObjectType())
3769f4a2713aSLionel Sambuc EmitFormatDiagnostic(
3770f4a2713aSLionel Sambuc S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3771f4a2713aSLionel Sambuc << S.getLangOpts().CPlusPlus11
3772f4a2713aSLionel Sambuc << ExprTy
3773f4a2713aSLionel Sambuc << CallType
3774f4a2713aSLionel Sambuc << AT.getRepresentativeTypeName(S.Context)
3775f4a2713aSLionel Sambuc << CSR
3776f4a2713aSLionel Sambuc << E->getSourceRange(),
3777f4a2713aSLionel Sambuc E->getLocStart(), /*IsStringLocation*/false, CSR);
3778f4a2713aSLionel Sambuc else
3779f4a2713aSLionel Sambuc // FIXME: If this is an initializer list, suggest removing the braces
3780f4a2713aSLionel Sambuc // or inserting a cast to the target type.
3781f4a2713aSLionel Sambuc S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3782f4a2713aSLionel Sambuc << isa<InitListExpr>(E) << ExprTy << CallType
3783f4a2713aSLionel Sambuc << AT.getRepresentativeTypeName(S.Context)
3784f4a2713aSLionel Sambuc << E->getSourceRange();
3785f4a2713aSLionel Sambuc break;
3786f4a2713aSLionel Sambuc }
3787f4a2713aSLionel Sambuc
3788f4a2713aSLionel Sambuc assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3789f4a2713aSLionel Sambuc "format string specifier index out of range");
3790f4a2713aSLionel Sambuc CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3791f4a2713aSLionel Sambuc }
3792f4a2713aSLionel Sambuc
3793f4a2713aSLionel Sambuc return true;
3794f4a2713aSLionel Sambuc }
3795f4a2713aSLionel Sambuc
3796f4a2713aSLionel Sambuc //===--- CHECK: Scanf format string checking ------------------------------===//
3797f4a2713aSLionel Sambuc
3798f4a2713aSLionel Sambuc namespace {
3799f4a2713aSLionel Sambuc class CheckScanfHandler : public CheckFormatHandler {
3800f4a2713aSLionel Sambuc public:
CheckScanfHandler(Sema & s,const StringLiteral * fexpr,const Expr * origFormatExpr,unsigned firstDataArg,unsigned numDataArgs,const char * beg,bool hasVAListArg,ArrayRef<const Expr * > Args,unsigned formatIdx,bool inFunctionCall,Sema::VariadicCallType CallType,llvm::SmallBitVector & CheckedVarArgs)3801f4a2713aSLionel Sambuc CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3802f4a2713aSLionel Sambuc const Expr *origFormatExpr, unsigned firstDataArg,
3803f4a2713aSLionel Sambuc unsigned numDataArgs, const char *beg, bool hasVAListArg,
3804f4a2713aSLionel Sambuc ArrayRef<const Expr *> Args,
3805f4a2713aSLionel Sambuc unsigned formatIdx, bool inFunctionCall,
3806f4a2713aSLionel Sambuc Sema::VariadicCallType CallType,
3807f4a2713aSLionel Sambuc llvm::SmallBitVector &CheckedVarArgs)
3808f4a2713aSLionel Sambuc : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3809f4a2713aSLionel Sambuc numDataArgs, beg, hasVAListArg,
3810f4a2713aSLionel Sambuc Args, formatIdx, inFunctionCall, CallType,
3811f4a2713aSLionel Sambuc CheckedVarArgs)
3812f4a2713aSLionel Sambuc {}
3813f4a2713aSLionel Sambuc
3814f4a2713aSLionel Sambuc bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3815f4a2713aSLionel Sambuc const char *startSpecifier,
3816*0a6a1f1dSLionel Sambuc unsigned specifierLen) override;
3817f4a2713aSLionel Sambuc
3818f4a2713aSLionel Sambuc bool HandleInvalidScanfConversionSpecifier(
3819f4a2713aSLionel Sambuc const analyze_scanf::ScanfSpecifier &FS,
3820f4a2713aSLionel Sambuc const char *startSpecifier,
3821*0a6a1f1dSLionel Sambuc unsigned specifierLen) override;
3822f4a2713aSLionel Sambuc
3823*0a6a1f1dSLionel Sambuc void HandleIncompleteScanList(const char *start, const char *end) override;
3824f4a2713aSLionel Sambuc };
3825f4a2713aSLionel Sambuc }
3826f4a2713aSLionel Sambuc
HandleIncompleteScanList(const char * start,const char * end)3827f4a2713aSLionel Sambuc void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3828f4a2713aSLionel Sambuc const char *end) {
3829f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3830f4a2713aSLionel Sambuc getLocationOfByte(end), /*IsStringLocation*/true,
3831f4a2713aSLionel Sambuc getSpecifierRange(start, end - start));
3832f4a2713aSLionel Sambuc }
3833f4a2713aSLionel Sambuc
HandleInvalidScanfConversionSpecifier(const analyze_scanf::ScanfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)3834f4a2713aSLionel Sambuc bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3835f4a2713aSLionel Sambuc const analyze_scanf::ScanfSpecifier &FS,
3836f4a2713aSLionel Sambuc const char *startSpecifier,
3837f4a2713aSLionel Sambuc unsigned specifierLen) {
3838f4a2713aSLionel Sambuc
3839f4a2713aSLionel Sambuc const analyze_scanf::ScanfConversionSpecifier &CS =
3840f4a2713aSLionel Sambuc FS.getConversionSpecifier();
3841f4a2713aSLionel Sambuc
3842f4a2713aSLionel Sambuc return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3843f4a2713aSLionel Sambuc getLocationOfByte(CS.getStart()),
3844f4a2713aSLionel Sambuc startSpecifier, specifierLen,
3845f4a2713aSLionel Sambuc CS.getStart(), CS.getLength());
3846f4a2713aSLionel Sambuc }
3847f4a2713aSLionel Sambuc
HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier & FS,const char * startSpecifier,unsigned specifierLen)3848f4a2713aSLionel Sambuc bool CheckScanfHandler::HandleScanfSpecifier(
3849f4a2713aSLionel Sambuc const analyze_scanf::ScanfSpecifier &FS,
3850f4a2713aSLionel Sambuc const char *startSpecifier,
3851f4a2713aSLionel Sambuc unsigned specifierLen) {
3852f4a2713aSLionel Sambuc
3853f4a2713aSLionel Sambuc using namespace analyze_scanf;
3854f4a2713aSLionel Sambuc using namespace analyze_format_string;
3855f4a2713aSLionel Sambuc
3856f4a2713aSLionel Sambuc const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3857f4a2713aSLionel Sambuc
3858f4a2713aSLionel Sambuc // Handle case where '%' and '*' don't consume an argument. These shouldn't
3859f4a2713aSLionel Sambuc // be used to decide if we are using positional arguments consistently.
3860f4a2713aSLionel Sambuc if (FS.consumesDataArgument()) {
3861f4a2713aSLionel Sambuc if (atFirstArg) {
3862f4a2713aSLionel Sambuc atFirstArg = false;
3863f4a2713aSLionel Sambuc usesPositionalArgs = FS.usesPositionalArg();
3864f4a2713aSLionel Sambuc }
3865f4a2713aSLionel Sambuc else if (usesPositionalArgs != FS.usesPositionalArg()) {
3866f4a2713aSLionel Sambuc HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3867f4a2713aSLionel Sambuc startSpecifier, specifierLen);
3868f4a2713aSLionel Sambuc return false;
3869f4a2713aSLionel Sambuc }
3870f4a2713aSLionel Sambuc }
3871f4a2713aSLionel Sambuc
3872f4a2713aSLionel Sambuc // Check if the field with is non-zero.
3873f4a2713aSLionel Sambuc const OptionalAmount &Amt = FS.getFieldWidth();
3874f4a2713aSLionel Sambuc if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3875f4a2713aSLionel Sambuc if (Amt.getConstantAmount() == 0) {
3876f4a2713aSLionel Sambuc const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3877f4a2713aSLionel Sambuc Amt.getConstantLength());
3878f4a2713aSLionel Sambuc EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3879f4a2713aSLionel Sambuc getLocationOfByte(Amt.getStart()),
3880f4a2713aSLionel Sambuc /*IsStringLocation*/true, R,
3881f4a2713aSLionel Sambuc FixItHint::CreateRemoval(R));
3882f4a2713aSLionel Sambuc }
3883f4a2713aSLionel Sambuc }
3884f4a2713aSLionel Sambuc
3885f4a2713aSLionel Sambuc if (!FS.consumesDataArgument()) {
3886f4a2713aSLionel Sambuc // FIXME: Technically specifying a precision or field width here
3887f4a2713aSLionel Sambuc // makes no sense. Worth issuing a warning at some point.
3888f4a2713aSLionel Sambuc return true;
3889f4a2713aSLionel Sambuc }
3890f4a2713aSLionel Sambuc
3891f4a2713aSLionel Sambuc // Consume the argument.
3892f4a2713aSLionel Sambuc unsigned argIndex = FS.getArgIndex();
3893f4a2713aSLionel Sambuc if (argIndex < NumDataArgs) {
3894f4a2713aSLionel Sambuc // The check to see if the argIndex is valid will come later.
3895f4a2713aSLionel Sambuc // We set the bit here because we may exit early from this
3896f4a2713aSLionel Sambuc // function if we encounter some other error.
3897f4a2713aSLionel Sambuc CoveredArgs.set(argIndex);
3898f4a2713aSLionel Sambuc }
3899f4a2713aSLionel Sambuc
3900f4a2713aSLionel Sambuc // Check the length modifier is valid with the given conversion specifier.
3901f4a2713aSLionel Sambuc if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3902f4a2713aSLionel Sambuc HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3903f4a2713aSLionel Sambuc diag::warn_format_nonsensical_length);
3904f4a2713aSLionel Sambuc else if (!FS.hasStandardLengthModifier())
3905f4a2713aSLionel Sambuc HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3906f4a2713aSLionel Sambuc else if (!FS.hasStandardLengthConversionCombination())
3907f4a2713aSLionel Sambuc HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3908f4a2713aSLionel Sambuc diag::warn_format_non_standard_conversion_spec);
3909f4a2713aSLionel Sambuc
3910f4a2713aSLionel Sambuc if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3911f4a2713aSLionel Sambuc HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3912f4a2713aSLionel Sambuc
3913f4a2713aSLionel Sambuc // The remaining checks depend on the data arguments.
3914f4a2713aSLionel Sambuc if (HasVAListArg)
3915f4a2713aSLionel Sambuc return true;
3916f4a2713aSLionel Sambuc
3917f4a2713aSLionel Sambuc if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3918f4a2713aSLionel Sambuc return false;
3919f4a2713aSLionel Sambuc
3920f4a2713aSLionel Sambuc // Check that the argument type matches the format specifier.
3921f4a2713aSLionel Sambuc const Expr *Ex = getDataArg(argIndex);
3922f4a2713aSLionel Sambuc if (!Ex)
3923f4a2713aSLionel Sambuc return true;
3924f4a2713aSLionel Sambuc
3925f4a2713aSLionel Sambuc const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3926f4a2713aSLionel Sambuc if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3927f4a2713aSLionel Sambuc ScanfSpecifier fixedFS = FS;
3928*0a6a1f1dSLionel Sambuc bool success = fixedFS.fixType(Ex->getType(),
3929*0a6a1f1dSLionel Sambuc Ex->IgnoreImpCasts()->getType(),
3930*0a6a1f1dSLionel Sambuc S.getLangOpts(), S.Context);
3931f4a2713aSLionel Sambuc
3932f4a2713aSLionel Sambuc if (success) {
3933f4a2713aSLionel Sambuc // Get the fix string from the fixed format specifier.
3934f4a2713aSLionel Sambuc SmallString<128> buf;
3935f4a2713aSLionel Sambuc llvm::raw_svector_ostream os(buf);
3936f4a2713aSLionel Sambuc fixedFS.toString(os);
3937f4a2713aSLionel Sambuc
3938f4a2713aSLionel Sambuc EmitFormatDiagnostic(
3939*0a6a1f1dSLionel Sambuc S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3940*0a6a1f1dSLionel Sambuc << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
3941f4a2713aSLionel Sambuc << Ex->getSourceRange(),
3942f4a2713aSLionel Sambuc Ex->getLocStart(),
3943f4a2713aSLionel Sambuc /*IsStringLocation*/false,
3944f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen),
3945f4a2713aSLionel Sambuc FixItHint::CreateReplacement(
3946f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen),
3947f4a2713aSLionel Sambuc os.str()));
3948f4a2713aSLionel Sambuc } else {
3949f4a2713aSLionel Sambuc EmitFormatDiagnostic(
3950*0a6a1f1dSLionel Sambuc S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3951*0a6a1f1dSLionel Sambuc << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
3952f4a2713aSLionel Sambuc << Ex->getSourceRange(),
3953f4a2713aSLionel Sambuc Ex->getLocStart(),
3954f4a2713aSLionel Sambuc /*IsStringLocation*/false,
3955f4a2713aSLionel Sambuc getSpecifierRange(startSpecifier, specifierLen));
3956f4a2713aSLionel Sambuc }
3957f4a2713aSLionel Sambuc }
3958f4a2713aSLionel Sambuc
3959f4a2713aSLionel Sambuc return true;
3960f4a2713aSLionel Sambuc }
3961f4a2713aSLionel Sambuc
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)3962f4a2713aSLionel Sambuc void Sema::CheckFormatString(const StringLiteral *FExpr,
3963f4a2713aSLionel Sambuc const Expr *OrigFormatExpr,
3964f4a2713aSLionel Sambuc ArrayRef<const Expr *> Args,
3965f4a2713aSLionel Sambuc bool HasVAListArg, unsigned format_idx,
3966f4a2713aSLionel Sambuc unsigned firstDataArg, FormatStringType Type,
3967f4a2713aSLionel Sambuc bool inFunctionCall, VariadicCallType CallType,
3968f4a2713aSLionel Sambuc llvm::SmallBitVector &CheckedVarArgs) {
3969f4a2713aSLionel Sambuc
3970f4a2713aSLionel Sambuc // CHECK: is the format string a wide literal?
3971f4a2713aSLionel Sambuc if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3972f4a2713aSLionel Sambuc CheckFormatHandler::EmitFormatDiagnostic(
3973f4a2713aSLionel Sambuc *this, inFunctionCall, Args[format_idx],
3974f4a2713aSLionel Sambuc PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3975f4a2713aSLionel Sambuc /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3976f4a2713aSLionel Sambuc return;
3977f4a2713aSLionel Sambuc }
3978f4a2713aSLionel Sambuc
3979f4a2713aSLionel Sambuc // Str - The format string. NOTE: this is NOT null-terminated!
3980f4a2713aSLionel Sambuc StringRef StrRef = FExpr->getString();
3981f4a2713aSLionel Sambuc const char *Str = StrRef.data();
3982*0a6a1f1dSLionel Sambuc // Account for cases where the string literal is truncated in a declaration.
3983*0a6a1f1dSLionel Sambuc const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3984*0a6a1f1dSLionel Sambuc assert(T && "String literal not of constant array type!");
3985*0a6a1f1dSLionel Sambuc size_t TypeSize = T->getSize().getZExtValue();
3986*0a6a1f1dSLionel Sambuc size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
3987f4a2713aSLionel Sambuc const unsigned numDataArgs = Args.size() - firstDataArg;
3988f4a2713aSLionel Sambuc
3989*0a6a1f1dSLionel Sambuc // Emit a warning if the string literal is truncated and does not contain an
3990*0a6a1f1dSLionel Sambuc // embedded null character.
3991*0a6a1f1dSLionel Sambuc if (TypeSize <= StrRef.size() &&
3992*0a6a1f1dSLionel Sambuc StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3993*0a6a1f1dSLionel Sambuc CheckFormatHandler::EmitFormatDiagnostic(
3994*0a6a1f1dSLionel Sambuc *this, inFunctionCall, Args[format_idx],
3995*0a6a1f1dSLionel Sambuc PDiag(diag::warn_printf_format_string_not_null_terminated),
3996*0a6a1f1dSLionel Sambuc FExpr->getLocStart(),
3997*0a6a1f1dSLionel Sambuc /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3998*0a6a1f1dSLionel Sambuc return;
3999*0a6a1f1dSLionel Sambuc }
4000*0a6a1f1dSLionel Sambuc
4001f4a2713aSLionel Sambuc // CHECK: empty format string?
4002f4a2713aSLionel Sambuc if (StrLen == 0 && numDataArgs > 0) {
4003f4a2713aSLionel Sambuc CheckFormatHandler::EmitFormatDiagnostic(
4004f4a2713aSLionel Sambuc *this, inFunctionCall, Args[format_idx],
4005f4a2713aSLionel Sambuc PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4006f4a2713aSLionel Sambuc /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
4007f4a2713aSLionel Sambuc return;
4008f4a2713aSLionel Sambuc }
4009f4a2713aSLionel Sambuc
4010f4a2713aSLionel Sambuc if (Type == FST_Printf || Type == FST_NSString) {
4011f4a2713aSLionel Sambuc CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
4012f4a2713aSLionel Sambuc numDataArgs, (Type == FST_NSString),
4013f4a2713aSLionel Sambuc Str, HasVAListArg, Args, format_idx,
4014f4a2713aSLionel Sambuc inFunctionCall, CallType, CheckedVarArgs);
4015f4a2713aSLionel Sambuc
4016f4a2713aSLionel Sambuc if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
4017f4a2713aSLionel Sambuc getLangOpts(),
4018f4a2713aSLionel Sambuc Context.getTargetInfo()))
4019f4a2713aSLionel Sambuc H.DoneProcessing();
4020f4a2713aSLionel Sambuc } else if (Type == FST_Scanf) {
4021f4a2713aSLionel Sambuc CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
4022f4a2713aSLionel Sambuc Str, HasVAListArg, Args, format_idx,
4023f4a2713aSLionel Sambuc inFunctionCall, CallType, CheckedVarArgs);
4024f4a2713aSLionel Sambuc
4025f4a2713aSLionel Sambuc if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
4026f4a2713aSLionel Sambuc getLangOpts(),
4027f4a2713aSLionel Sambuc Context.getTargetInfo()))
4028f4a2713aSLionel Sambuc H.DoneProcessing();
4029f4a2713aSLionel Sambuc } // TODO: handle other formats
4030f4a2713aSLionel Sambuc }
4031f4a2713aSLionel Sambuc
FormatStringHasSArg(const StringLiteral * FExpr)4032*0a6a1f1dSLionel Sambuc bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4033*0a6a1f1dSLionel Sambuc // Str - The format string. NOTE: this is NOT null-terminated!
4034*0a6a1f1dSLionel Sambuc StringRef StrRef = FExpr->getString();
4035*0a6a1f1dSLionel Sambuc const char *Str = StrRef.data();
4036*0a6a1f1dSLionel Sambuc // Account for cases where the string literal is truncated in a declaration.
4037*0a6a1f1dSLionel Sambuc const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4038*0a6a1f1dSLionel Sambuc assert(T && "String literal not of constant array type!");
4039*0a6a1f1dSLionel Sambuc size_t TypeSize = T->getSize().getZExtValue();
4040*0a6a1f1dSLionel Sambuc size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4041*0a6a1f1dSLionel Sambuc return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4042*0a6a1f1dSLionel Sambuc getLangOpts(),
4043*0a6a1f1dSLionel Sambuc Context.getTargetInfo());
4044*0a6a1f1dSLionel Sambuc }
4045*0a6a1f1dSLionel Sambuc
4046*0a6a1f1dSLionel Sambuc //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4047*0a6a1f1dSLionel Sambuc
4048*0a6a1f1dSLionel Sambuc // Returns the related absolute value function that is larger, of 0 if one
4049*0a6a1f1dSLionel Sambuc // does not exist.
getLargerAbsoluteValueFunction(unsigned AbsFunction)4050*0a6a1f1dSLionel Sambuc static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4051*0a6a1f1dSLionel Sambuc switch (AbsFunction) {
4052*0a6a1f1dSLionel Sambuc default:
4053*0a6a1f1dSLionel Sambuc return 0;
4054*0a6a1f1dSLionel Sambuc
4055*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_abs:
4056*0a6a1f1dSLionel Sambuc return Builtin::BI__builtin_labs;
4057*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_labs:
4058*0a6a1f1dSLionel Sambuc return Builtin::BI__builtin_llabs;
4059*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_llabs:
4060*0a6a1f1dSLionel Sambuc return 0;
4061*0a6a1f1dSLionel Sambuc
4062*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabsf:
4063*0a6a1f1dSLionel Sambuc return Builtin::BI__builtin_fabs;
4064*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabs:
4065*0a6a1f1dSLionel Sambuc return Builtin::BI__builtin_fabsl;
4066*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabsl:
4067*0a6a1f1dSLionel Sambuc return 0;
4068*0a6a1f1dSLionel Sambuc
4069*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabsf:
4070*0a6a1f1dSLionel Sambuc return Builtin::BI__builtin_cabs;
4071*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabs:
4072*0a6a1f1dSLionel Sambuc return Builtin::BI__builtin_cabsl;
4073*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabsl:
4074*0a6a1f1dSLionel Sambuc return 0;
4075*0a6a1f1dSLionel Sambuc
4076*0a6a1f1dSLionel Sambuc case Builtin::BIabs:
4077*0a6a1f1dSLionel Sambuc return Builtin::BIlabs;
4078*0a6a1f1dSLionel Sambuc case Builtin::BIlabs:
4079*0a6a1f1dSLionel Sambuc return Builtin::BIllabs;
4080*0a6a1f1dSLionel Sambuc case Builtin::BIllabs:
4081*0a6a1f1dSLionel Sambuc return 0;
4082*0a6a1f1dSLionel Sambuc
4083*0a6a1f1dSLionel Sambuc case Builtin::BIfabsf:
4084*0a6a1f1dSLionel Sambuc return Builtin::BIfabs;
4085*0a6a1f1dSLionel Sambuc case Builtin::BIfabs:
4086*0a6a1f1dSLionel Sambuc return Builtin::BIfabsl;
4087*0a6a1f1dSLionel Sambuc case Builtin::BIfabsl:
4088*0a6a1f1dSLionel Sambuc return 0;
4089*0a6a1f1dSLionel Sambuc
4090*0a6a1f1dSLionel Sambuc case Builtin::BIcabsf:
4091*0a6a1f1dSLionel Sambuc return Builtin::BIcabs;
4092*0a6a1f1dSLionel Sambuc case Builtin::BIcabs:
4093*0a6a1f1dSLionel Sambuc return Builtin::BIcabsl;
4094*0a6a1f1dSLionel Sambuc case Builtin::BIcabsl:
4095*0a6a1f1dSLionel Sambuc return 0;
4096*0a6a1f1dSLionel Sambuc }
4097*0a6a1f1dSLionel Sambuc }
4098*0a6a1f1dSLionel Sambuc
4099*0a6a1f1dSLionel Sambuc // Returns the argument type of the absolute value function.
getAbsoluteValueArgumentType(ASTContext & Context,unsigned AbsType)4100*0a6a1f1dSLionel Sambuc static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4101*0a6a1f1dSLionel Sambuc unsigned AbsType) {
4102*0a6a1f1dSLionel Sambuc if (AbsType == 0)
4103*0a6a1f1dSLionel Sambuc return QualType();
4104*0a6a1f1dSLionel Sambuc
4105*0a6a1f1dSLionel Sambuc ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4106*0a6a1f1dSLionel Sambuc QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4107*0a6a1f1dSLionel Sambuc if (Error != ASTContext::GE_None)
4108*0a6a1f1dSLionel Sambuc return QualType();
4109*0a6a1f1dSLionel Sambuc
4110*0a6a1f1dSLionel Sambuc const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4111*0a6a1f1dSLionel Sambuc if (!FT)
4112*0a6a1f1dSLionel Sambuc return QualType();
4113*0a6a1f1dSLionel Sambuc
4114*0a6a1f1dSLionel Sambuc if (FT->getNumParams() != 1)
4115*0a6a1f1dSLionel Sambuc return QualType();
4116*0a6a1f1dSLionel Sambuc
4117*0a6a1f1dSLionel Sambuc return FT->getParamType(0);
4118*0a6a1f1dSLionel Sambuc }
4119*0a6a1f1dSLionel Sambuc
4120*0a6a1f1dSLionel Sambuc // Returns the best absolute value function, or zero, based on type and
4121*0a6a1f1dSLionel Sambuc // current absolute value function.
getBestAbsFunction(ASTContext & Context,QualType ArgType,unsigned AbsFunctionKind)4122*0a6a1f1dSLionel Sambuc static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4123*0a6a1f1dSLionel Sambuc unsigned AbsFunctionKind) {
4124*0a6a1f1dSLionel Sambuc unsigned BestKind = 0;
4125*0a6a1f1dSLionel Sambuc uint64_t ArgSize = Context.getTypeSize(ArgType);
4126*0a6a1f1dSLionel Sambuc for (unsigned Kind = AbsFunctionKind; Kind != 0;
4127*0a6a1f1dSLionel Sambuc Kind = getLargerAbsoluteValueFunction(Kind)) {
4128*0a6a1f1dSLionel Sambuc QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4129*0a6a1f1dSLionel Sambuc if (Context.getTypeSize(ParamType) >= ArgSize) {
4130*0a6a1f1dSLionel Sambuc if (BestKind == 0)
4131*0a6a1f1dSLionel Sambuc BestKind = Kind;
4132*0a6a1f1dSLionel Sambuc else if (Context.hasSameType(ParamType, ArgType)) {
4133*0a6a1f1dSLionel Sambuc BestKind = Kind;
4134*0a6a1f1dSLionel Sambuc break;
4135*0a6a1f1dSLionel Sambuc }
4136*0a6a1f1dSLionel Sambuc }
4137*0a6a1f1dSLionel Sambuc }
4138*0a6a1f1dSLionel Sambuc return BestKind;
4139*0a6a1f1dSLionel Sambuc }
4140*0a6a1f1dSLionel Sambuc
4141*0a6a1f1dSLionel Sambuc enum AbsoluteValueKind {
4142*0a6a1f1dSLionel Sambuc AVK_Integer,
4143*0a6a1f1dSLionel Sambuc AVK_Floating,
4144*0a6a1f1dSLionel Sambuc AVK_Complex
4145*0a6a1f1dSLionel Sambuc };
4146*0a6a1f1dSLionel Sambuc
getAbsoluteValueKind(QualType T)4147*0a6a1f1dSLionel Sambuc static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4148*0a6a1f1dSLionel Sambuc if (T->isIntegralOrEnumerationType())
4149*0a6a1f1dSLionel Sambuc return AVK_Integer;
4150*0a6a1f1dSLionel Sambuc if (T->isRealFloatingType())
4151*0a6a1f1dSLionel Sambuc return AVK_Floating;
4152*0a6a1f1dSLionel Sambuc if (T->isAnyComplexType())
4153*0a6a1f1dSLionel Sambuc return AVK_Complex;
4154*0a6a1f1dSLionel Sambuc
4155*0a6a1f1dSLionel Sambuc llvm_unreachable("Type not integer, floating, or complex");
4156*0a6a1f1dSLionel Sambuc }
4157*0a6a1f1dSLionel Sambuc
4158*0a6a1f1dSLionel Sambuc // Changes the absolute value function to a different type. Preserves whether
4159*0a6a1f1dSLionel Sambuc // the function is a builtin.
changeAbsFunction(unsigned AbsKind,AbsoluteValueKind ValueKind)4160*0a6a1f1dSLionel Sambuc static unsigned changeAbsFunction(unsigned AbsKind,
4161*0a6a1f1dSLionel Sambuc AbsoluteValueKind ValueKind) {
4162*0a6a1f1dSLionel Sambuc switch (ValueKind) {
4163*0a6a1f1dSLionel Sambuc case AVK_Integer:
4164*0a6a1f1dSLionel Sambuc switch (AbsKind) {
4165*0a6a1f1dSLionel Sambuc default:
4166*0a6a1f1dSLionel Sambuc return 0;
4167*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabsf:
4168*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabs:
4169*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabsl:
4170*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabsf:
4171*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabs:
4172*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabsl:
4173*0a6a1f1dSLionel Sambuc return Builtin::BI__builtin_abs;
4174*0a6a1f1dSLionel Sambuc case Builtin::BIfabsf:
4175*0a6a1f1dSLionel Sambuc case Builtin::BIfabs:
4176*0a6a1f1dSLionel Sambuc case Builtin::BIfabsl:
4177*0a6a1f1dSLionel Sambuc case Builtin::BIcabsf:
4178*0a6a1f1dSLionel Sambuc case Builtin::BIcabs:
4179*0a6a1f1dSLionel Sambuc case Builtin::BIcabsl:
4180*0a6a1f1dSLionel Sambuc return Builtin::BIabs;
4181*0a6a1f1dSLionel Sambuc }
4182*0a6a1f1dSLionel Sambuc case AVK_Floating:
4183*0a6a1f1dSLionel Sambuc switch (AbsKind) {
4184*0a6a1f1dSLionel Sambuc default:
4185*0a6a1f1dSLionel Sambuc return 0;
4186*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_abs:
4187*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_labs:
4188*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_llabs:
4189*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabsf:
4190*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabs:
4191*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabsl:
4192*0a6a1f1dSLionel Sambuc return Builtin::BI__builtin_fabsf;
4193*0a6a1f1dSLionel Sambuc case Builtin::BIabs:
4194*0a6a1f1dSLionel Sambuc case Builtin::BIlabs:
4195*0a6a1f1dSLionel Sambuc case Builtin::BIllabs:
4196*0a6a1f1dSLionel Sambuc case Builtin::BIcabsf:
4197*0a6a1f1dSLionel Sambuc case Builtin::BIcabs:
4198*0a6a1f1dSLionel Sambuc case Builtin::BIcabsl:
4199*0a6a1f1dSLionel Sambuc return Builtin::BIfabsf;
4200*0a6a1f1dSLionel Sambuc }
4201*0a6a1f1dSLionel Sambuc case AVK_Complex:
4202*0a6a1f1dSLionel Sambuc switch (AbsKind) {
4203*0a6a1f1dSLionel Sambuc default:
4204*0a6a1f1dSLionel Sambuc return 0;
4205*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_abs:
4206*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_labs:
4207*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_llabs:
4208*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabsf:
4209*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabs:
4210*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabsl:
4211*0a6a1f1dSLionel Sambuc return Builtin::BI__builtin_cabsf;
4212*0a6a1f1dSLionel Sambuc case Builtin::BIabs:
4213*0a6a1f1dSLionel Sambuc case Builtin::BIlabs:
4214*0a6a1f1dSLionel Sambuc case Builtin::BIllabs:
4215*0a6a1f1dSLionel Sambuc case Builtin::BIfabsf:
4216*0a6a1f1dSLionel Sambuc case Builtin::BIfabs:
4217*0a6a1f1dSLionel Sambuc case Builtin::BIfabsl:
4218*0a6a1f1dSLionel Sambuc return Builtin::BIcabsf;
4219*0a6a1f1dSLionel Sambuc }
4220*0a6a1f1dSLionel Sambuc }
4221*0a6a1f1dSLionel Sambuc llvm_unreachable("Unable to convert function");
4222*0a6a1f1dSLionel Sambuc }
4223*0a6a1f1dSLionel Sambuc
getAbsoluteValueFunctionKind(const FunctionDecl * FDecl)4224*0a6a1f1dSLionel Sambuc static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4225*0a6a1f1dSLionel Sambuc const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4226*0a6a1f1dSLionel Sambuc if (!FnInfo)
4227*0a6a1f1dSLionel Sambuc return 0;
4228*0a6a1f1dSLionel Sambuc
4229*0a6a1f1dSLionel Sambuc switch (FDecl->getBuiltinID()) {
4230*0a6a1f1dSLionel Sambuc default:
4231*0a6a1f1dSLionel Sambuc return 0;
4232*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_abs:
4233*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabs:
4234*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabsf:
4235*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_fabsl:
4236*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_labs:
4237*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_llabs:
4238*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabs:
4239*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabsf:
4240*0a6a1f1dSLionel Sambuc case Builtin::BI__builtin_cabsl:
4241*0a6a1f1dSLionel Sambuc case Builtin::BIabs:
4242*0a6a1f1dSLionel Sambuc case Builtin::BIlabs:
4243*0a6a1f1dSLionel Sambuc case Builtin::BIllabs:
4244*0a6a1f1dSLionel Sambuc case Builtin::BIfabs:
4245*0a6a1f1dSLionel Sambuc case Builtin::BIfabsf:
4246*0a6a1f1dSLionel Sambuc case Builtin::BIfabsl:
4247*0a6a1f1dSLionel Sambuc case Builtin::BIcabs:
4248*0a6a1f1dSLionel Sambuc case Builtin::BIcabsf:
4249*0a6a1f1dSLionel Sambuc case Builtin::BIcabsl:
4250*0a6a1f1dSLionel Sambuc return FDecl->getBuiltinID();
4251*0a6a1f1dSLionel Sambuc }
4252*0a6a1f1dSLionel Sambuc llvm_unreachable("Unknown Builtin type");
4253*0a6a1f1dSLionel Sambuc }
4254*0a6a1f1dSLionel Sambuc
4255*0a6a1f1dSLionel Sambuc // If the replacement is valid, emit a note with replacement function.
4256*0a6a1f1dSLionel Sambuc // Additionally, suggest including the proper header if not already included.
emitReplacement(Sema & S,SourceLocation Loc,SourceRange Range,unsigned AbsKind,QualType ArgType)4257*0a6a1f1dSLionel Sambuc static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
4258*0a6a1f1dSLionel Sambuc unsigned AbsKind, QualType ArgType) {
4259*0a6a1f1dSLionel Sambuc bool EmitHeaderHint = true;
4260*0a6a1f1dSLionel Sambuc const char *HeaderName = nullptr;
4261*0a6a1f1dSLionel Sambuc const char *FunctionName = nullptr;
4262*0a6a1f1dSLionel Sambuc if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4263*0a6a1f1dSLionel Sambuc FunctionName = "std::abs";
4264*0a6a1f1dSLionel Sambuc if (ArgType->isIntegralOrEnumerationType()) {
4265*0a6a1f1dSLionel Sambuc HeaderName = "cstdlib";
4266*0a6a1f1dSLionel Sambuc } else if (ArgType->isRealFloatingType()) {
4267*0a6a1f1dSLionel Sambuc HeaderName = "cmath";
4268*0a6a1f1dSLionel Sambuc } else {
4269*0a6a1f1dSLionel Sambuc llvm_unreachable("Invalid Type");
4270*0a6a1f1dSLionel Sambuc }
4271*0a6a1f1dSLionel Sambuc
4272*0a6a1f1dSLionel Sambuc // Lookup all std::abs
4273*0a6a1f1dSLionel Sambuc if (NamespaceDecl *Std = S.getStdNamespace()) {
4274*0a6a1f1dSLionel Sambuc LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4275*0a6a1f1dSLionel Sambuc R.suppressDiagnostics();
4276*0a6a1f1dSLionel Sambuc S.LookupQualifiedName(R, Std);
4277*0a6a1f1dSLionel Sambuc
4278*0a6a1f1dSLionel Sambuc for (const auto *I : R) {
4279*0a6a1f1dSLionel Sambuc const FunctionDecl *FDecl = nullptr;
4280*0a6a1f1dSLionel Sambuc if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4281*0a6a1f1dSLionel Sambuc FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4282*0a6a1f1dSLionel Sambuc } else {
4283*0a6a1f1dSLionel Sambuc FDecl = dyn_cast<FunctionDecl>(I);
4284*0a6a1f1dSLionel Sambuc }
4285*0a6a1f1dSLionel Sambuc if (!FDecl)
4286*0a6a1f1dSLionel Sambuc continue;
4287*0a6a1f1dSLionel Sambuc
4288*0a6a1f1dSLionel Sambuc // Found std::abs(), check that they are the right ones.
4289*0a6a1f1dSLionel Sambuc if (FDecl->getNumParams() != 1)
4290*0a6a1f1dSLionel Sambuc continue;
4291*0a6a1f1dSLionel Sambuc
4292*0a6a1f1dSLionel Sambuc // Check that the parameter type can handle the argument.
4293*0a6a1f1dSLionel Sambuc QualType ParamType = FDecl->getParamDecl(0)->getType();
4294*0a6a1f1dSLionel Sambuc if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4295*0a6a1f1dSLionel Sambuc S.Context.getTypeSize(ArgType) <=
4296*0a6a1f1dSLionel Sambuc S.Context.getTypeSize(ParamType)) {
4297*0a6a1f1dSLionel Sambuc // Found a function, don't need the header hint.
4298*0a6a1f1dSLionel Sambuc EmitHeaderHint = false;
4299*0a6a1f1dSLionel Sambuc break;
4300*0a6a1f1dSLionel Sambuc }
4301*0a6a1f1dSLionel Sambuc }
4302*0a6a1f1dSLionel Sambuc }
4303*0a6a1f1dSLionel Sambuc } else {
4304*0a6a1f1dSLionel Sambuc FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4305*0a6a1f1dSLionel Sambuc HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4306*0a6a1f1dSLionel Sambuc
4307*0a6a1f1dSLionel Sambuc if (HeaderName) {
4308*0a6a1f1dSLionel Sambuc DeclarationName DN(&S.Context.Idents.get(FunctionName));
4309*0a6a1f1dSLionel Sambuc LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4310*0a6a1f1dSLionel Sambuc R.suppressDiagnostics();
4311*0a6a1f1dSLionel Sambuc S.LookupName(R, S.getCurScope());
4312*0a6a1f1dSLionel Sambuc
4313*0a6a1f1dSLionel Sambuc if (R.isSingleResult()) {
4314*0a6a1f1dSLionel Sambuc FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4315*0a6a1f1dSLionel Sambuc if (FD && FD->getBuiltinID() == AbsKind) {
4316*0a6a1f1dSLionel Sambuc EmitHeaderHint = false;
4317*0a6a1f1dSLionel Sambuc } else {
4318*0a6a1f1dSLionel Sambuc return;
4319*0a6a1f1dSLionel Sambuc }
4320*0a6a1f1dSLionel Sambuc } else if (!R.empty()) {
4321*0a6a1f1dSLionel Sambuc return;
4322*0a6a1f1dSLionel Sambuc }
4323*0a6a1f1dSLionel Sambuc }
4324*0a6a1f1dSLionel Sambuc }
4325*0a6a1f1dSLionel Sambuc
4326*0a6a1f1dSLionel Sambuc S.Diag(Loc, diag::note_replace_abs_function)
4327*0a6a1f1dSLionel Sambuc << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
4328*0a6a1f1dSLionel Sambuc
4329*0a6a1f1dSLionel Sambuc if (!HeaderName)
4330*0a6a1f1dSLionel Sambuc return;
4331*0a6a1f1dSLionel Sambuc
4332*0a6a1f1dSLionel Sambuc if (!EmitHeaderHint)
4333*0a6a1f1dSLionel Sambuc return;
4334*0a6a1f1dSLionel Sambuc
4335*0a6a1f1dSLionel Sambuc S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4336*0a6a1f1dSLionel Sambuc << FunctionName;
4337*0a6a1f1dSLionel Sambuc }
4338*0a6a1f1dSLionel Sambuc
IsFunctionStdAbs(const FunctionDecl * FDecl)4339*0a6a1f1dSLionel Sambuc static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4340*0a6a1f1dSLionel Sambuc if (!FDecl)
4341*0a6a1f1dSLionel Sambuc return false;
4342*0a6a1f1dSLionel Sambuc
4343*0a6a1f1dSLionel Sambuc if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4344*0a6a1f1dSLionel Sambuc return false;
4345*0a6a1f1dSLionel Sambuc
4346*0a6a1f1dSLionel Sambuc const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4347*0a6a1f1dSLionel Sambuc
4348*0a6a1f1dSLionel Sambuc while (ND && ND->isInlineNamespace()) {
4349*0a6a1f1dSLionel Sambuc ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
4350*0a6a1f1dSLionel Sambuc }
4351*0a6a1f1dSLionel Sambuc
4352*0a6a1f1dSLionel Sambuc if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4353*0a6a1f1dSLionel Sambuc return false;
4354*0a6a1f1dSLionel Sambuc
4355*0a6a1f1dSLionel Sambuc if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4356*0a6a1f1dSLionel Sambuc return false;
4357*0a6a1f1dSLionel Sambuc
4358*0a6a1f1dSLionel Sambuc return true;
4359*0a6a1f1dSLionel Sambuc }
4360*0a6a1f1dSLionel Sambuc
4361*0a6a1f1dSLionel Sambuc // Warn when using the wrong abs() function.
CheckAbsoluteValueFunction(const CallExpr * Call,const FunctionDecl * FDecl,IdentifierInfo * FnInfo)4362*0a6a1f1dSLionel Sambuc void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4363*0a6a1f1dSLionel Sambuc const FunctionDecl *FDecl,
4364*0a6a1f1dSLionel Sambuc IdentifierInfo *FnInfo) {
4365*0a6a1f1dSLionel Sambuc if (Call->getNumArgs() != 1)
4366*0a6a1f1dSLionel Sambuc return;
4367*0a6a1f1dSLionel Sambuc
4368*0a6a1f1dSLionel Sambuc unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
4369*0a6a1f1dSLionel Sambuc bool IsStdAbs = IsFunctionStdAbs(FDecl);
4370*0a6a1f1dSLionel Sambuc if (AbsKind == 0 && !IsStdAbs)
4371*0a6a1f1dSLionel Sambuc return;
4372*0a6a1f1dSLionel Sambuc
4373*0a6a1f1dSLionel Sambuc QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4374*0a6a1f1dSLionel Sambuc QualType ParamType = Call->getArg(0)->getType();
4375*0a6a1f1dSLionel Sambuc
4376*0a6a1f1dSLionel Sambuc // Unsigned types cannot be negative. Suggest removing the absolute value
4377*0a6a1f1dSLionel Sambuc // function call.
4378*0a6a1f1dSLionel Sambuc if (ArgType->isUnsignedIntegerType()) {
4379*0a6a1f1dSLionel Sambuc const char *FunctionName =
4380*0a6a1f1dSLionel Sambuc IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
4381*0a6a1f1dSLionel Sambuc Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4382*0a6a1f1dSLionel Sambuc Diag(Call->getExprLoc(), diag::note_remove_abs)
4383*0a6a1f1dSLionel Sambuc << FunctionName
4384*0a6a1f1dSLionel Sambuc << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4385*0a6a1f1dSLionel Sambuc return;
4386*0a6a1f1dSLionel Sambuc }
4387*0a6a1f1dSLionel Sambuc
4388*0a6a1f1dSLionel Sambuc // std::abs has overloads which prevent most of the absolute value problems
4389*0a6a1f1dSLionel Sambuc // from occurring.
4390*0a6a1f1dSLionel Sambuc if (IsStdAbs)
4391*0a6a1f1dSLionel Sambuc return;
4392*0a6a1f1dSLionel Sambuc
4393*0a6a1f1dSLionel Sambuc AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4394*0a6a1f1dSLionel Sambuc AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4395*0a6a1f1dSLionel Sambuc
4396*0a6a1f1dSLionel Sambuc // The argument and parameter are the same kind. Check if they are the right
4397*0a6a1f1dSLionel Sambuc // size.
4398*0a6a1f1dSLionel Sambuc if (ArgValueKind == ParamValueKind) {
4399*0a6a1f1dSLionel Sambuc if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4400*0a6a1f1dSLionel Sambuc return;
4401*0a6a1f1dSLionel Sambuc
4402*0a6a1f1dSLionel Sambuc unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4403*0a6a1f1dSLionel Sambuc Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4404*0a6a1f1dSLionel Sambuc << FDecl << ArgType << ParamType;
4405*0a6a1f1dSLionel Sambuc
4406*0a6a1f1dSLionel Sambuc if (NewAbsKind == 0)
4407*0a6a1f1dSLionel Sambuc return;
4408*0a6a1f1dSLionel Sambuc
4409*0a6a1f1dSLionel Sambuc emitReplacement(*this, Call->getExprLoc(),
4410*0a6a1f1dSLionel Sambuc Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4411*0a6a1f1dSLionel Sambuc return;
4412*0a6a1f1dSLionel Sambuc }
4413*0a6a1f1dSLionel Sambuc
4414*0a6a1f1dSLionel Sambuc // ArgValueKind != ParamValueKind
4415*0a6a1f1dSLionel Sambuc // The wrong type of absolute value function was used. Attempt to find the
4416*0a6a1f1dSLionel Sambuc // proper one.
4417*0a6a1f1dSLionel Sambuc unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4418*0a6a1f1dSLionel Sambuc NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4419*0a6a1f1dSLionel Sambuc if (NewAbsKind == 0)
4420*0a6a1f1dSLionel Sambuc return;
4421*0a6a1f1dSLionel Sambuc
4422*0a6a1f1dSLionel Sambuc Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4423*0a6a1f1dSLionel Sambuc << FDecl << ParamValueKind << ArgValueKind;
4424*0a6a1f1dSLionel Sambuc
4425*0a6a1f1dSLionel Sambuc emitReplacement(*this, Call->getExprLoc(),
4426*0a6a1f1dSLionel Sambuc Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4427*0a6a1f1dSLionel Sambuc return;
4428*0a6a1f1dSLionel Sambuc }
4429*0a6a1f1dSLionel Sambuc
4430f4a2713aSLionel Sambuc //===--- CHECK: Standard memory functions ---------------------------------===//
4431f4a2713aSLionel Sambuc
4432*0a6a1f1dSLionel Sambuc /// \brief Takes the expression passed to the size_t parameter of functions
4433*0a6a1f1dSLionel Sambuc /// such as memcmp, strncat, etc and warns if it's a comparison.
4434*0a6a1f1dSLionel Sambuc ///
4435*0a6a1f1dSLionel Sambuc /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
CheckMemorySizeofForComparison(Sema & S,const Expr * E,IdentifierInfo * FnName,SourceLocation FnLoc,SourceLocation RParenLoc)4436*0a6a1f1dSLionel Sambuc static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4437*0a6a1f1dSLionel Sambuc IdentifierInfo *FnName,
4438*0a6a1f1dSLionel Sambuc SourceLocation FnLoc,
4439*0a6a1f1dSLionel Sambuc SourceLocation RParenLoc) {
4440*0a6a1f1dSLionel Sambuc const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4441*0a6a1f1dSLionel Sambuc if (!Size)
4442f4a2713aSLionel Sambuc return false;
4443*0a6a1f1dSLionel Sambuc
4444*0a6a1f1dSLionel Sambuc // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4445*0a6a1f1dSLionel Sambuc if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4446*0a6a1f1dSLionel Sambuc return false;
4447*0a6a1f1dSLionel Sambuc
4448*0a6a1f1dSLionel Sambuc SourceRange SizeRange = Size->getSourceRange();
4449*0a6a1f1dSLionel Sambuc S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4450*0a6a1f1dSLionel Sambuc << SizeRange << FnName;
4451*0a6a1f1dSLionel Sambuc S.Diag(FnLoc, diag::note_memsize_comparison_paren)
4452*0a6a1f1dSLionel Sambuc << FnName << FixItHint::CreateInsertion(
4453*0a6a1f1dSLionel Sambuc S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
4454*0a6a1f1dSLionel Sambuc << FixItHint::CreateRemoval(RParenLoc);
4455*0a6a1f1dSLionel Sambuc S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
4456*0a6a1f1dSLionel Sambuc << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
4457*0a6a1f1dSLionel Sambuc << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4458*0a6a1f1dSLionel Sambuc ")");
4459*0a6a1f1dSLionel Sambuc
4460*0a6a1f1dSLionel Sambuc return true;
4461*0a6a1f1dSLionel Sambuc }
4462*0a6a1f1dSLionel Sambuc
4463*0a6a1f1dSLionel Sambuc /// \brief Determine whether the given type is or contains a dynamic class type
4464*0a6a1f1dSLionel Sambuc /// (e.g., whether it has a vtable).
getContainedDynamicClass(QualType T,bool & IsContained)4465*0a6a1f1dSLionel Sambuc static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4466*0a6a1f1dSLionel Sambuc bool &IsContained) {
4467*0a6a1f1dSLionel Sambuc // Look through array types while ignoring qualifiers.
4468*0a6a1f1dSLionel Sambuc const Type *Ty = T->getBaseElementTypeUnsafe();
4469*0a6a1f1dSLionel Sambuc IsContained = false;
4470*0a6a1f1dSLionel Sambuc
4471*0a6a1f1dSLionel Sambuc const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4472*0a6a1f1dSLionel Sambuc RD = RD ? RD->getDefinition() : nullptr;
4473*0a6a1f1dSLionel Sambuc if (!RD)
4474*0a6a1f1dSLionel Sambuc return nullptr;
4475*0a6a1f1dSLionel Sambuc
4476*0a6a1f1dSLionel Sambuc if (RD->isDynamicClass())
4477*0a6a1f1dSLionel Sambuc return RD;
4478*0a6a1f1dSLionel Sambuc
4479*0a6a1f1dSLionel Sambuc // Check all the fields. If any bases were dynamic, the class is dynamic.
4480*0a6a1f1dSLionel Sambuc // It's impossible for a class to transitively contain itself by value, so
4481*0a6a1f1dSLionel Sambuc // infinite recursion is impossible.
4482*0a6a1f1dSLionel Sambuc for (auto *FD : RD->fields()) {
4483*0a6a1f1dSLionel Sambuc bool SubContained;
4484*0a6a1f1dSLionel Sambuc if (const CXXRecordDecl *ContainedRD =
4485*0a6a1f1dSLionel Sambuc getContainedDynamicClass(FD->getType(), SubContained)) {
4486*0a6a1f1dSLionel Sambuc IsContained = true;
4487*0a6a1f1dSLionel Sambuc return ContainedRD;
4488*0a6a1f1dSLionel Sambuc }
4489*0a6a1f1dSLionel Sambuc }
4490*0a6a1f1dSLionel Sambuc
4491*0a6a1f1dSLionel Sambuc return nullptr;
4492f4a2713aSLionel Sambuc }
4493f4a2713aSLionel Sambuc
4494f4a2713aSLionel Sambuc /// \brief If E is a sizeof expression, returns its argument expression,
4495f4a2713aSLionel Sambuc /// otherwise returns NULL.
getSizeOfExprArg(const Expr * E)4496f4a2713aSLionel Sambuc static const Expr *getSizeOfExprArg(const Expr* E) {
4497f4a2713aSLionel Sambuc if (const UnaryExprOrTypeTraitExpr *SizeOf =
4498f4a2713aSLionel Sambuc dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4499f4a2713aSLionel Sambuc if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4500f4a2713aSLionel Sambuc return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
4501f4a2713aSLionel Sambuc
4502*0a6a1f1dSLionel Sambuc return nullptr;
4503f4a2713aSLionel Sambuc }
4504f4a2713aSLionel Sambuc
4505f4a2713aSLionel Sambuc /// \brief If E is a sizeof expression, returns its argument type.
getSizeOfArgType(const Expr * E)4506f4a2713aSLionel Sambuc static QualType getSizeOfArgType(const Expr* E) {
4507f4a2713aSLionel Sambuc if (const UnaryExprOrTypeTraitExpr *SizeOf =
4508f4a2713aSLionel Sambuc dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4509f4a2713aSLionel Sambuc if (SizeOf->getKind() == clang::UETT_SizeOf)
4510f4a2713aSLionel Sambuc return SizeOf->getTypeOfArgument();
4511f4a2713aSLionel Sambuc
4512f4a2713aSLionel Sambuc return QualType();
4513f4a2713aSLionel Sambuc }
4514f4a2713aSLionel Sambuc
4515f4a2713aSLionel Sambuc /// \brief Check for dangerous or invalid arguments to memset().
4516f4a2713aSLionel Sambuc ///
4517f4a2713aSLionel Sambuc /// This issues warnings on known problematic, dangerous or unspecified
4518f4a2713aSLionel Sambuc /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4519f4a2713aSLionel Sambuc /// function calls.
4520f4a2713aSLionel Sambuc ///
4521f4a2713aSLionel Sambuc /// \param Call The call expression to diagnose.
CheckMemaccessArguments(const CallExpr * Call,unsigned BId,IdentifierInfo * FnName)4522f4a2713aSLionel Sambuc void Sema::CheckMemaccessArguments(const CallExpr *Call,
4523f4a2713aSLionel Sambuc unsigned BId,
4524f4a2713aSLionel Sambuc IdentifierInfo *FnName) {
4525f4a2713aSLionel Sambuc assert(BId != 0);
4526f4a2713aSLionel Sambuc
4527f4a2713aSLionel Sambuc // It is possible to have a non-standard definition of memset. Validate
4528f4a2713aSLionel Sambuc // we have enough arguments, and if not, abort further checking.
4529f4a2713aSLionel Sambuc unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
4530f4a2713aSLionel Sambuc if (Call->getNumArgs() < ExpectedNumArgs)
4531f4a2713aSLionel Sambuc return;
4532f4a2713aSLionel Sambuc
4533f4a2713aSLionel Sambuc unsigned LastArg = (BId == Builtin::BImemset ||
4534f4a2713aSLionel Sambuc BId == Builtin::BIstrndup ? 1 : 2);
4535f4a2713aSLionel Sambuc unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
4536f4a2713aSLionel Sambuc const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
4537f4a2713aSLionel Sambuc
4538*0a6a1f1dSLionel Sambuc if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4539*0a6a1f1dSLionel Sambuc Call->getLocStart(), Call->getRParenLoc()))
4540*0a6a1f1dSLionel Sambuc return;
4541*0a6a1f1dSLionel Sambuc
4542f4a2713aSLionel Sambuc // We have special checking when the length is a sizeof expression.
4543f4a2713aSLionel Sambuc QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4544f4a2713aSLionel Sambuc const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4545f4a2713aSLionel Sambuc llvm::FoldingSetNodeID SizeOfArgID;
4546f4a2713aSLionel Sambuc
4547f4a2713aSLionel Sambuc for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4548f4a2713aSLionel Sambuc const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
4549f4a2713aSLionel Sambuc SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
4550f4a2713aSLionel Sambuc
4551f4a2713aSLionel Sambuc QualType DestTy = Dest->getType();
4552f4a2713aSLionel Sambuc if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4553f4a2713aSLionel Sambuc QualType PointeeTy = DestPtrTy->getPointeeType();
4554f4a2713aSLionel Sambuc
4555f4a2713aSLionel Sambuc // Never warn about void type pointers. This can be used to suppress
4556f4a2713aSLionel Sambuc // false positives.
4557f4a2713aSLionel Sambuc if (PointeeTy->isVoidType())
4558f4a2713aSLionel Sambuc continue;
4559f4a2713aSLionel Sambuc
4560f4a2713aSLionel Sambuc // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4561f4a2713aSLionel Sambuc // actually comparing the expressions for equality. Because computing the
4562f4a2713aSLionel Sambuc // expression IDs can be expensive, we only do this if the diagnostic is
4563f4a2713aSLionel Sambuc // enabled.
4564f4a2713aSLionel Sambuc if (SizeOfArg &&
4565*0a6a1f1dSLionel Sambuc !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4566f4a2713aSLionel Sambuc SizeOfArg->getExprLoc())) {
4567f4a2713aSLionel Sambuc // We only compute IDs for expressions if the warning is enabled, and
4568f4a2713aSLionel Sambuc // cache the sizeof arg's ID.
4569f4a2713aSLionel Sambuc if (SizeOfArgID == llvm::FoldingSetNodeID())
4570f4a2713aSLionel Sambuc SizeOfArg->Profile(SizeOfArgID, Context, true);
4571f4a2713aSLionel Sambuc llvm::FoldingSetNodeID DestID;
4572f4a2713aSLionel Sambuc Dest->Profile(DestID, Context, true);
4573f4a2713aSLionel Sambuc if (DestID == SizeOfArgID) {
4574f4a2713aSLionel Sambuc // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4575f4a2713aSLionel Sambuc // over sizeof(src) as well.
4576f4a2713aSLionel Sambuc unsigned ActionIdx = 0; // Default is to suggest dereferencing.
4577f4a2713aSLionel Sambuc StringRef ReadableName = FnName->getName();
4578f4a2713aSLionel Sambuc
4579f4a2713aSLionel Sambuc if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
4580f4a2713aSLionel Sambuc if (UnaryOp->getOpcode() == UO_AddrOf)
4581f4a2713aSLionel Sambuc ActionIdx = 1; // If its an address-of operator, just remove it.
4582f4a2713aSLionel Sambuc if (!PointeeTy->isIncompleteType() &&
4583f4a2713aSLionel Sambuc (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
4584f4a2713aSLionel Sambuc ActionIdx = 2; // If the pointee's size is sizeof(char),
4585f4a2713aSLionel Sambuc // suggest an explicit length.
4586f4a2713aSLionel Sambuc
4587f4a2713aSLionel Sambuc // If the function is defined as a builtin macro, do not show macro
4588f4a2713aSLionel Sambuc // expansion.
4589f4a2713aSLionel Sambuc SourceLocation SL = SizeOfArg->getExprLoc();
4590f4a2713aSLionel Sambuc SourceRange DSR = Dest->getSourceRange();
4591f4a2713aSLionel Sambuc SourceRange SSR = SizeOfArg->getSourceRange();
4592*0a6a1f1dSLionel Sambuc SourceManager &SM = getSourceManager();
4593f4a2713aSLionel Sambuc
4594f4a2713aSLionel Sambuc if (SM.isMacroArgExpansion(SL)) {
4595f4a2713aSLionel Sambuc ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4596f4a2713aSLionel Sambuc SL = SM.getSpellingLoc(SL);
4597f4a2713aSLionel Sambuc DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4598f4a2713aSLionel Sambuc SM.getSpellingLoc(DSR.getEnd()));
4599f4a2713aSLionel Sambuc SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4600f4a2713aSLionel Sambuc SM.getSpellingLoc(SSR.getEnd()));
4601f4a2713aSLionel Sambuc }
4602f4a2713aSLionel Sambuc
4603f4a2713aSLionel Sambuc DiagRuntimeBehavior(SL, SizeOfArg,
4604f4a2713aSLionel Sambuc PDiag(diag::warn_sizeof_pointer_expr_memaccess)
4605f4a2713aSLionel Sambuc << ReadableName
4606f4a2713aSLionel Sambuc << PointeeTy
4607f4a2713aSLionel Sambuc << DestTy
4608f4a2713aSLionel Sambuc << DSR
4609f4a2713aSLionel Sambuc << SSR);
4610f4a2713aSLionel Sambuc DiagRuntimeBehavior(SL, SizeOfArg,
4611f4a2713aSLionel Sambuc PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4612f4a2713aSLionel Sambuc << ActionIdx
4613f4a2713aSLionel Sambuc << SSR);
4614f4a2713aSLionel Sambuc
4615f4a2713aSLionel Sambuc break;
4616f4a2713aSLionel Sambuc }
4617f4a2713aSLionel Sambuc }
4618f4a2713aSLionel Sambuc
4619f4a2713aSLionel Sambuc // Also check for cases where the sizeof argument is the exact same
4620f4a2713aSLionel Sambuc // type as the memory argument, and where it points to a user-defined
4621f4a2713aSLionel Sambuc // record type.
4622f4a2713aSLionel Sambuc if (SizeOfArgTy != QualType()) {
4623f4a2713aSLionel Sambuc if (PointeeTy->isRecordType() &&
4624f4a2713aSLionel Sambuc Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4625f4a2713aSLionel Sambuc DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4626f4a2713aSLionel Sambuc PDiag(diag::warn_sizeof_pointer_type_memaccess)
4627f4a2713aSLionel Sambuc << FnName << SizeOfArgTy << ArgIdx
4628f4a2713aSLionel Sambuc << PointeeTy << Dest->getSourceRange()
4629f4a2713aSLionel Sambuc << LenExpr->getSourceRange());
4630f4a2713aSLionel Sambuc break;
4631f4a2713aSLionel Sambuc }
4632f4a2713aSLionel Sambuc }
4633f4a2713aSLionel Sambuc
4634f4a2713aSLionel Sambuc // Always complain about dynamic classes.
4635*0a6a1f1dSLionel Sambuc bool IsContained;
4636*0a6a1f1dSLionel Sambuc if (const CXXRecordDecl *ContainedRD =
4637*0a6a1f1dSLionel Sambuc getContainedDynamicClass(PointeeTy, IsContained)) {
4638f4a2713aSLionel Sambuc
4639f4a2713aSLionel Sambuc unsigned OperationType = 0;
4640f4a2713aSLionel Sambuc // "overwritten" if we're warning about the destination for any call
4641f4a2713aSLionel Sambuc // but memcmp; otherwise a verb appropriate to the call.
4642f4a2713aSLionel Sambuc if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4643f4a2713aSLionel Sambuc if (BId == Builtin::BImemcpy)
4644f4a2713aSLionel Sambuc OperationType = 1;
4645f4a2713aSLionel Sambuc else if(BId == Builtin::BImemmove)
4646f4a2713aSLionel Sambuc OperationType = 2;
4647f4a2713aSLionel Sambuc else if (BId == Builtin::BImemcmp)
4648f4a2713aSLionel Sambuc OperationType = 3;
4649f4a2713aSLionel Sambuc }
4650f4a2713aSLionel Sambuc
4651f4a2713aSLionel Sambuc DiagRuntimeBehavior(
4652f4a2713aSLionel Sambuc Dest->getExprLoc(), Dest,
4653f4a2713aSLionel Sambuc PDiag(diag::warn_dyn_class_memaccess)
4654f4a2713aSLionel Sambuc << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4655*0a6a1f1dSLionel Sambuc << FnName << IsContained << ContainedRD << OperationType
4656f4a2713aSLionel Sambuc << Call->getCallee()->getSourceRange());
4657f4a2713aSLionel Sambuc } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4658f4a2713aSLionel Sambuc BId != Builtin::BImemset)
4659f4a2713aSLionel Sambuc DiagRuntimeBehavior(
4660f4a2713aSLionel Sambuc Dest->getExprLoc(), Dest,
4661f4a2713aSLionel Sambuc PDiag(diag::warn_arc_object_memaccess)
4662f4a2713aSLionel Sambuc << ArgIdx << FnName << PointeeTy
4663f4a2713aSLionel Sambuc << Call->getCallee()->getSourceRange());
4664f4a2713aSLionel Sambuc else
4665f4a2713aSLionel Sambuc continue;
4666f4a2713aSLionel Sambuc
4667f4a2713aSLionel Sambuc DiagRuntimeBehavior(
4668f4a2713aSLionel Sambuc Dest->getExprLoc(), Dest,
4669f4a2713aSLionel Sambuc PDiag(diag::note_bad_memaccess_silence)
4670f4a2713aSLionel Sambuc << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4671f4a2713aSLionel Sambuc break;
4672f4a2713aSLionel Sambuc }
4673f4a2713aSLionel Sambuc }
4674f4a2713aSLionel Sambuc }
4675f4a2713aSLionel Sambuc
4676f4a2713aSLionel Sambuc // A little helper routine: ignore addition and subtraction of integer literals.
4677f4a2713aSLionel Sambuc // This intentionally does not ignore all integer constant expressions because
4678f4a2713aSLionel Sambuc // we don't want to remove sizeof().
ignoreLiteralAdditions(const Expr * Ex,ASTContext & Ctx)4679f4a2713aSLionel Sambuc static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4680f4a2713aSLionel Sambuc Ex = Ex->IgnoreParenCasts();
4681f4a2713aSLionel Sambuc
4682f4a2713aSLionel Sambuc for (;;) {
4683f4a2713aSLionel Sambuc const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4684f4a2713aSLionel Sambuc if (!BO || !BO->isAdditiveOp())
4685f4a2713aSLionel Sambuc break;
4686f4a2713aSLionel Sambuc
4687f4a2713aSLionel Sambuc const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4688f4a2713aSLionel Sambuc const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4689f4a2713aSLionel Sambuc
4690f4a2713aSLionel Sambuc if (isa<IntegerLiteral>(RHS))
4691f4a2713aSLionel Sambuc Ex = LHS;
4692f4a2713aSLionel Sambuc else if (isa<IntegerLiteral>(LHS))
4693f4a2713aSLionel Sambuc Ex = RHS;
4694f4a2713aSLionel Sambuc else
4695f4a2713aSLionel Sambuc break;
4696f4a2713aSLionel Sambuc }
4697f4a2713aSLionel Sambuc
4698f4a2713aSLionel Sambuc return Ex;
4699f4a2713aSLionel Sambuc }
4700f4a2713aSLionel Sambuc
isConstantSizeArrayWithMoreThanOneElement(QualType Ty,ASTContext & Context)4701f4a2713aSLionel Sambuc static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4702f4a2713aSLionel Sambuc ASTContext &Context) {
4703f4a2713aSLionel Sambuc // Only handle constant-sized or VLAs, but not flexible members.
4704f4a2713aSLionel Sambuc if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4705f4a2713aSLionel Sambuc // Only issue the FIXIT for arrays of size > 1.
4706f4a2713aSLionel Sambuc if (CAT->getSize().getSExtValue() <= 1)
4707f4a2713aSLionel Sambuc return false;
4708f4a2713aSLionel Sambuc } else if (!Ty->isVariableArrayType()) {
4709f4a2713aSLionel Sambuc return false;
4710f4a2713aSLionel Sambuc }
4711f4a2713aSLionel Sambuc return true;
4712f4a2713aSLionel Sambuc }
4713f4a2713aSLionel Sambuc
4714f4a2713aSLionel Sambuc // Warn if the user has made the 'size' argument to strlcpy or strlcat
4715f4a2713aSLionel Sambuc // be the size of the source, instead of the destination.
CheckStrlcpycatArguments(const CallExpr * Call,IdentifierInfo * FnName)4716f4a2713aSLionel Sambuc void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4717f4a2713aSLionel Sambuc IdentifierInfo *FnName) {
4718f4a2713aSLionel Sambuc
4719f4a2713aSLionel Sambuc // Don't crash if the user has the wrong number of arguments
4720*0a6a1f1dSLionel Sambuc unsigned NumArgs = Call->getNumArgs();
4721*0a6a1f1dSLionel Sambuc if ((NumArgs != 3) && (NumArgs != 4))
4722f4a2713aSLionel Sambuc return;
4723f4a2713aSLionel Sambuc
4724f4a2713aSLionel Sambuc const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4725f4a2713aSLionel Sambuc const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4726*0a6a1f1dSLionel Sambuc const Expr *CompareWithSrc = nullptr;
4727*0a6a1f1dSLionel Sambuc
4728*0a6a1f1dSLionel Sambuc if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4729*0a6a1f1dSLionel Sambuc Call->getLocStart(), Call->getRParenLoc()))
4730*0a6a1f1dSLionel Sambuc return;
4731f4a2713aSLionel Sambuc
4732f4a2713aSLionel Sambuc // Look for 'strlcpy(dst, x, sizeof(x))'
4733f4a2713aSLionel Sambuc if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4734f4a2713aSLionel Sambuc CompareWithSrc = Ex;
4735f4a2713aSLionel Sambuc else {
4736f4a2713aSLionel Sambuc // Look for 'strlcpy(dst, x, strlen(x))'
4737f4a2713aSLionel Sambuc if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
4738*0a6a1f1dSLionel Sambuc if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4739*0a6a1f1dSLionel Sambuc SizeCall->getNumArgs() == 1)
4740f4a2713aSLionel Sambuc CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4741f4a2713aSLionel Sambuc }
4742f4a2713aSLionel Sambuc }
4743f4a2713aSLionel Sambuc
4744f4a2713aSLionel Sambuc if (!CompareWithSrc)
4745f4a2713aSLionel Sambuc return;
4746f4a2713aSLionel Sambuc
4747f4a2713aSLionel Sambuc // Determine if the argument to sizeof/strlen is equal to the source
4748f4a2713aSLionel Sambuc // argument. In principle there's all kinds of things you could do
4749f4a2713aSLionel Sambuc // here, for instance creating an == expression and evaluating it with
4750f4a2713aSLionel Sambuc // EvaluateAsBooleanCondition, but this uses a more direct technique:
4751f4a2713aSLionel Sambuc const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4752f4a2713aSLionel Sambuc if (!SrcArgDRE)
4753f4a2713aSLionel Sambuc return;
4754f4a2713aSLionel Sambuc
4755f4a2713aSLionel Sambuc const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4756f4a2713aSLionel Sambuc if (!CompareWithSrcDRE ||
4757f4a2713aSLionel Sambuc SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4758f4a2713aSLionel Sambuc return;
4759f4a2713aSLionel Sambuc
4760f4a2713aSLionel Sambuc const Expr *OriginalSizeArg = Call->getArg(2);
4761f4a2713aSLionel Sambuc Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4762f4a2713aSLionel Sambuc << OriginalSizeArg->getSourceRange() << FnName;
4763f4a2713aSLionel Sambuc
4764f4a2713aSLionel Sambuc // Output a FIXIT hint if the destination is an array (rather than a
4765f4a2713aSLionel Sambuc // pointer to an array). This could be enhanced to handle some
4766f4a2713aSLionel Sambuc // pointers if we know the actual size, like if DstArg is 'array+2'
4767f4a2713aSLionel Sambuc // we could say 'sizeof(array)-2'.
4768f4a2713aSLionel Sambuc const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
4769f4a2713aSLionel Sambuc if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
4770f4a2713aSLionel Sambuc return;
4771f4a2713aSLionel Sambuc
4772f4a2713aSLionel Sambuc SmallString<128> sizeString;
4773f4a2713aSLionel Sambuc llvm::raw_svector_ostream OS(sizeString);
4774f4a2713aSLionel Sambuc OS << "sizeof(";
4775*0a6a1f1dSLionel Sambuc DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4776f4a2713aSLionel Sambuc OS << ")";
4777f4a2713aSLionel Sambuc
4778f4a2713aSLionel Sambuc Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4779f4a2713aSLionel Sambuc << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4780f4a2713aSLionel Sambuc OS.str());
4781f4a2713aSLionel Sambuc }
4782f4a2713aSLionel Sambuc
4783f4a2713aSLionel Sambuc /// Check if two expressions refer to the same declaration.
referToTheSameDecl(const Expr * E1,const Expr * E2)4784f4a2713aSLionel Sambuc static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4785f4a2713aSLionel Sambuc if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4786f4a2713aSLionel Sambuc if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4787f4a2713aSLionel Sambuc return D1->getDecl() == D2->getDecl();
4788f4a2713aSLionel Sambuc return false;
4789f4a2713aSLionel Sambuc }
4790f4a2713aSLionel Sambuc
getStrlenExprArg(const Expr * E)4791f4a2713aSLionel Sambuc static const Expr *getStrlenExprArg(const Expr *E) {
4792f4a2713aSLionel Sambuc if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4793f4a2713aSLionel Sambuc const FunctionDecl *FD = CE->getDirectCallee();
4794f4a2713aSLionel Sambuc if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4795*0a6a1f1dSLionel Sambuc return nullptr;
4796f4a2713aSLionel Sambuc return CE->getArg(0)->IgnoreParenCasts();
4797f4a2713aSLionel Sambuc }
4798*0a6a1f1dSLionel Sambuc return nullptr;
4799f4a2713aSLionel Sambuc }
4800f4a2713aSLionel Sambuc
4801f4a2713aSLionel Sambuc // Warn on anti-patterns as the 'size' argument to strncat.
4802f4a2713aSLionel Sambuc // The correct size argument should look like following:
4803f4a2713aSLionel Sambuc // strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
CheckStrncatArguments(const CallExpr * CE,IdentifierInfo * FnName)4804f4a2713aSLionel Sambuc void Sema::CheckStrncatArguments(const CallExpr *CE,
4805f4a2713aSLionel Sambuc IdentifierInfo *FnName) {
4806f4a2713aSLionel Sambuc // Don't crash if the user has the wrong number of arguments.
4807f4a2713aSLionel Sambuc if (CE->getNumArgs() < 3)
4808f4a2713aSLionel Sambuc return;
4809f4a2713aSLionel Sambuc const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4810f4a2713aSLionel Sambuc const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4811f4a2713aSLionel Sambuc const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4812f4a2713aSLionel Sambuc
4813*0a6a1f1dSLionel Sambuc if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4814*0a6a1f1dSLionel Sambuc CE->getRParenLoc()))
4815*0a6a1f1dSLionel Sambuc return;
4816*0a6a1f1dSLionel Sambuc
4817f4a2713aSLionel Sambuc // Identify common expressions, which are wrongly used as the size argument
4818f4a2713aSLionel Sambuc // to strncat and may lead to buffer overflows.
4819f4a2713aSLionel Sambuc unsigned PatternType = 0;
4820f4a2713aSLionel Sambuc if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4821f4a2713aSLionel Sambuc // - sizeof(dst)
4822f4a2713aSLionel Sambuc if (referToTheSameDecl(SizeOfArg, DstArg))
4823f4a2713aSLionel Sambuc PatternType = 1;
4824f4a2713aSLionel Sambuc // - sizeof(src)
4825f4a2713aSLionel Sambuc else if (referToTheSameDecl(SizeOfArg, SrcArg))
4826f4a2713aSLionel Sambuc PatternType = 2;
4827f4a2713aSLionel Sambuc } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4828f4a2713aSLionel Sambuc if (BE->getOpcode() == BO_Sub) {
4829f4a2713aSLionel Sambuc const Expr *L = BE->getLHS()->IgnoreParenCasts();
4830f4a2713aSLionel Sambuc const Expr *R = BE->getRHS()->IgnoreParenCasts();
4831f4a2713aSLionel Sambuc // - sizeof(dst) - strlen(dst)
4832f4a2713aSLionel Sambuc if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4833f4a2713aSLionel Sambuc referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4834f4a2713aSLionel Sambuc PatternType = 1;
4835f4a2713aSLionel Sambuc // - sizeof(src) - (anything)
4836f4a2713aSLionel Sambuc else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4837f4a2713aSLionel Sambuc PatternType = 2;
4838f4a2713aSLionel Sambuc }
4839f4a2713aSLionel Sambuc }
4840f4a2713aSLionel Sambuc
4841f4a2713aSLionel Sambuc if (PatternType == 0)
4842f4a2713aSLionel Sambuc return;
4843f4a2713aSLionel Sambuc
4844f4a2713aSLionel Sambuc // Generate the diagnostic.
4845f4a2713aSLionel Sambuc SourceLocation SL = LenArg->getLocStart();
4846f4a2713aSLionel Sambuc SourceRange SR = LenArg->getSourceRange();
4847*0a6a1f1dSLionel Sambuc SourceManager &SM = getSourceManager();
4848f4a2713aSLionel Sambuc
4849f4a2713aSLionel Sambuc // If the function is defined as a builtin macro, do not show macro expansion.
4850f4a2713aSLionel Sambuc if (SM.isMacroArgExpansion(SL)) {
4851f4a2713aSLionel Sambuc SL = SM.getSpellingLoc(SL);
4852f4a2713aSLionel Sambuc SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4853f4a2713aSLionel Sambuc SM.getSpellingLoc(SR.getEnd()));
4854f4a2713aSLionel Sambuc }
4855f4a2713aSLionel Sambuc
4856f4a2713aSLionel Sambuc // Check if the destination is an array (rather than a pointer to an array).
4857f4a2713aSLionel Sambuc QualType DstTy = DstArg->getType();
4858f4a2713aSLionel Sambuc bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4859f4a2713aSLionel Sambuc Context);
4860f4a2713aSLionel Sambuc if (!isKnownSizeArray) {
4861f4a2713aSLionel Sambuc if (PatternType == 1)
4862f4a2713aSLionel Sambuc Diag(SL, diag::warn_strncat_wrong_size) << SR;
4863f4a2713aSLionel Sambuc else
4864f4a2713aSLionel Sambuc Diag(SL, diag::warn_strncat_src_size) << SR;
4865f4a2713aSLionel Sambuc return;
4866f4a2713aSLionel Sambuc }
4867f4a2713aSLionel Sambuc
4868f4a2713aSLionel Sambuc if (PatternType == 1)
4869f4a2713aSLionel Sambuc Diag(SL, diag::warn_strncat_large_size) << SR;
4870f4a2713aSLionel Sambuc else
4871f4a2713aSLionel Sambuc Diag(SL, diag::warn_strncat_src_size) << SR;
4872f4a2713aSLionel Sambuc
4873f4a2713aSLionel Sambuc SmallString<128> sizeString;
4874f4a2713aSLionel Sambuc llvm::raw_svector_ostream OS(sizeString);
4875f4a2713aSLionel Sambuc OS << "sizeof(";
4876*0a6a1f1dSLionel Sambuc DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4877f4a2713aSLionel Sambuc OS << ") - ";
4878f4a2713aSLionel Sambuc OS << "strlen(";
4879*0a6a1f1dSLionel Sambuc DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4880f4a2713aSLionel Sambuc OS << ") - 1";
4881f4a2713aSLionel Sambuc
4882f4a2713aSLionel Sambuc Diag(SL, diag::note_strncat_wrong_size)
4883f4a2713aSLionel Sambuc << FixItHint::CreateReplacement(SR, OS.str());
4884f4a2713aSLionel Sambuc }
4885f4a2713aSLionel Sambuc
4886f4a2713aSLionel Sambuc //===--- CHECK: Return Address of Stack Variable --------------------------===//
4887f4a2713aSLionel Sambuc
4888f4a2713aSLionel Sambuc static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4889f4a2713aSLionel Sambuc Decl *ParentDecl);
4890f4a2713aSLionel Sambuc static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4891f4a2713aSLionel Sambuc Decl *ParentDecl);
4892f4a2713aSLionel Sambuc
4893f4a2713aSLionel Sambuc /// CheckReturnStackAddr - Check if a return statement returns the address
4894f4a2713aSLionel Sambuc /// of a stack variable.
4895*0a6a1f1dSLionel Sambuc static void
CheckReturnStackAddr(Sema & S,Expr * RetValExp,QualType lhsType,SourceLocation ReturnLoc)4896*0a6a1f1dSLionel Sambuc CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4897f4a2713aSLionel Sambuc SourceLocation ReturnLoc) {
4898f4a2713aSLionel Sambuc
4899*0a6a1f1dSLionel Sambuc Expr *stackE = nullptr;
4900f4a2713aSLionel Sambuc SmallVector<DeclRefExpr *, 8> refVars;
4901f4a2713aSLionel Sambuc
4902f4a2713aSLionel Sambuc // Perform checking for returned stack addresses, local blocks,
4903f4a2713aSLionel Sambuc // label addresses or references to temporaries.
4904f4a2713aSLionel Sambuc if (lhsType->isPointerType() ||
4905*0a6a1f1dSLionel Sambuc (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
4906*0a6a1f1dSLionel Sambuc stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
4907f4a2713aSLionel Sambuc } else if (lhsType->isReferenceType()) {
4908*0a6a1f1dSLionel Sambuc stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
4909f4a2713aSLionel Sambuc }
4910f4a2713aSLionel Sambuc
4911*0a6a1f1dSLionel Sambuc if (!stackE)
4912f4a2713aSLionel Sambuc return; // Nothing suspicious was found.
4913f4a2713aSLionel Sambuc
4914f4a2713aSLionel Sambuc SourceLocation diagLoc;
4915f4a2713aSLionel Sambuc SourceRange diagRange;
4916f4a2713aSLionel Sambuc if (refVars.empty()) {
4917f4a2713aSLionel Sambuc diagLoc = stackE->getLocStart();
4918f4a2713aSLionel Sambuc diagRange = stackE->getSourceRange();
4919f4a2713aSLionel Sambuc } else {
4920f4a2713aSLionel Sambuc // We followed through a reference variable. 'stackE' contains the
4921f4a2713aSLionel Sambuc // problematic expression but we will warn at the return statement pointing
4922f4a2713aSLionel Sambuc // at the reference variable. We will later display the "trail" of
4923f4a2713aSLionel Sambuc // reference variables using notes.
4924f4a2713aSLionel Sambuc diagLoc = refVars[0]->getLocStart();
4925f4a2713aSLionel Sambuc diagRange = refVars[0]->getSourceRange();
4926f4a2713aSLionel Sambuc }
4927f4a2713aSLionel Sambuc
4928f4a2713aSLionel Sambuc if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4929*0a6a1f1dSLionel Sambuc S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4930f4a2713aSLionel Sambuc : diag::warn_ret_stack_addr)
4931f4a2713aSLionel Sambuc << DR->getDecl()->getDeclName() << diagRange;
4932f4a2713aSLionel Sambuc } else if (isa<BlockExpr>(stackE)) { // local block.
4933*0a6a1f1dSLionel Sambuc S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4934f4a2713aSLionel Sambuc } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4935*0a6a1f1dSLionel Sambuc S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4936f4a2713aSLionel Sambuc } else { // local temporary.
4937*0a6a1f1dSLionel Sambuc S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4938f4a2713aSLionel Sambuc : diag::warn_ret_local_temp_addr)
4939f4a2713aSLionel Sambuc << diagRange;
4940f4a2713aSLionel Sambuc }
4941f4a2713aSLionel Sambuc
4942f4a2713aSLionel Sambuc // Display the "trail" of reference variables that we followed until we
4943f4a2713aSLionel Sambuc // found the problematic expression using notes.
4944f4a2713aSLionel Sambuc for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4945f4a2713aSLionel Sambuc VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4946f4a2713aSLionel Sambuc // If this var binds to another reference var, show the range of the next
4947f4a2713aSLionel Sambuc // var, otherwise the var binds to the problematic expression, in which case
4948f4a2713aSLionel Sambuc // show the range of the expression.
4949f4a2713aSLionel Sambuc SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4950f4a2713aSLionel Sambuc : stackE->getSourceRange();
4951*0a6a1f1dSLionel Sambuc S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4952f4a2713aSLionel Sambuc << VD->getDeclName() << range;
4953f4a2713aSLionel Sambuc }
4954f4a2713aSLionel Sambuc }
4955f4a2713aSLionel Sambuc
4956f4a2713aSLionel Sambuc /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4957f4a2713aSLionel Sambuc /// check if the expression in a return statement evaluates to an address
4958f4a2713aSLionel Sambuc /// to a location on the stack, a local block, an address of a label, or a
4959f4a2713aSLionel Sambuc /// reference to local temporary. The recursion is used to traverse the
4960f4a2713aSLionel Sambuc /// AST of the return expression, with recursion backtracking when we
4961f4a2713aSLionel Sambuc /// encounter a subexpression that (1) clearly does not lead to one of the
4962f4a2713aSLionel Sambuc /// above problematic expressions (2) is something we cannot determine leads to
4963f4a2713aSLionel Sambuc /// a problematic expression based on such local checking.
4964f4a2713aSLionel Sambuc ///
4965f4a2713aSLionel Sambuc /// Both EvalAddr and EvalVal follow through reference variables to evaluate
4966f4a2713aSLionel Sambuc /// the expression that they point to. Such variables are added to the
4967f4a2713aSLionel Sambuc /// 'refVars' vector so that we know what the reference variable "trail" was.
4968f4a2713aSLionel Sambuc ///
4969f4a2713aSLionel Sambuc /// EvalAddr processes expressions that are pointers that are used as
4970f4a2713aSLionel Sambuc /// references (and not L-values). EvalVal handles all other values.
4971f4a2713aSLionel Sambuc /// At the base case of the recursion is a check for the above problematic
4972f4a2713aSLionel Sambuc /// expressions.
4973f4a2713aSLionel Sambuc ///
4974f4a2713aSLionel Sambuc /// This implementation handles:
4975f4a2713aSLionel Sambuc ///
4976f4a2713aSLionel Sambuc /// * pointer-to-pointer casts
4977f4a2713aSLionel Sambuc /// * implicit conversions from array references to pointers
4978f4a2713aSLionel Sambuc /// * taking the address of fields
4979f4a2713aSLionel Sambuc /// * arbitrary interplay between "&" and "*" operators
4980f4a2713aSLionel Sambuc /// * pointer arithmetic from an address of a stack variable
4981f4a2713aSLionel Sambuc /// * taking the address of an array element where the array is on the stack
EvalAddr(Expr * E,SmallVectorImpl<DeclRefExpr * > & refVars,Decl * ParentDecl)4982f4a2713aSLionel Sambuc static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4983f4a2713aSLionel Sambuc Decl *ParentDecl) {
4984f4a2713aSLionel Sambuc if (E->isTypeDependent())
4985*0a6a1f1dSLionel Sambuc return nullptr;
4986f4a2713aSLionel Sambuc
4987f4a2713aSLionel Sambuc // We should only be called for evaluating pointer expressions.
4988f4a2713aSLionel Sambuc assert((E->getType()->isAnyPointerType() ||
4989f4a2713aSLionel Sambuc E->getType()->isBlockPointerType() ||
4990f4a2713aSLionel Sambuc E->getType()->isObjCQualifiedIdType()) &&
4991f4a2713aSLionel Sambuc "EvalAddr only works on pointers");
4992f4a2713aSLionel Sambuc
4993f4a2713aSLionel Sambuc E = E->IgnoreParens();
4994f4a2713aSLionel Sambuc
4995f4a2713aSLionel Sambuc // Our "symbolic interpreter" is just a dispatch off the currently
4996f4a2713aSLionel Sambuc // viewed AST node. We then recursively traverse the AST by calling
4997f4a2713aSLionel Sambuc // EvalAddr and EvalVal appropriately.
4998f4a2713aSLionel Sambuc switch (E->getStmtClass()) {
4999f4a2713aSLionel Sambuc case Stmt::DeclRefExprClass: {
5000f4a2713aSLionel Sambuc DeclRefExpr *DR = cast<DeclRefExpr>(E);
5001f4a2713aSLionel Sambuc
5002*0a6a1f1dSLionel Sambuc // If we leave the immediate function, the lifetime isn't about to end.
5003*0a6a1f1dSLionel Sambuc if (DR->refersToEnclosingVariableOrCapture())
5004*0a6a1f1dSLionel Sambuc return nullptr;
5005*0a6a1f1dSLionel Sambuc
5006f4a2713aSLionel Sambuc if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5007f4a2713aSLionel Sambuc // If this is a reference variable, follow through to the expression that
5008f4a2713aSLionel Sambuc // it points to.
5009f4a2713aSLionel Sambuc if (V->hasLocalStorage() &&
5010f4a2713aSLionel Sambuc V->getType()->isReferenceType() && V->hasInit()) {
5011f4a2713aSLionel Sambuc // Add the reference variable to the "trail".
5012f4a2713aSLionel Sambuc refVars.push_back(DR);
5013f4a2713aSLionel Sambuc return EvalAddr(V->getInit(), refVars, ParentDecl);
5014f4a2713aSLionel Sambuc }
5015f4a2713aSLionel Sambuc
5016*0a6a1f1dSLionel Sambuc return nullptr;
5017f4a2713aSLionel Sambuc }
5018f4a2713aSLionel Sambuc
5019f4a2713aSLionel Sambuc case Stmt::UnaryOperatorClass: {
5020f4a2713aSLionel Sambuc // The only unary operator that make sense to handle here
5021f4a2713aSLionel Sambuc // is AddrOf. All others don't make sense as pointers.
5022f4a2713aSLionel Sambuc UnaryOperator *U = cast<UnaryOperator>(E);
5023f4a2713aSLionel Sambuc
5024f4a2713aSLionel Sambuc if (U->getOpcode() == UO_AddrOf)
5025f4a2713aSLionel Sambuc return EvalVal(U->getSubExpr(), refVars, ParentDecl);
5026f4a2713aSLionel Sambuc else
5027*0a6a1f1dSLionel Sambuc return nullptr;
5028f4a2713aSLionel Sambuc }
5029f4a2713aSLionel Sambuc
5030f4a2713aSLionel Sambuc case Stmt::BinaryOperatorClass: {
5031f4a2713aSLionel Sambuc // Handle pointer arithmetic. All other binary operators are not valid
5032f4a2713aSLionel Sambuc // in this context.
5033f4a2713aSLionel Sambuc BinaryOperator *B = cast<BinaryOperator>(E);
5034f4a2713aSLionel Sambuc BinaryOperatorKind op = B->getOpcode();
5035f4a2713aSLionel Sambuc
5036f4a2713aSLionel Sambuc if (op != BO_Add && op != BO_Sub)
5037*0a6a1f1dSLionel Sambuc return nullptr;
5038f4a2713aSLionel Sambuc
5039f4a2713aSLionel Sambuc Expr *Base = B->getLHS();
5040f4a2713aSLionel Sambuc
5041f4a2713aSLionel Sambuc // Determine which argument is the real pointer base. It could be
5042f4a2713aSLionel Sambuc // the RHS argument instead of the LHS.
5043f4a2713aSLionel Sambuc if (!Base->getType()->isPointerType()) Base = B->getRHS();
5044f4a2713aSLionel Sambuc
5045f4a2713aSLionel Sambuc assert (Base->getType()->isPointerType());
5046f4a2713aSLionel Sambuc return EvalAddr(Base, refVars, ParentDecl);
5047f4a2713aSLionel Sambuc }
5048f4a2713aSLionel Sambuc
5049f4a2713aSLionel Sambuc // For conditional operators we need to see if either the LHS or RHS are
5050f4a2713aSLionel Sambuc // valid DeclRefExpr*s. If one of them is valid, we return it.
5051f4a2713aSLionel Sambuc case Stmt::ConditionalOperatorClass: {
5052f4a2713aSLionel Sambuc ConditionalOperator *C = cast<ConditionalOperator>(E);
5053f4a2713aSLionel Sambuc
5054f4a2713aSLionel Sambuc // Handle the GNU extension for missing LHS.
5055*0a6a1f1dSLionel Sambuc // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5056*0a6a1f1dSLionel Sambuc if (Expr *LHSExpr = C->getLHS()) {
5057f4a2713aSLionel Sambuc // In C++, we can have a throw-expression, which has 'void' type.
5058*0a6a1f1dSLionel Sambuc if (!LHSExpr->getType()->isVoidType())
5059*0a6a1f1dSLionel Sambuc if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
5060f4a2713aSLionel Sambuc return LHS;
5061f4a2713aSLionel Sambuc }
5062f4a2713aSLionel Sambuc
5063f4a2713aSLionel Sambuc // In C++, we can have a throw-expression, which has 'void' type.
5064f4a2713aSLionel Sambuc if (C->getRHS()->getType()->isVoidType())
5065*0a6a1f1dSLionel Sambuc return nullptr;
5066f4a2713aSLionel Sambuc
5067f4a2713aSLionel Sambuc return EvalAddr(C->getRHS(), refVars, ParentDecl);
5068f4a2713aSLionel Sambuc }
5069f4a2713aSLionel Sambuc
5070f4a2713aSLionel Sambuc case Stmt::BlockExprClass:
5071f4a2713aSLionel Sambuc if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
5072f4a2713aSLionel Sambuc return E; // local block.
5073*0a6a1f1dSLionel Sambuc return nullptr;
5074f4a2713aSLionel Sambuc
5075f4a2713aSLionel Sambuc case Stmt::AddrLabelExprClass:
5076f4a2713aSLionel Sambuc return E; // address of label.
5077f4a2713aSLionel Sambuc
5078f4a2713aSLionel Sambuc case Stmt::ExprWithCleanupsClass:
5079f4a2713aSLionel Sambuc return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5080f4a2713aSLionel Sambuc ParentDecl);
5081f4a2713aSLionel Sambuc
5082f4a2713aSLionel Sambuc // For casts, we need to handle conversions from arrays to
5083f4a2713aSLionel Sambuc // pointer values, and pointer-to-pointer conversions.
5084f4a2713aSLionel Sambuc case Stmt::ImplicitCastExprClass:
5085f4a2713aSLionel Sambuc case Stmt::CStyleCastExprClass:
5086f4a2713aSLionel Sambuc case Stmt::CXXFunctionalCastExprClass:
5087f4a2713aSLionel Sambuc case Stmt::ObjCBridgedCastExprClass:
5088f4a2713aSLionel Sambuc case Stmt::CXXStaticCastExprClass:
5089f4a2713aSLionel Sambuc case Stmt::CXXDynamicCastExprClass:
5090f4a2713aSLionel Sambuc case Stmt::CXXConstCastExprClass:
5091f4a2713aSLionel Sambuc case Stmt::CXXReinterpretCastExprClass: {
5092f4a2713aSLionel Sambuc Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5093f4a2713aSLionel Sambuc switch (cast<CastExpr>(E)->getCastKind()) {
5094f4a2713aSLionel Sambuc case CK_LValueToRValue:
5095f4a2713aSLionel Sambuc case CK_NoOp:
5096f4a2713aSLionel Sambuc case CK_BaseToDerived:
5097f4a2713aSLionel Sambuc case CK_DerivedToBase:
5098f4a2713aSLionel Sambuc case CK_UncheckedDerivedToBase:
5099f4a2713aSLionel Sambuc case CK_Dynamic:
5100f4a2713aSLionel Sambuc case CK_CPointerToObjCPointerCast:
5101f4a2713aSLionel Sambuc case CK_BlockPointerToObjCPointerCast:
5102f4a2713aSLionel Sambuc case CK_AnyPointerToBlockPointerCast:
5103f4a2713aSLionel Sambuc return EvalAddr(SubExpr, refVars, ParentDecl);
5104f4a2713aSLionel Sambuc
5105f4a2713aSLionel Sambuc case CK_ArrayToPointerDecay:
5106f4a2713aSLionel Sambuc return EvalVal(SubExpr, refVars, ParentDecl);
5107f4a2713aSLionel Sambuc
5108*0a6a1f1dSLionel Sambuc case CK_BitCast:
5109*0a6a1f1dSLionel Sambuc if (SubExpr->getType()->isAnyPointerType() ||
5110*0a6a1f1dSLionel Sambuc SubExpr->getType()->isBlockPointerType() ||
5111*0a6a1f1dSLionel Sambuc SubExpr->getType()->isObjCQualifiedIdType())
5112*0a6a1f1dSLionel Sambuc return EvalAddr(SubExpr, refVars, ParentDecl);
5113*0a6a1f1dSLionel Sambuc else
5114*0a6a1f1dSLionel Sambuc return nullptr;
5115*0a6a1f1dSLionel Sambuc
5116f4a2713aSLionel Sambuc default:
5117*0a6a1f1dSLionel Sambuc return nullptr;
5118f4a2713aSLionel Sambuc }
5119f4a2713aSLionel Sambuc }
5120f4a2713aSLionel Sambuc
5121f4a2713aSLionel Sambuc case Stmt::MaterializeTemporaryExprClass:
5122f4a2713aSLionel Sambuc if (Expr *Result = EvalAddr(
5123f4a2713aSLionel Sambuc cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5124f4a2713aSLionel Sambuc refVars, ParentDecl))
5125f4a2713aSLionel Sambuc return Result;
5126f4a2713aSLionel Sambuc
5127f4a2713aSLionel Sambuc return E;
5128f4a2713aSLionel Sambuc
5129f4a2713aSLionel Sambuc // Everything else: we simply don't reason about them.
5130f4a2713aSLionel Sambuc default:
5131*0a6a1f1dSLionel Sambuc return nullptr;
5132f4a2713aSLionel Sambuc }
5133f4a2713aSLionel Sambuc }
5134f4a2713aSLionel Sambuc
5135f4a2713aSLionel Sambuc
5136f4a2713aSLionel Sambuc /// EvalVal - This function is complements EvalAddr in the mutual recursion.
5137f4a2713aSLionel Sambuc /// See the comments for EvalAddr for more details.
EvalVal(Expr * E,SmallVectorImpl<DeclRefExpr * > & refVars,Decl * ParentDecl)5138f4a2713aSLionel Sambuc static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5139f4a2713aSLionel Sambuc Decl *ParentDecl) {
5140f4a2713aSLionel Sambuc do {
5141f4a2713aSLionel Sambuc // We should only be called for evaluating non-pointer expressions, or
5142f4a2713aSLionel Sambuc // expressions with a pointer type that are not used as references but instead
5143f4a2713aSLionel Sambuc // are l-values (e.g., DeclRefExpr with a pointer type).
5144f4a2713aSLionel Sambuc
5145f4a2713aSLionel Sambuc // Our "symbolic interpreter" is just a dispatch off the currently
5146f4a2713aSLionel Sambuc // viewed AST node. We then recursively traverse the AST by calling
5147f4a2713aSLionel Sambuc // EvalAddr and EvalVal appropriately.
5148f4a2713aSLionel Sambuc
5149f4a2713aSLionel Sambuc E = E->IgnoreParens();
5150f4a2713aSLionel Sambuc switch (E->getStmtClass()) {
5151f4a2713aSLionel Sambuc case Stmt::ImplicitCastExprClass: {
5152f4a2713aSLionel Sambuc ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
5153f4a2713aSLionel Sambuc if (IE->getValueKind() == VK_LValue) {
5154f4a2713aSLionel Sambuc E = IE->getSubExpr();
5155f4a2713aSLionel Sambuc continue;
5156f4a2713aSLionel Sambuc }
5157*0a6a1f1dSLionel Sambuc return nullptr;
5158f4a2713aSLionel Sambuc }
5159f4a2713aSLionel Sambuc
5160f4a2713aSLionel Sambuc case Stmt::ExprWithCleanupsClass:
5161f4a2713aSLionel Sambuc return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
5162f4a2713aSLionel Sambuc
5163f4a2713aSLionel Sambuc case Stmt::DeclRefExprClass: {
5164f4a2713aSLionel Sambuc // When we hit a DeclRefExpr we are looking at code that refers to a
5165f4a2713aSLionel Sambuc // variable's name. If it's not a reference variable we check if it has
5166f4a2713aSLionel Sambuc // local storage within the function, and if so, return the expression.
5167f4a2713aSLionel Sambuc DeclRefExpr *DR = cast<DeclRefExpr>(E);
5168f4a2713aSLionel Sambuc
5169*0a6a1f1dSLionel Sambuc // If we leave the immediate function, the lifetime isn't about to end.
5170*0a6a1f1dSLionel Sambuc if (DR->refersToEnclosingVariableOrCapture())
5171*0a6a1f1dSLionel Sambuc return nullptr;
5172*0a6a1f1dSLionel Sambuc
5173f4a2713aSLionel Sambuc if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5174f4a2713aSLionel Sambuc // Check if it refers to itself, e.g. "int& i = i;".
5175f4a2713aSLionel Sambuc if (V == ParentDecl)
5176f4a2713aSLionel Sambuc return DR;
5177f4a2713aSLionel Sambuc
5178f4a2713aSLionel Sambuc if (V->hasLocalStorage()) {
5179f4a2713aSLionel Sambuc if (!V->getType()->isReferenceType())
5180f4a2713aSLionel Sambuc return DR;
5181f4a2713aSLionel Sambuc
5182f4a2713aSLionel Sambuc // Reference variable, follow through to the expression that
5183f4a2713aSLionel Sambuc // it points to.
5184f4a2713aSLionel Sambuc if (V->hasInit()) {
5185f4a2713aSLionel Sambuc // Add the reference variable to the "trail".
5186f4a2713aSLionel Sambuc refVars.push_back(DR);
5187f4a2713aSLionel Sambuc return EvalVal(V->getInit(), refVars, V);
5188f4a2713aSLionel Sambuc }
5189f4a2713aSLionel Sambuc }
5190f4a2713aSLionel Sambuc }
5191f4a2713aSLionel Sambuc
5192*0a6a1f1dSLionel Sambuc return nullptr;
5193f4a2713aSLionel Sambuc }
5194f4a2713aSLionel Sambuc
5195f4a2713aSLionel Sambuc case Stmt::UnaryOperatorClass: {
5196f4a2713aSLionel Sambuc // The only unary operator that make sense to handle here
5197f4a2713aSLionel Sambuc // is Deref. All others don't resolve to a "name." This includes
5198f4a2713aSLionel Sambuc // handling all sorts of rvalues passed to a unary operator.
5199f4a2713aSLionel Sambuc UnaryOperator *U = cast<UnaryOperator>(E);
5200f4a2713aSLionel Sambuc
5201f4a2713aSLionel Sambuc if (U->getOpcode() == UO_Deref)
5202f4a2713aSLionel Sambuc return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
5203f4a2713aSLionel Sambuc
5204*0a6a1f1dSLionel Sambuc return nullptr;
5205f4a2713aSLionel Sambuc }
5206f4a2713aSLionel Sambuc
5207f4a2713aSLionel Sambuc case Stmt::ArraySubscriptExprClass: {
5208f4a2713aSLionel Sambuc // Array subscripts are potential references to data on the stack. We
5209f4a2713aSLionel Sambuc // retrieve the DeclRefExpr* for the array variable if it indeed
5210f4a2713aSLionel Sambuc // has local storage.
5211f4a2713aSLionel Sambuc return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
5212f4a2713aSLionel Sambuc }
5213f4a2713aSLionel Sambuc
5214f4a2713aSLionel Sambuc case Stmt::ConditionalOperatorClass: {
5215f4a2713aSLionel Sambuc // For conditional operators we need to see if either the LHS or RHS are
5216f4a2713aSLionel Sambuc // non-NULL Expr's. If one is non-NULL, we return it.
5217f4a2713aSLionel Sambuc ConditionalOperator *C = cast<ConditionalOperator>(E);
5218f4a2713aSLionel Sambuc
5219f4a2713aSLionel Sambuc // Handle the GNU extension for missing LHS.
5220*0a6a1f1dSLionel Sambuc if (Expr *LHSExpr = C->getLHS()) {
5221*0a6a1f1dSLionel Sambuc // In C++, we can have a throw-expression, which has 'void' type.
5222*0a6a1f1dSLionel Sambuc if (!LHSExpr->getType()->isVoidType())
5223*0a6a1f1dSLionel Sambuc if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5224f4a2713aSLionel Sambuc return LHS;
5225*0a6a1f1dSLionel Sambuc }
5226*0a6a1f1dSLionel Sambuc
5227*0a6a1f1dSLionel Sambuc // In C++, we can have a throw-expression, which has 'void' type.
5228*0a6a1f1dSLionel Sambuc if (C->getRHS()->getType()->isVoidType())
5229*0a6a1f1dSLionel Sambuc return nullptr;
5230f4a2713aSLionel Sambuc
5231f4a2713aSLionel Sambuc return EvalVal(C->getRHS(), refVars, ParentDecl);
5232f4a2713aSLionel Sambuc }
5233f4a2713aSLionel Sambuc
5234f4a2713aSLionel Sambuc // Accesses to members are potential references to data on the stack.
5235f4a2713aSLionel Sambuc case Stmt::MemberExprClass: {
5236f4a2713aSLionel Sambuc MemberExpr *M = cast<MemberExpr>(E);
5237f4a2713aSLionel Sambuc
5238f4a2713aSLionel Sambuc // Check for indirect access. We only want direct field accesses.
5239f4a2713aSLionel Sambuc if (M->isArrow())
5240*0a6a1f1dSLionel Sambuc return nullptr;
5241f4a2713aSLionel Sambuc
5242f4a2713aSLionel Sambuc // Check whether the member type is itself a reference, in which case
5243f4a2713aSLionel Sambuc // we're not going to refer to the member, but to what the member refers to.
5244f4a2713aSLionel Sambuc if (M->getMemberDecl()->getType()->isReferenceType())
5245*0a6a1f1dSLionel Sambuc return nullptr;
5246f4a2713aSLionel Sambuc
5247f4a2713aSLionel Sambuc return EvalVal(M->getBase(), refVars, ParentDecl);
5248f4a2713aSLionel Sambuc }
5249f4a2713aSLionel Sambuc
5250f4a2713aSLionel Sambuc case Stmt::MaterializeTemporaryExprClass:
5251f4a2713aSLionel Sambuc if (Expr *Result = EvalVal(
5252f4a2713aSLionel Sambuc cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5253f4a2713aSLionel Sambuc refVars, ParentDecl))
5254f4a2713aSLionel Sambuc return Result;
5255f4a2713aSLionel Sambuc
5256f4a2713aSLionel Sambuc return E;
5257f4a2713aSLionel Sambuc
5258f4a2713aSLionel Sambuc default:
5259f4a2713aSLionel Sambuc // Check that we don't return or take the address of a reference to a
5260f4a2713aSLionel Sambuc // temporary. This is only useful in C++.
5261f4a2713aSLionel Sambuc if (!E->isTypeDependent() && E->isRValue())
5262f4a2713aSLionel Sambuc return E;
5263f4a2713aSLionel Sambuc
5264f4a2713aSLionel Sambuc // Everything else: we simply don't reason about them.
5265*0a6a1f1dSLionel Sambuc return nullptr;
5266f4a2713aSLionel Sambuc }
5267f4a2713aSLionel Sambuc } while (true);
5268f4a2713aSLionel Sambuc }
5269f4a2713aSLionel Sambuc
5270*0a6a1f1dSLionel Sambuc void
CheckReturnValExpr(Expr * RetValExp,QualType lhsType,SourceLocation ReturnLoc,bool isObjCMethod,const AttrVec * Attrs,const FunctionDecl * FD)5271*0a6a1f1dSLionel Sambuc Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5272*0a6a1f1dSLionel Sambuc SourceLocation ReturnLoc,
5273*0a6a1f1dSLionel Sambuc bool isObjCMethod,
5274*0a6a1f1dSLionel Sambuc const AttrVec *Attrs,
5275*0a6a1f1dSLionel Sambuc const FunctionDecl *FD) {
5276*0a6a1f1dSLionel Sambuc CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5277*0a6a1f1dSLionel Sambuc
5278*0a6a1f1dSLionel Sambuc // Check if the return value is null but should not be.
5279*0a6a1f1dSLionel Sambuc if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5280*0a6a1f1dSLionel Sambuc CheckNonNullExpr(*this, RetValExp))
5281*0a6a1f1dSLionel Sambuc Diag(ReturnLoc, diag::warn_null_ret)
5282*0a6a1f1dSLionel Sambuc << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5283*0a6a1f1dSLionel Sambuc
5284*0a6a1f1dSLionel Sambuc // C++11 [basic.stc.dynamic.allocation]p4:
5285*0a6a1f1dSLionel Sambuc // If an allocation function declared with a non-throwing
5286*0a6a1f1dSLionel Sambuc // exception-specification fails to allocate storage, it shall return
5287*0a6a1f1dSLionel Sambuc // a null pointer. Any other allocation function that fails to allocate
5288*0a6a1f1dSLionel Sambuc // storage shall indicate failure only by throwing an exception [...]
5289*0a6a1f1dSLionel Sambuc if (FD) {
5290*0a6a1f1dSLionel Sambuc OverloadedOperatorKind Op = FD->getOverloadedOperator();
5291*0a6a1f1dSLionel Sambuc if (Op == OO_New || Op == OO_Array_New) {
5292*0a6a1f1dSLionel Sambuc const FunctionProtoType *Proto
5293*0a6a1f1dSLionel Sambuc = FD->getType()->castAs<FunctionProtoType>();
5294*0a6a1f1dSLionel Sambuc if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5295*0a6a1f1dSLionel Sambuc CheckNonNullExpr(*this, RetValExp))
5296*0a6a1f1dSLionel Sambuc Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5297*0a6a1f1dSLionel Sambuc << FD << getLangOpts().CPlusPlus11;
5298*0a6a1f1dSLionel Sambuc }
5299*0a6a1f1dSLionel Sambuc }
5300*0a6a1f1dSLionel Sambuc }
5301*0a6a1f1dSLionel Sambuc
5302f4a2713aSLionel Sambuc //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5303f4a2713aSLionel Sambuc
5304f4a2713aSLionel Sambuc /// Check for comparisons of floating point operands using != and ==.
5305f4a2713aSLionel Sambuc /// Issue a warning if these are no self-comparisons, as they are not likely
5306f4a2713aSLionel Sambuc /// to do what the programmer intended.
CheckFloatComparison(SourceLocation Loc,Expr * LHS,Expr * RHS)5307f4a2713aSLionel Sambuc void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
5308f4a2713aSLionel Sambuc Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5309f4a2713aSLionel Sambuc Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
5310f4a2713aSLionel Sambuc
5311f4a2713aSLionel Sambuc // Special case: check for x == x (which is OK).
5312f4a2713aSLionel Sambuc // Do not emit warnings for such cases.
5313f4a2713aSLionel Sambuc if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5314f4a2713aSLionel Sambuc if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5315f4a2713aSLionel Sambuc if (DRL->getDecl() == DRR->getDecl())
5316f4a2713aSLionel Sambuc return;
5317f4a2713aSLionel Sambuc
5318f4a2713aSLionel Sambuc
5319f4a2713aSLionel Sambuc // Special case: check for comparisons against literals that can be exactly
5320f4a2713aSLionel Sambuc // represented by APFloat. In such cases, do not emit a warning. This
5321f4a2713aSLionel Sambuc // is a heuristic: often comparison against such literals are used to
5322f4a2713aSLionel Sambuc // detect if a value in a variable has not changed. This clearly can
5323f4a2713aSLionel Sambuc // lead to false negatives.
5324f4a2713aSLionel Sambuc if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5325f4a2713aSLionel Sambuc if (FLL->isExact())
5326f4a2713aSLionel Sambuc return;
5327f4a2713aSLionel Sambuc } else
5328f4a2713aSLionel Sambuc if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5329f4a2713aSLionel Sambuc if (FLR->isExact())
5330f4a2713aSLionel Sambuc return;
5331f4a2713aSLionel Sambuc
5332f4a2713aSLionel Sambuc // Check for comparisons with builtin types.
5333f4a2713aSLionel Sambuc if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
5334*0a6a1f1dSLionel Sambuc if (CL->getBuiltinCallee())
5335f4a2713aSLionel Sambuc return;
5336f4a2713aSLionel Sambuc
5337f4a2713aSLionel Sambuc if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
5338*0a6a1f1dSLionel Sambuc if (CR->getBuiltinCallee())
5339f4a2713aSLionel Sambuc return;
5340f4a2713aSLionel Sambuc
5341f4a2713aSLionel Sambuc // Emit the diagnostic.
5342f4a2713aSLionel Sambuc Diag(Loc, diag::warn_floatingpoint_eq)
5343f4a2713aSLionel Sambuc << LHS->getSourceRange() << RHS->getSourceRange();
5344f4a2713aSLionel Sambuc }
5345f4a2713aSLionel Sambuc
5346f4a2713aSLionel Sambuc //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5347f4a2713aSLionel Sambuc //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
5348f4a2713aSLionel Sambuc
5349f4a2713aSLionel Sambuc namespace {
5350f4a2713aSLionel Sambuc
5351f4a2713aSLionel Sambuc /// Structure recording the 'active' range of an integer-valued
5352f4a2713aSLionel Sambuc /// expression.
5353f4a2713aSLionel Sambuc struct IntRange {
5354f4a2713aSLionel Sambuc /// The number of bits active in the int.
5355f4a2713aSLionel Sambuc unsigned Width;
5356f4a2713aSLionel Sambuc
5357f4a2713aSLionel Sambuc /// True if the int is known not to have negative values.
5358f4a2713aSLionel Sambuc bool NonNegative;
5359f4a2713aSLionel Sambuc
IntRange__anon0a2745240711::IntRange5360f4a2713aSLionel Sambuc IntRange(unsigned Width, bool NonNegative)
5361f4a2713aSLionel Sambuc : Width(Width), NonNegative(NonNegative)
5362f4a2713aSLionel Sambuc {}
5363f4a2713aSLionel Sambuc
5364f4a2713aSLionel Sambuc /// Returns the range of the bool type.
forBoolType__anon0a2745240711::IntRange5365f4a2713aSLionel Sambuc static IntRange forBoolType() {
5366f4a2713aSLionel Sambuc return IntRange(1, true);
5367f4a2713aSLionel Sambuc }
5368f4a2713aSLionel Sambuc
5369f4a2713aSLionel Sambuc /// Returns the range of an opaque value of the given integral type.
forValueOfType__anon0a2745240711::IntRange5370f4a2713aSLionel Sambuc static IntRange forValueOfType(ASTContext &C, QualType T) {
5371f4a2713aSLionel Sambuc return forValueOfCanonicalType(C,
5372f4a2713aSLionel Sambuc T->getCanonicalTypeInternal().getTypePtr());
5373f4a2713aSLionel Sambuc }
5374f4a2713aSLionel Sambuc
5375f4a2713aSLionel Sambuc /// Returns the range of an opaque value of a canonical integral type.
forValueOfCanonicalType__anon0a2745240711::IntRange5376f4a2713aSLionel Sambuc static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
5377f4a2713aSLionel Sambuc assert(T->isCanonicalUnqualified());
5378f4a2713aSLionel Sambuc
5379f4a2713aSLionel Sambuc if (const VectorType *VT = dyn_cast<VectorType>(T))
5380f4a2713aSLionel Sambuc T = VT->getElementType().getTypePtr();
5381f4a2713aSLionel Sambuc if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5382f4a2713aSLionel Sambuc T = CT->getElementType().getTypePtr();
5383*0a6a1f1dSLionel Sambuc if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5384*0a6a1f1dSLionel Sambuc T = AT->getValueType().getTypePtr();
5385f4a2713aSLionel Sambuc
5386f4a2713aSLionel Sambuc // For enum types, use the known bit width of the enumerators.
5387f4a2713aSLionel Sambuc if (const EnumType *ET = dyn_cast<EnumType>(T)) {
5388f4a2713aSLionel Sambuc EnumDecl *Enum = ET->getDecl();
5389f4a2713aSLionel Sambuc if (!Enum->isCompleteDefinition())
5390f4a2713aSLionel Sambuc return IntRange(C.getIntWidth(QualType(T, 0)), false);
5391f4a2713aSLionel Sambuc
5392f4a2713aSLionel Sambuc unsigned NumPositive = Enum->getNumPositiveBits();
5393f4a2713aSLionel Sambuc unsigned NumNegative = Enum->getNumNegativeBits();
5394f4a2713aSLionel Sambuc
5395f4a2713aSLionel Sambuc if (NumNegative == 0)
5396f4a2713aSLionel Sambuc return IntRange(NumPositive, true/*NonNegative*/);
5397f4a2713aSLionel Sambuc else
5398f4a2713aSLionel Sambuc return IntRange(std::max(NumPositive + 1, NumNegative),
5399f4a2713aSLionel Sambuc false/*NonNegative*/);
5400f4a2713aSLionel Sambuc }
5401f4a2713aSLionel Sambuc
5402f4a2713aSLionel Sambuc const BuiltinType *BT = cast<BuiltinType>(T);
5403f4a2713aSLionel Sambuc assert(BT->isInteger());
5404f4a2713aSLionel Sambuc
5405f4a2713aSLionel Sambuc return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5406f4a2713aSLionel Sambuc }
5407f4a2713aSLionel Sambuc
5408f4a2713aSLionel Sambuc /// Returns the "target" range of a canonical integral type, i.e.
5409f4a2713aSLionel Sambuc /// the range of values expressible in the type.
5410f4a2713aSLionel Sambuc ///
5411f4a2713aSLionel Sambuc /// This matches forValueOfCanonicalType except that enums have the
5412f4a2713aSLionel Sambuc /// full range of their type, not the range of their enumerators.
forTargetOfCanonicalType__anon0a2745240711::IntRange5413f4a2713aSLionel Sambuc static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5414f4a2713aSLionel Sambuc assert(T->isCanonicalUnqualified());
5415f4a2713aSLionel Sambuc
5416f4a2713aSLionel Sambuc if (const VectorType *VT = dyn_cast<VectorType>(T))
5417f4a2713aSLionel Sambuc T = VT->getElementType().getTypePtr();
5418f4a2713aSLionel Sambuc if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5419f4a2713aSLionel Sambuc T = CT->getElementType().getTypePtr();
5420*0a6a1f1dSLionel Sambuc if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5421*0a6a1f1dSLionel Sambuc T = AT->getValueType().getTypePtr();
5422f4a2713aSLionel Sambuc if (const EnumType *ET = dyn_cast<EnumType>(T))
5423f4a2713aSLionel Sambuc T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
5424f4a2713aSLionel Sambuc
5425f4a2713aSLionel Sambuc const BuiltinType *BT = cast<BuiltinType>(T);
5426f4a2713aSLionel Sambuc assert(BT->isInteger());
5427f4a2713aSLionel Sambuc
5428f4a2713aSLionel Sambuc return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5429f4a2713aSLionel Sambuc }
5430f4a2713aSLionel Sambuc
5431f4a2713aSLionel Sambuc /// Returns the supremum of two ranges: i.e. their conservative merge.
join__anon0a2745240711::IntRange5432f4a2713aSLionel Sambuc static IntRange join(IntRange L, IntRange R) {
5433f4a2713aSLionel Sambuc return IntRange(std::max(L.Width, R.Width),
5434f4a2713aSLionel Sambuc L.NonNegative && R.NonNegative);
5435f4a2713aSLionel Sambuc }
5436f4a2713aSLionel Sambuc
5437f4a2713aSLionel Sambuc /// Returns the infinum of two ranges: i.e. their aggressive merge.
meet__anon0a2745240711::IntRange5438f4a2713aSLionel Sambuc static IntRange meet(IntRange L, IntRange R) {
5439f4a2713aSLionel Sambuc return IntRange(std::min(L.Width, R.Width),
5440f4a2713aSLionel Sambuc L.NonNegative || R.NonNegative);
5441f4a2713aSLionel Sambuc }
5442f4a2713aSLionel Sambuc };
5443f4a2713aSLionel Sambuc
GetValueRange(ASTContext & C,llvm::APSInt & value,unsigned MaxWidth)5444f4a2713aSLionel Sambuc static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5445f4a2713aSLionel Sambuc unsigned MaxWidth) {
5446f4a2713aSLionel Sambuc if (value.isSigned() && value.isNegative())
5447f4a2713aSLionel Sambuc return IntRange(value.getMinSignedBits(), false);
5448f4a2713aSLionel Sambuc
5449f4a2713aSLionel Sambuc if (value.getBitWidth() > MaxWidth)
5450f4a2713aSLionel Sambuc value = value.trunc(MaxWidth);
5451f4a2713aSLionel Sambuc
5452f4a2713aSLionel Sambuc // isNonNegative() just checks the sign bit without considering
5453f4a2713aSLionel Sambuc // signedness.
5454f4a2713aSLionel Sambuc return IntRange(value.getActiveBits(), true);
5455f4a2713aSLionel Sambuc }
5456f4a2713aSLionel Sambuc
GetValueRange(ASTContext & C,APValue & result,QualType Ty,unsigned MaxWidth)5457f4a2713aSLionel Sambuc static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5458f4a2713aSLionel Sambuc unsigned MaxWidth) {
5459f4a2713aSLionel Sambuc if (result.isInt())
5460f4a2713aSLionel Sambuc return GetValueRange(C, result.getInt(), MaxWidth);
5461f4a2713aSLionel Sambuc
5462f4a2713aSLionel Sambuc if (result.isVector()) {
5463f4a2713aSLionel Sambuc IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5464f4a2713aSLionel Sambuc for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5465f4a2713aSLionel Sambuc IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5466f4a2713aSLionel Sambuc R = IntRange::join(R, El);
5467f4a2713aSLionel Sambuc }
5468f4a2713aSLionel Sambuc return R;
5469f4a2713aSLionel Sambuc }
5470f4a2713aSLionel Sambuc
5471f4a2713aSLionel Sambuc if (result.isComplexInt()) {
5472f4a2713aSLionel Sambuc IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5473f4a2713aSLionel Sambuc IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5474f4a2713aSLionel Sambuc return IntRange::join(R, I);
5475f4a2713aSLionel Sambuc }
5476f4a2713aSLionel Sambuc
5477f4a2713aSLionel Sambuc // This can happen with lossless casts to intptr_t of "based" lvalues.
5478f4a2713aSLionel Sambuc // Assume it might use arbitrary bits.
5479f4a2713aSLionel Sambuc // FIXME: The only reason we need to pass the type in here is to get
5480f4a2713aSLionel Sambuc // the sign right on this one case. It would be nice if APValue
5481f4a2713aSLionel Sambuc // preserved this.
5482f4a2713aSLionel Sambuc assert(result.isLValue() || result.isAddrLabelDiff());
5483f4a2713aSLionel Sambuc return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
5484f4a2713aSLionel Sambuc }
5485f4a2713aSLionel Sambuc
GetExprType(Expr * E)5486f4a2713aSLionel Sambuc static QualType GetExprType(Expr *E) {
5487f4a2713aSLionel Sambuc QualType Ty = E->getType();
5488f4a2713aSLionel Sambuc if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5489f4a2713aSLionel Sambuc Ty = AtomicRHS->getValueType();
5490f4a2713aSLionel Sambuc return Ty;
5491f4a2713aSLionel Sambuc }
5492f4a2713aSLionel Sambuc
5493f4a2713aSLionel Sambuc /// Pseudo-evaluate the given integer expression, estimating the
5494f4a2713aSLionel Sambuc /// range of values it might take.
5495f4a2713aSLionel Sambuc ///
5496f4a2713aSLionel Sambuc /// \param MaxWidth - the width to which the value will be truncated
GetExprRange(ASTContext & C,Expr * E,unsigned MaxWidth)5497f4a2713aSLionel Sambuc static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
5498f4a2713aSLionel Sambuc E = E->IgnoreParens();
5499f4a2713aSLionel Sambuc
5500f4a2713aSLionel Sambuc // Try a full evaluation first.
5501f4a2713aSLionel Sambuc Expr::EvalResult result;
5502f4a2713aSLionel Sambuc if (E->EvaluateAsRValue(result, C))
5503f4a2713aSLionel Sambuc return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
5504f4a2713aSLionel Sambuc
5505f4a2713aSLionel Sambuc // I think we only want to look through implicit casts here; if the
5506f4a2713aSLionel Sambuc // user has an explicit widening cast, we should treat the value as
5507f4a2713aSLionel Sambuc // being of the new, wider type.
5508f4a2713aSLionel Sambuc if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
5509f4a2713aSLionel Sambuc if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
5510f4a2713aSLionel Sambuc return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5511f4a2713aSLionel Sambuc
5512f4a2713aSLionel Sambuc IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
5513f4a2713aSLionel Sambuc
5514f4a2713aSLionel Sambuc bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
5515f4a2713aSLionel Sambuc
5516f4a2713aSLionel Sambuc // Assume that non-integer casts can span the full range of the type.
5517f4a2713aSLionel Sambuc if (!isIntegerCast)
5518f4a2713aSLionel Sambuc return OutputTypeRange;
5519f4a2713aSLionel Sambuc
5520f4a2713aSLionel Sambuc IntRange SubRange
5521f4a2713aSLionel Sambuc = GetExprRange(C, CE->getSubExpr(),
5522f4a2713aSLionel Sambuc std::min(MaxWidth, OutputTypeRange.Width));
5523f4a2713aSLionel Sambuc
5524f4a2713aSLionel Sambuc // Bail out if the subexpr's range is as wide as the cast type.
5525f4a2713aSLionel Sambuc if (SubRange.Width >= OutputTypeRange.Width)
5526f4a2713aSLionel Sambuc return OutputTypeRange;
5527f4a2713aSLionel Sambuc
5528f4a2713aSLionel Sambuc // Otherwise, we take the smaller width, and we're non-negative if
5529f4a2713aSLionel Sambuc // either the output type or the subexpr is.
5530f4a2713aSLionel Sambuc return IntRange(SubRange.Width,
5531f4a2713aSLionel Sambuc SubRange.NonNegative || OutputTypeRange.NonNegative);
5532f4a2713aSLionel Sambuc }
5533f4a2713aSLionel Sambuc
5534f4a2713aSLionel Sambuc if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5535f4a2713aSLionel Sambuc // If we can fold the condition, just take that operand.
5536f4a2713aSLionel Sambuc bool CondResult;
5537f4a2713aSLionel Sambuc if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5538f4a2713aSLionel Sambuc return GetExprRange(C, CondResult ? CO->getTrueExpr()
5539f4a2713aSLionel Sambuc : CO->getFalseExpr(),
5540f4a2713aSLionel Sambuc MaxWidth);
5541f4a2713aSLionel Sambuc
5542f4a2713aSLionel Sambuc // Otherwise, conservatively merge.
5543f4a2713aSLionel Sambuc IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5544f4a2713aSLionel Sambuc IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5545f4a2713aSLionel Sambuc return IntRange::join(L, R);
5546f4a2713aSLionel Sambuc }
5547f4a2713aSLionel Sambuc
5548f4a2713aSLionel Sambuc if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5549f4a2713aSLionel Sambuc switch (BO->getOpcode()) {
5550f4a2713aSLionel Sambuc
5551f4a2713aSLionel Sambuc // Boolean-valued operations are single-bit and positive.
5552f4a2713aSLionel Sambuc case BO_LAnd:
5553f4a2713aSLionel Sambuc case BO_LOr:
5554f4a2713aSLionel Sambuc case BO_LT:
5555f4a2713aSLionel Sambuc case BO_GT:
5556f4a2713aSLionel Sambuc case BO_LE:
5557f4a2713aSLionel Sambuc case BO_GE:
5558f4a2713aSLionel Sambuc case BO_EQ:
5559f4a2713aSLionel Sambuc case BO_NE:
5560f4a2713aSLionel Sambuc return IntRange::forBoolType();
5561f4a2713aSLionel Sambuc
5562f4a2713aSLionel Sambuc // The type of the assignments is the type of the LHS, so the RHS
5563f4a2713aSLionel Sambuc // is not necessarily the same type.
5564f4a2713aSLionel Sambuc case BO_MulAssign:
5565f4a2713aSLionel Sambuc case BO_DivAssign:
5566f4a2713aSLionel Sambuc case BO_RemAssign:
5567f4a2713aSLionel Sambuc case BO_AddAssign:
5568f4a2713aSLionel Sambuc case BO_SubAssign:
5569f4a2713aSLionel Sambuc case BO_XorAssign:
5570f4a2713aSLionel Sambuc case BO_OrAssign:
5571f4a2713aSLionel Sambuc // TODO: bitfields?
5572f4a2713aSLionel Sambuc return IntRange::forValueOfType(C, GetExprType(E));
5573f4a2713aSLionel Sambuc
5574f4a2713aSLionel Sambuc // Simple assignments just pass through the RHS, which will have
5575f4a2713aSLionel Sambuc // been coerced to the LHS type.
5576f4a2713aSLionel Sambuc case BO_Assign:
5577f4a2713aSLionel Sambuc // TODO: bitfields?
5578f4a2713aSLionel Sambuc return GetExprRange(C, BO->getRHS(), MaxWidth);
5579f4a2713aSLionel Sambuc
5580f4a2713aSLionel Sambuc // Operations with opaque sources are black-listed.
5581f4a2713aSLionel Sambuc case BO_PtrMemD:
5582f4a2713aSLionel Sambuc case BO_PtrMemI:
5583f4a2713aSLionel Sambuc return IntRange::forValueOfType(C, GetExprType(E));
5584f4a2713aSLionel Sambuc
5585f4a2713aSLionel Sambuc // Bitwise-and uses the *infinum* of the two source ranges.
5586f4a2713aSLionel Sambuc case BO_And:
5587f4a2713aSLionel Sambuc case BO_AndAssign:
5588f4a2713aSLionel Sambuc return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5589f4a2713aSLionel Sambuc GetExprRange(C, BO->getRHS(), MaxWidth));
5590f4a2713aSLionel Sambuc
5591f4a2713aSLionel Sambuc // Left shift gets black-listed based on a judgement call.
5592f4a2713aSLionel Sambuc case BO_Shl:
5593f4a2713aSLionel Sambuc // ...except that we want to treat '1 << (blah)' as logically
5594f4a2713aSLionel Sambuc // positive. It's an important idiom.
5595f4a2713aSLionel Sambuc if (IntegerLiteral *I
5596f4a2713aSLionel Sambuc = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5597f4a2713aSLionel Sambuc if (I->getValue() == 1) {
5598f4a2713aSLionel Sambuc IntRange R = IntRange::forValueOfType(C, GetExprType(E));
5599f4a2713aSLionel Sambuc return IntRange(R.Width, /*NonNegative*/ true);
5600f4a2713aSLionel Sambuc }
5601f4a2713aSLionel Sambuc }
5602f4a2713aSLionel Sambuc // fallthrough
5603f4a2713aSLionel Sambuc
5604f4a2713aSLionel Sambuc case BO_ShlAssign:
5605f4a2713aSLionel Sambuc return IntRange::forValueOfType(C, GetExprType(E));
5606f4a2713aSLionel Sambuc
5607f4a2713aSLionel Sambuc // Right shift by a constant can narrow its left argument.
5608f4a2713aSLionel Sambuc case BO_Shr:
5609f4a2713aSLionel Sambuc case BO_ShrAssign: {
5610f4a2713aSLionel Sambuc IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5611f4a2713aSLionel Sambuc
5612f4a2713aSLionel Sambuc // If the shift amount is a positive constant, drop the width by
5613f4a2713aSLionel Sambuc // that much.
5614f4a2713aSLionel Sambuc llvm::APSInt shift;
5615f4a2713aSLionel Sambuc if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5616f4a2713aSLionel Sambuc shift.isNonNegative()) {
5617f4a2713aSLionel Sambuc unsigned zext = shift.getZExtValue();
5618f4a2713aSLionel Sambuc if (zext >= L.Width)
5619f4a2713aSLionel Sambuc L.Width = (L.NonNegative ? 0 : 1);
5620f4a2713aSLionel Sambuc else
5621f4a2713aSLionel Sambuc L.Width -= zext;
5622f4a2713aSLionel Sambuc }
5623f4a2713aSLionel Sambuc
5624f4a2713aSLionel Sambuc return L;
5625f4a2713aSLionel Sambuc }
5626f4a2713aSLionel Sambuc
5627f4a2713aSLionel Sambuc // Comma acts as its right operand.
5628f4a2713aSLionel Sambuc case BO_Comma:
5629f4a2713aSLionel Sambuc return GetExprRange(C, BO->getRHS(), MaxWidth);
5630f4a2713aSLionel Sambuc
5631f4a2713aSLionel Sambuc // Black-list pointer subtractions.
5632f4a2713aSLionel Sambuc case BO_Sub:
5633f4a2713aSLionel Sambuc if (BO->getLHS()->getType()->isPointerType())
5634f4a2713aSLionel Sambuc return IntRange::forValueOfType(C, GetExprType(E));
5635f4a2713aSLionel Sambuc break;
5636f4a2713aSLionel Sambuc
5637f4a2713aSLionel Sambuc // The width of a division result is mostly determined by the size
5638f4a2713aSLionel Sambuc // of the LHS.
5639f4a2713aSLionel Sambuc case BO_Div: {
5640f4a2713aSLionel Sambuc // Don't 'pre-truncate' the operands.
5641f4a2713aSLionel Sambuc unsigned opWidth = C.getIntWidth(GetExprType(E));
5642f4a2713aSLionel Sambuc IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5643f4a2713aSLionel Sambuc
5644f4a2713aSLionel Sambuc // If the divisor is constant, use that.
5645f4a2713aSLionel Sambuc llvm::APSInt divisor;
5646f4a2713aSLionel Sambuc if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5647f4a2713aSLionel Sambuc unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5648f4a2713aSLionel Sambuc if (log2 >= L.Width)
5649f4a2713aSLionel Sambuc L.Width = (L.NonNegative ? 0 : 1);
5650f4a2713aSLionel Sambuc else
5651f4a2713aSLionel Sambuc L.Width = std::min(L.Width - log2, MaxWidth);
5652f4a2713aSLionel Sambuc return L;
5653f4a2713aSLionel Sambuc }
5654f4a2713aSLionel Sambuc
5655f4a2713aSLionel Sambuc // Otherwise, just use the LHS's width.
5656f4a2713aSLionel Sambuc IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5657f4a2713aSLionel Sambuc return IntRange(L.Width, L.NonNegative && R.NonNegative);
5658f4a2713aSLionel Sambuc }
5659f4a2713aSLionel Sambuc
5660f4a2713aSLionel Sambuc // The result of a remainder can't be larger than the result of
5661f4a2713aSLionel Sambuc // either side.
5662f4a2713aSLionel Sambuc case BO_Rem: {
5663f4a2713aSLionel Sambuc // Don't 'pre-truncate' the operands.
5664f4a2713aSLionel Sambuc unsigned opWidth = C.getIntWidth(GetExprType(E));
5665f4a2713aSLionel Sambuc IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5666f4a2713aSLionel Sambuc IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5667f4a2713aSLionel Sambuc
5668f4a2713aSLionel Sambuc IntRange meet = IntRange::meet(L, R);
5669f4a2713aSLionel Sambuc meet.Width = std::min(meet.Width, MaxWidth);
5670f4a2713aSLionel Sambuc return meet;
5671f4a2713aSLionel Sambuc }
5672f4a2713aSLionel Sambuc
5673f4a2713aSLionel Sambuc // The default behavior is okay for these.
5674f4a2713aSLionel Sambuc case BO_Mul:
5675f4a2713aSLionel Sambuc case BO_Add:
5676f4a2713aSLionel Sambuc case BO_Xor:
5677f4a2713aSLionel Sambuc case BO_Or:
5678f4a2713aSLionel Sambuc break;
5679f4a2713aSLionel Sambuc }
5680f4a2713aSLionel Sambuc
5681f4a2713aSLionel Sambuc // The default case is to treat the operation as if it were closed
5682f4a2713aSLionel Sambuc // on the narrowest type that encompasses both operands.
5683f4a2713aSLionel Sambuc IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5684f4a2713aSLionel Sambuc IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5685f4a2713aSLionel Sambuc return IntRange::join(L, R);
5686f4a2713aSLionel Sambuc }
5687f4a2713aSLionel Sambuc
5688f4a2713aSLionel Sambuc if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5689f4a2713aSLionel Sambuc switch (UO->getOpcode()) {
5690f4a2713aSLionel Sambuc // Boolean-valued operations are white-listed.
5691f4a2713aSLionel Sambuc case UO_LNot:
5692f4a2713aSLionel Sambuc return IntRange::forBoolType();
5693f4a2713aSLionel Sambuc
5694f4a2713aSLionel Sambuc // Operations with opaque sources are black-listed.
5695f4a2713aSLionel Sambuc case UO_Deref:
5696f4a2713aSLionel Sambuc case UO_AddrOf: // should be impossible
5697f4a2713aSLionel Sambuc return IntRange::forValueOfType(C, GetExprType(E));
5698f4a2713aSLionel Sambuc
5699f4a2713aSLionel Sambuc default:
5700f4a2713aSLionel Sambuc return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5701f4a2713aSLionel Sambuc }
5702f4a2713aSLionel Sambuc }
5703f4a2713aSLionel Sambuc
5704f4a2713aSLionel Sambuc if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5705f4a2713aSLionel Sambuc return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5706f4a2713aSLionel Sambuc
5707f4a2713aSLionel Sambuc if (FieldDecl *BitField = E->getSourceBitField())
5708f4a2713aSLionel Sambuc return IntRange(BitField->getBitWidthValue(C),
5709f4a2713aSLionel Sambuc BitField->getType()->isUnsignedIntegerOrEnumerationType());
5710f4a2713aSLionel Sambuc
5711f4a2713aSLionel Sambuc return IntRange::forValueOfType(C, GetExprType(E));
5712f4a2713aSLionel Sambuc }
5713f4a2713aSLionel Sambuc
GetExprRange(ASTContext & C,Expr * E)5714f4a2713aSLionel Sambuc static IntRange GetExprRange(ASTContext &C, Expr *E) {
5715f4a2713aSLionel Sambuc return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
5716f4a2713aSLionel Sambuc }
5717f4a2713aSLionel Sambuc
5718f4a2713aSLionel Sambuc /// Checks whether the given value, which currently has the given
5719f4a2713aSLionel Sambuc /// source semantics, has the same value when coerced through the
5720f4a2713aSLionel Sambuc /// target semantics.
IsSameFloatAfterCast(const llvm::APFloat & value,const llvm::fltSemantics & Src,const llvm::fltSemantics & Tgt)5721f4a2713aSLionel Sambuc static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5722f4a2713aSLionel Sambuc const llvm::fltSemantics &Src,
5723f4a2713aSLionel Sambuc const llvm::fltSemantics &Tgt) {
5724f4a2713aSLionel Sambuc llvm::APFloat truncated = value;
5725f4a2713aSLionel Sambuc
5726f4a2713aSLionel Sambuc bool ignored;
5727f4a2713aSLionel Sambuc truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5728f4a2713aSLionel Sambuc truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5729f4a2713aSLionel Sambuc
5730f4a2713aSLionel Sambuc return truncated.bitwiseIsEqual(value);
5731f4a2713aSLionel Sambuc }
5732f4a2713aSLionel Sambuc
5733f4a2713aSLionel Sambuc /// Checks whether the given value, which currently has the given
5734f4a2713aSLionel Sambuc /// source semantics, has the same value when coerced through the
5735f4a2713aSLionel Sambuc /// target semantics.
5736f4a2713aSLionel Sambuc ///
5737f4a2713aSLionel Sambuc /// The value might be a vector of floats (or a complex number).
IsSameFloatAfterCast(const APValue & value,const llvm::fltSemantics & Src,const llvm::fltSemantics & Tgt)5738f4a2713aSLionel Sambuc static bool IsSameFloatAfterCast(const APValue &value,
5739f4a2713aSLionel Sambuc const llvm::fltSemantics &Src,
5740f4a2713aSLionel Sambuc const llvm::fltSemantics &Tgt) {
5741f4a2713aSLionel Sambuc if (value.isFloat())
5742f4a2713aSLionel Sambuc return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5743f4a2713aSLionel Sambuc
5744f4a2713aSLionel Sambuc if (value.isVector()) {
5745f4a2713aSLionel Sambuc for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5746f4a2713aSLionel Sambuc if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5747f4a2713aSLionel Sambuc return false;
5748f4a2713aSLionel Sambuc return true;
5749f4a2713aSLionel Sambuc }
5750f4a2713aSLionel Sambuc
5751f4a2713aSLionel Sambuc assert(value.isComplexFloat());
5752f4a2713aSLionel Sambuc return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5753f4a2713aSLionel Sambuc IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5754f4a2713aSLionel Sambuc }
5755f4a2713aSLionel Sambuc
5756f4a2713aSLionel Sambuc static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
5757f4a2713aSLionel Sambuc
IsZero(Sema & S,Expr * E)5758f4a2713aSLionel Sambuc static bool IsZero(Sema &S, Expr *E) {
5759f4a2713aSLionel Sambuc // Suppress cases where we are comparing against an enum constant.
5760f4a2713aSLionel Sambuc if (const DeclRefExpr *DR =
5761f4a2713aSLionel Sambuc dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5762f4a2713aSLionel Sambuc if (isa<EnumConstantDecl>(DR->getDecl()))
5763f4a2713aSLionel Sambuc return false;
5764f4a2713aSLionel Sambuc
5765f4a2713aSLionel Sambuc // Suppress cases where the '0' value is expanded from a macro.
5766f4a2713aSLionel Sambuc if (E->getLocStart().isMacroID())
5767f4a2713aSLionel Sambuc return false;
5768f4a2713aSLionel Sambuc
5769f4a2713aSLionel Sambuc llvm::APSInt Value;
5770f4a2713aSLionel Sambuc return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5771f4a2713aSLionel Sambuc }
5772f4a2713aSLionel Sambuc
HasEnumType(Expr * E)5773f4a2713aSLionel Sambuc static bool HasEnumType(Expr *E) {
5774f4a2713aSLionel Sambuc // Strip off implicit integral promotions.
5775f4a2713aSLionel Sambuc while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5776f4a2713aSLionel Sambuc if (ICE->getCastKind() != CK_IntegralCast &&
5777f4a2713aSLionel Sambuc ICE->getCastKind() != CK_NoOp)
5778f4a2713aSLionel Sambuc break;
5779f4a2713aSLionel Sambuc E = ICE->getSubExpr();
5780f4a2713aSLionel Sambuc }
5781f4a2713aSLionel Sambuc
5782f4a2713aSLionel Sambuc return E->getType()->isEnumeralType();
5783f4a2713aSLionel Sambuc }
5784f4a2713aSLionel Sambuc
CheckTrivialUnsignedComparison(Sema & S,BinaryOperator * E)5785f4a2713aSLionel Sambuc static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
5786f4a2713aSLionel Sambuc // Disable warning in template instantiations.
5787f4a2713aSLionel Sambuc if (!S.ActiveTemplateInstantiations.empty())
5788f4a2713aSLionel Sambuc return;
5789f4a2713aSLionel Sambuc
5790f4a2713aSLionel Sambuc BinaryOperatorKind op = E->getOpcode();
5791f4a2713aSLionel Sambuc if (E->isValueDependent())
5792f4a2713aSLionel Sambuc return;
5793f4a2713aSLionel Sambuc
5794f4a2713aSLionel Sambuc if (op == BO_LT && IsZero(S, E->getRHS())) {
5795f4a2713aSLionel Sambuc S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5796f4a2713aSLionel Sambuc << "< 0" << "false" << HasEnumType(E->getLHS())
5797f4a2713aSLionel Sambuc << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5798f4a2713aSLionel Sambuc } else if (op == BO_GE && IsZero(S, E->getRHS())) {
5799f4a2713aSLionel Sambuc S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5800f4a2713aSLionel Sambuc << ">= 0" << "true" << HasEnumType(E->getLHS())
5801f4a2713aSLionel Sambuc << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5802f4a2713aSLionel Sambuc } else if (op == BO_GT && IsZero(S, E->getLHS())) {
5803f4a2713aSLionel Sambuc S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5804f4a2713aSLionel Sambuc << "0 >" << "false" << HasEnumType(E->getRHS())
5805f4a2713aSLionel Sambuc << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5806f4a2713aSLionel Sambuc } else if (op == BO_LE && IsZero(S, E->getLHS())) {
5807f4a2713aSLionel Sambuc S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5808f4a2713aSLionel Sambuc << "0 <=" << "true" << HasEnumType(E->getRHS())
5809f4a2713aSLionel Sambuc << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5810f4a2713aSLionel Sambuc }
5811f4a2713aSLionel Sambuc }
5812f4a2713aSLionel Sambuc
DiagnoseOutOfRangeComparison(Sema & S,BinaryOperator * E,Expr * Constant,Expr * Other,llvm::APSInt Value,bool RhsConstant)5813f4a2713aSLionel Sambuc static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
5814f4a2713aSLionel Sambuc Expr *Constant, Expr *Other,
5815f4a2713aSLionel Sambuc llvm::APSInt Value,
5816f4a2713aSLionel Sambuc bool RhsConstant) {
5817f4a2713aSLionel Sambuc // Disable warning in template instantiations.
5818f4a2713aSLionel Sambuc if (!S.ActiveTemplateInstantiations.empty())
5819f4a2713aSLionel Sambuc return;
5820f4a2713aSLionel Sambuc
5821*0a6a1f1dSLionel Sambuc // TODO: Investigate using GetExprRange() to get tighter bounds
5822*0a6a1f1dSLionel Sambuc // on the bit ranges.
5823*0a6a1f1dSLionel Sambuc QualType OtherT = Other->getType();
5824*0a6a1f1dSLionel Sambuc if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5825*0a6a1f1dSLionel Sambuc OtherT = AT->getValueType();
5826*0a6a1f1dSLionel Sambuc IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5827*0a6a1f1dSLionel Sambuc unsigned OtherWidth = OtherRange.Width;
5828*0a6a1f1dSLionel Sambuc
5829*0a6a1f1dSLionel Sambuc bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5830*0a6a1f1dSLionel Sambuc
5831f4a2713aSLionel Sambuc // 0 values are handled later by CheckTrivialUnsignedComparison().
5832*0a6a1f1dSLionel Sambuc if ((Value == 0) && (!OtherIsBooleanType))
5833f4a2713aSLionel Sambuc return;
5834f4a2713aSLionel Sambuc
5835f4a2713aSLionel Sambuc BinaryOperatorKind op = E->getOpcode();
5836*0a6a1f1dSLionel Sambuc bool IsTrue = true;
5837*0a6a1f1dSLionel Sambuc
5838*0a6a1f1dSLionel Sambuc // Used for diagnostic printout.
5839*0a6a1f1dSLionel Sambuc enum {
5840*0a6a1f1dSLionel Sambuc LiteralConstant = 0,
5841*0a6a1f1dSLionel Sambuc CXXBoolLiteralTrue,
5842*0a6a1f1dSLionel Sambuc CXXBoolLiteralFalse
5843*0a6a1f1dSLionel Sambuc } LiteralOrBoolConstant = LiteralConstant;
5844*0a6a1f1dSLionel Sambuc
5845*0a6a1f1dSLionel Sambuc if (!OtherIsBooleanType) {
5846f4a2713aSLionel Sambuc QualType ConstantT = Constant->getType();
5847f4a2713aSLionel Sambuc QualType CommonT = E->getLHS()->getType();
5848*0a6a1f1dSLionel Sambuc
5849f4a2713aSLionel Sambuc if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5850f4a2713aSLionel Sambuc return;
5851*0a6a1f1dSLionel Sambuc assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5852*0a6a1f1dSLionel Sambuc "comparison with non-integer type");
5853f4a2713aSLionel Sambuc
5854f4a2713aSLionel Sambuc bool ConstantSigned = ConstantT->isSignedIntegerType();
5855f4a2713aSLionel Sambuc bool CommonSigned = CommonT->isSignedIntegerType();
5856f4a2713aSLionel Sambuc
5857f4a2713aSLionel Sambuc bool EqualityOnly = false;
5858f4a2713aSLionel Sambuc
5859f4a2713aSLionel Sambuc if (CommonSigned) {
5860f4a2713aSLionel Sambuc // The common type is signed, therefore no signed to unsigned conversion.
5861f4a2713aSLionel Sambuc if (!OtherRange.NonNegative) {
5862f4a2713aSLionel Sambuc // Check that the constant is representable in type OtherT.
5863f4a2713aSLionel Sambuc if (ConstantSigned) {
5864f4a2713aSLionel Sambuc if (OtherWidth >= Value.getMinSignedBits())
5865f4a2713aSLionel Sambuc return;
5866f4a2713aSLionel Sambuc } else { // !ConstantSigned
5867f4a2713aSLionel Sambuc if (OtherWidth >= Value.getActiveBits() + 1)
5868f4a2713aSLionel Sambuc return;
5869f4a2713aSLionel Sambuc }
5870f4a2713aSLionel Sambuc } else { // !OtherSigned
5871f4a2713aSLionel Sambuc // Check that the constant is representable in type OtherT.
5872f4a2713aSLionel Sambuc // Negative values are out of range.
5873f4a2713aSLionel Sambuc if (ConstantSigned) {
5874f4a2713aSLionel Sambuc if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5875f4a2713aSLionel Sambuc return;
5876f4a2713aSLionel Sambuc } else { // !ConstantSigned
5877f4a2713aSLionel Sambuc if (OtherWidth >= Value.getActiveBits())
5878f4a2713aSLionel Sambuc return;
5879f4a2713aSLionel Sambuc }
5880f4a2713aSLionel Sambuc }
5881f4a2713aSLionel Sambuc } else { // !CommonSigned
5882f4a2713aSLionel Sambuc if (OtherRange.NonNegative) {
5883f4a2713aSLionel Sambuc if (OtherWidth >= Value.getActiveBits())
5884f4a2713aSLionel Sambuc return;
5885*0a6a1f1dSLionel Sambuc } else { // OtherSigned
5886*0a6a1f1dSLionel Sambuc assert(!ConstantSigned &&
5887*0a6a1f1dSLionel Sambuc "Two signed types converted to unsigned types.");
5888f4a2713aSLionel Sambuc // Check to see if the constant is representable in OtherT.
5889f4a2713aSLionel Sambuc if (OtherWidth > Value.getActiveBits())
5890f4a2713aSLionel Sambuc return;
5891f4a2713aSLionel Sambuc // Check to see if the constant is equivalent to a negative value
5892f4a2713aSLionel Sambuc // cast to CommonT.
5893*0a6a1f1dSLionel Sambuc if (S.Context.getIntWidth(ConstantT) ==
5894*0a6a1f1dSLionel Sambuc S.Context.getIntWidth(CommonT) &&
5895f4a2713aSLionel Sambuc Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5896f4a2713aSLionel Sambuc return;
5897*0a6a1f1dSLionel Sambuc // The constant value rests between values that OtherT can represent
5898*0a6a1f1dSLionel Sambuc // after conversion. Relational comparison still works, but equality
5899f4a2713aSLionel Sambuc // comparisons will be tautological.
5900f4a2713aSLionel Sambuc EqualityOnly = true;
5901f4a2713aSLionel Sambuc }
5902f4a2713aSLionel Sambuc }
5903f4a2713aSLionel Sambuc
5904f4a2713aSLionel Sambuc bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5905f4a2713aSLionel Sambuc
5906f4a2713aSLionel Sambuc if (op == BO_EQ || op == BO_NE) {
5907f4a2713aSLionel Sambuc IsTrue = op == BO_NE;
5908f4a2713aSLionel Sambuc } else if (EqualityOnly) {
5909f4a2713aSLionel Sambuc return;
5910f4a2713aSLionel Sambuc } else if (RhsConstant) {
5911f4a2713aSLionel Sambuc if (op == BO_GT || op == BO_GE)
5912f4a2713aSLionel Sambuc IsTrue = !PositiveConstant;
5913f4a2713aSLionel Sambuc else // op == BO_LT || op == BO_LE
5914f4a2713aSLionel Sambuc IsTrue = PositiveConstant;
5915f4a2713aSLionel Sambuc } else {
5916f4a2713aSLionel Sambuc if (op == BO_LT || op == BO_LE)
5917f4a2713aSLionel Sambuc IsTrue = !PositiveConstant;
5918f4a2713aSLionel Sambuc else // op == BO_GT || op == BO_GE
5919f4a2713aSLionel Sambuc IsTrue = PositiveConstant;
5920f4a2713aSLionel Sambuc }
5921*0a6a1f1dSLionel Sambuc } else {
5922*0a6a1f1dSLionel Sambuc // Other isKnownToHaveBooleanValue
5923*0a6a1f1dSLionel Sambuc enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5924*0a6a1f1dSLionel Sambuc enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5925*0a6a1f1dSLionel Sambuc enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5926*0a6a1f1dSLionel Sambuc
5927*0a6a1f1dSLionel Sambuc static const struct LinkedConditions {
5928*0a6a1f1dSLionel Sambuc CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5929*0a6a1f1dSLionel Sambuc CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5930*0a6a1f1dSLionel Sambuc CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5931*0a6a1f1dSLionel Sambuc CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5932*0a6a1f1dSLionel Sambuc CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5933*0a6a1f1dSLionel Sambuc CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5934*0a6a1f1dSLionel Sambuc
5935*0a6a1f1dSLionel Sambuc } TruthTable = {
5936*0a6a1f1dSLionel Sambuc // Constant on LHS. | Constant on RHS. |
5937*0a6a1f1dSLionel Sambuc // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5938*0a6a1f1dSLionel Sambuc { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5939*0a6a1f1dSLionel Sambuc { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5940*0a6a1f1dSLionel Sambuc { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5941*0a6a1f1dSLionel Sambuc { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5942*0a6a1f1dSLionel Sambuc { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5943*0a6a1f1dSLionel Sambuc { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5944*0a6a1f1dSLionel Sambuc };
5945*0a6a1f1dSLionel Sambuc
5946*0a6a1f1dSLionel Sambuc bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5947*0a6a1f1dSLionel Sambuc
5948*0a6a1f1dSLionel Sambuc enum ConstantValue ConstVal = Zero;
5949*0a6a1f1dSLionel Sambuc if (Value.isUnsigned() || Value.isNonNegative()) {
5950*0a6a1f1dSLionel Sambuc if (Value == 0) {
5951*0a6a1f1dSLionel Sambuc LiteralOrBoolConstant =
5952*0a6a1f1dSLionel Sambuc ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5953*0a6a1f1dSLionel Sambuc ConstVal = Zero;
5954*0a6a1f1dSLionel Sambuc } else if (Value == 1) {
5955*0a6a1f1dSLionel Sambuc LiteralOrBoolConstant =
5956*0a6a1f1dSLionel Sambuc ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5957*0a6a1f1dSLionel Sambuc ConstVal = One;
5958*0a6a1f1dSLionel Sambuc } else {
5959*0a6a1f1dSLionel Sambuc LiteralOrBoolConstant = LiteralConstant;
5960*0a6a1f1dSLionel Sambuc ConstVal = GT_One;
5961*0a6a1f1dSLionel Sambuc }
5962*0a6a1f1dSLionel Sambuc } else {
5963*0a6a1f1dSLionel Sambuc ConstVal = LT_Zero;
5964*0a6a1f1dSLionel Sambuc }
5965*0a6a1f1dSLionel Sambuc
5966*0a6a1f1dSLionel Sambuc CompareBoolWithConstantResult CmpRes;
5967*0a6a1f1dSLionel Sambuc
5968*0a6a1f1dSLionel Sambuc switch (op) {
5969*0a6a1f1dSLionel Sambuc case BO_LT:
5970*0a6a1f1dSLionel Sambuc CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5971*0a6a1f1dSLionel Sambuc break;
5972*0a6a1f1dSLionel Sambuc case BO_GT:
5973*0a6a1f1dSLionel Sambuc CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5974*0a6a1f1dSLionel Sambuc break;
5975*0a6a1f1dSLionel Sambuc case BO_LE:
5976*0a6a1f1dSLionel Sambuc CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5977*0a6a1f1dSLionel Sambuc break;
5978*0a6a1f1dSLionel Sambuc case BO_GE:
5979*0a6a1f1dSLionel Sambuc CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5980*0a6a1f1dSLionel Sambuc break;
5981*0a6a1f1dSLionel Sambuc case BO_EQ:
5982*0a6a1f1dSLionel Sambuc CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5983*0a6a1f1dSLionel Sambuc break;
5984*0a6a1f1dSLionel Sambuc case BO_NE:
5985*0a6a1f1dSLionel Sambuc CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5986*0a6a1f1dSLionel Sambuc break;
5987*0a6a1f1dSLionel Sambuc default:
5988*0a6a1f1dSLionel Sambuc CmpRes = Unkwn;
5989*0a6a1f1dSLionel Sambuc break;
5990*0a6a1f1dSLionel Sambuc }
5991*0a6a1f1dSLionel Sambuc
5992*0a6a1f1dSLionel Sambuc if (CmpRes == AFals) {
5993*0a6a1f1dSLionel Sambuc IsTrue = false;
5994*0a6a1f1dSLionel Sambuc } else if (CmpRes == ATrue) {
5995*0a6a1f1dSLionel Sambuc IsTrue = true;
5996*0a6a1f1dSLionel Sambuc } else {
5997*0a6a1f1dSLionel Sambuc return;
5998*0a6a1f1dSLionel Sambuc }
5999*0a6a1f1dSLionel Sambuc }
6000f4a2713aSLionel Sambuc
6001f4a2713aSLionel Sambuc // If this is a comparison to an enum constant, include that
6002f4a2713aSLionel Sambuc // constant in the diagnostic.
6003*0a6a1f1dSLionel Sambuc const EnumConstantDecl *ED = nullptr;
6004f4a2713aSLionel Sambuc if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6005f4a2713aSLionel Sambuc ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6006f4a2713aSLionel Sambuc
6007f4a2713aSLionel Sambuc SmallString<64> PrettySourceValue;
6008f4a2713aSLionel Sambuc llvm::raw_svector_ostream OS(PrettySourceValue);
6009f4a2713aSLionel Sambuc if (ED)
6010f4a2713aSLionel Sambuc OS << '\'' << *ED << "' (" << Value << ")";
6011f4a2713aSLionel Sambuc else
6012f4a2713aSLionel Sambuc OS << Value;
6013f4a2713aSLionel Sambuc
6014*0a6a1f1dSLionel Sambuc S.DiagRuntimeBehavior(
6015*0a6a1f1dSLionel Sambuc E->getOperatorLoc(), E,
6016*0a6a1f1dSLionel Sambuc S.PDiag(diag::warn_out_of_range_compare)
6017*0a6a1f1dSLionel Sambuc << OS.str() << LiteralOrBoolConstant
6018*0a6a1f1dSLionel Sambuc << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6019*0a6a1f1dSLionel Sambuc << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
6020f4a2713aSLionel Sambuc }
6021f4a2713aSLionel Sambuc
6022f4a2713aSLionel Sambuc /// Analyze the operands of the given comparison. Implements the
6023f4a2713aSLionel Sambuc /// fallback case from AnalyzeComparison.
AnalyzeImpConvsInComparison(Sema & S,BinaryOperator * E)6024f4a2713aSLionel Sambuc static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
6025f4a2713aSLionel Sambuc AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6026f4a2713aSLionel Sambuc AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6027f4a2713aSLionel Sambuc }
6028f4a2713aSLionel Sambuc
6029f4a2713aSLionel Sambuc /// \brief Implements -Wsign-compare.
6030f4a2713aSLionel Sambuc ///
6031f4a2713aSLionel Sambuc /// \param E the binary operator to check for warnings
AnalyzeComparison(Sema & S,BinaryOperator * E)6032f4a2713aSLionel Sambuc static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
6033f4a2713aSLionel Sambuc // The type the comparison is being performed in.
6034f4a2713aSLionel Sambuc QualType T = E->getLHS()->getType();
6035*0a6a1f1dSLionel Sambuc
6036*0a6a1f1dSLionel Sambuc // Only analyze comparison operators where both sides have been converted to
6037*0a6a1f1dSLionel Sambuc // the same type.
6038*0a6a1f1dSLionel Sambuc if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6039*0a6a1f1dSLionel Sambuc return AnalyzeImpConvsInComparison(S, E);
6040*0a6a1f1dSLionel Sambuc
6041*0a6a1f1dSLionel Sambuc // Don't analyze value-dependent comparisons directly.
6042f4a2713aSLionel Sambuc if (E->isValueDependent())
6043f4a2713aSLionel Sambuc return AnalyzeImpConvsInComparison(S, E);
6044f4a2713aSLionel Sambuc
6045f4a2713aSLionel Sambuc Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6046f4a2713aSLionel Sambuc Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
6047f4a2713aSLionel Sambuc
6048f4a2713aSLionel Sambuc bool IsComparisonConstant = false;
6049f4a2713aSLionel Sambuc
6050f4a2713aSLionel Sambuc // Check whether an integer constant comparison results in a value
6051f4a2713aSLionel Sambuc // of 'true' or 'false'.
6052f4a2713aSLionel Sambuc if (T->isIntegralType(S.Context)) {
6053f4a2713aSLionel Sambuc llvm::APSInt RHSValue;
6054f4a2713aSLionel Sambuc bool IsRHSIntegralLiteral =
6055f4a2713aSLionel Sambuc RHS->isIntegerConstantExpr(RHSValue, S.Context);
6056f4a2713aSLionel Sambuc llvm::APSInt LHSValue;
6057f4a2713aSLionel Sambuc bool IsLHSIntegralLiteral =
6058f4a2713aSLionel Sambuc LHS->isIntegerConstantExpr(LHSValue, S.Context);
6059f4a2713aSLionel Sambuc if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6060f4a2713aSLionel Sambuc DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6061f4a2713aSLionel Sambuc else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6062f4a2713aSLionel Sambuc DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6063f4a2713aSLionel Sambuc else
6064f4a2713aSLionel Sambuc IsComparisonConstant =
6065f4a2713aSLionel Sambuc (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
6066f4a2713aSLionel Sambuc } else if (!T->hasUnsignedIntegerRepresentation())
6067f4a2713aSLionel Sambuc IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
6068f4a2713aSLionel Sambuc
6069f4a2713aSLionel Sambuc // We don't do anything special if this isn't an unsigned integral
6070f4a2713aSLionel Sambuc // comparison: we're only interested in integral comparisons, and
6071f4a2713aSLionel Sambuc // signed comparisons only happen in cases we don't care to warn about.
6072f4a2713aSLionel Sambuc //
6073f4a2713aSLionel Sambuc // We also don't care about value-dependent expressions or expressions
6074f4a2713aSLionel Sambuc // whose result is a constant.
6075f4a2713aSLionel Sambuc if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
6076f4a2713aSLionel Sambuc return AnalyzeImpConvsInComparison(S, E);
6077f4a2713aSLionel Sambuc
6078f4a2713aSLionel Sambuc // Check to see if one of the (unmodified) operands is of different
6079f4a2713aSLionel Sambuc // signedness.
6080f4a2713aSLionel Sambuc Expr *signedOperand, *unsignedOperand;
6081f4a2713aSLionel Sambuc if (LHS->getType()->hasSignedIntegerRepresentation()) {
6082f4a2713aSLionel Sambuc assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
6083f4a2713aSLionel Sambuc "unsigned comparison between two signed integer expressions?");
6084f4a2713aSLionel Sambuc signedOperand = LHS;
6085f4a2713aSLionel Sambuc unsignedOperand = RHS;
6086f4a2713aSLionel Sambuc } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6087f4a2713aSLionel Sambuc signedOperand = RHS;
6088f4a2713aSLionel Sambuc unsignedOperand = LHS;
6089f4a2713aSLionel Sambuc } else {
6090f4a2713aSLionel Sambuc CheckTrivialUnsignedComparison(S, E);
6091f4a2713aSLionel Sambuc return AnalyzeImpConvsInComparison(S, E);
6092f4a2713aSLionel Sambuc }
6093f4a2713aSLionel Sambuc
6094f4a2713aSLionel Sambuc // Otherwise, calculate the effective range of the signed operand.
6095f4a2713aSLionel Sambuc IntRange signedRange = GetExprRange(S.Context, signedOperand);
6096f4a2713aSLionel Sambuc
6097f4a2713aSLionel Sambuc // Go ahead and analyze implicit conversions in the operands. Note
6098f4a2713aSLionel Sambuc // that we skip the implicit conversions on both sides.
6099f4a2713aSLionel Sambuc AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6100f4a2713aSLionel Sambuc AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
6101f4a2713aSLionel Sambuc
6102f4a2713aSLionel Sambuc // If the signed range is non-negative, -Wsign-compare won't fire,
6103f4a2713aSLionel Sambuc // but we should still check for comparisons which are always true
6104f4a2713aSLionel Sambuc // or false.
6105f4a2713aSLionel Sambuc if (signedRange.NonNegative)
6106f4a2713aSLionel Sambuc return CheckTrivialUnsignedComparison(S, E);
6107f4a2713aSLionel Sambuc
6108f4a2713aSLionel Sambuc // For (in)equality comparisons, if the unsigned operand is a
6109f4a2713aSLionel Sambuc // constant which cannot collide with a overflowed signed operand,
6110f4a2713aSLionel Sambuc // then reinterpreting the signed operand as unsigned will not
6111f4a2713aSLionel Sambuc // change the result of the comparison.
6112f4a2713aSLionel Sambuc if (E->isEqualityOp()) {
6113f4a2713aSLionel Sambuc unsigned comparisonWidth = S.Context.getIntWidth(T);
6114f4a2713aSLionel Sambuc IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
6115f4a2713aSLionel Sambuc
6116f4a2713aSLionel Sambuc // We should never be unable to prove that the unsigned operand is
6117f4a2713aSLionel Sambuc // non-negative.
6118f4a2713aSLionel Sambuc assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6119f4a2713aSLionel Sambuc
6120f4a2713aSLionel Sambuc if (unsignedRange.Width < comparisonWidth)
6121f4a2713aSLionel Sambuc return;
6122f4a2713aSLionel Sambuc }
6123f4a2713aSLionel Sambuc
6124f4a2713aSLionel Sambuc S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6125f4a2713aSLionel Sambuc S.PDiag(diag::warn_mixed_sign_comparison)
6126f4a2713aSLionel Sambuc << LHS->getType() << RHS->getType()
6127f4a2713aSLionel Sambuc << LHS->getSourceRange() << RHS->getSourceRange());
6128f4a2713aSLionel Sambuc }
6129f4a2713aSLionel Sambuc
6130f4a2713aSLionel Sambuc /// Analyzes an attempt to assign the given value to a bitfield.
6131f4a2713aSLionel Sambuc ///
6132f4a2713aSLionel Sambuc /// Returns true if there was something fishy about the attempt.
AnalyzeBitFieldAssignment(Sema & S,FieldDecl * Bitfield,Expr * Init,SourceLocation InitLoc)6133f4a2713aSLionel Sambuc static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6134f4a2713aSLionel Sambuc SourceLocation InitLoc) {
6135f4a2713aSLionel Sambuc assert(Bitfield->isBitField());
6136f4a2713aSLionel Sambuc if (Bitfield->isInvalidDecl())
6137f4a2713aSLionel Sambuc return false;
6138f4a2713aSLionel Sambuc
6139f4a2713aSLionel Sambuc // White-list bool bitfields.
6140f4a2713aSLionel Sambuc if (Bitfield->getType()->isBooleanType())
6141f4a2713aSLionel Sambuc return false;
6142f4a2713aSLionel Sambuc
6143f4a2713aSLionel Sambuc // Ignore value- or type-dependent expressions.
6144f4a2713aSLionel Sambuc if (Bitfield->getBitWidth()->isValueDependent() ||
6145f4a2713aSLionel Sambuc Bitfield->getBitWidth()->isTypeDependent() ||
6146f4a2713aSLionel Sambuc Init->isValueDependent() ||
6147f4a2713aSLionel Sambuc Init->isTypeDependent())
6148f4a2713aSLionel Sambuc return false;
6149f4a2713aSLionel Sambuc
6150f4a2713aSLionel Sambuc Expr *OriginalInit = Init->IgnoreParenImpCasts();
6151f4a2713aSLionel Sambuc
6152f4a2713aSLionel Sambuc llvm::APSInt Value;
6153f4a2713aSLionel Sambuc if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
6154f4a2713aSLionel Sambuc return false;
6155f4a2713aSLionel Sambuc
6156f4a2713aSLionel Sambuc unsigned OriginalWidth = Value.getBitWidth();
6157f4a2713aSLionel Sambuc unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
6158f4a2713aSLionel Sambuc
6159f4a2713aSLionel Sambuc if (OriginalWidth <= FieldWidth)
6160f4a2713aSLionel Sambuc return false;
6161f4a2713aSLionel Sambuc
6162f4a2713aSLionel Sambuc // Compute the value which the bitfield will contain.
6163f4a2713aSLionel Sambuc llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
6164f4a2713aSLionel Sambuc TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
6165f4a2713aSLionel Sambuc
6166f4a2713aSLionel Sambuc // Check whether the stored value is equal to the original value.
6167f4a2713aSLionel Sambuc TruncatedValue = TruncatedValue.extend(OriginalWidth);
6168f4a2713aSLionel Sambuc if (llvm::APSInt::isSameValue(Value, TruncatedValue))
6169f4a2713aSLionel Sambuc return false;
6170f4a2713aSLionel Sambuc
6171f4a2713aSLionel Sambuc // Special-case bitfields of width 1: booleans are naturally 0/1, and
6172f4a2713aSLionel Sambuc // therefore don't strictly fit into a signed bitfield of width 1.
6173f4a2713aSLionel Sambuc if (FieldWidth == 1 && Value == 1)
6174f4a2713aSLionel Sambuc return false;
6175f4a2713aSLionel Sambuc
6176f4a2713aSLionel Sambuc std::string PrettyValue = Value.toString(10);
6177f4a2713aSLionel Sambuc std::string PrettyTrunc = TruncatedValue.toString(10);
6178f4a2713aSLionel Sambuc
6179f4a2713aSLionel Sambuc S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6180f4a2713aSLionel Sambuc << PrettyValue << PrettyTrunc << OriginalInit->getType()
6181f4a2713aSLionel Sambuc << Init->getSourceRange();
6182f4a2713aSLionel Sambuc
6183f4a2713aSLionel Sambuc return true;
6184f4a2713aSLionel Sambuc }
6185f4a2713aSLionel Sambuc
6186f4a2713aSLionel Sambuc /// Analyze the given simple or compound assignment for warning-worthy
6187f4a2713aSLionel Sambuc /// operations.
AnalyzeAssignment(Sema & S,BinaryOperator * E)6188f4a2713aSLionel Sambuc static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
6189f4a2713aSLionel Sambuc // Just recurse on the LHS.
6190f4a2713aSLionel Sambuc AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6191f4a2713aSLionel Sambuc
6192f4a2713aSLionel Sambuc // We want to recurse on the RHS as normal unless we're assigning to
6193f4a2713aSLionel Sambuc // a bitfield.
6194f4a2713aSLionel Sambuc if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
6195f4a2713aSLionel Sambuc if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
6196f4a2713aSLionel Sambuc E->getOperatorLoc())) {
6197f4a2713aSLionel Sambuc // Recurse, ignoring any implicit conversions on the RHS.
6198f4a2713aSLionel Sambuc return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6199f4a2713aSLionel Sambuc E->getOperatorLoc());
6200f4a2713aSLionel Sambuc }
6201f4a2713aSLionel Sambuc }
6202f4a2713aSLionel Sambuc
6203f4a2713aSLionel Sambuc AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6204f4a2713aSLionel Sambuc }
6205f4a2713aSLionel Sambuc
6206f4a2713aSLionel Sambuc /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
DiagnoseImpCast(Sema & S,Expr * E,QualType SourceType,QualType T,SourceLocation CContext,unsigned diag,bool pruneControlFlow=false)6207f4a2713aSLionel Sambuc static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
6208f4a2713aSLionel Sambuc SourceLocation CContext, unsigned diag,
6209f4a2713aSLionel Sambuc bool pruneControlFlow = false) {
6210f4a2713aSLionel Sambuc if (pruneControlFlow) {
6211f4a2713aSLionel Sambuc S.DiagRuntimeBehavior(E->getExprLoc(), E,
6212f4a2713aSLionel Sambuc S.PDiag(diag)
6213f4a2713aSLionel Sambuc << SourceType << T << E->getSourceRange()
6214f4a2713aSLionel Sambuc << SourceRange(CContext));
6215f4a2713aSLionel Sambuc return;
6216f4a2713aSLionel Sambuc }
6217f4a2713aSLionel Sambuc S.Diag(E->getExprLoc(), diag)
6218f4a2713aSLionel Sambuc << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6219f4a2713aSLionel Sambuc }
6220f4a2713aSLionel Sambuc
6221f4a2713aSLionel Sambuc /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
DiagnoseImpCast(Sema & S,Expr * E,QualType T,SourceLocation CContext,unsigned diag,bool pruneControlFlow=false)6222f4a2713aSLionel Sambuc static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
6223f4a2713aSLionel Sambuc SourceLocation CContext, unsigned diag,
6224f4a2713aSLionel Sambuc bool pruneControlFlow = false) {
6225f4a2713aSLionel Sambuc DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
6226f4a2713aSLionel Sambuc }
6227f4a2713aSLionel Sambuc
6228f4a2713aSLionel Sambuc /// Diagnose an implicit cast from a literal expression. Does not warn when the
6229f4a2713aSLionel Sambuc /// cast wouldn't lose information.
DiagnoseFloatingLiteralImpCast(Sema & S,FloatingLiteral * FL,QualType T,SourceLocation CContext)6230f4a2713aSLionel Sambuc void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6231f4a2713aSLionel Sambuc SourceLocation CContext) {
6232f4a2713aSLionel Sambuc // Try to convert the literal exactly to an integer. If we can, don't warn.
6233f4a2713aSLionel Sambuc bool isExact = false;
6234f4a2713aSLionel Sambuc const llvm::APFloat &Value = FL->getValue();
6235f4a2713aSLionel Sambuc llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6236f4a2713aSLionel Sambuc T->hasUnsignedIntegerRepresentation());
6237f4a2713aSLionel Sambuc if (Value.convertToInteger(IntegerValue,
6238f4a2713aSLionel Sambuc llvm::APFloat::rmTowardZero, &isExact)
6239f4a2713aSLionel Sambuc == llvm::APFloat::opOK && isExact)
6240f4a2713aSLionel Sambuc return;
6241f4a2713aSLionel Sambuc
6242f4a2713aSLionel Sambuc // FIXME: Force the precision of the source value down so we don't print
6243f4a2713aSLionel Sambuc // digits which are usually useless (we don't really care here if we
6244f4a2713aSLionel Sambuc // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6245f4a2713aSLionel Sambuc // would automatically print the shortest representation, but it's a bit
6246f4a2713aSLionel Sambuc // tricky to implement.
6247f4a2713aSLionel Sambuc SmallString<16> PrettySourceValue;
6248f4a2713aSLionel Sambuc unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6249f4a2713aSLionel Sambuc precision = (precision * 59 + 195) / 196;
6250f4a2713aSLionel Sambuc Value.toString(PrettySourceValue, precision);
6251f4a2713aSLionel Sambuc
6252f4a2713aSLionel Sambuc SmallString<16> PrettyTargetValue;
6253f4a2713aSLionel Sambuc if (T->isSpecificBuiltinType(BuiltinType::Bool))
6254f4a2713aSLionel Sambuc PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6255f4a2713aSLionel Sambuc else
6256f4a2713aSLionel Sambuc IntegerValue.toString(PrettyTargetValue);
6257f4a2713aSLionel Sambuc
6258f4a2713aSLionel Sambuc S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
6259f4a2713aSLionel Sambuc << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6260f4a2713aSLionel Sambuc << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
6261f4a2713aSLionel Sambuc }
6262f4a2713aSLionel Sambuc
PrettyPrintInRange(const llvm::APSInt & Value,IntRange Range)6263f4a2713aSLionel Sambuc std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6264f4a2713aSLionel Sambuc if (!Range.Width) return "0";
6265f4a2713aSLionel Sambuc
6266f4a2713aSLionel Sambuc llvm::APSInt ValueInRange = Value;
6267f4a2713aSLionel Sambuc ValueInRange.setIsSigned(!Range.NonNegative);
6268f4a2713aSLionel Sambuc ValueInRange = ValueInRange.trunc(Range.Width);
6269f4a2713aSLionel Sambuc return ValueInRange.toString(10);
6270f4a2713aSLionel Sambuc }
6271f4a2713aSLionel Sambuc
IsImplicitBoolFloatConversion(Sema & S,Expr * Ex,bool ToBool)6272f4a2713aSLionel Sambuc static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6273f4a2713aSLionel Sambuc if (!isa<ImplicitCastExpr>(Ex))
6274f4a2713aSLionel Sambuc return false;
6275f4a2713aSLionel Sambuc
6276f4a2713aSLionel Sambuc Expr *InnerE = Ex->IgnoreParenImpCasts();
6277f4a2713aSLionel Sambuc const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6278f4a2713aSLionel Sambuc const Type *Source =
6279f4a2713aSLionel Sambuc S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6280f4a2713aSLionel Sambuc if (Target->isDependentType())
6281f4a2713aSLionel Sambuc return false;
6282f4a2713aSLionel Sambuc
6283f4a2713aSLionel Sambuc const BuiltinType *FloatCandidateBT =
6284f4a2713aSLionel Sambuc dyn_cast<BuiltinType>(ToBool ? Source : Target);
6285f4a2713aSLionel Sambuc const Type *BoolCandidateType = ToBool ? Target : Source;
6286f4a2713aSLionel Sambuc
6287f4a2713aSLionel Sambuc return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6288f4a2713aSLionel Sambuc FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6289f4a2713aSLionel Sambuc }
6290f4a2713aSLionel Sambuc
CheckImplicitArgumentConversions(Sema & S,CallExpr * TheCall,SourceLocation CC)6291f4a2713aSLionel Sambuc void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6292f4a2713aSLionel Sambuc SourceLocation CC) {
6293f4a2713aSLionel Sambuc unsigned NumArgs = TheCall->getNumArgs();
6294f4a2713aSLionel Sambuc for (unsigned i = 0; i < NumArgs; ++i) {
6295f4a2713aSLionel Sambuc Expr *CurrA = TheCall->getArg(i);
6296f4a2713aSLionel Sambuc if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6297f4a2713aSLionel Sambuc continue;
6298f4a2713aSLionel Sambuc
6299f4a2713aSLionel Sambuc bool IsSwapped = ((i > 0) &&
6300f4a2713aSLionel Sambuc IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6301f4a2713aSLionel Sambuc IsSwapped |= ((i < (NumArgs - 1)) &&
6302f4a2713aSLionel Sambuc IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6303f4a2713aSLionel Sambuc if (IsSwapped) {
6304f4a2713aSLionel Sambuc // Warn on this floating-point to bool conversion.
6305f4a2713aSLionel Sambuc DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6306f4a2713aSLionel Sambuc CurrA->getType(), CC,
6307f4a2713aSLionel Sambuc diag::warn_impcast_floating_point_to_bool);
6308f4a2713aSLionel Sambuc }
6309f4a2713aSLionel Sambuc }
6310f4a2713aSLionel Sambuc }
6311f4a2713aSLionel Sambuc
DiagnoseNullConversion(Sema & S,Expr * E,QualType T,SourceLocation CC)6312*0a6a1f1dSLionel Sambuc static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6313*0a6a1f1dSLionel Sambuc SourceLocation CC) {
6314*0a6a1f1dSLionel Sambuc if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6315*0a6a1f1dSLionel Sambuc E->getExprLoc()))
6316*0a6a1f1dSLionel Sambuc return;
6317*0a6a1f1dSLionel Sambuc
6318*0a6a1f1dSLionel Sambuc // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6319*0a6a1f1dSLionel Sambuc const Expr::NullPointerConstantKind NullKind =
6320*0a6a1f1dSLionel Sambuc E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6321*0a6a1f1dSLionel Sambuc if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6322*0a6a1f1dSLionel Sambuc return;
6323*0a6a1f1dSLionel Sambuc
6324*0a6a1f1dSLionel Sambuc // Return if target type is a safe conversion.
6325*0a6a1f1dSLionel Sambuc if (T->isAnyPointerType() || T->isBlockPointerType() ||
6326*0a6a1f1dSLionel Sambuc T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6327*0a6a1f1dSLionel Sambuc return;
6328*0a6a1f1dSLionel Sambuc
6329*0a6a1f1dSLionel Sambuc SourceLocation Loc = E->getSourceRange().getBegin();
6330*0a6a1f1dSLionel Sambuc
6331*0a6a1f1dSLionel Sambuc // __null is usually wrapped in a macro. Go up a macro if that is the case.
6332*0a6a1f1dSLionel Sambuc if (NullKind == Expr::NPCK_GNUNull) {
6333*0a6a1f1dSLionel Sambuc if (Loc.isMacroID())
6334*0a6a1f1dSLionel Sambuc Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6335*0a6a1f1dSLionel Sambuc }
6336*0a6a1f1dSLionel Sambuc
6337*0a6a1f1dSLionel Sambuc // Only warn if the null and context location are in the same macro expansion.
6338*0a6a1f1dSLionel Sambuc if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6339*0a6a1f1dSLionel Sambuc return;
6340*0a6a1f1dSLionel Sambuc
6341*0a6a1f1dSLionel Sambuc S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6342*0a6a1f1dSLionel Sambuc << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6343*0a6a1f1dSLionel Sambuc << FixItHint::CreateReplacement(Loc,
6344*0a6a1f1dSLionel Sambuc S.getFixItZeroLiteralForType(T, Loc));
6345*0a6a1f1dSLionel Sambuc }
6346*0a6a1f1dSLionel Sambuc
CheckImplicitConversion(Sema & S,Expr * E,QualType T,SourceLocation CC,bool * ICContext=nullptr)6347f4a2713aSLionel Sambuc void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
6348*0a6a1f1dSLionel Sambuc SourceLocation CC, bool *ICContext = nullptr) {
6349f4a2713aSLionel Sambuc if (E->isTypeDependent() || E->isValueDependent()) return;
6350f4a2713aSLionel Sambuc
6351f4a2713aSLionel Sambuc const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6352f4a2713aSLionel Sambuc const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6353f4a2713aSLionel Sambuc if (Source == Target) return;
6354f4a2713aSLionel Sambuc if (Target->isDependentType()) return;
6355f4a2713aSLionel Sambuc
6356f4a2713aSLionel Sambuc // If the conversion context location is invalid don't complain. We also
6357f4a2713aSLionel Sambuc // don't want to emit a warning if the issue occurs from the expansion of
6358f4a2713aSLionel Sambuc // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6359f4a2713aSLionel Sambuc // delay this check as long as possible. Once we detect we are in that
6360f4a2713aSLionel Sambuc // scenario, we just return.
6361f4a2713aSLionel Sambuc if (CC.isInvalid())
6362f4a2713aSLionel Sambuc return;
6363f4a2713aSLionel Sambuc
6364f4a2713aSLionel Sambuc // Diagnose implicit casts to bool.
6365f4a2713aSLionel Sambuc if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6366f4a2713aSLionel Sambuc if (isa<StringLiteral>(E))
6367f4a2713aSLionel Sambuc // Warn on string literal to bool. Checks for string literals in logical
6368*0a6a1f1dSLionel Sambuc // and expressions, for instance, assert(0 && "error here"), are
6369*0a6a1f1dSLionel Sambuc // prevented by a check in AnalyzeImplicitConversions().
6370f4a2713aSLionel Sambuc return DiagnoseImpCast(S, E, T, CC,
6371f4a2713aSLionel Sambuc diag::warn_impcast_string_literal_to_bool);
6372*0a6a1f1dSLionel Sambuc if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6373*0a6a1f1dSLionel Sambuc isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6374*0a6a1f1dSLionel Sambuc // This covers the literal expressions that evaluate to Objective-C
6375*0a6a1f1dSLionel Sambuc // objects.
6376*0a6a1f1dSLionel Sambuc return DiagnoseImpCast(S, E, T, CC,
6377*0a6a1f1dSLionel Sambuc diag::warn_impcast_objective_c_literal_to_bool);
6378f4a2713aSLionel Sambuc }
6379*0a6a1f1dSLionel Sambuc if (Source->isPointerType() || Source->canDecayToPointerType()) {
6380*0a6a1f1dSLionel Sambuc // Warn on pointer to bool conversion that is always true.
6381*0a6a1f1dSLionel Sambuc S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6382*0a6a1f1dSLionel Sambuc SourceRange(CC));
6383f4a2713aSLionel Sambuc }
6384f4a2713aSLionel Sambuc }
6385f4a2713aSLionel Sambuc
6386f4a2713aSLionel Sambuc // Strip vector types.
6387f4a2713aSLionel Sambuc if (isa<VectorType>(Source)) {
6388f4a2713aSLionel Sambuc if (!isa<VectorType>(Target)) {
6389f4a2713aSLionel Sambuc if (S.SourceMgr.isInSystemMacro(CC))
6390f4a2713aSLionel Sambuc return;
6391f4a2713aSLionel Sambuc return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
6392f4a2713aSLionel Sambuc }
6393f4a2713aSLionel Sambuc
6394f4a2713aSLionel Sambuc // If the vector cast is cast between two vectors of the same size, it is
6395f4a2713aSLionel Sambuc // a bitcast, not a conversion.
6396f4a2713aSLionel Sambuc if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6397f4a2713aSLionel Sambuc return;
6398f4a2713aSLionel Sambuc
6399f4a2713aSLionel Sambuc Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6400f4a2713aSLionel Sambuc Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6401f4a2713aSLionel Sambuc }
6402*0a6a1f1dSLionel Sambuc if (auto VecTy = dyn_cast<VectorType>(Target))
6403*0a6a1f1dSLionel Sambuc Target = VecTy->getElementType().getTypePtr();
6404f4a2713aSLionel Sambuc
6405f4a2713aSLionel Sambuc // Strip complex types.
6406f4a2713aSLionel Sambuc if (isa<ComplexType>(Source)) {
6407f4a2713aSLionel Sambuc if (!isa<ComplexType>(Target)) {
6408f4a2713aSLionel Sambuc if (S.SourceMgr.isInSystemMacro(CC))
6409f4a2713aSLionel Sambuc return;
6410f4a2713aSLionel Sambuc
6411f4a2713aSLionel Sambuc return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
6412f4a2713aSLionel Sambuc }
6413f4a2713aSLionel Sambuc
6414f4a2713aSLionel Sambuc Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6415f4a2713aSLionel Sambuc Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6416f4a2713aSLionel Sambuc }
6417f4a2713aSLionel Sambuc
6418f4a2713aSLionel Sambuc const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6419f4a2713aSLionel Sambuc const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6420f4a2713aSLionel Sambuc
6421f4a2713aSLionel Sambuc // If the source is floating point...
6422f4a2713aSLionel Sambuc if (SourceBT && SourceBT->isFloatingPoint()) {
6423f4a2713aSLionel Sambuc // ...and the target is floating point...
6424f4a2713aSLionel Sambuc if (TargetBT && TargetBT->isFloatingPoint()) {
6425f4a2713aSLionel Sambuc // ...then warn if we're dropping FP rank.
6426f4a2713aSLionel Sambuc
6427f4a2713aSLionel Sambuc // Builtin FP kinds are ordered by increasing FP rank.
6428f4a2713aSLionel Sambuc if (SourceBT->getKind() > TargetBT->getKind()) {
6429f4a2713aSLionel Sambuc // Don't warn about float constants that are precisely
6430f4a2713aSLionel Sambuc // representable in the target type.
6431f4a2713aSLionel Sambuc Expr::EvalResult result;
6432f4a2713aSLionel Sambuc if (E->EvaluateAsRValue(result, S.Context)) {
6433f4a2713aSLionel Sambuc // Value might be a float, a float vector, or a float complex.
6434f4a2713aSLionel Sambuc if (IsSameFloatAfterCast(result.Val,
6435f4a2713aSLionel Sambuc S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6436f4a2713aSLionel Sambuc S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
6437f4a2713aSLionel Sambuc return;
6438f4a2713aSLionel Sambuc }
6439f4a2713aSLionel Sambuc
6440f4a2713aSLionel Sambuc if (S.SourceMgr.isInSystemMacro(CC))
6441f4a2713aSLionel Sambuc return;
6442f4a2713aSLionel Sambuc
6443f4a2713aSLionel Sambuc DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
6444f4a2713aSLionel Sambuc }
6445f4a2713aSLionel Sambuc return;
6446f4a2713aSLionel Sambuc }
6447f4a2713aSLionel Sambuc
6448f4a2713aSLionel Sambuc // If the target is integral, always warn.
6449f4a2713aSLionel Sambuc if (TargetBT && TargetBT->isInteger()) {
6450f4a2713aSLionel Sambuc if (S.SourceMgr.isInSystemMacro(CC))
6451f4a2713aSLionel Sambuc return;
6452f4a2713aSLionel Sambuc
6453f4a2713aSLionel Sambuc Expr *InnerE = E->IgnoreParenImpCasts();
6454f4a2713aSLionel Sambuc // We also want to warn on, e.g., "int i = -1.234"
6455f4a2713aSLionel Sambuc if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6456f4a2713aSLionel Sambuc if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6457f4a2713aSLionel Sambuc InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6458f4a2713aSLionel Sambuc
6459f4a2713aSLionel Sambuc if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6460f4a2713aSLionel Sambuc DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
6461f4a2713aSLionel Sambuc } else {
6462f4a2713aSLionel Sambuc DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6463f4a2713aSLionel Sambuc }
6464f4a2713aSLionel Sambuc }
6465f4a2713aSLionel Sambuc
6466f4a2713aSLionel Sambuc // If the target is bool, warn if expr is a function or method call.
6467f4a2713aSLionel Sambuc if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6468f4a2713aSLionel Sambuc isa<CallExpr>(E)) {
6469f4a2713aSLionel Sambuc // Check last argument of function call to see if it is an
6470f4a2713aSLionel Sambuc // implicit cast from a type matching the type the result
6471f4a2713aSLionel Sambuc // is being cast to.
6472f4a2713aSLionel Sambuc CallExpr *CEx = cast<CallExpr>(E);
6473f4a2713aSLionel Sambuc unsigned NumArgs = CEx->getNumArgs();
6474f4a2713aSLionel Sambuc if (NumArgs > 0) {
6475f4a2713aSLionel Sambuc Expr *LastA = CEx->getArg(NumArgs - 1);
6476f4a2713aSLionel Sambuc Expr *InnerE = LastA->IgnoreParenImpCasts();
6477f4a2713aSLionel Sambuc const Type *InnerType =
6478f4a2713aSLionel Sambuc S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6479f4a2713aSLionel Sambuc if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6480f4a2713aSLionel Sambuc // Warn on this floating-point to bool conversion
6481f4a2713aSLionel Sambuc DiagnoseImpCast(S, E, T, CC,
6482f4a2713aSLionel Sambuc diag::warn_impcast_floating_point_to_bool);
6483f4a2713aSLionel Sambuc }
6484f4a2713aSLionel Sambuc }
6485f4a2713aSLionel Sambuc }
6486f4a2713aSLionel Sambuc return;
6487f4a2713aSLionel Sambuc }
6488f4a2713aSLionel Sambuc
6489*0a6a1f1dSLionel Sambuc DiagnoseNullConversion(S, E, T, CC);
6490f4a2713aSLionel Sambuc
6491f4a2713aSLionel Sambuc if (!Source->isIntegerType() || !Target->isIntegerType())
6492f4a2713aSLionel Sambuc return;
6493f4a2713aSLionel Sambuc
6494f4a2713aSLionel Sambuc // TODO: remove this early return once the false positives for constant->bool
6495f4a2713aSLionel Sambuc // in templates, macros, etc, are reduced or removed.
6496f4a2713aSLionel Sambuc if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6497f4a2713aSLionel Sambuc return;
6498f4a2713aSLionel Sambuc
6499f4a2713aSLionel Sambuc IntRange SourceRange = GetExprRange(S.Context, E);
6500f4a2713aSLionel Sambuc IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
6501f4a2713aSLionel Sambuc
6502f4a2713aSLionel Sambuc if (SourceRange.Width > TargetRange.Width) {
6503f4a2713aSLionel Sambuc // If the source is a constant, use a default-on diagnostic.
6504f4a2713aSLionel Sambuc // TODO: this should happen for bitfield stores, too.
6505f4a2713aSLionel Sambuc llvm::APSInt Value(32);
6506f4a2713aSLionel Sambuc if (E->isIntegerConstantExpr(Value, S.Context)) {
6507f4a2713aSLionel Sambuc if (S.SourceMgr.isInSystemMacro(CC))
6508f4a2713aSLionel Sambuc return;
6509f4a2713aSLionel Sambuc
6510f4a2713aSLionel Sambuc std::string PrettySourceValue = Value.toString(10);
6511f4a2713aSLionel Sambuc std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
6512f4a2713aSLionel Sambuc
6513f4a2713aSLionel Sambuc S.DiagRuntimeBehavior(E->getExprLoc(), E,
6514f4a2713aSLionel Sambuc S.PDiag(diag::warn_impcast_integer_precision_constant)
6515f4a2713aSLionel Sambuc << PrettySourceValue << PrettyTargetValue
6516f4a2713aSLionel Sambuc << E->getType() << T << E->getSourceRange()
6517f4a2713aSLionel Sambuc << clang::SourceRange(CC));
6518f4a2713aSLionel Sambuc return;
6519f4a2713aSLionel Sambuc }
6520f4a2713aSLionel Sambuc
6521f4a2713aSLionel Sambuc // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6522f4a2713aSLionel Sambuc if (S.SourceMgr.isInSystemMacro(CC))
6523f4a2713aSLionel Sambuc return;
6524f4a2713aSLionel Sambuc
6525f4a2713aSLionel Sambuc if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
6526f4a2713aSLionel Sambuc return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6527f4a2713aSLionel Sambuc /* pruneControlFlow */ true);
6528f4a2713aSLionel Sambuc return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
6529f4a2713aSLionel Sambuc }
6530f4a2713aSLionel Sambuc
6531f4a2713aSLionel Sambuc if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6532f4a2713aSLionel Sambuc (!TargetRange.NonNegative && SourceRange.NonNegative &&
6533f4a2713aSLionel Sambuc SourceRange.Width == TargetRange.Width)) {
6534f4a2713aSLionel Sambuc
6535f4a2713aSLionel Sambuc if (S.SourceMgr.isInSystemMacro(CC))
6536f4a2713aSLionel Sambuc return;
6537f4a2713aSLionel Sambuc
6538f4a2713aSLionel Sambuc unsigned DiagID = diag::warn_impcast_integer_sign;
6539f4a2713aSLionel Sambuc
6540f4a2713aSLionel Sambuc // Traditionally, gcc has warned about this under -Wsign-compare.
6541f4a2713aSLionel Sambuc // We also want to warn about it in -Wconversion.
6542f4a2713aSLionel Sambuc // So if -Wconversion is off, use a completely identical diagnostic
6543f4a2713aSLionel Sambuc // in the sign-compare group.
6544f4a2713aSLionel Sambuc // The conditional-checking code will
6545f4a2713aSLionel Sambuc if (ICContext) {
6546f4a2713aSLionel Sambuc DiagID = diag::warn_impcast_integer_sign_conditional;
6547f4a2713aSLionel Sambuc *ICContext = true;
6548f4a2713aSLionel Sambuc }
6549f4a2713aSLionel Sambuc
6550f4a2713aSLionel Sambuc return DiagnoseImpCast(S, E, T, CC, DiagID);
6551f4a2713aSLionel Sambuc }
6552f4a2713aSLionel Sambuc
6553f4a2713aSLionel Sambuc // Diagnose conversions between different enumeration types.
6554f4a2713aSLionel Sambuc // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6555f4a2713aSLionel Sambuc // type, to give us better diagnostics.
6556f4a2713aSLionel Sambuc QualType SourceType = E->getType();
6557f4a2713aSLionel Sambuc if (!S.getLangOpts().CPlusPlus) {
6558f4a2713aSLionel Sambuc if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6559f4a2713aSLionel Sambuc if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6560f4a2713aSLionel Sambuc EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6561f4a2713aSLionel Sambuc SourceType = S.Context.getTypeDeclType(Enum);
6562f4a2713aSLionel Sambuc Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6563f4a2713aSLionel Sambuc }
6564f4a2713aSLionel Sambuc }
6565f4a2713aSLionel Sambuc
6566f4a2713aSLionel Sambuc if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6567f4a2713aSLionel Sambuc if (const EnumType *TargetEnum = Target->getAs<EnumType>())
6568f4a2713aSLionel Sambuc if (SourceEnum->getDecl()->hasNameForLinkage() &&
6569f4a2713aSLionel Sambuc TargetEnum->getDecl()->hasNameForLinkage() &&
6570f4a2713aSLionel Sambuc SourceEnum != TargetEnum) {
6571f4a2713aSLionel Sambuc if (S.SourceMgr.isInSystemMacro(CC))
6572f4a2713aSLionel Sambuc return;
6573f4a2713aSLionel Sambuc
6574f4a2713aSLionel Sambuc return DiagnoseImpCast(S, E, SourceType, T, CC,
6575f4a2713aSLionel Sambuc diag::warn_impcast_different_enum_types);
6576f4a2713aSLionel Sambuc }
6577f4a2713aSLionel Sambuc
6578f4a2713aSLionel Sambuc return;
6579f4a2713aSLionel Sambuc }
6580f4a2713aSLionel Sambuc
6581f4a2713aSLionel Sambuc void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6582f4a2713aSLionel Sambuc SourceLocation CC, QualType T);
6583f4a2713aSLionel Sambuc
CheckConditionalOperand(Sema & S,Expr * E,QualType T,SourceLocation CC,bool & ICContext)6584f4a2713aSLionel Sambuc void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
6585f4a2713aSLionel Sambuc SourceLocation CC, bool &ICContext) {
6586f4a2713aSLionel Sambuc E = E->IgnoreParenImpCasts();
6587f4a2713aSLionel Sambuc
6588f4a2713aSLionel Sambuc if (isa<ConditionalOperator>(E))
6589f4a2713aSLionel Sambuc return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
6590f4a2713aSLionel Sambuc
6591f4a2713aSLionel Sambuc AnalyzeImplicitConversions(S, E, CC);
6592f4a2713aSLionel Sambuc if (E->getType() != T)
6593f4a2713aSLionel Sambuc return CheckImplicitConversion(S, E, T, CC, &ICContext);
6594f4a2713aSLionel Sambuc return;
6595f4a2713aSLionel Sambuc }
6596f4a2713aSLionel Sambuc
CheckConditionalOperator(Sema & S,ConditionalOperator * E,SourceLocation CC,QualType T)6597f4a2713aSLionel Sambuc void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6598f4a2713aSLionel Sambuc SourceLocation CC, QualType T) {
6599*0a6a1f1dSLionel Sambuc AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
6600f4a2713aSLionel Sambuc
6601f4a2713aSLionel Sambuc bool Suspicious = false;
6602f4a2713aSLionel Sambuc CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6603f4a2713aSLionel Sambuc CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
6604f4a2713aSLionel Sambuc
6605f4a2713aSLionel Sambuc // If -Wconversion would have warned about either of the candidates
6606f4a2713aSLionel Sambuc // for a signedness conversion to the context type...
6607f4a2713aSLionel Sambuc if (!Suspicious) return;
6608f4a2713aSLionel Sambuc
6609f4a2713aSLionel Sambuc // ...but it's currently ignored...
6610*0a6a1f1dSLionel Sambuc if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
6611f4a2713aSLionel Sambuc return;
6612f4a2713aSLionel Sambuc
6613f4a2713aSLionel Sambuc // ...then check whether it would have warned about either of the
6614f4a2713aSLionel Sambuc // candidates for a signedness conversion to the condition type.
6615f4a2713aSLionel Sambuc if (E->getType() == T) return;
6616f4a2713aSLionel Sambuc
6617f4a2713aSLionel Sambuc Suspicious = false;
6618f4a2713aSLionel Sambuc CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6619f4a2713aSLionel Sambuc E->getType(), CC, &Suspicious);
6620f4a2713aSLionel Sambuc if (!Suspicious)
6621f4a2713aSLionel Sambuc CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
6622f4a2713aSLionel Sambuc E->getType(), CC, &Suspicious);
6623f4a2713aSLionel Sambuc }
6624f4a2713aSLionel Sambuc
6625*0a6a1f1dSLionel Sambuc /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6626*0a6a1f1dSLionel Sambuc /// Input argument E is a logical expression.
CheckBoolLikeConversion(Sema & S,Expr * E,SourceLocation CC)6627*0a6a1f1dSLionel Sambuc static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6628*0a6a1f1dSLionel Sambuc if (S.getLangOpts().Bool)
6629*0a6a1f1dSLionel Sambuc return;
6630*0a6a1f1dSLionel Sambuc CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6631*0a6a1f1dSLionel Sambuc }
6632*0a6a1f1dSLionel Sambuc
6633f4a2713aSLionel Sambuc /// AnalyzeImplicitConversions - Find and report any interesting
6634f4a2713aSLionel Sambuc /// implicit conversions in the given expression. There are a couple
6635f4a2713aSLionel Sambuc /// of competing diagnostics here, -Wconversion and -Wsign-compare.
AnalyzeImplicitConversions(Sema & S,Expr * OrigE,SourceLocation CC)6636f4a2713aSLionel Sambuc void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
6637f4a2713aSLionel Sambuc QualType T = OrigE->getType();
6638f4a2713aSLionel Sambuc Expr *E = OrigE->IgnoreParenImpCasts();
6639f4a2713aSLionel Sambuc
6640f4a2713aSLionel Sambuc if (E->isTypeDependent() || E->isValueDependent())
6641f4a2713aSLionel Sambuc return;
6642f4a2713aSLionel Sambuc
6643f4a2713aSLionel Sambuc // For conditional operators, we analyze the arguments as if they
6644f4a2713aSLionel Sambuc // were being fed directly into the output.
6645f4a2713aSLionel Sambuc if (isa<ConditionalOperator>(E)) {
6646f4a2713aSLionel Sambuc ConditionalOperator *CO = cast<ConditionalOperator>(E);
6647f4a2713aSLionel Sambuc CheckConditionalOperator(S, CO, CC, T);
6648f4a2713aSLionel Sambuc return;
6649f4a2713aSLionel Sambuc }
6650f4a2713aSLionel Sambuc
6651f4a2713aSLionel Sambuc // Check implicit argument conversions for function calls.
6652f4a2713aSLionel Sambuc if (CallExpr *Call = dyn_cast<CallExpr>(E))
6653f4a2713aSLionel Sambuc CheckImplicitArgumentConversions(S, Call, CC);
6654f4a2713aSLionel Sambuc
6655f4a2713aSLionel Sambuc // Go ahead and check any implicit conversions we might have skipped.
6656f4a2713aSLionel Sambuc // The non-canonical typecheck is just an optimization;
6657f4a2713aSLionel Sambuc // CheckImplicitConversion will filter out dead implicit conversions.
6658f4a2713aSLionel Sambuc if (E->getType() != T)
6659f4a2713aSLionel Sambuc CheckImplicitConversion(S, E, T, CC);
6660f4a2713aSLionel Sambuc
6661f4a2713aSLionel Sambuc // Now continue drilling into this expression.
6662f4a2713aSLionel Sambuc
6663f4a2713aSLionel Sambuc if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
6664f4a2713aSLionel Sambuc if (POE->getResultExpr())
6665f4a2713aSLionel Sambuc E = POE->getResultExpr();
6666f4a2713aSLionel Sambuc }
6667f4a2713aSLionel Sambuc
6668f4a2713aSLionel Sambuc if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6669f4a2713aSLionel Sambuc return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6670f4a2713aSLionel Sambuc
6671f4a2713aSLionel Sambuc // Skip past explicit casts.
6672f4a2713aSLionel Sambuc if (isa<ExplicitCastExpr>(E)) {
6673f4a2713aSLionel Sambuc E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
6674f4a2713aSLionel Sambuc return AnalyzeImplicitConversions(S, E, CC);
6675f4a2713aSLionel Sambuc }
6676f4a2713aSLionel Sambuc
6677f4a2713aSLionel Sambuc if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6678f4a2713aSLionel Sambuc // Do a somewhat different check with comparison operators.
6679f4a2713aSLionel Sambuc if (BO->isComparisonOp())
6680f4a2713aSLionel Sambuc return AnalyzeComparison(S, BO);
6681f4a2713aSLionel Sambuc
6682f4a2713aSLionel Sambuc // And with simple assignments.
6683f4a2713aSLionel Sambuc if (BO->getOpcode() == BO_Assign)
6684f4a2713aSLionel Sambuc return AnalyzeAssignment(S, BO);
6685f4a2713aSLionel Sambuc }
6686f4a2713aSLionel Sambuc
6687f4a2713aSLionel Sambuc // These break the otherwise-useful invariant below. Fortunately,
6688f4a2713aSLionel Sambuc // we don't really need to recurse into them, because any internal
6689f4a2713aSLionel Sambuc // expressions should have been analyzed already when they were
6690f4a2713aSLionel Sambuc // built into statements.
6691f4a2713aSLionel Sambuc if (isa<StmtExpr>(E)) return;
6692f4a2713aSLionel Sambuc
6693f4a2713aSLionel Sambuc // Don't descend into unevaluated contexts.
6694f4a2713aSLionel Sambuc if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
6695f4a2713aSLionel Sambuc
6696f4a2713aSLionel Sambuc // Now just recurse over the expression's children.
6697f4a2713aSLionel Sambuc CC = E->getExprLoc();
6698f4a2713aSLionel Sambuc BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
6699*0a6a1f1dSLionel Sambuc bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
6700f4a2713aSLionel Sambuc for (Stmt::child_range I = E->children(); I; ++I) {
6701f4a2713aSLionel Sambuc Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
6702f4a2713aSLionel Sambuc if (!ChildExpr)
6703f4a2713aSLionel Sambuc continue;
6704f4a2713aSLionel Sambuc
6705*0a6a1f1dSLionel Sambuc if (IsLogicalAndOperator &&
6706f4a2713aSLionel Sambuc isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
6707*0a6a1f1dSLionel Sambuc // Ignore checking string literals that are in logical and operators.
6708*0a6a1f1dSLionel Sambuc // This is a common pattern for asserts.
6709f4a2713aSLionel Sambuc continue;
6710f4a2713aSLionel Sambuc AnalyzeImplicitConversions(S, ChildExpr, CC);
6711f4a2713aSLionel Sambuc }
6712*0a6a1f1dSLionel Sambuc
6713*0a6a1f1dSLionel Sambuc if (BO && BO->isLogicalOp()) {
6714*0a6a1f1dSLionel Sambuc Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6715*0a6a1f1dSLionel Sambuc if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6716*0a6a1f1dSLionel Sambuc ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
6717*0a6a1f1dSLionel Sambuc
6718*0a6a1f1dSLionel Sambuc SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6719*0a6a1f1dSLionel Sambuc if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6720*0a6a1f1dSLionel Sambuc ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
6721*0a6a1f1dSLionel Sambuc }
6722*0a6a1f1dSLionel Sambuc
6723*0a6a1f1dSLionel Sambuc if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6724*0a6a1f1dSLionel Sambuc if (U->getOpcode() == UO_LNot)
6725*0a6a1f1dSLionel Sambuc ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
6726f4a2713aSLionel Sambuc }
6727f4a2713aSLionel Sambuc
6728f4a2713aSLionel Sambuc } // end anonymous namespace
6729f4a2713aSLionel Sambuc
6730*0a6a1f1dSLionel Sambuc enum {
6731*0a6a1f1dSLionel Sambuc AddressOf,
6732*0a6a1f1dSLionel Sambuc FunctionPointer,
6733*0a6a1f1dSLionel Sambuc ArrayPointer
6734*0a6a1f1dSLionel Sambuc };
6735*0a6a1f1dSLionel Sambuc
6736*0a6a1f1dSLionel Sambuc // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6737*0a6a1f1dSLionel Sambuc // Returns true when emitting a warning about taking the address of a reference.
CheckForReference(Sema & SemaRef,const Expr * E,PartialDiagnostic PD)6738*0a6a1f1dSLionel Sambuc static bool CheckForReference(Sema &SemaRef, const Expr *E,
6739*0a6a1f1dSLionel Sambuc PartialDiagnostic PD) {
6740*0a6a1f1dSLionel Sambuc E = E->IgnoreParenImpCasts();
6741*0a6a1f1dSLionel Sambuc
6742*0a6a1f1dSLionel Sambuc const FunctionDecl *FD = nullptr;
6743*0a6a1f1dSLionel Sambuc
6744*0a6a1f1dSLionel Sambuc if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6745*0a6a1f1dSLionel Sambuc if (!DRE->getDecl()->getType()->isReferenceType())
6746*0a6a1f1dSLionel Sambuc return false;
6747*0a6a1f1dSLionel Sambuc } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6748*0a6a1f1dSLionel Sambuc if (!M->getMemberDecl()->getType()->isReferenceType())
6749*0a6a1f1dSLionel Sambuc return false;
6750*0a6a1f1dSLionel Sambuc } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6751*0a6a1f1dSLionel Sambuc if (!Call->getCallReturnType()->isReferenceType())
6752*0a6a1f1dSLionel Sambuc return false;
6753*0a6a1f1dSLionel Sambuc FD = Call->getDirectCallee();
6754*0a6a1f1dSLionel Sambuc } else {
6755*0a6a1f1dSLionel Sambuc return false;
6756*0a6a1f1dSLionel Sambuc }
6757*0a6a1f1dSLionel Sambuc
6758*0a6a1f1dSLionel Sambuc SemaRef.Diag(E->getExprLoc(), PD);
6759*0a6a1f1dSLionel Sambuc
6760*0a6a1f1dSLionel Sambuc // If possible, point to location of function.
6761*0a6a1f1dSLionel Sambuc if (FD) {
6762*0a6a1f1dSLionel Sambuc SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6763*0a6a1f1dSLionel Sambuc }
6764*0a6a1f1dSLionel Sambuc
6765*0a6a1f1dSLionel Sambuc return true;
6766*0a6a1f1dSLionel Sambuc }
6767*0a6a1f1dSLionel Sambuc
6768*0a6a1f1dSLionel Sambuc // Returns true if the SourceLocation is expanded from any macro body.
6769*0a6a1f1dSLionel Sambuc // Returns false if the SourceLocation is invalid, is from not in a macro
6770*0a6a1f1dSLionel Sambuc // expansion, or is from expanded from a top-level macro argument.
IsInAnyMacroBody(const SourceManager & SM,SourceLocation Loc)6771*0a6a1f1dSLionel Sambuc static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6772*0a6a1f1dSLionel Sambuc if (Loc.isInvalid())
6773*0a6a1f1dSLionel Sambuc return false;
6774*0a6a1f1dSLionel Sambuc
6775*0a6a1f1dSLionel Sambuc while (Loc.isMacroID()) {
6776*0a6a1f1dSLionel Sambuc if (SM.isMacroBodyExpansion(Loc))
6777*0a6a1f1dSLionel Sambuc return true;
6778*0a6a1f1dSLionel Sambuc Loc = SM.getImmediateMacroCallerLoc(Loc);
6779*0a6a1f1dSLionel Sambuc }
6780*0a6a1f1dSLionel Sambuc
6781*0a6a1f1dSLionel Sambuc return false;
6782*0a6a1f1dSLionel Sambuc }
6783*0a6a1f1dSLionel Sambuc
6784*0a6a1f1dSLionel Sambuc /// \brief Diagnose pointers that are always non-null.
6785*0a6a1f1dSLionel Sambuc /// \param E the expression containing the pointer
6786*0a6a1f1dSLionel Sambuc /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6787*0a6a1f1dSLionel Sambuc /// compared to a null pointer
6788*0a6a1f1dSLionel Sambuc /// \param IsEqual True when the comparison is equal to a null pointer
6789*0a6a1f1dSLionel Sambuc /// \param Range Extra SourceRange to highlight in the diagnostic
DiagnoseAlwaysNonNullPointer(Expr * E,Expr::NullPointerConstantKind NullKind,bool IsEqual,SourceRange Range)6790*0a6a1f1dSLionel Sambuc void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6791*0a6a1f1dSLionel Sambuc Expr::NullPointerConstantKind NullKind,
6792*0a6a1f1dSLionel Sambuc bool IsEqual, SourceRange Range) {
6793*0a6a1f1dSLionel Sambuc if (!E)
6794*0a6a1f1dSLionel Sambuc return;
6795*0a6a1f1dSLionel Sambuc
6796*0a6a1f1dSLionel Sambuc // Don't warn inside macros.
6797*0a6a1f1dSLionel Sambuc if (E->getExprLoc().isMacroID()) {
6798*0a6a1f1dSLionel Sambuc const SourceManager &SM = getSourceManager();
6799*0a6a1f1dSLionel Sambuc if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6800*0a6a1f1dSLionel Sambuc IsInAnyMacroBody(SM, Range.getBegin()))
6801*0a6a1f1dSLionel Sambuc return;
6802*0a6a1f1dSLionel Sambuc }
6803*0a6a1f1dSLionel Sambuc E = E->IgnoreImpCasts();
6804*0a6a1f1dSLionel Sambuc
6805*0a6a1f1dSLionel Sambuc const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6806*0a6a1f1dSLionel Sambuc
6807*0a6a1f1dSLionel Sambuc if (isa<CXXThisExpr>(E)) {
6808*0a6a1f1dSLionel Sambuc unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6809*0a6a1f1dSLionel Sambuc : diag::warn_this_bool_conversion;
6810*0a6a1f1dSLionel Sambuc Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6811*0a6a1f1dSLionel Sambuc return;
6812*0a6a1f1dSLionel Sambuc }
6813*0a6a1f1dSLionel Sambuc
6814*0a6a1f1dSLionel Sambuc bool IsAddressOf = false;
6815*0a6a1f1dSLionel Sambuc
6816*0a6a1f1dSLionel Sambuc if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6817*0a6a1f1dSLionel Sambuc if (UO->getOpcode() != UO_AddrOf)
6818*0a6a1f1dSLionel Sambuc return;
6819*0a6a1f1dSLionel Sambuc IsAddressOf = true;
6820*0a6a1f1dSLionel Sambuc E = UO->getSubExpr();
6821*0a6a1f1dSLionel Sambuc }
6822*0a6a1f1dSLionel Sambuc
6823*0a6a1f1dSLionel Sambuc if (IsAddressOf) {
6824*0a6a1f1dSLionel Sambuc unsigned DiagID = IsCompare
6825*0a6a1f1dSLionel Sambuc ? diag::warn_address_of_reference_null_compare
6826*0a6a1f1dSLionel Sambuc : diag::warn_address_of_reference_bool_conversion;
6827*0a6a1f1dSLionel Sambuc PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6828*0a6a1f1dSLionel Sambuc << IsEqual;
6829*0a6a1f1dSLionel Sambuc if (CheckForReference(*this, E, PD)) {
6830*0a6a1f1dSLionel Sambuc return;
6831*0a6a1f1dSLionel Sambuc }
6832*0a6a1f1dSLionel Sambuc }
6833*0a6a1f1dSLionel Sambuc
6834*0a6a1f1dSLionel Sambuc // Expect to find a single Decl. Skip anything more complicated.
6835*0a6a1f1dSLionel Sambuc ValueDecl *D = nullptr;
6836*0a6a1f1dSLionel Sambuc if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6837*0a6a1f1dSLionel Sambuc D = R->getDecl();
6838*0a6a1f1dSLionel Sambuc } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6839*0a6a1f1dSLionel Sambuc D = M->getMemberDecl();
6840*0a6a1f1dSLionel Sambuc }
6841*0a6a1f1dSLionel Sambuc
6842*0a6a1f1dSLionel Sambuc // Weak Decls can be null.
6843*0a6a1f1dSLionel Sambuc if (!D || D->isWeak())
6844*0a6a1f1dSLionel Sambuc return;
6845*0a6a1f1dSLionel Sambuc
6846*0a6a1f1dSLionel Sambuc // Check for parameter decl with nonnull attribute
6847*0a6a1f1dSLionel Sambuc if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6848*0a6a1f1dSLionel Sambuc if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6849*0a6a1f1dSLionel Sambuc if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6850*0a6a1f1dSLionel Sambuc unsigned NumArgs = FD->getNumParams();
6851*0a6a1f1dSLionel Sambuc llvm::SmallBitVector AttrNonNull(NumArgs);
6852*0a6a1f1dSLionel Sambuc for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6853*0a6a1f1dSLionel Sambuc if (!NonNull->args_size()) {
6854*0a6a1f1dSLionel Sambuc AttrNonNull.set(0, NumArgs);
6855*0a6a1f1dSLionel Sambuc break;
6856*0a6a1f1dSLionel Sambuc }
6857*0a6a1f1dSLionel Sambuc for (unsigned Val : NonNull->args()) {
6858*0a6a1f1dSLionel Sambuc if (Val >= NumArgs)
6859*0a6a1f1dSLionel Sambuc continue;
6860*0a6a1f1dSLionel Sambuc AttrNonNull.set(Val);
6861*0a6a1f1dSLionel Sambuc }
6862*0a6a1f1dSLionel Sambuc }
6863*0a6a1f1dSLionel Sambuc if (!AttrNonNull.empty())
6864*0a6a1f1dSLionel Sambuc for (unsigned i = 0; i < NumArgs; ++i)
6865*0a6a1f1dSLionel Sambuc if (FD->getParamDecl(i) == PV &&
6866*0a6a1f1dSLionel Sambuc (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
6867*0a6a1f1dSLionel Sambuc std::string Str;
6868*0a6a1f1dSLionel Sambuc llvm::raw_string_ostream S(Str);
6869*0a6a1f1dSLionel Sambuc E->printPretty(S, nullptr, getPrintingPolicy());
6870*0a6a1f1dSLionel Sambuc unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6871*0a6a1f1dSLionel Sambuc : diag::warn_cast_nonnull_to_bool;
6872*0a6a1f1dSLionel Sambuc Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6873*0a6a1f1dSLionel Sambuc << Range << IsEqual;
6874*0a6a1f1dSLionel Sambuc return;
6875*0a6a1f1dSLionel Sambuc }
6876*0a6a1f1dSLionel Sambuc }
6877*0a6a1f1dSLionel Sambuc }
6878*0a6a1f1dSLionel Sambuc
6879*0a6a1f1dSLionel Sambuc QualType T = D->getType();
6880*0a6a1f1dSLionel Sambuc const bool IsArray = T->isArrayType();
6881*0a6a1f1dSLionel Sambuc const bool IsFunction = T->isFunctionType();
6882*0a6a1f1dSLionel Sambuc
6883*0a6a1f1dSLionel Sambuc // Address of function is used to silence the function warning.
6884*0a6a1f1dSLionel Sambuc if (IsAddressOf && IsFunction) {
6885*0a6a1f1dSLionel Sambuc return;
6886*0a6a1f1dSLionel Sambuc }
6887*0a6a1f1dSLionel Sambuc
6888*0a6a1f1dSLionel Sambuc // Found nothing.
6889*0a6a1f1dSLionel Sambuc if (!IsAddressOf && !IsFunction && !IsArray)
6890*0a6a1f1dSLionel Sambuc return;
6891*0a6a1f1dSLionel Sambuc
6892*0a6a1f1dSLionel Sambuc // Pretty print the expression for the diagnostic.
6893*0a6a1f1dSLionel Sambuc std::string Str;
6894*0a6a1f1dSLionel Sambuc llvm::raw_string_ostream S(Str);
6895*0a6a1f1dSLionel Sambuc E->printPretty(S, nullptr, getPrintingPolicy());
6896*0a6a1f1dSLionel Sambuc
6897*0a6a1f1dSLionel Sambuc unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6898*0a6a1f1dSLionel Sambuc : diag::warn_impcast_pointer_to_bool;
6899*0a6a1f1dSLionel Sambuc unsigned DiagType;
6900*0a6a1f1dSLionel Sambuc if (IsAddressOf)
6901*0a6a1f1dSLionel Sambuc DiagType = AddressOf;
6902*0a6a1f1dSLionel Sambuc else if (IsFunction)
6903*0a6a1f1dSLionel Sambuc DiagType = FunctionPointer;
6904*0a6a1f1dSLionel Sambuc else if (IsArray)
6905*0a6a1f1dSLionel Sambuc DiagType = ArrayPointer;
6906*0a6a1f1dSLionel Sambuc else
6907*0a6a1f1dSLionel Sambuc llvm_unreachable("Could not determine diagnostic.");
6908*0a6a1f1dSLionel Sambuc Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6909*0a6a1f1dSLionel Sambuc << Range << IsEqual;
6910*0a6a1f1dSLionel Sambuc
6911*0a6a1f1dSLionel Sambuc if (!IsFunction)
6912*0a6a1f1dSLionel Sambuc return;
6913*0a6a1f1dSLionel Sambuc
6914*0a6a1f1dSLionel Sambuc // Suggest '&' to silence the function warning.
6915*0a6a1f1dSLionel Sambuc Diag(E->getExprLoc(), diag::note_function_warning_silence)
6916*0a6a1f1dSLionel Sambuc << FixItHint::CreateInsertion(E->getLocStart(), "&");
6917*0a6a1f1dSLionel Sambuc
6918*0a6a1f1dSLionel Sambuc // Check to see if '()' fixit should be emitted.
6919*0a6a1f1dSLionel Sambuc QualType ReturnType;
6920*0a6a1f1dSLionel Sambuc UnresolvedSet<4> NonTemplateOverloads;
6921*0a6a1f1dSLionel Sambuc tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6922*0a6a1f1dSLionel Sambuc if (ReturnType.isNull())
6923*0a6a1f1dSLionel Sambuc return;
6924*0a6a1f1dSLionel Sambuc
6925*0a6a1f1dSLionel Sambuc if (IsCompare) {
6926*0a6a1f1dSLionel Sambuc // There are two cases here. If there is null constant, the only suggest
6927*0a6a1f1dSLionel Sambuc // for a pointer return type. If the null is 0, then suggest if the return
6928*0a6a1f1dSLionel Sambuc // type is a pointer or an integer type.
6929*0a6a1f1dSLionel Sambuc if (!ReturnType->isPointerType()) {
6930*0a6a1f1dSLionel Sambuc if (NullKind == Expr::NPCK_ZeroExpression ||
6931*0a6a1f1dSLionel Sambuc NullKind == Expr::NPCK_ZeroLiteral) {
6932*0a6a1f1dSLionel Sambuc if (!ReturnType->isIntegerType())
6933*0a6a1f1dSLionel Sambuc return;
6934*0a6a1f1dSLionel Sambuc } else {
6935*0a6a1f1dSLionel Sambuc return;
6936*0a6a1f1dSLionel Sambuc }
6937*0a6a1f1dSLionel Sambuc }
6938*0a6a1f1dSLionel Sambuc } else { // !IsCompare
6939*0a6a1f1dSLionel Sambuc // For function to bool, only suggest if the function pointer has bool
6940*0a6a1f1dSLionel Sambuc // return type.
6941*0a6a1f1dSLionel Sambuc if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6942*0a6a1f1dSLionel Sambuc return;
6943*0a6a1f1dSLionel Sambuc }
6944*0a6a1f1dSLionel Sambuc Diag(E->getExprLoc(), diag::note_function_to_function_call)
6945*0a6a1f1dSLionel Sambuc << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
6946*0a6a1f1dSLionel Sambuc }
6947*0a6a1f1dSLionel Sambuc
6948*0a6a1f1dSLionel Sambuc
6949f4a2713aSLionel Sambuc /// Diagnoses "dangerous" implicit conversions within the given
6950f4a2713aSLionel Sambuc /// expression (which is a full expression). Implements -Wconversion
6951f4a2713aSLionel Sambuc /// and -Wsign-compare.
6952f4a2713aSLionel Sambuc ///
6953f4a2713aSLionel Sambuc /// \param CC the "context" location of the implicit conversion, i.e.
6954f4a2713aSLionel Sambuc /// the most location of the syntactic entity requiring the implicit
6955f4a2713aSLionel Sambuc /// conversion
CheckImplicitConversions(Expr * E,SourceLocation CC)6956f4a2713aSLionel Sambuc void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
6957f4a2713aSLionel Sambuc // Don't diagnose in unevaluated contexts.
6958f4a2713aSLionel Sambuc if (isUnevaluatedContext())
6959f4a2713aSLionel Sambuc return;
6960f4a2713aSLionel Sambuc
6961f4a2713aSLionel Sambuc // Don't diagnose for value- or type-dependent expressions.
6962f4a2713aSLionel Sambuc if (E->isTypeDependent() || E->isValueDependent())
6963f4a2713aSLionel Sambuc return;
6964f4a2713aSLionel Sambuc
6965f4a2713aSLionel Sambuc // Check for array bounds violations in cases where the check isn't triggered
6966f4a2713aSLionel Sambuc // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6967f4a2713aSLionel Sambuc // ArraySubscriptExpr is on the RHS of a variable initialization.
6968f4a2713aSLionel Sambuc CheckArrayAccess(E);
6969f4a2713aSLionel Sambuc
6970f4a2713aSLionel Sambuc // This is not the right CC for (e.g.) a variable initialization.
6971f4a2713aSLionel Sambuc AnalyzeImplicitConversions(*this, E, CC);
6972f4a2713aSLionel Sambuc }
6973f4a2713aSLionel Sambuc
6974*0a6a1f1dSLionel Sambuc /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6975*0a6a1f1dSLionel Sambuc /// Input argument E is a logical expression.
CheckBoolLikeConversion(Expr * E,SourceLocation CC)6976*0a6a1f1dSLionel Sambuc void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
6977*0a6a1f1dSLionel Sambuc ::CheckBoolLikeConversion(*this, E, CC);
6978*0a6a1f1dSLionel Sambuc }
6979*0a6a1f1dSLionel Sambuc
6980f4a2713aSLionel Sambuc /// Diagnose when expression is an integer constant expression and its evaluation
6981f4a2713aSLionel Sambuc /// results in integer overflow
CheckForIntOverflow(Expr * E)6982f4a2713aSLionel Sambuc void Sema::CheckForIntOverflow (Expr *E) {
6983*0a6a1f1dSLionel Sambuc if (isa<BinaryOperator>(E->IgnoreParenCasts()))
6984*0a6a1f1dSLionel Sambuc E->IgnoreParenCasts()->EvaluateForOverflow(Context);
6985f4a2713aSLionel Sambuc }
6986f4a2713aSLionel Sambuc
6987f4a2713aSLionel Sambuc namespace {
6988f4a2713aSLionel Sambuc /// \brief Visitor for expressions which looks for unsequenced operations on the
6989f4a2713aSLionel Sambuc /// same object.
6990f4a2713aSLionel Sambuc class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
6991f4a2713aSLionel Sambuc typedef EvaluatedExprVisitor<SequenceChecker> Base;
6992f4a2713aSLionel Sambuc
6993f4a2713aSLionel Sambuc /// \brief A tree of sequenced regions within an expression. Two regions are
6994f4a2713aSLionel Sambuc /// unsequenced if one is an ancestor or a descendent of the other. When we
6995f4a2713aSLionel Sambuc /// finish processing an expression with sequencing, such as a comma
6996f4a2713aSLionel Sambuc /// expression, we fold its tree nodes into its parent, since they are
6997f4a2713aSLionel Sambuc /// unsequenced with respect to nodes we will visit later.
6998f4a2713aSLionel Sambuc class SequenceTree {
6999f4a2713aSLionel Sambuc struct Value {
Value__anon0a2745240a11::SequenceChecker::SequenceTree::Value7000f4a2713aSLionel Sambuc explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7001f4a2713aSLionel Sambuc unsigned Parent : 31;
7002f4a2713aSLionel Sambuc bool Merged : 1;
7003f4a2713aSLionel Sambuc };
7004f4a2713aSLionel Sambuc SmallVector<Value, 8> Values;
7005f4a2713aSLionel Sambuc
7006f4a2713aSLionel Sambuc public:
7007f4a2713aSLionel Sambuc /// \brief A region within an expression which may be sequenced with respect
7008f4a2713aSLionel Sambuc /// to some other region.
7009f4a2713aSLionel Sambuc class Seq {
Seq(unsigned N)7010f4a2713aSLionel Sambuc explicit Seq(unsigned N) : Index(N) {}
7011f4a2713aSLionel Sambuc unsigned Index;
7012f4a2713aSLionel Sambuc friend class SequenceTree;
7013f4a2713aSLionel Sambuc public:
Seq()7014f4a2713aSLionel Sambuc Seq() : Index(0) {}
7015f4a2713aSLionel Sambuc };
7016f4a2713aSLionel Sambuc
SequenceTree()7017f4a2713aSLionel Sambuc SequenceTree() { Values.push_back(Value(0)); }
root() const7018f4a2713aSLionel Sambuc Seq root() const { return Seq(0); }
7019f4a2713aSLionel Sambuc
7020f4a2713aSLionel Sambuc /// \brief Create a new sequence of operations, which is an unsequenced
7021f4a2713aSLionel Sambuc /// subset of \p Parent. This sequence of operations is sequenced with
7022f4a2713aSLionel Sambuc /// respect to other children of \p Parent.
allocate(Seq Parent)7023f4a2713aSLionel Sambuc Seq allocate(Seq Parent) {
7024f4a2713aSLionel Sambuc Values.push_back(Value(Parent.Index));
7025f4a2713aSLionel Sambuc return Seq(Values.size() - 1);
7026f4a2713aSLionel Sambuc }
7027f4a2713aSLionel Sambuc
7028f4a2713aSLionel Sambuc /// \brief Merge a sequence of operations into its parent.
merge(Seq S)7029f4a2713aSLionel Sambuc void merge(Seq S) {
7030f4a2713aSLionel Sambuc Values[S.Index].Merged = true;
7031f4a2713aSLionel Sambuc }
7032f4a2713aSLionel Sambuc
7033f4a2713aSLionel Sambuc /// \brief Determine whether two operations are unsequenced. This operation
7034f4a2713aSLionel Sambuc /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7035f4a2713aSLionel Sambuc /// should have been merged into its parent as appropriate.
isUnsequenced(Seq Cur,Seq Old)7036f4a2713aSLionel Sambuc bool isUnsequenced(Seq Cur, Seq Old) {
7037f4a2713aSLionel Sambuc unsigned C = representative(Cur.Index);
7038f4a2713aSLionel Sambuc unsigned Target = representative(Old.Index);
7039f4a2713aSLionel Sambuc while (C >= Target) {
7040f4a2713aSLionel Sambuc if (C == Target)
7041f4a2713aSLionel Sambuc return true;
7042f4a2713aSLionel Sambuc C = Values[C].Parent;
7043f4a2713aSLionel Sambuc }
7044f4a2713aSLionel Sambuc return false;
7045f4a2713aSLionel Sambuc }
7046f4a2713aSLionel Sambuc
7047f4a2713aSLionel Sambuc private:
7048f4a2713aSLionel Sambuc /// \brief Pick a representative for a sequence.
representative(unsigned K)7049f4a2713aSLionel Sambuc unsigned representative(unsigned K) {
7050f4a2713aSLionel Sambuc if (Values[K].Merged)
7051f4a2713aSLionel Sambuc // Perform path compression as we go.
7052f4a2713aSLionel Sambuc return Values[K].Parent = representative(Values[K].Parent);
7053f4a2713aSLionel Sambuc return K;
7054f4a2713aSLionel Sambuc }
7055f4a2713aSLionel Sambuc };
7056f4a2713aSLionel Sambuc
7057f4a2713aSLionel Sambuc /// An object for which we can track unsequenced uses.
7058f4a2713aSLionel Sambuc typedef NamedDecl *Object;
7059f4a2713aSLionel Sambuc
7060f4a2713aSLionel Sambuc /// Different flavors of object usage which we track. We only track the
7061f4a2713aSLionel Sambuc /// least-sequenced usage of each kind.
7062f4a2713aSLionel Sambuc enum UsageKind {
7063f4a2713aSLionel Sambuc /// A read of an object. Multiple unsequenced reads are OK.
7064f4a2713aSLionel Sambuc UK_Use,
7065f4a2713aSLionel Sambuc /// A modification of an object which is sequenced before the value
7066f4a2713aSLionel Sambuc /// computation of the expression, such as ++n in C++.
7067f4a2713aSLionel Sambuc UK_ModAsValue,
7068f4a2713aSLionel Sambuc /// A modification of an object which is not sequenced before the value
7069f4a2713aSLionel Sambuc /// computation of the expression, such as n++.
7070f4a2713aSLionel Sambuc UK_ModAsSideEffect,
7071f4a2713aSLionel Sambuc
7072f4a2713aSLionel Sambuc UK_Count = UK_ModAsSideEffect + 1
7073f4a2713aSLionel Sambuc };
7074f4a2713aSLionel Sambuc
7075f4a2713aSLionel Sambuc struct Usage {
Usage__anon0a2745240a11::SequenceChecker::Usage7076*0a6a1f1dSLionel Sambuc Usage() : Use(nullptr), Seq() {}
7077f4a2713aSLionel Sambuc Expr *Use;
7078f4a2713aSLionel Sambuc SequenceTree::Seq Seq;
7079f4a2713aSLionel Sambuc };
7080f4a2713aSLionel Sambuc
7081f4a2713aSLionel Sambuc struct UsageInfo {
UsageInfo__anon0a2745240a11::SequenceChecker::UsageInfo7082f4a2713aSLionel Sambuc UsageInfo() : Diagnosed(false) {}
7083f4a2713aSLionel Sambuc Usage Uses[UK_Count];
7084f4a2713aSLionel Sambuc /// Have we issued a diagnostic for this variable already?
7085f4a2713aSLionel Sambuc bool Diagnosed;
7086f4a2713aSLionel Sambuc };
7087f4a2713aSLionel Sambuc typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7088f4a2713aSLionel Sambuc
7089f4a2713aSLionel Sambuc Sema &SemaRef;
7090f4a2713aSLionel Sambuc /// Sequenced regions within the expression.
7091f4a2713aSLionel Sambuc SequenceTree Tree;
7092f4a2713aSLionel Sambuc /// Declaration modifications and references which we have seen.
7093f4a2713aSLionel Sambuc UsageInfoMap UsageMap;
7094f4a2713aSLionel Sambuc /// The region we are currently within.
7095f4a2713aSLionel Sambuc SequenceTree::Seq Region;
7096f4a2713aSLionel Sambuc /// Filled in with declarations which were modified as a side-effect
7097f4a2713aSLionel Sambuc /// (that is, post-increment operations).
7098f4a2713aSLionel Sambuc SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
7099f4a2713aSLionel Sambuc /// Expressions to check later. We defer checking these to reduce
7100f4a2713aSLionel Sambuc /// stack usage.
7101f4a2713aSLionel Sambuc SmallVectorImpl<Expr *> &WorkList;
7102f4a2713aSLionel Sambuc
7103f4a2713aSLionel Sambuc /// RAII object wrapping the visitation of a sequenced subexpression of an
7104f4a2713aSLionel Sambuc /// expression. At the end of this process, the side-effects of the evaluation
7105f4a2713aSLionel Sambuc /// become sequenced with respect to the value computation of the result, so
7106f4a2713aSLionel Sambuc /// we downgrade any UK_ModAsSideEffect within the evaluation to
7107f4a2713aSLionel Sambuc /// UK_ModAsValue.
7108f4a2713aSLionel Sambuc struct SequencedSubexpression {
SequencedSubexpression__anon0a2745240a11::SequenceChecker::SequencedSubexpression7109f4a2713aSLionel Sambuc SequencedSubexpression(SequenceChecker &Self)
7110f4a2713aSLionel Sambuc : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7111f4a2713aSLionel Sambuc Self.ModAsSideEffect = &ModAsSideEffect;
7112f4a2713aSLionel Sambuc }
~SequencedSubexpression__anon0a2745240a11::SequenceChecker::SequencedSubexpression7113f4a2713aSLionel Sambuc ~SequencedSubexpression() {
7114*0a6a1f1dSLionel Sambuc for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7115*0a6a1f1dSLionel Sambuc MI != ME; ++MI) {
7116*0a6a1f1dSLionel Sambuc UsageInfo &U = Self.UsageMap[MI->first];
7117*0a6a1f1dSLionel Sambuc auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7118*0a6a1f1dSLionel Sambuc Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7119*0a6a1f1dSLionel Sambuc SideEffectUsage = MI->second;
7120f4a2713aSLionel Sambuc }
7121f4a2713aSLionel Sambuc Self.ModAsSideEffect = OldModAsSideEffect;
7122f4a2713aSLionel Sambuc }
7123f4a2713aSLionel Sambuc
7124f4a2713aSLionel Sambuc SequenceChecker &Self;
7125f4a2713aSLionel Sambuc SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7126f4a2713aSLionel Sambuc SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
7127f4a2713aSLionel Sambuc };
7128f4a2713aSLionel Sambuc
7129f4a2713aSLionel Sambuc /// RAII object wrapping the visitation of a subexpression which we might
7130f4a2713aSLionel Sambuc /// choose to evaluate as a constant. If any subexpression is evaluated and
7131f4a2713aSLionel Sambuc /// found to be non-constant, this allows us to suppress the evaluation of
7132f4a2713aSLionel Sambuc /// the outer expression.
7133f4a2713aSLionel Sambuc class EvaluationTracker {
7134f4a2713aSLionel Sambuc public:
EvaluationTracker(SequenceChecker & Self)7135f4a2713aSLionel Sambuc EvaluationTracker(SequenceChecker &Self)
7136f4a2713aSLionel Sambuc : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7137f4a2713aSLionel Sambuc Self.EvalTracker = this;
7138f4a2713aSLionel Sambuc }
~EvaluationTracker()7139f4a2713aSLionel Sambuc ~EvaluationTracker() {
7140f4a2713aSLionel Sambuc Self.EvalTracker = Prev;
7141f4a2713aSLionel Sambuc if (Prev)
7142f4a2713aSLionel Sambuc Prev->EvalOK &= EvalOK;
7143f4a2713aSLionel Sambuc }
7144f4a2713aSLionel Sambuc
evaluate(const Expr * E,bool & Result)7145f4a2713aSLionel Sambuc bool evaluate(const Expr *E, bool &Result) {
7146f4a2713aSLionel Sambuc if (!EvalOK || E->isValueDependent())
7147f4a2713aSLionel Sambuc return false;
7148f4a2713aSLionel Sambuc EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7149f4a2713aSLionel Sambuc return EvalOK;
7150f4a2713aSLionel Sambuc }
7151f4a2713aSLionel Sambuc
7152f4a2713aSLionel Sambuc private:
7153f4a2713aSLionel Sambuc SequenceChecker &Self;
7154f4a2713aSLionel Sambuc EvaluationTracker *Prev;
7155f4a2713aSLionel Sambuc bool EvalOK;
7156f4a2713aSLionel Sambuc } *EvalTracker;
7157f4a2713aSLionel Sambuc
7158f4a2713aSLionel Sambuc /// \brief Find the object which is produced by the specified expression,
7159f4a2713aSLionel Sambuc /// if any.
getObject(Expr * E,bool Mod) const7160f4a2713aSLionel Sambuc Object getObject(Expr *E, bool Mod) const {
7161f4a2713aSLionel Sambuc E = E->IgnoreParenCasts();
7162f4a2713aSLionel Sambuc if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7163f4a2713aSLionel Sambuc if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7164f4a2713aSLionel Sambuc return getObject(UO->getSubExpr(), Mod);
7165f4a2713aSLionel Sambuc } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7166f4a2713aSLionel Sambuc if (BO->getOpcode() == BO_Comma)
7167f4a2713aSLionel Sambuc return getObject(BO->getRHS(), Mod);
7168f4a2713aSLionel Sambuc if (Mod && BO->isAssignmentOp())
7169f4a2713aSLionel Sambuc return getObject(BO->getLHS(), Mod);
7170f4a2713aSLionel Sambuc } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7171f4a2713aSLionel Sambuc // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7172f4a2713aSLionel Sambuc if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7173f4a2713aSLionel Sambuc return ME->getMemberDecl();
7174f4a2713aSLionel Sambuc } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7175f4a2713aSLionel Sambuc // FIXME: If this is a reference, map through to its value.
7176f4a2713aSLionel Sambuc return DRE->getDecl();
7177*0a6a1f1dSLionel Sambuc return nullptr;
7178f4a2713aSLionel Sambuc }
7179f4a2713aSLionel Sambuc
7180f4a2713aSLionel Sambuc /// \brief Note that an object was modified or used by an expression.
addUsage(UsageInfo & UI,Object O,Expr * Ref,UsageKind UK)7181f4a2713aSLionel Sambuc void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7182f4a2713aSLionel Sambuc Usage &U = UI.Uses[UK];
7183f4a2713aSLionel Sambuc if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7184f4a2713aSLionel Sambuc if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7185f4a2713aSLionel Sambuc ModAsSideEffect->push_back(std::make_pair(O, U));
7186f4a2713aSLionel Sambuc U.Use = Ref;
7187f4a2713aSLionel Sambuc U.Seq = Region;
7188f4a2713aSLionel Sambuc }
7189f4a2713aSLionel Sambuc }
7190f4a2713aSLionel Sambuc /// \brief Check whether a modification or use conflicts with a prior usage.
checkUsage(Object O,UsageInfo & UI,Expr * Ref,UsageKind OtherKind,bool IsModMod)7191f4a2713aSLionel Sambuc void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7192f4a2713aSLionel Sambuc bool IsModMod) {
7193f4a2713aSLionel Sambuc if (UI.Diagnosed)
7194f4a2713aSLionel Sambuc return;
7195f4a2713aSLionel Sambuc
7196f4a2713aSLionel Sambuc const Usage &U = UI.Uses[OtherKind];
7197f4a2713aSLionel Sambuc if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7198f4a2713aSLionel Sambuc return;
7199f4a2713aSLionel Sambuc
7200f4a2713aSLionel Sambuc Expr *Mod = U.Use;
7201f4a2713aSLionel Sambuc Expr *ModOrUse = Ref;
7202f4a2713aSLionel Sambuc if (OtherKind == UK_Use)
7203f4a2713aSLionel Sambuc std::swap(Mod, ModOrUse);
7204f4a2713aSLionel Sambuc
7205f4a2713aSLionel Sambuc SemaRef.Diag(Mod->getExprLoc(),
7206f4a2713aSLionel Sambuc IsModMod ? diag::warn_unsequenced_mod_mod
7207f4a2713aSLionel Sambuc : diag::warn_unsequenced_mod_use)
7208f4a2713aSLionel Sambuc << O << SourceRange(ModOrUse->getExprLoc());
7209f4a2713aSLionel Sambuc UI.Diagnosed = true;
7210f4a2713aSLionel Sambuc }
7211f4a2713aSLionel Sambuc
notePreUse(Object O,Expr * Use)7212f4a2713aSLionel Sambuc void notePreUse(Object O, Expr *Use) {
7213f4a2713aSLionel Sambuc UsageInfo &U = UsageMap[O];
7214f4a2713aSLionel Sambuc // Uses conflict with other modifications.
7215f4a2713aSLionel Sambuc checkUsage(O, U, Use, UK_ModAsValue, false);
7216f4a2713aSLionel Sambuc }
notePostUse(Object O,Expr * Use)7217f4a2713aSLionel Sambuc void notePostUse(Object O, Expr *Use) {
7218f4a2713aSLionel Sambuc UsageInfo &U = UsageMap[O];
7219f4a2713aSLionel Sambuc checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7220f4a2713aSLionel Sambuc addUsage(U, O, Use, UK_Use);
7221f4a2713aSLionel Sambuc }
7222f4a2713aSLionel Sambuc
notePreMod(Object O,Expr * Mod)7223f4a2713aSLionel Sambuc void notePreMod(Object O, Expr *Mod) {
7224f4a2713aSLionel Sambuc UsageInfo &U = UsageMap[O];
7225f4a2713aSLionel Sambuc // Modifications conflict with other modifications and with uses.
7226f4a2713aSLionel Sambuc checkUsage(O, U, Mod, UK_ModAsValue, true);
7227f4a2713aSLionel Sambuc checkUsage(O, U, Mod, UK_Use, false);
7228f4a2713aSLionel Sambuc }
notePostMod(Object O,Expr * Use,UsageKind UK)7229f4a2713aSLionel Sambuc void notePostMod(Object O, Expr *Use, UsageKind UK) {
7230f4a2713aSLionel Sambuc UsageInfo &U = UsageMap[O];
7231f4a2713aSLionel Sambuc checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7232f4a2713aSLionel Sambuc addUsage(U, O, Use, UK);
7233f4a2713aSLionel Sambuc }
7234f4a2713aSLionel Sambuc
7235f4a2713aSLionel Sambuc public:
SequenceChecker(Sema & S,Expr * E,SmallVectorImpl<Expr * > & WorkList)7236f4a2713aSLionel Sambuc SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
7237*0a6a1f1dSLionel Sambuc : Base(S.Context), SemaRef(S), Region(Tree.root()),
7238*0a6a1f1dSLionel Sambuc ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
7239f4a2713aSLionel Sambuc Visit(E);
7240f4a2713aSLionel Sambuc }
7241f4a2713aSLionel Sambuc
VisitStmt(Stmt * S)7242f4a2713aSLionel Sambuc void VisitStmt(Stmt *S) {
7243f4a2713aSLionel Sambuc // Skip all statements which aren't expressions for now.
7244f4a2713aSLionel Sambuc }
7245f4a2713aSLionel Sambuc
VisitExpr(Expr * E)7246f4a2713aSLionel Sambuc void VisitExpr(Expr *E) {
7247f4a2713aSLionel Sambuc // By default, just recurse to evaluated subexpressions.
7248f4a2713aSLionel Sambuc Base::VisitStmt(E);
7249f4a2713aSLionel Sambuc }
7250f4a2713aSLionel Sambuc
VisitCastExpr(CastExpr * E)7251f4a2713aSLionel Sambuc void VisitCastExpr(CastExpr *E) {
7252f4a2713aSLionel Sambuc Object O = Object();
7253f4a2713aSLionel Sambuc if (E->getCastKind() == CK_LValueToRValue)
7254f4a2713aSLionel Sambuc O = getObject(E->getSubExpr(), false);
7255f4a2713aSLionel Sambuc
7256f4a2713aSLionel Sambuc if (O)
7257f4a2713aSLionel Sambuc notePreUse(O, E);
7258f4a2713aSLionel Sambuc VisitExpr(E);
7259f4a2713aSLionel Sambuc if (O)
7260f4a2713aSLionel Sambuc notePostUse(O, E);
7261f4a2713aSLionel Sambuc }
7262f4a2713aSLionel Sambuc
VisitBinComma(BinaryOperator * BO)7263f4a2713aSLionel Sambuc void VisitBinComma(BinaryOperator *BO) {
7264f4a2713aSLionel Sambuc // C++11 [expr.comma]p1:
7265f4a2713aSLionel Sambuc // Every value computation and side effect associated with the left
7266f4a2713aSLionel Sambuc // expression is sequenced before every value computation and side
7267f4a2713aSLionel Sambuc // effect associated with the right expression.
7268f4a2713aSLionel Sambuc SequenceTree::Seq LHS = Tree.allocate(Region);
7269f4a2713aSLionel Sambuc SequenceTree::Seq RHS = Tree.allocate(Region);
7270f4a2713aSLionel Sambuc SequenceTree::Seq OldRegion = Region;
7271f4a2713aSLionel Sambuc
7272f4a2713aSLionel Sambuc {
7273f4a2713aSLionel Sambuc SequencedSubexpression SeqLHS(*this);
7274f4a2713aSLionel Sambuc Region = LHS;
7275f4a2713aSLionel Sambuc Visit(BO->getLHS());
7276f4a2713aSLionel Sambuc }
7277f4a2713aSLionel Sambuc
7278f4a2713aSLionel Sambuc Region = RHS;
7279f4a2713aSLionel Sambuc Visit(BO->getRHS());
7280f4a2713aSLionel Sambuc
7281f4a2713aSLionel Sambuc Region = OldRegion;
7282f4a2713aSLionel Sambuc
7283f4a2713aSLionel Sambuc // Forget that LHS and RHS are sequenced. They are both unsequenced
7284f4a2713aSLionel Sambuc // with respect to other stuff.
7285f4a2713aSLionel Sambuc Tree.merge(LHS);
7286f4a2713aSLionel Sambuc Tree.merge(RHS);
7287f4a2713aSLionel Sambuc }
7288f4a2713aSLionel Sambuc
VisitBinAssign(BinaryOperator * BO)7289f4a2713aSLionel Sambuc void VisitBinAssign(BinaryOperator *BO) {
7290f4a2713aSLionel Sambuc // The modification is sequenced after the value computation of the LHS
7291f4a2713aSLionel Sambuc // and RHS, so check it before inspecting the operands and update the
7292f4a2713aSLionel Sambuc // map afterwards.
7293f4a2713aSLionel Sambuc Object O = getObject(BO->getLHS(), true);
7294f4a2713aSLionel Sambuc if (!O)
7295f4a2713aSLionel Sambuc return VisitExpr(BO);
7296f4a2713aSLionel Sambuc
7297f4a2713aSLionel Sambuc notePreMod(O, BO);
7298f4a2713aSLionel Sambuc
7299f4a2713aSLionel Sambuc // C++11 [expr.ass]p7:
7300f4a2713aSLionel Sambuc // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7301f4a2713aSLionel Sambuc // only once.
7302f4a2713aSLionel Sambuc //
7303f4a2713aSLionel Sambuc // Therefore, for a compound assignment operator, O is considered used
7304f4a2713aSLionel Sambuc // everywhere except within the evaluation of E1 itself.
7305f4a2713aSLionel Sambuc if (isa<CompoundAssignOperator>(BO))
7306f4a2713aSLionel Sambuc notePreUse(O, BO);
7307f4a2713aSLionel Sambuc
7308f4a2713aSLionel Sambuc Visit(BO->getLHS());
7309f4a2713aSLionel Sambuc
7310f4a2713aSLionel Sambuc if (isa<CompoundAssignOperator>(BO))
7311f4a2713aSLionel Sambuc notePostUse(O, BO);
7312f4a2713aSLionel Sambuc
7313f4a2713aSLionel Sambuc Visit(BO->getRHS());
7314f4a2713aSLionel Sambuc
7315f4a2713aSLionel Sambuc // C++11 [expr.ass]p1:
7316f4a2713aSLionel Sambuc // the assignment is sequenced [...] before the value computation of the
7317f4a2713aSLionel Sambuc // assignment expression.
7318f4a2713aSLionel Sambuc // C11 6.5.16/3 has no such rule.
7319f4a2713aSLionel Sambuc notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7320f4a2713aSLionel Sambuc : UK_ModAsSideEffect);
7321f4a2713aSLionel Sambuc }
VisitCompoundAssignOperator(CompoundAssignOperator * CAO)7322f4a2713aSLionel Sambuc void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7323f4a2713aSLionel Sambuc VisitBinAssign(CAO);
7324f4a2713aSLionel Sambuc }
7325f4a2713aSLionel Sambuc
VisitUnaryPreInc(UnaryOperator * UO)7326f4a2713aSLionel Sambuc void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
VisitUnaryPreDec(UnaryOperator * UO)7327f4a2713aSLionel Sambuc void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
VisitUnaryPreIncDec(UnaryOperator * UO)7328f4a2713aSLionel Sambuc void VisitUnaryPreIncDec(UnaryOperator *UO) {
7329f4a2713aSLionel Sambuc Object O = getObject(UO->getSubExpr(), true);
7330f4a2713aSLionel Sambuc if (!O)
7331f4a2713aSLionel Sambuc return VisitExpr(UO);
7332f4a2713aSLionel Sambuc
7333f4a2713aSLionel Sambuc notePreMod(O, UO);
7334f4a2713aSLionel Sambuc Visit(UO->getSubExpr());
7335f4a2713aSLionel Sambuc // C++11 [expr.pre.incr]p1:
7336f4a2713aSLionel Sambuc // the expression ++x is equivalent to x+=1
7337f4a2713aSLionel Sambuc notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7338f4a2713aSLionel Sambuc : UK_ModAsSideEffect);
7339f4a2713aSLionel Sambuc }
7340f4a2713aSLionel Sambuc
VisitUnaryPostInc(UnaryOperator * UO)7341f4a2713aSLionel Sambuc void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
VisitUnaryPostDec(UnaryOperator * UO)7342f4a2713aSLionel Sambuc void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
VisitUnaryPostIncDec(UnaryOperator * UO)7343f4a2713aSLionel Sambuc void VisitUnaryPostIncDec(UnaryOperator *UO) {
7344f4a2713aSLionel Sambuc Object O = getObject(UO->getSubExpr(), true);
7345f4a2713aSLionel Sambuc if (!O)
7346f4a2713aSLionel Sambuc return VisitExpr(UO);
7347f4a2713aSLionel Sambuc
7348f4a2713aSLionel Sambuc notePreMod(O, UO);
7349f4a2713aSLionel Sambuc Visit(UO->getSubExpr());
7350f4a2713aSLionel Sambuc notePostMod(O, UO, UK_ModAsSideEffect);
7351f4a2713aSLionel Sambuc }
7352f4a2713aSLionel Sambuc
7353f4a2713aSLionel Sambuc /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
VisitBinLOr(BinaryOperator * BO)7354f4a2713aSLionel Sambuc void VisitBinLOr(BinaryOperator *BO) {
7355f4a2713aSLionel Sambuc // The side-effects of the LHS of an '&&' are sequenced before the
7356f4a2713aSLionel Sambuc // value computation of the RHS, and hence before the value computation
7357f4a2713aSLionel Sambuc // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7358f4a2713aSLionel Sambuc // as if they were unconditionally sequenced.
7359f4a2713aSLionel Sambuc EvaluationTracker Eval(*this);
7360f4a2713aSLionel Sambuc {
7361f4a2713aSLionel Sambuc SequencedSubexpression Sequenced(*this);
7362f4a2713aSLionel Sambuc Visit(BO->getLHS());
7363f4a2713aSLionel Sambuc }
7364f4a2713aSLionel Sambuc
7365f4a2713aSLionel Sambuc bool Result;
7366f4a2713aSLionel Sambuc if (Eval.evaluate(BO->getLHS(), Result)) {
7367f4a2713aSLionel Sambuc if (!Result)
7368f4a2713aSLionel Sambuc Visit(BO->getRHS());
7369f4a2713aSLionel Sambuc } else {
7370f4a2713aSLionel Sambuc // Check for unsequenced operations in the RHS, treating it as an
7371f4a2713aSLionel Sambuc // entirely separate evaluation.
7372f4a2713aSLionel Sambuc //
7373f4a2713aSLionel Sambuc // FIXME: If there are operations in the RHS which are unsequenced
7374f4a2713aSLionel Sambuc // with respect to operations outside the RHS, and those operations
7375f4a2713aSLionel Sambuc // are unconditionally evaluated, diagnose them.
7376f4a2713aSLionel Sambuc WorkList.push_back(BO->getRHS());
7377f4a2713aSLionel Sambuc }
7378f4a2713aSLionel Sambuc }
VisitBinLAnd(BinaryOperator * BO)7379f4a2713aSLionel Sambuc void VisitBinLAnd(BinaryOperator *BO) {
7380f4a2713aSLionel Sambuc EvaluationTracker Eval(*this);
7381f4a2713aSLionel Sambuc {
7382f4a2713aSLionel Sambuc SequencedSubexpression Sequenced(*this);
7383f4a2713aSLionel Sambuc Visit(BO->getLHS());
7384f4a2713aSLionel Sambuc }
7385f4a2713aSLionel Sambuc
7386f4a2713aSLionel Sambuc bool Result;
7387f4a2713aSLionel Sambuc if (Eval.evaluate(BO->getLHS(), Result)) {
7388f4a2713aSLionel Sambuc if (Result)
7389f4a2713aSLionel Sambuc Visit(BO->getRHS());
7390f4a2713aSLionel Sambuc } else {
7391f4a2713aSLionel Sambuc WorkList.push_back(BO->getRHS());
7392f4a2713aSLionel Sambuc }
7393f4a2713aSLionel Sambuc }
7394f4a2713aSLionel Sambuc
7395f4a2713aSLionel Sambuc // Only visit the condition, unless we can be sure which subexpression will
7396f4a2713aSLionel Sambuc // be chosen.
VisitAbstractConditionalOperator(AbstractConditionalOperator * CO)7397f4a2713aSLionel Sambuc void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
7398f4a2713aSLionel Sambuc EvaluationTracker Eval(*this);
7399f4a2713aSLionel Sambuc {
7400f4a2713aSLionel Sambuc SequencedSubexpression Sequenced(*this);
7401f4a2713aSLionel Sambuc Visit(CO->getCond());
7402f4a2713aSLionel Sambuc }
7403f4a2713aSLionel Sambuc
7404f4a2713aSLionel Sambuc bool Result;
7405f4a2713aSLionel Sambuc if (Eval.evaluate(CO->getCond(), Result))
7406f4a2713aSLionel Sambuc Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
7407f4a2713aSLionel Sambuc else {
7408f4a2713aSLionel Sambuc WorkList.push_back(CO->getTrueExpr());
7409f4a2713aSLionel Sambuc WorkList.push_back(CO->getFalseExpr());
7410f4a2713aSLionel Sambuc }
7411f4a2713aSLionel Sambuc }
7412f4a2713aSLionel Sambuc
VisitCallExpr(CallExpr * CE)7413f4a2713aSLionel Sambuc void VisitCallExpr(CallExpr *CE) {
7414f4a2713aSLionel Sambuc // C++11 [intro.execution]p15:
7415f4a2713aSLionel Sambuc // When calling a function [...], every value computation and side effect
7416f4a2713aSLionel Sambuc // associated with any argument expression, or with the postfix expression
7417f4a2713aSLionel Sambuc // designating the called function, is sequenced before execution of every
7418f4a2713aSLionel Sambuc // expression or statement in the body of the function [and thus before
7419f4a2713aSLionel Sambuc // the value computation of its result].
7420f4a2713aSLionel Sambuc SequencedSubexpression Sequenced(*this);
7421f4a2713aSLionel Sambuc Base::VisitCallExpr(CE);
7422f4a2713aSLionel Sambuc
7423f4a2713aSLionel Sambuc // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7424f4a2713aSLionel Sambuc }
7425f4a2713aSLionel Sambuc
VisitCXXConstructExpr(CXXConstructExpr * CCE)7426f4a2713aSLionel Sambuc void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
7427f4a2713aSLionel Sambuc // This is a call, so all subexpressions are sequenced before the result.
7428f4a2713aSLionel Sambuc SequencedSubexpression Sequenced(*this);
7429f4a2713aSLionel Sambuc
7430f4a2713aSLionel Sambuc if (!CCE->isListInitialization())
7431f4a2713aSLionel Sambuc return VisitExpr(CCE);
7432f4a2713aSLionel Sambuc
7433f4a2713aSLionel Sambuc // In C++11, list initializations are sequenced.
7434f4a2713aSLionel Sambuc SmallVector<SequenceTree::Seq, 32> Elts;
7435f4a2713aSLionel Sambuc SequenceTree::Seq Parent = Region;
7436f4a2713aSLionel Sambuc for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7437f4a2713aSLionel Sambuc E = CCE->arg_end();
7438f4a2713aSLionel Sambuc I != E; ++I) {
7439f4a2713aSLionel Sambuc Region = Tree.allocate(Parent);
7440f4a2713aSLionel Sambuc Elts.push_back(Region);
7441f4a2713aSLionel Sambuc Visit(*I);
7442f4a2713aSLionel Sambuc }
7443f4a2713aSLionel Sambuc
7444f4a2713aSLionel Sambuc // Forget that the initializers are sequenced.
7445f4a2713aSLionel Sambuc Region = Parent;
7446f4a2713aSLionel Sambuc for (unsigned I = 0; I < Elts.size(); ++I)
7447f4a2713aSLionel Sambuc Tree.merge(Elts[I]);
7448f4a2713aSLionel Sambuc }
7449f4a2713aSLionel Sambuc
VisitInitListExpr(InitListExpr * ILE)7450f4a2713aSLionel Sambuc void VisitInitListExpr(InitListExpr *ILE) {
7451f4a2713aSLionel Sambuc if (!SemaRef.getLangOpts().CPlusPlus11)
7452f4a2713aSLionel Sambuc return VisitExpr(ILE);
7453f4a2713aSLionel Sambuc
7454f4a2713aSLionel Sambuc // In C++11, list initializations are sequenced.
7455f4a2713aSLionel Sambuc SmallVector<SequenceTree::Seq, 32> Elts;
7456f4a2713aSLionel Sambuc SequenceTree::Seq Parent = Region;
7457f4a2713aSLionel Sambuc for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7458f4a2713aSLionel Sambuc Expr *E = ILE->getInit(I);
7459f4a2713aSLionel Sambuc if (!E) continue;
7460f4a2713aSLionel Sambuc Region = Tree.allocate(Parent);
7461f4a2713aSLionel Sambuc Elts.push_back(Region);
7462f4a2713aSLionel Sambuc Visit(E);
7463f4a2713aSLionel Sambuc }
7464f4a2713aSLionel Sambuc
7465f4a2713aSLionel Sambuc // Forget that the initializers are sequenced.
7466f4a2713aSLionel Sambuc Region = Parent;
7467f4a2713aSLionel Sambuc for (unsigned I = 0; I < Elts.size(); ++I)
7468f4a2713aSLionel Sambuc Tree.merge(Elts[I]);
7469f4a2713aSLionel Sambuc }
7470f4a2713aSLionel Sambuc };
7471f4a2713aSLionel Sambuc }
7472f4a2713aSLionel Sambuc
CheckUnsequencedOperations(Expr * E)7473f4a2713aSLionel Sambuc void Sema::CheckUnsequencedOperations(Expr *E) {
7474f4a2713aSLionel Sambuc SmallVector<Expr *, 8> WorkList;
7475f4a2713aSLionel Sambuc WorkList.push_back(E);
7476f4a2713aSLionel Sambuc while (!WorkList.empty()) {
7477f4a2713aSLionel Sambuc Expr *Item = WorkList.pop_back_val();
7478f4a2713aSLionel Sambuc SequenceChecker(*this, Item, WorkList);
7479f4a2713aSLionel Sambuc }
7480f4a2713aSLionel Sambuc }
7481f4a2713aSLionel Sambuc
CheckCompletedExpr(Expr * E,SourceLocation CheckLoc,bool IsConstexpr)7482f4a2713aSLionel Sambuc void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7483f4a2713aSLionel Sambuc bool IsConstexpr) {
7484f4a2713aSLionel Sambuc CheckImplicitConversions(E, CheckLoc);
7485f4a2713aSLionel Sambuc CheckUnsequencedOperations(E);
7486f4a2713aSLionel Sambuc if (!IsConstexpr && !E->isValueDependent())
7487f4a2713aSLionel Sambuc CheckForIntOverflow(E);
7488f4a2713aSLionel Sambuc }
7489f4a2713aSLionel Sambuc
CheckBitFieldInitialization(SourceLocation InitLoc,FieldDecl * BitField,Expr * Init)7490f4a2713aSLionel Sambuc void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7491f4a2713aSLionel Sambuc FieldDecl *BitField,
7492f4a2713aSLionel Sambuc Expr *Init) {
7493f4a2713aSLionel Sambuc (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7494f4a2713aSLionel Sambuc }
7495f4a2713aSLionel Sambuc
7496f4a2713aSLionel Sambuc /// CheckParmsForFunctionDef - Check that the parameters of the given
7497f4a2713aSLionel Sambuc /// function are appropriate for the definition of a function. This
7498f4a2713aSLionel Sambuc /// takes care of any checks that cannot be performed on the
7499f4a2713aSLionel Sambuc /// declaration itself, e.g., that the types of each of the function
7500f4a2713aSLionel Sambuc /// parameters are complete.
CheckParmsForFunctionDef(ParmVarDecl * const * P,ParmVarDecl * const * PEnd,bool CheckParameterNames)7501f4a2713aSLionel Sambuc bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7502f4a2713aSLionel Sambuc ParmVarDecl *const *PEnd,
7503f4a2713aSLionel Sambuc bool CheckParameterNames) {
7504f4a2713aSLionel Sambuc bool HasInvalidParm = false;
7505f4a2713aSLionel Sambuc for (; P != PEnd; ++P) {
7506f4a2713aSLionel Sambuc ParmVarDecl *Param = *P;
7507f4a2713aSLionel Sambuc
7508f4a2713aSLionel Sambuc // C99 6.7.5.3p4: the parameters in a parameter type list in a
7509f4a2713aSLionel Sambuc // function declarator that is part of a function definition of
7510f4a2713aSLionel Sambuc // that function shall not have incomplete type.
7511f4a2713aSLionel Sambuc //
7512f4a2713aSLionel Sambuc // This is also C++ [dcl.fct]p6.
7513f4a2713aSLionel Sambuc if (!Param->isInvalidDecl() &&
7514f4a2713aSLionel Sambuc RequireCompleteType(Param->getLocation(), Param->getType(),
7515f4a2713aSLionel Sambuc diag::err_typecheck_decl_incomplete_type)) {
7516f4a2713aSLionel Sambuc Param->setInvalidDecl();
7517f4a2713aSLionel Sambuc HasInvalidParm = true;
7518f4a2713aSLionel Sambuc }
7519f4a2713aSLionel Sambuc
7520f4a2713aSLionel Sambuc // C99 6.9.1p5: If the declarator includes a parameter type list, the
7521f4a2713aSLionel Sambuc // declaration of each parameter shall include an identifier.
7522f4a2713aSLionel Sambuc if (CheckParameterNames &&
7523*0a6a1f1dSLionel Sambuc Param->getIdentifier() == nullptr &&
7524f4a2713aSLionel Sambuc !Param->isImplicit() &&
7525f4a2713aSLionel Sambuc !getLangOpts().CPlusPlus)
7526f4a2713aSLionel Sambuc Diag(Param->getLocation(), diag::err_parameter_name_omitted);
7527f4a2713aSLionel Sambuc
7528f4a2713aSLionel Sambuc // C99 6.7.5.3p12:
7529f4a2713aSLionel Sambuc // If the function declarator is not part of a definition of that
7530f4a2713aSLionel Sambuc // function, parameters may have incomplete type and may use the [*]
7531f4a2713aSLionel Sambuc // notation in their sequences of declarator specifiers to specify
7532f4a2713aSLionel Sambuc // variable length array types.
7533f4a2713aSLionel Sambuc QualType PType = Param->getOriginalType();
7534f4a2713aSLionel Sambuc while (const ArrayType *AT = Context.getAsArrayType(PType)) {
7535f4a2713aSLionel Sambuc if (AT->getSizeModifier() == ArrayType::Star) {
7536f4a2713aSLionel Sambuc // FIXME: This diagnostic should point the '[*]' if source-location
7537f4a2713aSLionel Sambuc // information is added for it.
7538f4a2713aSLionel Sambuc Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
7539f4a2713aSLionel Sambuc break;
7540f4a2713aSLionel Sambuc }
7541f4a2713aSLionel Sambuc PType= AT->getElementType();
7542f4a2713aSLionel Sambuc }
7543f4a2713aSLionel Sambuc
7544f4a2713aSLionel Sambuc // MSVC destroys objects passed by value in the callee. Therefore a
7545f4a2713aSLionel Sambuc // function definition which takes such a parameter must be able to call the
7546*0a6a1f1dSLionel Sambuc // object's destructor. However, we don't perform any direct access check
7547*0a6a1f1dSLionel Sambuc // on the dtor.
7548*0a6a1f1dSLionel Sambuc if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7549*0a6a1f1dSLionel Sambuc .getCXXABI()
7550*0a6a1f1dSLionel Sambuc .areArgsDestroyedLeftToRightInCallee()) {
7551*0a6a1f1dSLionel Sambuc if (!Param->isInvalidDecl()) {
7552*0a6a1f1dSLionel Sambuc if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7553*0a6a1f1dSLionel Sambuc CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7554*0a6a1f1dSLionel Sambuc if (!ClassDecl->isInvalidDecl() &&
7555*0a6a1f1dSLionel Sambuc !ClassDecl->hasIrrelevantDestructor() &&
7556*0a6a1f1dSLionel Sambuc !ClassDecl->isDependentContext()) {
7557*0a6a1f1dSLionel Sambuc CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7558*0a6a1f1dSLionel Sambuc MarkFunctionReferenced(Param->getLocation(), Destructor);
7559*0a6a1f1dSLionel Sambuc DiagnoseUseOfDecl(Destructor, Param->getLocation());
7560*0a6a1f1dSLionel Sambuc }
7561*0a6a1f1dSLionel Sambuc }
7562*0a6a1f1dSLionel Sambuc }
7563f4a2713aSLionel Sambuc }
7564f4a2713aSLionel Sambuc }
7565f4a2713aSLionel Sambuc
7566f4a2713aSLionel Sambuc return HasInvalidParm;
7567f4a2713aSLionel Sambuc }
7568f4a2713aSLionel Sambuc
7569f4a2713aSLionel Sambuc /// CheckCastAlign - Implements -Wcast-align, which warns when a
7570f4a2713aSLionel Sambuc /// pointer cast increases the alignment requirements.
CheckCastAlign(Expr * Op,QualType T,SourceRange TRange)7571f4a2713aSLionel Sambuc void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7572f4a2713aSLionel Sambuc // This is actually a lot of work to potentially be doing on every
7573f4a2713aSLionel Sambuc // cast; don't do it if we're ignoring -Wcast_align (as is the default).
7574*0a6a1f1dSLionel Sambuc if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
7575f4a2713aSLionel Sambuc return;
7576f4a2713aSLionel Sambuc
7577f4a2713aSLionel Sambuc // Ignore dependent types.
7578f4a2713aSLionel Sambuc if (T->isDependentType() || Op->getType()->isDependentType())
7579f4a2713aSLionel Sambuc return;
7580f4a2713aSLionel Sambuc
7581f4a2713aSLionel Sambuc // Require that the destination be a pointer type.
7582f4a2713aSLionel Sambuc const PointerType *DestPtr = T->getAs<PointerType>();
7583f4a2713aSLionel Sambuc if (!DestPtr) return;
7584f4a2713aSLionel Sambuc
7585f4a2713aSLionel Sambuc // If the destination has alignment 1, we're done.
7586f4a2713aSLionel Sambuc QualType DestPointee = DestPtr->getPointeeType();
7587f4a2713aSLionel Sambuc if (DestPointee->isIncompleteType()) return;
7588f4a2713aSLionel Sambuc CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7589f4a2713aSLionel Sambuc if (DestAlign.isOne()) return;
7590f4a2713aSLionel Sambuc
7591f4a2713aSLionel Sambuc // Require that the source be a pointer type.
7592f4a2713aSLionel Sambuc const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7593f4a2713aSLionel Sambuc if (!SrcPtr) return;
7594f4a2713aSLionel Sambuc QualType SrcPointee = SrcPtr->getPointeeType();
7595f4a2713aSLionel Sambuc
7596f4a2713aSLionel Sambuc // Whitelist casts from cv void*. We already implicitly
7597f4a2713aSLionel Sambuc // whitelisted casts to cv void*, since they have alignment 1.
7598f4a2713aSLionel Sambuc // Also whitelist casts involving incomplete types, which implicitly
7599f4a2713aSLionel Sambuc // includes 'void'.
7600f4a2713aSLionel Sambuc if (SrcPointee->isIncompleteType()) return;
7601f4a2713aSLionel Sambuc
7602f4a2713aSLionel Sambuc CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7603f4a2713aSLionel Sambuc if (SrcAlign >= DestAlign) return;
7604f4a2713aSLionel Sambuc
7605f4a2713aSLionel Sambuc Diag(TRange.getBegin(), diag::warn_cast_align)
7606f4a2713aSLionel Sambuc << Op->getType() << T
7607f4a2713aSLionel Sambuc << static_cast<unsigned>(SrcAlign.getQuantity())
7608f4a2713aSLionel Sambuc << static_cast<unsigned>(DestAlign.getQuantity())
7609f4a2713aSLionel Sambuc << TRange << Op->getSourceRange();
7610f4a2713aSLionel Sambuc }
7611f4a2713aSLionel Sambuc
getElementType(const Expr * BaseExpr)7612f4a2713aSLionel Sambuc static const Type* getElementType(const Expr *BaseExpr) {
7613f4a2713aSLionel Sambuc const Type* EltType = BaseExpr->getType().getTypePtr();
7614f4a2713aSLionel Sambuc if (EltType->isAnyPointerType())
7615f4a2713aSLionel Sambuc return EltType->getPointeeType().getTypePtr();
7616f4a2713aSLionel Sambuc else if (EltType->isArrayType())
7617f4a2713aSLionel Sambuc return EltType->getBaseElementTypeUnsafe();
7618f4a2713aSLionel Sambuc return EltType;
7619f4a2713aSLionel Sambuc }
7620f4a2713aSLionel Sambuc
7621f4a2713aSLionel Sambuc /// \brief Check whether this array fits the idiom of a size-one tail padded
7622f4a2713aSLionel Sambuc /// array member of a struct.
7623f4a2713aSLionel Sambuc ///
7624f4a2713aSLionel Sambuc /// We avoid emitting out-of-bounds access warnings for such arrays as they are
7625f4a2713aSLionel Sambuc /// commonly used to emulate flexible arrays in C89 code.
IsTailPaddedMemberArray(Sema & S,llvm::APInt Size,const NamedDecl * ND)7626f4a2713aSLionel Sambuc static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7627f4a2713aSLionel Sambuc const NamedDecl *ND) {
7628f4a2713aSLionel Sambuc if (Size != 1 || !ND) return false;
7629f4a2713aSLionel Sambuc
7630f4a2713aSLionel Sambuc const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7631f4a2713aSLionel Sambuc if (!FD) return false;
7632f4a2713aSLionel Sambuc
7633f4a2713aSLionel Sambuc // Don't consider sizes resulting from macro expansions or template argument
7634f4a2713aSLionel Sambuc // substitution to form C89 tail-padded arrays.
7635f4a2713aSLionel Sambuc
7636f4a2713aSLionel Sambuc TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
7637f4a2713aSLionel Sambuc while (TInfo) {
7638f4a2713aSLionel Sambuc TypeLoc TL = TInfo->getTypeLoc();
7639f4a2713aSLionel Sambuc // Look through typedefs.
7640f4a2713aSLionel Sambuc if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7641f4a2713aSLionel Sambuc const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
7642f4a2713aSLionel Sambuc TInfo = TDL->getTypeSourceInfo();
7643f4a2713aSLionel Sambuc continue;
7644f4a2713aSLionel Sambuc }
7645f4a2713aSLionel Sambuc if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7646f4a2713aSLionel Sambuc const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
7647f4a2713aSLionel Sambuc if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7648f4a2713aSLionel Sambuc return false;
7649f4a2713aSLionel Sambuc }
7650f4a2713aSLionel Sambuc break;
7651f4a2713aSLionel Sambuc }
7652f4a2713aSLionel Sambuc
7653f4a2713aSLionel Sambuc const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
7654f4a2713aSLionel Sambuc if (!RD) return false;
7655f4a2713aSLionel Sambuc if (RD->isUnion()) return false;
7656f4a2713aSLionel Sambuc if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7657f4a2713aSLionel Sambuc if (!CRD->isStandardLayout()) return false;
7658f4a2713aSLionel Sambuc }
7659f4a2713aSLionel Sambuc
7660f4a2713aSLionel Sambuc // See if this is the last field decl in the record.
7661f4a2713aSLionel Sambuc const Decl *D = FD;
7662f4a2713aSLionel Sambuc while ((D = D->getNextDeclInContext()))
7663f4a2713aSLionel Sambuc if (isa<FieldDecl>(D))
7664f4a2713aSLionel Sambuc return false;
7665f4a2713aSLionel Sambuc return true;
7666f4a2713aSLionel Sambuc }
7667f4a2713aSLionel Sambuc
CheckArrayAccess(const Expr * BaseExpr,const Expr * IndexExpr,const ArraySubscriptExpr * ASE,bool AllowOnePastEnd,bool IndexNegated)7668f4a2713aSLionel Sambuc void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7669f4a2713aSLionel Sambuc const ArraySubscriptExpr *ASE,
7670f4a2713aSLionel Sambuc bool AllowOnePastEnd, bool IndexNegated) {
7671f4a2713aSLionel Sambuc IndexExpr = IndexExpr->IgnoreParenImpCasts();
7672f4a2713aSLionel Sambuc if (IndexExpr->isValueDependent())
7673f4a2713aSLionel Sambuc return;
7674f4a2713aSLionel Sambuc
7675f4a2713aSLionel Sambuc const Type *EffectiveType = getElementType(BaseExpr);
7676f4a2713aSLionel Sambuc BaseExpr = BaseExpr->IgnoreParenCasts();
7677f4a2713aSLionel Sambuc const ConstantArrayType *ArrayTy =
7678f4a2713aSLionel Sambuc Context.getAsConstantArrayType(BaseExpr->getType());
7679f4a2713aSLionel Sambuc if (!ArrayTy)
7680f4a2713aSLionel Sambuc return;
7681f4a2713aSLionel Sambuc
7682f4a2713aSLionel Sambuc llvm::APSInt index;
7683f4a2713aSLionel Sambuc if (!IndexExpr->EvaluateAsInt(index, Context))
7684f4a2713aSLionel Sambuc return;
7685f4a2713aSLionel Sambuc if (IndexNegated)
7686f4a2713aSLionel Sambuc index = -index;
7687f4a2713aSLionel Sambuc
7688*0a6a1f1dSLionel Sambuc const NamedDecl *ND = nullptr;
7689f4a2713aSLionel Sambuc if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7690f4a2713aSLionel Sambuc ND = dyn_cast<NamedDecl>(DRE->getDecl());
7691f4a2713aSLionel Sambuc if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7692f4a2713aSLionel Sambuc ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7693f4a2713aSLionel Sambuc
7694f4a2713aSLionel Sambuc if (index.isUnsigned() || !index.isNegative()) {
7695f4a2713aSLionel Sambuc llvm::APInt size = ArrayTy->getSize();
7696f4a2713aSLionel Sambuc if (!size.isStrictlyPositive())
7697f4a2713aSLionel Sambuc return;
7698f4a2713aSLionel Sambuc
7699f4a2713aSLionel Sambuc const Type* BaseType = getElementType(BaseExpr);
7700f4a2713aSLionel Sambuc if (BaseType != EffectiveType) {
7701f4a2713aSLionel Sambuc // Make sure we're comparing apples to apples when comparing index to size
7702f4a2713aSLionel Sambuc uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7703f4a2713aSLionel Sambuc uint64_t array_typesize = Context.getTypeSize(BaseType);
7704f4a2713aSLionel Sambuc // Handle ptrarith_typesize being zero, such as when casting to void*
7705f4a2713aSLionel Sambuc if (!ptrarith_typesize) ptrarith_typesize = 1;
7706f4a2713aSLionel Sambuc if (ptrarith_typesize != array_typesize) {
7707f4a2713aSLionel Sambuc // There's a cast to a different size type involved
7708f4a2713aSLionel Sambuc uint64_t ratio = array_typesize / ptrarith_typesize;
7709f4a2713aSLionel Sambuc // TODO: Be smarter about handling cases where array_typesize is not a
7710f4a2713aSLionel Sambuc // multiple of ptrarith_typesize
7711f4a2713aSLionel Sambuc if (ptrarith_typesize * ratio == array_typesize)
7712f4a2713aSLionel Sambuc size *= llvm::APInt(size.getBitWidth(), ratio);
7713f4a2713aSLionel Sambuc }
7714f4a2713aSLionel Sambuc }
7715f4a2713aSLionel Sambuc
7716f4a2713aSLionel Sambuc if (size.getBitWidth() > index.getBitWidth())
7717f4a2713aSLionel Sambuc index = index.zext(size.getBitWidth());
7718f4a2713aSLionel Sambuc else if (size.getBitWidth() < index.getBitWidth())
7719f4a2713aSLionel Sambuc size = size.zext(index.getBitWidth());
7720f4a2713aSLionel Sambuc
7721f4a2713aSLionel Sambuc // For array subscripting the index must be less than size, but for pointer
7722f4a2713aSLionel Sambuc // arithmetic also allow the index (offset) to be equal to size since
7723f4a2713aSLionel Sambuc // computing the next address after the end of the array is legal and
7724f4a2713aSLionel Sambuc // commonly done e.g. in C++ iterators and range-based for loops.
7725f4a2713aSLionel Sambuc if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
7726f4a2713aSLionel Sambuc return;
7727f4a2713aSLionel Sambuc
7728f4a2713aSLionel Sambuc // Also don't warn for arrays of size 1 which are members of some
7729f4a2713aSLionel Sambuc // structure. These are often used to approximate flexible arrays in C89
7730f4a2713aSLionel Sambuc // code.
7731f4a2713aSLionel Sambuc if (IsTailPaddedMemberArray(*this, size, ND))
7732f4a2713aSLionel Sambuc return;
7733f4a2713aSLionel Sambuc
7734f4a2713aSLionel Sambuc // Suppress the warning if the subscript expression (as identified by the
7735f4a2713aSLionel Sambuc // ']' location) and the index expression are both from macro expansions
7736f4a2713aSLionel Sambuc // within a system header.
7737f4a2713aSLionel Sambuc if (ASE) {
7738f4a2713aSLionel Sambuc SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7739f4a2713aSLionel Sambuc ASE->getRBracketLoc());
7740f4a2713aSLionel Sambuc if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7741f4a2713aSLionel Sambuc SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7742f4a2713aSLionel Sambuc IndexExpr->getLocStart());
7743f4a2713aSLionel Sambuc if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
7744f4a2713aSLionel Sambuc return;
7745f4a2713aSLionel Sambuc }
7746f4a2713aSLionel Sambuc }
7747f4a2713aSLionel Sambuc
7748f4a2713aSLionel Sambuc unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
7749f4a2713aSLionel Sambuc if (ASE)
7750f4a2713aSLionel Sambuc DiagID = diag::warn_array_index_exceeds_bounds;
7751f4a2713aSLionel Sambuc
7752f4a2713aSLionel Sambuc DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7753f4a2713aSLionel Sambuc PDiag(DiagID) << index.toString(10, true)
7754f4a2713aSLionel Sambuc << size.toString(10, true)
7755f4a2713aSLionel Sambuc << (unsigned)size.getLimitedValue(~0U)
7756f4a2713aSLionel Sambuc << IndexExpr->getSourceRange());
7757f4a2713aSLionel Sambuc } else {
7758f4a2713aSLionel Sambuc unsigned DiagID = diag::warn_array_index_precedes_bounds;
7759f4a2713aSLionel Sambuc if (!ASE) {
7760f4a2713aSLionel Sambuc DiagID = diag::warn_ptr_arith_precedes_bounds;
7761f4a2713aSLionel Sambuc if (index.isNegative()) index = -index;
7762f4a2713aSLionel Sambuc }
7763f4a2713aSLionel Sambuc
7764f4a2713aSLionel Sambuc DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7765f4a2713aSLionel Sambuc PDiag(DiagID) << index.toString(10, true)
7766f4a2713aSLionel Sambuc << IndexExpr->getSourceRange());
7767f4a2713aSLionel Sambuc }
7768f4a2713aSLionel Sambuc
7769f4a2713aSLionel Sambuc if (!ND) {
7770f4a2713aSLionel Sambuc // Try harder to find a NamedDecl to point at in the note.
7771f4a2713aSLionel Sambuc while (const ArraySubscriptExpr *ASE =
7772f4a2713aSLionel Sambuc dyn_cast<ArraySubscriptExpr>(BaseExpr))
7773f4a2713aSLionel Sambuc BaseExpr = ASE->getBase()->IgnoreParenCasts();
7774f4a2713aSLionel Sambuc if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7775f4a2713aSLionel Sambuc ND = dyn_cast<NamedDecl>(DRE->getDecl());
7776f4a2713aSLionel Sambuc if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7777f4a2713aSLionel Sambuc ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7778f4a2713aSLionel Sambuc }
7779f4a2713aSLionel Sambuc
7780f4a2713aSLionel Sambuc if (ND)
7781f4a2713aSLionel Sambuc DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7782f4a2713aSLionel Sambuc PDiag(diag::note_array_index_out_of_bounds)
7783f4a2713aSLionel Sambuc << ND->getDeclName());
7784f4a2713aSLionel Sambuc }
7785f4a2713aSLionel Sambuc
CheckArrayAccess(const Expr * expr)7786f4a2713aSLionel Sambuc void Sema::CheckArrayAccess(const Expr *expr) {
7787f4a2713aSLionel Sambuc int AllowOnePastEnd = 0;
7788f4a2713aSLionel Sambuc while (expr) {
7789f4a2713aSLionel Sambuc expr = expr->IgnoreParenImpCasts();
7790f4a2713aSLionel Sambuc switch (expr->getStmtClass()) {
7791f4a2713aSLionel Sambuc case Stmt::ArraySubscriptExprClass: {
7792f4a2713aSLionel Sambuc const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
7793f4a2713aSLionel Sambuc CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
7794f4a2713aSLionel Sambuc AllowOnePastEnd > 0);
7795f4a2713aSLionel Sambuc return;
7796f4a2713aSLionel Sambuc }
7797f4a2713aSLionel Sambuc case Stmt::UnaryOperatorClass: {
7798f4a2713aSLionel Sambuc // Only unwrap the * and & unary operators
7799f4a2713aSLionel Sambuc const UnaryOperator *UO = cast<UnaryOperator>(expr);
7800f4a2713aSLionel Sambuc expr = UO->getSubExpr();
7801f4a2713aSLionel Sambuc switch (UO->getOpcode()) {
7802f4a2713aSLionel Sambuc case UO_AddrOf:
7803f4a2713aSLionel Sambuc AllowOnePastEnd++;
7804f4a2713aSLionel Sambuc break;
7805f4a2713aSLionel Sambuc case UO_Deref:
7806f4a2713aSLionel Sambuc AllowOnePastEnd--;
7807f4a2713aSLionel Sambuc break;
7808f4a2713aSLionel Sambuc default:
7809f4a2713aSLionel Sambuc return;
7810f4a2713aSLionel Sambuc }
7811f4a2713aSLionel Sambuc break;
7812f4a2713aSLionel Sambuc }
7813f4a2713aSLionel Sambuc case Stmt::ConditionalOperatorClass: {
7814f4a2713aSLionel Sambuc const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7815f4a2713aSLionel Sambuc if (const Expr *lhs = cond->getLHS())
7816f4a2713aSLionel Sambuc CheckArrayAccess(lhs);
7817f4a2713aSLionel Sambuc if (const Expr *rhs = cond->getRHS())
7818f4a2713aSLionel Sambuc CheckArrayAccess(rhs);
7819f4a2713aSLionel Sambuc return;
7820f4a2713aSLionel Sambuc }
7821f4a2713aSLionel Sambuc default:
7822f4a2713aSLionel Sambuc return;
7823f4a2713aSLionel Sambuc }
7824f4a2713aSLionel Sambuc }
7825f4a2713aSLionel Sambuc }
7826f4a2713aSLionel Sambuc
7827f4a2713aSLionel Sambuc //===--- CHECK: Objective-C retain cycles ----------------------------------//
7828f4a2713aSLionel Sambuc
7829f4a2713aSLionel Sambuc namespace {
7830f4a2713aSLionel Sambuc struct RetainCycleOwner {
RetainCycleOwner__anon0a2745240b11::RetainCycleOwner7831*0a6a1f1dSLionel Sambuc RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
7832f4a2713aSLionel Sambuc VarDecl *Variable;
7833f4a2713aSLionel Sambuc SourceRange Range;
7834f4a2713aSLionel Sambuc SourceLocation Loc;
7835f4a2713aSLionel Sambuc bool Indirect;
7836f4a2713aSLionel Sambuc
setLocsFrom__anon0a2745240b11::RetainCycleOwner7837f4a2713aSLionel Sambuc void setLocsFrom(Expr *e) {
7838f4a2713aSLionel Sambuc Loc = e->getExprLoc();
7839f4a2713aSLionel Sambuc Range = e->getSourceRange();
7840f4a2713aSLionel Sambuc }
7841f4a2713aSLionel Sambuc };
7842f4a2713aSLionel Sambuc }
7843f4a2713aSLionel Sambuc
7844f4a2713aSLionel Sambuc /// Consider whether capturing the given variable can possibly lead to
7845f4a2713aSLionel Sambuc /// a retain cycle.
considerVariable(VarDecl * var,Expr * ref,RetainCycleOwner & owner)7846f4a2713aSLionel Sambuc static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
7847f4a2713aSLionel Sambuc // In ARC, it's captured strongly iff the variable has __strong
7848f4a2713aSLionel Sambuc // lifetime. In MRR, it's captured strongly if the variable is
7849f4a2713aSLionel Sambuc // __block and has an appropriate type.
7850f4a2713aSLionel Sambuc if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7851f4a2713aSLionel Sambuc return false;
7852f4a2713aSLionel Sambuc
7853f4a2713aSLionel Sambuc owner.Variable = var;
7854f4a2713aSLionel Sambuc if (ref)
7855f4a2713aSLionel Sambuc owner.setLocsFrom(ref);
7856f4a2713aSLionel Sambuc return true;
7857f4a2713aSLionel Sambuc }
7858f4a2713aSLionel Sambuc
findRetainCycleOwner(Sema & S,Expr * e,RetainCycleOwner & owner)7859f4a2713aSLionel Sambuc static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
7860f4a2713aSLionel Sambuc while (true) {
7861f4a2713aSLionel Sambuc e = e->IgnoreParens();
7862f4a2713aSLionel Sambuc if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7863f4a2713aSLionel Sambuc switch (cast->getCastKind()) {
7864f4a2713aSLionel Sambuc case CK_BitCast:
7865f4a2713aSLionel Sambuc case CK_LValueBitCast:
7866f4a2713aSLionel Sambuc case CK_LValueToRValue:
7867f4a2713aSLionel Sambuc case CK_ARCReclaimReturnedObject:
7868f4a2713aSLionel Sambuc e = cast->getSubExpr();
7869f4a2713aSLionel Sambuc continue;
7870f4a2713aSLionel Sambuc
7871f4a2713aSLionel Sambuc default:
7872f4a2713aSLionel Sambuc return false;
7873f4a2713aSLionel Sambuc }
7874f4a2713aSLionel Sambuc }
7875f4a2713aSLionel Sambuc
7876f4a2713aSLionel Sambuc if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7877f4a2713aSLionel Sambuc ObjCIvarDecl *ivar = ref->getDecl();
7878f4a2713aSLionel Sambuc if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7879f4a2713aSLionel Sambuc return false;
7880f4a2713aSLionel Sambuc
7881f4a2713aSLionel Sambuc // Try to find a retain cycle in the base.
7882f4a2713aSLionel Sambuc if (!findRetainCycleOwner(S, ref->getBase(), owner))
7883f4a2713aSLionel Sambuc return false;
7884f4a2713aSLionel Sambuc
7885f4a2713aSLionel Sambuc if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7886f4a2713aSLionel Sambuc owner.Indirect = true;
7887f4a2713aSLionel Sambuc return true;
7888f4a2713aSLionel Sambuc }
7889f4a2713aSLionel Sambuc
7890f4a2713aSLionel Sambuc if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7891f4a2713aSLionel Sambuc VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7892f4a2713aSLionel Sambuc if (!var) return false;
7893f4a2713aSLionel Sambuc return considerVariable(var, ref, owner);
7894f4a2713aSLionel Sambuc }
7895f4a2713aSLionel Sambuc
7896f4a2713aSLionel Sambuc if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7897f4a2713aSLionel Sambuc if (member->isArrow()) return false;
7898f4a2713aSLionel Sambuc
7899f4a2713aSLionel Sambuc // Don't count this as an indirect ownership.
7900f4a2713aSLionel Sambuc e = member->getBase();
7901f4a2713aSLionel Sambuc continue;
7902f4a2713aSLionel Sambuc }
7903f4a2713aSLionel Sambuc
7904f4a2713aSLionel Sambuc if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7905f4a2713aSLionel Sambuc // Only pay attention to pseudo-objects on property references.
7906f4a2713aSLionel Sambuc ObjCPropertyRefExpr *pre
7907f4a2713aSLionel Sambuc = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7908f4a2713aSLionel Sambuc ->IgnoreParens());
7909f4a2713aSLionel Sambuc if (!pre) return false;
7910f4a2713aSLionel Sambuc if (pre->isImplicitProperty()) return false;
7911f4a2713aSLionel Sambuc ObjCPropertyDecl *property = pre->getExplicitProperty();
7912f4a2713aSLionel Sambuc if (!property->isRetaining() &&
7913f4a2713aSLionel Sambuc !(property->getPropertyIvarDecl() &&
7914f4a2713aSLionel Sambuc property->getPropertyIvarDecl()->getType()
7915f4a2713aSLionel Sambuc .getObjCLifetime() == Qualifiers::OCL_Strong))
7916f4a2713aSLionel Sambuc return false;
7917f4a2713aSLionel Sambuc
7918f4a2713aSLionel Sambuc owner.Indirect = true;
7919f4a2713aSLionel Sambuc if (pre->isSuperReceiver()) {
7920f4a2713aSLionel Sambuc owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7921f4a2713aSLionel Sambuc if (!owner.Variable)
7922f4a2713aSLionel Sambuc return false;
7923f4a2713aSLionel Sambuc owner.Loc = pre->getLocation();
7924f4a2713aSLionel Sambuc owner.Range = pre->getSourceRange();
7925f4a2713aSLionel Sambuc return true;
7926f4a2713aSLionel Sambuc }
7927f4a2713aSLionel Sambuc e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7928f4a2713aSLionel Sambuc ->getSourceExpr());
7929f4a2713aSLionel Sambuc continue;
7930f4a2713aSLionel Sambuc }
7931f4a2713aSLionel Sambuc
7932f4a2713aSLionel Sambuc // Array ivars?
7933f4a2713aSLionel Sambuc
7934f4a2713aSLionel Sambuc return false;
7935f4a2713aSLionel Sambuc }
7936f4a2713aSLionel Sambuc }
7937f4a2713aSLionel Sambuc
7938f4a2713aSLionel Sambuc namespace {
7939f4a2713aSLionel Sambuc struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
FindCaptureVisitor__anon0a2745240c11::FindCaptureVisitor7940f4a2713aSLionel Sambuc FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7941f4a2713aSLionel Sambuc : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7942*0a6a1f1dSLionel Sambuc Context(Context), Variable(variable), Capturer(nullptr),
7943*0a6a1f1dSLionel Sambuc VarWillBeReased(false) {}
7944*0a6a1f1dSLionel Sambuc ASTContext &Context;
7945f4a2713aSLionel Sambuc VarDecl *Variable;
7946f4a2713aSLionel Sambuc Expr *Capturer;
7947*0a6a1f1dSLionel Sambuc bool VarWillBeReased;
7948f4a2713aSLionel Sambuc
VisitDeclRefExpr__anon0a2745240c11::FindCaptureVisitor7949f4a2713aSLionel Sambuc void VisitDeclRefExpr(DeclRefExpr *ref) {
7950f4a2713aSLionel Sambuc if (ref->getDecl() == Variable && !Capturer)
7951f4a2713aSLionel Sambuc Capturer = ref;
7952f4a2713aSLionel Sambuc }
7953f4a2713aSLionel Sambuc
VisitObjCIvarRefExpr__anon0a2745240c11::FindCaptureVisitor7954f4a2713aSLionel Sambuc void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7955f4a2713aSLionel Sambuc if (Capturer) return;
7956f4a2713aSLionel Sambuc Visit(ref->getBase());
7957f4a2713aSLionel Sambuc if (Capturer && ref->isFreeIvar())
7958f4a2713aSLionel Sambuc Capturer = ref;
7959f4a2713aSLionel Sambuc }
7960f4a2713aSLionel Sambuc
VisitBlockExpr__anon0a2745240c11::FindCaptureVisitor7961f4a2713aSLionel Sambuc void VisitBlockExpr(BlockExpr *block) {
7962f4a2713aSLionel Sambuc // Look inside nested blocks
7963f4a2713aSLionel Sambuc if (block->getBlockDecl()->capturesVariable(Variable))
7964f4a2713aSLionel Sambuc Visit(block->getBlockDecl()->getBody());
7965f4a2713aSLionel Sambuc }
7966f4a2713aSLionel Sambuc
VisitOpaqueValueExpr__anon0a2745240c11::FindCaptureVisitor7967f4a2713aSLionel Sambuc void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7968f4a2713aSLionel Sambuc if (Capturer) return;
7969f4a2713aSLionel Sambuc if (OVE->getSourceExpr())
7970f4a2713aSLionel Sambuc Visit(OVE->getSourceExpr());
7971f4a2713aSLionel Sambuc }
VisitBinaryOperator__anon0a2745240c11::FindCaptureVisitor7972*0a6a1f1dSLionel Sambuc void VisitBinaryOperator(BinaryOperator *BinOp) {
7973*0a6a1f1dSLionel Sambuc if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7974*0a6a1f1dSLionel Sambuc return;
7975*0a6a1f1dSLionel Sambuc Expr *LHS = BinOp->getLHS();
7976*0a6a1f1dSLionel Sambuc if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7977*0a6a1f1dSLionel Sambuc if (DRE->getDecl() != Variable)
7978*0a6a1f1dSLionel Sambuc return;
7979*0a6a1f1dSLionel Sambuc if (Expr *RHS = BinOp->getRHS()) {
7980*0a6a1f1dSLionel Sambuc RHS = RHS->IgnoreParenCasts();
7981*0a6a1f1dSLionel Sambuc llvm::APSInt Value;
7982*0a6a1f1dSLionel Sambuc VarWillBeReased =
7983*0a6a1f1dSLionel Sambuc (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7984*0a6a1f1dSLionel Sambuc }
7985*0a6a1f1dSLionel Sambuc }
7986*0a6a1f1dSLionel Sambuc }
7987f4a2713aSLionel Sambuc };
7988f4a2713aSLionel Sambuc }
7989f4a2713aSLionel Sambuc
7990f4a2713aSLionel Sambuc /// Check whether the given argument is a block which captures a
7991f4a2713aSLionel Sambuc /// variable.
findCapturingExpr(Sema & S,Expr * e,RetainCycleOwner & owner)7992f4a2713aSLionel Sambuc static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7993f4a2713aSLionel Sambuc assert(owner.Variable && owner.Loc.isValid());
7994f4a2713aSLionel Sambuc
7995f4a2713aSLionel Sambuc e = e->IgnoreParenCasts();
7996f4a2713aSLionel Sambuc
7997f4a2713aSLionel Sambuc // Look through [^{...} copy] and Block_copy(^{...}).
7998f4a2713aSLionel Sambuc if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7999f4a2713aSLionel Sambuc Selector Cmd = ME->getSelector();
8000f4a2713aSLionel Sambuc if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8001f4a2713aSLionel Sambuc e = ME->getInstanceReceiver();
8002f4a2713aSLionel Sambuc if (!e)
8003*0a6a1f1dSLionel Sambuc return nullptr;
8004f4a2713aSLionel Sambuc e = e->IgnoreParenCasts();
8005f4a2713aSLionel Sambuc }
8006f4a2713aSLionel Sambuc } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8007f4a2713aSLionel Sambuc if (CE->getNumArgs() == 1) {
8008f4a2713aSLionel Sambuc FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
8009f4a2713aSLionel Sambuc if (Fn) {
8010f4a2713aSLionel Sambuc const IdentifierInfo *FnI = Fn->getIdentifier();
8011f4a2713aSLionel Sambuc if (FnI && FnI->isStr("_Block_copy")) {
8012f4a2713aSLionel Sambuc e = CE->getArg(0)->IgnoreParenCasts();
8013f4a2713aSLionel Sambuc }
8014f4a2713aSLionel Sambuc }
8015f4a2713aSLionel Sambuc }
8016f4a2713aSLionel Sambuc }
8017f4a2713aSLionel Sambuc
8018f4a2713aSLionel Sambuc BlockExpr *block = dyn_cast<BlockExpr>(e);
8019f4a2713aSLionel Sambuc if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
8020*0a6a1f1dSLionel Sambuc return nullptr;
8021f4a2713aSLionel Sambuc
8022f4a2713aSLionel Sambuc FindCaptureVisitor visitor(S.Context, owner.Variable);
8023f4a2713aSLionel Sambuc visitor.Visit(block->getBlockDecl()->getBody());
8024*0a6a1f1dSLionel Sambuc return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
8025f4a2713aSLionel Sambuc }
8026f4a2713aSLionel Sambuc
diagnoseRetainCycle(Sema & S,Expr * capturer,RetainCycleOwner & owner)8027f4a2713aSLionel Sambuc static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8028f4a2713aSLionel Sambuc RetainCycleOwner &owner) {
8029f4a2713aSLionel Sambuc assert(capturer);
8030f4a2713aSLionel Sambuc assert(owner.Variable && owner.Loc.isValid());
8031f4a2713aSLionel Sambuc
8032f4a2713aSLionel Sambuc S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8033f4a2713aSLionel Sambuc << owner.Variable << capturer->getSourceRange();
8034f4a2713aSLionel Sambuc S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8035f4a2713aSLionel Sambuc << owner.Indirect << owner.Range;
8036f4a2713aSLionel Sambuc }
8037f4a2713aSLionel Sambuc
8038f4a2713aSLionel Sambuc /// Check for a keyword selector that starts with the word 'add' or
8039f4a2713aSLionel Sambuc /// 'set'.
isSetterLikeSelector(Selector sel)8040f4a2713aSLionel Sambuc static bool isSetterLikeSelector(Selector sel) {
8041f4a2713aSLionel Sambuc if (sel.isUnarySelector()) return false;
8042f4a2713aSLionel Sambuc
8043f4a2713aSLionel Sambuc StringRef str = sel.getNameForSlot(0);
8044f4a2713aSLionel Sambuc while (!str.empty() && str.front() == '_') str = str.substr(1);
8045f4a2713aSLionel Sambuc if (str.startswith("set"))
8046f4a2713aSLionel Sambuc str = str.substr(3);
8047f4a2713aSLionel Sambuc else if (str.startswith("add")) {
8048f4a2713aSLionel Sambuc // Specially whitelist 'addOperationWithBlock:'.
8049f4a2713aSLionel Sambuc if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8050f4a2713aSLionel Sambuc return false;
8051f4a2713aSLionel Sambuc str = str.substr(3);
8052f4a2713aSLionel Sambuc }
8053f4a2713aSLionel Sambuc else
8054f4a2713aSLionel Sambuc return false;
8055f4a2713aSLionel Sambuc
8056f4a2713aSLionel Sambuc if (str.empty()) return true;
8057f4a2713aSLionel Sambuc return !isLowercase(str.front());
8058f4a2713aSLionel Sambuc }
8059f4a2713aSLionel Sambuc
8060f4a2713aSLionel Sambuc /// Check a message send to see if it's likely to cause a retain cycle.
checkRetainCycles(ObjCMessageExpr * msg)8061f4a2713aSLionel Sambuc void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8062f4a2713aSLionel Sambuc // Only check instance methods whose selector looks like a setter.
8063f4a2713aSLionel Sambuc if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8064f4a2713aSLionel Sambuc return;
8065f4a2713aSLionel Sambuc
8066f4a2713aSLionel Sambuc // Try to find a variable that the receiver is strongly owned by.
8067f4a2713aSLionel Sambuc RetainCycleOwner owner;
8068f4a2713aSLionel Sambuc if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
8069f4a2713aSLionel Sambuc if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
8070f4a2713aSLionel Sambuc return;
8071f4a2713aSLionel Sambuc } else {
8072f4a2713aSLionel Sambuc assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8073f4a2713aSLionel Sambuc owner.Variable = getCurMethodDecl()->getSelfDecl();
8074f4a2713aSLionel Sambuc owner.Loc = msg->getSuperLoc();
8075f4a2713aSLionel Sambuc owner.Range = msg->getSuperLoc();
8076f4a2713aSLionel Sambuc }
8077f4a2713aSLionel Sambuc
8078f4a2713aSLionel Sambuc // Check whether the receiver is captured by any of the arguments.
8079f4a2713aSLionel Sambuc for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8080f4a2713aSLionel Sambuc if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8081f4a2713aSLionel Sambuc return diagnoseRetainCycle(*this, capturer, owner);
8082f4a2713aSLionel Sambuc }
8083f4a2713aSLionel Sambuc
8084f4a2713aSLionel Sambuc /// Check a property assign to see if it's likely to cause a retain cycle.
checkRetainCycles(Expr * receiver,Expr * argument)8085f4a2713aSLionel Sambuc void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8086f4a2713aSLionel Sambuc RetainCycleOwner owner;
8087f4a2713aSLionel Sambuc if (!findRetainCycleOwner(*this, receiver, owner))
8088f4a2713aSLionel Sambuc return;
8089f4a2713aSLionel Sambuc
8090f4a2713aSLionel Sambuc if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8091f4a2713aSLionel Sambuc diagnoseRetainCycle(*this, capturer, owner);
8092f4a2713aSLionel Sambuc }
8093f4a2713aSLionel Sambuc
checkRetainCycles(VarDecl * Var,Expr * Init)8094f4a2713aSLionel Sambuc void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8095f4a2713aSLionel Sambuc RetainCycleOwner Owner;
8096*0a6a1f1dSLionel Sambuc if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
8097f4a2713aSLionel Sambuc return;
8098f4a2713aSLionel Sambuc
8099f4a2713aSLionel Sambuc // Because we don't have an expression for the variable, we have to set the
8100f4a2713aSLionel Sambuc // location explicitly here.
8101f4a2713aSLionel Sambuc Owner.Loc = Var->getLocation();
8102f4a2713aSLionel Sambuc Owner.Range = Var->getSourceRange();
8103f4a2713aSLionel Sambuc
8104f4a2713aSLionel Sambuc if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8105f4a2713aSLionel Sambuc diagnoseRetainCycle(*this, Capturer, Owner);
8106f4a2713aSLionel Sambuc }
8107f4a2713aSLionel Sambuc
checkUnsafeAssignLiteral(Sema & S,SourceLocation Loc,Expr * RHS,bool isProperty)8108f4a2713aSLionel Sambuc static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8109f4a2713aSLionel Sambuc Expr *RHS, bool isProperty) {
8110f4a2713aSLionel Sambuc // Check if RHS is an Objective-C object literal, which also can get
8111f4a2713aSLionel Sambuc // immediately zapped in a weak reference. Note that we explicitly
8112f4a2713aSLionel Sambuc // allow ObjCStringLiterals, since those are designed to never really die.
8113f4a2713aSLionel Sambuc RHS = RHS->IgnoreParenImpCasts();
8114f4a2713aSLionel Sambuc
8115f4a2713aSLionel Sambuc // This enum needs to match with the 'select' in
8116f4a2713aSLionel Sambuc // warn_objc_arc_literal_assign (off-by-1).
8117f4a2713aSLionel Sambuc Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8118f4a2713aSLionel Sambuc if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8119f4a2713aSLionel Sambuc return false;
8120f4a2713aSLionel Sambuc
8121f4a2713aSLionel Sambuc S.Diag(Loc, diag::warn_arc_literal_assign)
8122f4a2713aSLionel Sambuc << (unsigned) Kind
8123f4a2713aSLionel Sambuc << (isProperty ? 0 : 1)
8124f4a2713aSLionel Sambuc << RHS->getSourceRange();
8125f4a2713aSLionel Sambuc
8126f4a2713aSLionel Sambuc return true;
8127f4a2713aSLionel Sambuc }
8128f4a2713aSLionel Sambuc
checkUnsafeAssignObject(Sema & S,SourceLocation Loc,Qualifiers::ObjCLifetime LT,Expr * RHS,bool isProperty)8129f4a2713aSLionel Sambuc static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8130f4a2713aSLionel Sambuc Qualifiers::ObjCLifetime LT,
8131f4a2713aSLionel Sambuc Expr *RHS, bool isProperty) {
8132f4a2713aSLionel Sambuc // Strip off any implicit cast added to get to the one ARC-specific.
8133f4a2713aSLionel Sambuc while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8134f4a2713aSLionel Sambuc if (cast->getCastKind() == CK_ARCConsumeObject) {
8135f4a2713aSLionel Sambuc S.Diag(Loc, diag::warn_arc_retained_assign)
8136f4a2713aSLionel Sambuc << (LT == Qualifiers::OCL_ExplicitNone)
8137f4a2713aSLionel Sambuc << (isProperty ? 0 : 1)
8138f4a2713aSLionel Sambuc << RHS->getSourceRange();
8139f4a2713aSLionel Sambuc return true;
8140f4a2713aSLionel Sambuc }
8141f4a2713aSLionel Sambuc RHS = cast->getSubExpr();
8142f4a2713aSLionel Sambuc }
8143f4a2713aSLionel Sambuc
8144f4a2713aSLionel Sambuc if (LT == Qualifiers::OCL_Weak &&
8145f4a2713aSLionel Sambuc checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8146f4a2713aSLionel Sambuc return true;
8147f4a2713aSLionel Sambuc
8148f4a2713aSLionel Sambuc return false;
8149f4a2713aSLionel Sambuc }
8150f4a2713aSLionel Sambuc
checkUnsafeAssigns(SourceLocation Loc,QualType LHS,Expr * RHS)8151f4a2713aSLionel Sambuc bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8152f4a2713aSLionel Sambuc QualType LHS, Expr *RHS) {
8153f4a2713aSLionel Sambuc Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8154f4a2713aSLionel Sambuc
8155f4a2713aSLionel Sambuc if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8156f4a2713aSLionel Sambuc return false;
8157f4a2713aSLionel Sambuc
8158f4a2713aSLionel Sambuc if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8159f4a2713aSLionel Sambuc return true;
8160f4a2713aSLionel Sambuc
8161f4a2713aSLionel Sambuc return false;
8162f4a2713aSLionel Sambuc }
8163f4a2713aSLionel Sambuc
checkUnsafeExprAssigns(SourceLocation Loc,Expr * LHS,Expr * RHS)8164f4a2713aSLionel Sambuc void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8165f4a2713aSLionel Sambuc Expr *LHS, Expr *RHS) {
8166f4a2713aSLionel Sambuc QualType LHSType;
8167f4a2713aSLionel Sambuc // PropertyRef on LHS type need be directly obtained from
8168*0a6a1f1dSLionel Sambuc // its declaration as it has a PseudoType.
8169f4a2713aSLionel Sambuc ObjCPropertyRefExpr *PRE
8170f4a2713aSLionel Sambuc = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8171f4a2713aSLionel Sambuc if (PRE && !PRE->isImplicitProperty()) {
8172f4a2713aSLionel Sambuc const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8173f4a2713aSLionel Sambuc if (PD)
8174f4a2713aSLionel Sambuc LHSType = PD->getType();
8175f4a2713aSLionel Sambuc }
8176f4a2713aSLionel Sambuc
8177f4a2713aSLionel Sambuc if (LHSType.isNull())
8178f4a2713aSLionel Sambuc LHSType = LHS->getType();
8179f4a2713aSLionel Sambuc
8180f4a2713aSLionel Sambuc Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8181f4a2713aSLionel Sambuc
8182f4a2713aSLionel Sambuc if (LT == Qualifiers::OCL_Weak) {
8183*0a6a1f1dSLionel Sambuc if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
8184f4a2713aSLionel Sambuc getCurFunction()->markSafeWeakUse(LHS);
8185f4a2713aSLionel Sambuc }
8186f4a2713aSLionel Sambuc
8187f4a2713aSLionel Sambuc if (checkUnsafeAssigns(Loc, LHSType, RHS))
8188f4a2713aSLionel Sambuc return;
8189f4a2713aSLionel Sambuc
8190f4a2713aSLionel Sambuc // FIXME. Check for other life times.
8191f4a2713aSLionel Sambuc if (LT != Qualifiers::OCL_None)
8192f4a2713aSLionel Sambuc return;
8193f4a2713aSLionel Sambuc
8194f4a2713aSLionel Sambuc if (PRE) {
8195f4a2713aSLionel Sambuc if (PRE->isImplicitProperty())
8196f4a2713aSLionel Sambuc return;
8197f4a2713aSLionel Sambuc const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8198f4a2713aSLionel Sambuc if (!PD)
8199f4a2713aSLionel Sambuc return;
8200f4a2713aSLionel Sambuc
8201f4a2713aSLionel Sambuc unsigned Attributes = PD->getPropertyAttributes();
8202f4a2713aSLionel Sambuc if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
8203f4a2713aSLionel Sambuc // when 'assign' attribute was not explicitly specified
8204f4a2713aSLionel Sambuc // by user, ignore it and rely on property type itself
8205f4a2713aSLionel Sambuc // for lifetime info.
8206f4a2713aSLionel Sambuc unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8207f4a2713aSLionel Sambuc if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8208f4a2713aSLionel Sambuc LHSType->isObjCRetainableType())
8209f4a2713aSLionel Sambuc return;
8210f4a2713aSLionel Sambuc
8211f4a2713aSLionel Sambuc while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8212f4a2713aSLionel Sambuc if (cast->getCastKind() == CK_ARCConsumeObject) {
8213f4a2713aSLionel Sambuc Diag(Loc, diag::warn_arc_retained_property_assign)
8214f4a2713aSLionel Sambuc << RHS->getSourceRange();
8215f4a2713aSLionel Sambuc return;
8216f4a2713aSLionel Sambuc }
8217f4a2713aSLionel Sambuc RHS = cast->getSubExpr();
8218f4a2713aSLionel Sambuc }
8219f4a2713aSLionel Sambuc }
8220f4a2713aSLionel Sambuc else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
8221f4a2713aSLionel Sambuc if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8222f4a2713aSLionel Sambuc return;
8223f4a2713aSLionel Sambuc }
8224f4a2713aSLionel Sambuc }
8225f4a2713aSLionel Sambuc }
8226f4a2713aSLionel Sambuc
8227f4a2713aSLionel Sambuc //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8228f4a2713aSLionel Sambuc
8229f4a2713aSLionel Sambuc namespace {
ShouldDiagnoseEmptyStmtBody(const SourceManager & SourceMgr,SourceLocation StmtLoc,const NullStmt * Body)8230f4a2713aSLionel Sambuc bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8231f4a2713aSLionel Sambuc SourceLocation StmtLoc,
8232f4a2713aSLionel Sambuc const NullStmt *Body) {
8233f4a2713aSLionel Sambuc // Do not warn if the body is a macro that expands to nothing, e.g:
8234f4a2713aSLionel Sambuc //
8235f4a2713aSLionel Sambuc // #define CALL(x)
8236f4a2713aSLionel Sambuc // if (condition)
8237f4a2713aSLionel Sambuc // CALL(0);
8238f4a2713aSLionel Sambuc //
8239f4a2713aSLionel Sambuc if (Body->hasLeadingEmptyMacro())
8240f4a2713aSLionel Sambuc return false;
8241f4a2713aSLionel Sambuc
8242f4a2713aSLionel Sambuc // Get line numbers of statement and body.
8243f4a2713aSLionel Sambuc bool StmtLineInvalid;
8244f4a2713aSLionel Sambuc unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8245f4a2713aSLionel Sambuc &StmtLineInvalid);
8246f4a2713aSLionel Sambuc if (StmtLineInvalid)
8247f4a2713aSLionel Sambuc return false;
8248f4a2713aSLionel Sambuc
8249f4a2713aSLionel Sambuc bool BodyLineInvalid;
8250f4a2713aSLionel Sambuc unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8251f4a2713aSLionel Sambuc &BodyLineInvalid);
8252f4a2713aSLionel Sambuc if (BodyLineInvalid)
8253f4a2713aSLionel Sambuc return false;
8254f4a2713aSLionel Sambuc
8255f4a2713aSLionel Sambuc // Warn if null statement and body are on the same line.
8256f4a2713aSLionel Sambuc if (StmtLine != BodyLine)
8257f4a2713aSLionel Sambuc return false;
8258f4a2713aSLionel Sambuc
8259f4a2713aSLionel Sambuc return true;
8260f4a2713aSLionel Sambuc }
8261f4a2713aSLionel Sambuc } // Unnamed namespace
8262f4a2713aSLionel Sambuc
DiagnoseEmptyStmtBody(SourceLocation StmtLoc,const Stmt * Body,unsigned DiagID)8263f4a2713aSLionel Sambuc void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8264f4a2713aSLionel Sambuc const Stmt *Body,
8265f4a2713aSLionel Sambuc unsigned DiagID) {
8266f4a2713aSLionel Sambuc // Since this is a syntactic check, don't emit diagnostic for template
8267f4a2713aSLionel Sambuc // instantiations, this just adds noise.
8268f4a2713aSLionel Sambuc if (CurrentInstantiationScope)
8269f4a2713aSLionel Sambuc return;
8270f4a2713aSLionel Sambuc
8271f4a2713aSLionel Sambuc // The body should be a null statement.
8272f4a2713aSLionel Sambuc const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8273f4a2713aSLionel Sambuc if (!NBody)
8274f4a2713aSLionel Sambuc return;
8275f4a2713aSLionel Sambuc
8276f4a2713aSLionel Sambuc // Do the usual checks.
8277f4a2713aSLionel Sambuc if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8278f4a2713aSLionel Sambuc return;
8279f4a2713aSLionel Sambuc
8280f4a2713aSLionel Sambuc Diag(NBody->getSemiLoc(), DiagID);
8281f4a2713aSLionel Sambuc Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8282f4a2713aSLionel Sambuc }
8283f4a2713aSLionel Sambuc
DiagnoseEmptyLoopBody(const Stmt * S,const Stmt * PossibleBody)8284f4a2713aSLionel Sambuc void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8285f4a2713aSLionel Sambuc const Stmt *PossibleBody) {
8286f4a2713aSLionel Sambuc assert(!CurrentInstantiationScope); // Ensured by caller
8287f4a2713aSLionel Sambuc
8288f4a2713aSLionel Sambuc SourceLocation StmtLoc;
8289f4a2713aSLionel Sambuc const Stmt *Body;
8290f4a2713aSLionel Sambuc unsigned DiagID;
8291f4a2713aSLionel Sambuc if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8292f4a2713aSLionel Sambuc StmtLoc = FS->getRParenLoc();
8293f4a2713aSLionel Sambuc Body = FS->getBody();
8294f4a2713aSLionel Sambuc DiagID = diag::warn_empty_for_body;
8295f4a2713aSLionel Sambuc } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8296f4a2713aSLionel Sambuc StmtLoc = WS->getCond()->getSourceRange().getEnd();
8297f4a2713aSLionel Sambuc Body = WS->getBody();
8298f4a2713aSLionel Sambuc DiagID = diag::warn_empty_while_body;
8299f4a2713aSLionel Sambuc } else
8300f4a2713aSLionel Sambuc return; // Neither `for' nor `while'.
8301f4a2713aSLionel Sambuc
8302f4a2713aSLionel Sambuc // The body should be a null statement.
8303f4a2713aSLionel Sambuc const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8304f4a2713aSLionel Sambuc if (!NBody)
8305f4a2713aSLionel Sambuc return;
8306f4a2713aSLionel Sambuc
8307f4a2713aSLionel Sambuc // Skip expensive checks if diagnostic is disabled.
8308*0a6a1f1dSLionel Sambuc if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
8309f4a2713aSLionel Sambuc return;
8310f4a2713aSLionel Sambuc
8311f4a2713aSLionel Sambuc // Do the usual checks.
8312f4a2713aSLionel Sambuc if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8313f4a2713aSLionel Sambuc return;
8314f4a2713aSLionel Sambuc
8315f4a2713aSLionel Sambuc // `for(...);' and `while(...);' are popular idioms, so in order to keep
8316f4a2713aSLionel Sambuc // noise level low, emit diagnostics only if for/while is followed by a
8317f4a2713aSLionel Sambuc // CompoundStmt, e.g.:
8318f4a2713aSLionel Sambuc // for (int i = 0; i < n; i++);
8319f4a2713aSLionel Sambuc // {
8320f4a2713aSLionel Sambuc // a(i);
8321f4a2713aSLionel Sambuc // }
8322f4a2713aSLionel Sambuc // or if for/while is followed by a statement with more indentation
8323f4a2713aSLionel Sambuc // than for/while itself:
8324f4a2713aSLionel Sambuc // for (int i = 0; i < n; i++);
8325f4a2713aSLionel Sambuc // a(i);
8326f4a2713aSLionel Sambuc bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8327f4a2713aSLionel Sambuc if (!ProbableTypo) {
8328f4a2713aSLionel Sambuc bool BodyColInvalid;
8329f4a2713aSLionel Sambuc unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8330f4a2713aSLionel Sambuc PossibleBody->getLocStart(),
8331f4a2713aSLionel Sambuc &BodyColInvalid);
8332f4a2713aSLionel Sambuc if (BodyColInvalid)
8333f4a2713aSLionel Sambuc return;
8334f4a2713aSLionel Sambuc
8335f4a2713aSLionel Sambuc bool StmtColInvalid;
8336f4a2713aSLionel Sambuc unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8337f4a2713aSLionel Sambuc S->getLocStart(),
8338f4a2713aSLionel Sambuc &StmtColInvalid);
8339f4a2713aSLionel Sambuc if (StmtColInvalid)
8340f4a2713aSLionel Sambuc return;
8341f4a2713aSLionel Sambuc
8342f4a2713aSLionel Sambuc if (BodyCol > StmtCol)
8343f4a2713aSLionel Sambuc ProbableTypo = true;
8344f4a2713aSLionel Sambuc }
8345f4a2713aSLionel Sambuc
8346f4a2713aSLionel Sambuc if (ProbableTypo) {
8347f4a2713aSLionel Sambuc Diag(NBody->getSemiLoc(), DiagID);
8348f4a2713aSLionel Sambuc Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8349f4a2713aSLionel Sambuc }
8350f4a2713aSLionel Sambuc }
8351f4a2713aSLionel Sambuc
8352*0a6a1f1dSLionel Sambuc //===--- CHECK: Warn on self move with std::move. -------------------------===//
8353*0a6a1f1dSLionel Sambuc
8354*0a6a1f1dSLionel Sambuc /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
DiagnoseSelfMove(const Expr * LHSExpr,const Expr * RHSExpr,SourceLocation OpLoc)8355*0a6a1f1dSLionel Sambuc void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8356*0a6a1f1dSLionel Sambuc SourceLocation OpLoc) {
8357*0a6a1f1dSLionel Sambuc
8358*0a6a1f1dSLionel Sambuc if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8359*0a6a1f1dSLionel Sambuc return;
8360*0a6a1f1dSLionel Sambuc
8361*0a6a1f1dSLionel Sambuc if (!ActiveTemplateInstantiations.empty())
8362*0a6a1f1dSLionel Sambuc return;
8363*0a6a1f1dSLionel Sambuc
8364*0a6a1f1dSLionel Sambuc // Strip parens and casts away.
8365*0a6a1f1dSLionel Sambuc LHSExpr = LHSExpr->IgnoreParenImpCasts();
8366*0a6a1f1dSLionel Sambuc RHSExpr = RHSExpr->IgnoreParenImpCasts();
8367*0a6a1f1dSLionel Sambuc
8368*0a6a1f1dSLionel Sambuc // Check for a call expression
8369*0a6a1f1dSLionel Sambuc const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8370*0a6a1f1dSLionel Sambuc if (!CE || CE->getNumArgs() != 1)
8371*0a6a1f1dSLionel Sambuc return;
8372*0a6a1f1dSLionel Sambuc
8373*0a6a1f1dSLionel Sambuc // Check for a call to std::move
8374*0a6a1f1dSLionel Sambuc const FunctionDecl *FD = CE->getDirectCallee();
8375*0a6a1f1dSLionel Sambuc if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8376*0a6a1f1dSLionel Sambuc !FD->getIdentifier()->isStr("move"))
8377*0a6a1f1dSLionel Sambuc return;
8378*0a6a1f1dSLionel Sambuc
8379*0a6a1f1dSLionel Sambuc // Get argument from std::move
8380*0a6a1f1dSLionel Sambuc RHSExpr = CE->getArg(0);
8381*0a6a1f1dSLionel Sambuc
8382*0a6a1f1dSLionel Sambuc const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8383*0a6a1f1dSLionel Sambuc const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8384*0a6a1f1dSLionel Sambuc
8385*0a6a1f1dSLionel Sambuc // Two DeclRefExpr's, check that the decls are the same.
8386*0a6a1f1dSLionel Sambuc if (LHSDeclRef && RHSDeclRef) {
8387*0a6a1f1dSLionel Sambuc if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8388*0a6a1f1dSLionel Sambuc return;
8389*0a6a1f1dSLionel Sambuc if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8390*0a6a1f1dSLionel Sambuc RHSDeclRef->getDecl()->getCanonicalDecl())
8391*0a6a1f1dSLionel Sambuc return;
8392*0a6a1f1dSLionel Sambuc
8393*0a6a1f1dSLionel Sambuc Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8394*0a6a1f1dSLionel Sambuc << LHSExpr->getSourceRange()
8395*0a6a1f1dSLionel Sambuc << RHSExpr->getSourceRange();
8396*0a6a1f1dSLionel Sambuc return;
8397*0a6a1f1dSLionel Sambuc }
8398*0a6a1f1dSLionel Sambuc
8399*0a6a1f1dSLionel Sambuc // Member variables require a different approach to check for self moves.
8400*0a6a1f1dSLionel Sambuc // MemberExpr's are the same if every nested MemberExpr refers to the same
8401*0a6a1f1dSLionel Sambuc // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8402*0a6a1f1dSLionel Sambuc // the base Expr's are CXXThisExpr's.
8403*0a6a1f1dSLionel Sambuc const Expr *LHSBase = LHSExpr;
8404*0a6a1f1dSLionel Sambuc const Expr *RHSBase = RHSExpr;
8405*0a6a1f1dSLionel Sambuc const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8406*0a6a1f1dSLionel Sambuc const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8407*0a6a1f1dSLionel Sambuc if (!LHSME || !RHSME)
8408*0a6a1f1dSLionel Sambuc return;
8409*0a6a1f1dSLionel Sambuc
8410*0a6a1f1dSLionel Sambuc while (LHSME && RHSME) {
8411*0a6a1f1dSLionel Sambuc if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8412*0a6a1f1dSLionel Sambuc RHSME->getMemberDecl()->getCanonicalDecl())
8413*0a6a1f1dSLionel Sambuc return;
8414*0a6a1f1dSLionel Sambuc
8415*0a6a1f1dSLionel Sambuc LHSBase = LHSME->getBase();
8416*0a6a1f1dSLionel Sambuc RHSBase = RHSME->getBase();
8417*0a6a1f1dSLionel Sambuc LHSME = dyn_cast<MemberExpr>(LHSBase);
8418*0a6a1f1dSLionel Sambuc RHSME = dyn_cast<MemberExpr>(RHSBase);
8419*0a6a1f1dSLionel Sambuc }
8420*0a6a1f1dSLionel Sambuc
8421*0a6a1f1dSLionel Sambuc LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8422*0a6a1f1dSLionel Sambuc RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8423*0a6a1f1dSLionel Sambuc if (LHSDeclRef && RHSDeclRef) {
8424*0a6a1f1dSLionel Sambuc if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8425*0a6a1f1dSLionel Sambuc return;
8426*0a6a1f1dSLionel Sambuc if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8427*0a6a1f1dSLionel Sambuc RHSDeclRef->getDecl()->getCanonicalDecl())
8428*0a6a1f1dSLionel Sambuc return;
8429*0a6a1f1dSLionel Sambuc
8430*0a6a1f1dSLionel Sambuc Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8431*0a6a1f1dSLionel Sambuc << LHSExpr->getSourceRange()
8432*0a6a1f1dSLionel Sambuc << RHSExpr->getSourceRange();
8433*0a6a1f1dSLionel Sambuc return;
8434*0a6a1f1dSLionel Sambuc }
8435*0a6a1f1dSLionel Sambuc
8436*0a6a1f1dSLionel Sambuc if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8437*0a6a1f1dSLionel Sambuc Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8438*0a6a1f1dSLionel Sambuc << LHSExpr->getSourceRange()
8439*0a6a1f1dSLionel Sambuc << RHSExpr->getSourceRange();
8440*0a6a1f1dSLionel Sambuc }
8441*0a6a1f1dSLionel Sambuc
8442f4a2713aSLionel Sambuc //===--- Layout compatibility ----------------------------------------------//
8443f4a2713aSLionel Sambuc
8444f4a2713aSLionel Sambuc namespace {
8445f4a2713aSLionel Sambuc
8446f4a2713aSLionel Sambuc bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8447f4a2713aSLionel Sambuc
8448f4a2713aSLionel Sambuc /// \brief Check if two enumeration types are layout-compatible.
isLayoutCompatible(ASTContext & C,EnumDecl * ED1,EnumDecl * ED2)8449f4a2713aSLionel Sambuc bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8450f4a2713aSLionel Sambuc // C++11 [dcl.enum] p8:
8451f4a2713aSLionel Sambuc // Two enumeration types are layout-compatible if they have the same
8452f4a2713aSLionel Sambuc // underlying type.
8453f4a2713aSLionel Sambuc return ED1->isComplete() && ED2->isComplete() &&
8454f4a2713aSLionel Sambuc C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8455f4a2713aSLionel Sambuc }
8456f4a2713aSLionel Sambuc
8457f4a2713aSLionel Sambuc /// \brief Check if two fields are layout-compatible.
isLayoutCompatible(ASTContext & C,FieldDecl * Field1,FieldDecl * Field2)8458f4a2713aSLionel Sambuc bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8459f4a2713aSLionel Sambuc if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8460f4a2713aSLionel Sambuc return false;
8461f4a2713aSLionel Sambuc
8462f4a2713aSLionel Sambuc if (Field1->isBitField() != Field2->isBitField())
8463f4a2713aSLionel Sambuc return false;
8464f4a2713aSLionel Sambuc
8465f4a2713aSLionel Sambuc if (Field1->isBitField()) {
8466f4a2713aSLionel Sambuc // Make sure that the bit-fields are the same length.
8467f4a2713aSLionel Sambuc unsigned Bits1 = Field1->getBitWidthValue(C);
8468f4a2713aSLionel Sambuc unsigned Bits2 = Field2->getBitWidthValue(C);
8469f4a2713aSLionel Sambuc
8470f4a2713aSLionel Sambuc if (Bits1 != Bits2)
8471f4a2713aSLionel Sambuc return false;
8472f4a2713aSLionel Sambuc }
8473f4a2713aSLionel Sambuc
8474f4a2713aSLionel Sambuc return true;
8475f4a2713aSLionel Sambuc }
8476f4a2713aSLionel Sambuc
8477f4a2713aSLionel Sambuc /// \brief Check if two standard-layout structs are layout-compatible.
8478f4a2713aSLionel Sambuc /// (C++11 [class.mem] p17)
isLayoutCompatibleStruct(ASTContext & C,RecordDecl * RD1,RecordDecl * RD2)8479f4a2713aSLionel Sambuc bool isLayoutCompatibleStruct(ASTContext &C,
8480f4a2713aSLionel Sambuc RecordDecl *RD1,
8481f4a2713aSLionel Sambuc RecordDecl *RD2) {
8482f4a2713aSLionel Sambuc // If both records are C++ classes, check that base classes match.
8483f4a2713aSLionel Sambuc if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8484f4a2713aSLionel Sambuc // If one of records is a CXXRecordDecl we are in C++ mode,
8485f4a2713aSLionel Sambuc // thus the other one is a CXXRecordDecl, too.
8486f4a2713aSLionel Sambuc const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8487f4a2713aSLionel Sambuc // Check number of base classes.
8488f4a2713aSLionel Sambuc if (D1CXX->getNumBases() != D2CXX->getNumBases())
8489f4a2713aSLionel Sambuc return false;
8490f4a2713aSLionel Sambuc
8491f4a2713aSLionel Sambuc // Check the base classes.
8492f4a2713aSLionel Sambuc for (CXXRecordDecl::base_class_const_iterator
8493f4a2713aSLionel Sambuc Base1 = D1CXX->bases_begin(),
8494f4a2713aSLionel Sambuc BaseEnd1 = D1CXX->bases_end(),
8495f4a2713aSLionel Sambuc Base2 = D2CXX->bases_begin();
8496f4a2713aSLionel Sambuc Base1 != BaseEnd1;
8497f4a2713aSLionel Sambuc ++Base1, ++Base2) {
8498f4a2713aSLionel Sambuc if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8499f4a2713aSLionel Sambuc return false;
8500f4a2713aSLionel Sambuc }
8501f4a2713aSLionel Sambuc } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8502f4a2713aSLionel Sambuc // If only RD2 is a C++ class, it should have zero base classes.
8503f4a2713aSLionel Sambuc if (D2CXX->getNumBases() > 0)
8504f4a2713aSLionel Sambuc return false;
8505f4a2713aSLionel Sambuc }
8506f4a2713aSLionel Sambuc
8507f4a2713aSLionel Sambuc // Check the fields.
8508f4a2713aSLionel Sambuc RecordDecl::field_iterator Field2 = RD2->field_begin(),
8509f4a2713aSLionel Sambuc Field2End = RD2->field_end(),
8510f4a2713aSLionel Sambuc Field1 = RD1->field_begin(),
8511f4a2713aSLionel Sambuc Field1End = RD1->field_end();
8512f4a2713aSLionel Sambuc for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8513f4a2713aSLionel Sambuc if (!isLayoutCompatible(C, *Field1, *Field2))
8514f4a2713aSLionel Sambuc return false;
8515f4a2713aSLionel Sambuc }
8516f4a2713aSLionel Sambuc if (Field1 != Field1End || Field2 != Field2End)
8517f4a2713aSLionel Sambuc return false;
8518f4a2713aSLionel Sambuc
8519f4a2713aSLionel Sambuc return true;
8520f4a2713aSLionel Sambuc }
8521f4a2713aSLionel Sambuc
8522f4a2713aSLionel Sambuc /// \brief Check if two standard-layout unions are layout-compatible.
8523f4a2713aSLionel Sambuc /// (C++11 [class.mem] p18)
isLayoutCompatibleUnion(ASTContext & C,RecordDecl * RD1,RecordDecl * RD2)8524f4a2713aSLionel Sambuc bool isLayoutCompatibleUnion(ASTContext &C,
8525f4a2713aSLionel Sambuc RecordDecl *RD1,
8526f4a2713aSLionel Sambuc RecordDecl *RD2) {
8527f4a2713aSLionel Sambuc llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
8528*0a6a1f1dSLionel Sambuc for (auto *Field2 : RD2->fields())
8529*0a6a1f1dSLionel Sambuc UnmatchedFields.insert(Field2);
8530f4a2713aSLionel Sambuc
8531*0a6a1f1dSLionel Sambuc for (auto *Field1 : RD1->fields()) {
8532f4a2713aSLionel Sambuc llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8533f4a2713aSLionel Sambuc I = UnmatchedFields.begin(),
8534f4a2713aSLionel Sambuc E = UnmatchedFields.end();
8535f4a2713aSLionel Sambuc
8536f4a2713aSLionel Sambuc for ( ; I != E; ++I) {
8537*0a6a1f1dSLionel Sambuc if (isLayoutCompatible(C, Field1, *I)) {
8538f4a2713aSLionel Sambuc bool Result = UnmatchedFields.erase(*I);
8539f4a2713aSLionel Sambuc (void) Result;
8540f4a2713aSLionel Sambuc assert(Result);
8541f4a2713aSLionel Sambuc break;
8542f4a2713aSLionel Sambuc }
8543f4a2713aSLionel Sambuc }
8544f4a2713aSLionel Sambuc if (I == E)
8545f4a2713aSLionel Sambuc return false;
8546f4a2713aSLionel Sambuc }
8547f4a2713aSLionel Sambuc
8548f4a2713aSLionel Sambuc return UnmatchedFields.empty();
8549f4a2713aSLionel Sambuc }
8550f4a2713aSLionel Sambuc
isLayoutCompatible(ASTContext & C,RecordDecl * RD1,RecordDecl * RD2)8551f4a2713aSLionel Sambuc bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8552f4a2713aSLionel Sambuc if (RD1->isUnion() != RD2->isUnion())
8553f4a2713aSLionel Sambuc return false;
8554f4a2713aSLionel Sambuc
8555f4a2713aSLionel Sambuc if (RD1->isUnion())
8556f4a2713aSLionel Sambuc return isLayoutCompatibleUnion(C, RD1, RD2);
8557f4a2713aSLionel Sambuc else
8558f4a2713aSLionel Sambuc return isLayoutCompatibleStruct(C, RD1, RD2);
8559f4a2713aSLionel Sambuc }
8560f4a2713aSLionel Sambuc
8561f4a2713aSLionel Sambuc /// \brief Check if two types are layout-compatible in C++11 sense.
isLayoutCompatible(ASTContext & C,QualType T1,QualType T2)8562f4a2713aSLionel Sambuc bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8563f4a2713aSLionel Sambuc if (T1.isNull() || T2.isNull())
8564f4a2713aSLionel Sambuc return false;
8565f4a2713aSLionel Sambuc
8566f4a2713aSLionel Sambuc // C++11 [basic.types] p11:
8567f4a2713aSLionel Sambuc // If two types T1 and T2 are the same type, then T1 and T2 are
8568f4a2713aSLionel Sambuc // layout-compatible types.
8569f4a2713aSLionel Sambuc if (C.hasSameType(T1, T2))
8570f4a2713aSLionel Sambuc return true;
8571f4a2713aSLionel Sambuc
8572f4a2713aSLionel Sambuc T1 = T1.getCanonicalType().getUnqualifiedType();
8573f4a2713aSLionel Sambuc T2 = T2.getCanonicalType().getUnqualifiedType();
8574f4a2713aSLionel Sambuc
8575f4a2713aSLionel Sambuc const Type::TypeClass TC1 = T1->getTypeClass();
8576f4a2713aSLionel Sambuc const Type::TypeClass TC2 = T2->getTypeClass();
8577f4a2713aSLionel Sambuc
8578f4a2713aSLionel Sambuc if (TC1 != TC2)
8579f4a2713aSLionel Sambuc return false;
8580f4a2713aSLionel Sambuc
8581f4a2713aSLionel Sambuc if (TC1 == Type::Enum) {
8582f4a2713aSLionel Sambuc return isLayoutCompatible(C,
8583f4a2713aSLionel Sambuc cast<EnumType>(T1)->getDecl(),
8584f4a2713aSLionel Sambuc cast<EnumType>(T2)->getDecl());
8585f4a2713aSLionel Sambuc } else if (TC1 == Type::Record) {
8586f4a2713aSLionel Sambuc if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8587f4a2713aSLionel Sambuc return false;
8588f4a2713aSLionel Sambuc
8589f4a2713aSLionel Sambuc return isLayoutCompatible(C,
8590f4a2713aSLionel Sambuc cast<RecordType>(T1)->getDecl(),
8591f4a2713aSLionel Sambuc cast<RecordType>(T2)->getDecl());
8592f4a2713aSLionel Sambuc }
8593f4a2713aSLionel Sambuc
8594f4a2713aSLionel Sambuc return false;
8595f4a2713aSLionel Sambuc }
8596f4a2713aSLionel Sambuc }
8597f4a2713aSLionel Sambuc
8598f4a2713aSLionel Sambuc //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8599f4a2713aSLionel Sambuc
8600f4a2713aSLionel Sambuc namespace {
8601f4a2713aSLionel Sambuc /// \brief Given a type tag expression find the type tag itself.
8602f4a2713aSLionel Sambuc ///
8603f4a2713aSLionel Sambuc /// \param TypeExpr Type tag expression, as it appears in user's code.
8604f4a2713aSLionel Sambuc ///
8605f4a2713aSLionel Sambuc /// \param VD Declaration of an identifier that appears in a type tag.
8606f4a2713aSLionel Sambuc ///
8607f4a2713aSLionel Sambuc /// \param MagicValue Type tag magic value.
FindTypeTagExpr(const Expr * TypeExpr,const ASTContext & Ctx,const ValueDecl ** VD,uint64_t * MagicValue)8608f4a2713aSLionel Sambuc bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8609f4a2713aSLionel Sambuc const ValueDecl **VD, uint64_t *MagicValue) {
8610f4a2713aSLionel Sambuc while(true) {
8611f4a2713aSLionel Sambuc if (!TypeExpr)
8612f4a2713aSLionel Sambuc return false;
8613f4a2713aSLionel Sambuc
8614f4a2713aSLionel Sambuc TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8615f4a2713aSLionel Sambuc
8616f4a2713aSLionel Sambuc switch (TypeExpr->getStmtClass()) {
8617f4a2713aSLionel Sambuc case Stmt::UnaryOperatorClass: {
8618f4a2713aSLionel Sambuc const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8619f4a2713aSLionel Sambuc if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8620f4a2713aSLionel Sambuc TypeExpr = UO->getSubExpr();
8621f4a2713aSLionel Sambuc continue;
8622f4a2713aSLionel Sambuc }
8623f4a2713aSLionel Sambuc return false;
8624f4a2713aSLionel Sambuc }
8625f4a2713aSLionel Sambuc
8626f4a2713aSLionel Sambuc case Stmt::DeclRefExprClass: {
8627f4a2713aSLionel Sambuc const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8628f4a2713aSLionel Sambuc *VD = DRE->getDecl();
8629f4a2713aSLionel Sambuc return true;
8630f4a2713aSLionel Sambuc }
8631f4a2713aSLionel Sambuc
8632f4a2713aSLionel Sambuc case Stmt::IntegerLiteralClass: {
8633f4a2713aSLionel Sambuc const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8634f4a2713aSLionel Sambuc llvm::APInt MagicValueAPInt = IL->getValue();
8635f4a2713aSLionel Sambuc if (MagicValueAPInt.getActiveBits() <= 64) {
8636f4a2713aSLionel Sambuc *MagicValue = MagicValueAPInt.getZExtValue();
8637f4a2713aSLionel Sambuc return true;
8638f4a2713aSLionel Sambuc } else
8639f4a2713aSLionel Sambuc return false;
8640f4a2713aSLionel Sambuc }
8641f4a2713aSLionel Sambuc
8642f4a2713aSLionel Sambuc case Stmt::BinaryConditionalOperatorClass:
8643f4a2713aSLionel Sambuc case Stmt::ConditionalOperatorClass: {
8644f4a2713aSLionel Sambuc const AbstractConditionalOperator *ACO =
8645f4a2713aSLionel Sambuc cast<AbstractConditionalOperator>(TypeExpr);
8646f4a2713aSLionel Sambuc bool Result;
8647f4a2713aSLionel Sambuc if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8648f4a2713aSLionel Sambuc if (Result)
8649f4a2713aSLionel Sambuc TypeExpr = ACO->getTrueExpr();
8650f4a2713aSLionel Sambuc else
8651f4a2713aSLionel Sambuc TypeExpr = ACO->getFalseExpr();
8652f4a2713aSLionel Sambuc continue;
8653f4a2713aSLionel Sambuc }
8654f4a2713aSLionel Sambuc return false;
8655f4a2713aSLionel Sambuc }
8656f4a2713aSLionel Sambuc
8657f4a2713aSLionel Sambuc case Stmt::BinaryOperatorClass: {
8658f4a2713aSLionel Sambuc const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8659f4a2713aSLionel Sambuc if (BO->getOpcode() == BO_Comma) {
8660f4a2713aSLionel Sambuc TypeExpr = BO->getRHS();
8661f4a2713aSLionel Sambuc continue;
8662f4a2713aSLionel Sambuc }
8663f4a2713aSLionel Sambuc return false;
8664f4a2713aSLionel Sambuc }
8665f4a2713aSLionel Sambuc
8666f4a2713aSLionel Sambuc default:
8667f4a2713aSLionel Sambuc return false;
8668f4a2713aSLionel Sambuc }
8669f4a2713aSLionel Sambuc }
8670f4a2713aSLionel Sambuc }
8671f4a2713aSLionel Sambuc
8672f4a2713aSLionel Sambuc /// \brief Retrieve the C type corresponding to type tag TypeExpr.
8673f4a2713aSLionel Sambuc ///
8674f4a2713aSLionel Sambuc /// \param TypeExpr Expression that specifies a type tag.
8675f4a2713aSLionel Sambuc ///
8676f4a2713aSLionel Sambuc /// \param MagicValues Registered magic values.
8677f4a2713aSLionel Sambuc ///
8678f4a2713aSLionel Sambuc /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8679f4a2713aSLionel Sambuc /// kind.
8680f4a2713aSLionel Sambuc ///
8681f4a2713aSLionel Sambuc /// \param TypeInfo Information about the corresponding C type.
8682f4a2713aSLionel Sambuc ///
8683f4a2713aSLionel Sambuc /// \returns true if the corresponding C type was found.
GetMatchingCType(const IdentifierInfo * ArgumentKind,const Expr * TypeExpr,const ASTContext & Ctx,const llvm::DenseMap<Sema::TypeTagMagicValue,Sema::TypeTagData> * MagicValues,bool & FoundWrongKind,Sema::TypeTagData & TypeInfo)8684f4a2713aSLionel Sambuc bool GetMatchingCType(
8685f4a2713aSLionel Sambuc const IdentifierInfo *ArgumentKind,
8686f4a2713aSLionel Sambuc const Expr *TypeExpr, const ASTContext &Ctx,
8687f4a2713aSLionel Sambuc const llvm::DenseMap<Sema::TypeTagMagicValue,
8688f4a2713aSLionel Sambuc Sema::TypeTagData> *MagicValues,
8689f4a2713aSLionel Sambuc bool &FoundWrongKind,
8690f4a2713aSLionel Sambuc Sema::TypeTagData &TypeInfo) {
8691f4a2713aSLionel Sambuc FoundWrongKind = false;
8692f4a2713aSLionel Sambuc
8693f4a2713aSLionel Sambuc // Variable declaration that has type_tag_for_datatype attribute.
8694*0a6a1f1dSLionel Sambuc const ValueDecl *VD = nullptr;
8695f4a2713aSLionel Sambuc
8696f4a2713aSLionel Sambuc uint64_t MagicValue;
8697f4a2713aSLionel Sambuc
8698f4a2713aSLionel Sambuc if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8699f4a2713aSLionel Sambuc return false;
8700f4a2713aSLionel Sambuc
8701f4a2713aSLionel Sambuc if (VD) {
8702*0a6a1f1dSLionel Sambuc if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
8703f4a2713aSLionel Sambuc if (I->getArgumentKind() != ArgumentKind) {
8704f4a2713aSLionel Sambuc FoundWrongKind = true;
8705f4a2713aSLionel Sambuc return false;
8706f4a2713aSLionel Sambuc }
8707f4a2713aSLionel Sambuc TypeInfo.Type = I->getMatchingCType();
8708f4a2713aSLionel Sambuc TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8709f4a2713aSLionel Sambuc TypeInfo.MustBeNull = I->getMustBeNull();
8710f4a2713aSLionel Sambuc return true;
8711f4a2713aSLionel Sambuc }
8712f4a2713aSLionel Sambuc return false;
8713f4a2713aSLionel Sambuc }
8714f4a2713aSLionel Sambuc
8715f4a2713aSLionel Sambuc if (!MagicValues)
8716f4a2713aSLionel Sambuc return false;
8717f4a2713aSLionel Sambuc
8718f4a2713aSLionel Sambuc llvm::DenseMap<Sema::TypeTagMagicValue,
8719f4a2713aSLionel Sambuc Sema::TypeTagData>::const_iterator I =
8720f4a2713aSLionel Sambuc MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8721f4a2713aSLionel Sambuc if (I == MagicValues->end())
8722f4a2713aSLionel Sambuc return false;
8723f4a2713aSLionel Sambuc
8724f4a2713aSLionel Sambuc TypeInfo = I->second;
8725f4a2713aSLionel Sambuc return true;
8726f4a2713aSLionel Sambuc }
8727f4a2713aSLionel Sambuc } // unnamed namespace
8728f4a2713aSLionel Sambuc
RegisterTypeTagForDatatype(const IdentifierInfo * ArgumentKind,uint64_t MagicValue,QualType Type,bool LayoutCompatible,bool MustBeNull)8729f4a2713aSLionel Sambuc void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8730f4a2713aSLionel Sambuc uint64_t MagicValue, QualType Type,
8731f4a2713aSLionel Sambuc bool LayoutCompatible,
8732f4a2713aSLionel Sambuc bool MustBeNull) {
8733f4a2713aSLionel Sambuc if (!TypeTagForDatatypeMagicValues)
8734f4a2713aSLionel Sambuc TypeTagForDatatypeMagicValues.reset(
8735f4a2713aSLionel Sambuc new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8736f4a2713aSLionel Sambuc
8737f4a2713aSLionel Sambuc TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8738f4a2713aSLionel Sambuc (*TypeTagForDatatypeMagicValues)[Magic] =
8739f4a2713aSLionel Sambuc TypeTagData(Type, LayoutCompatible, MustBeNull);
8740f4a2713aSLionel Sambuc }
8741f4a2713aSLionel Sambuc
8742f4a2713aSLionel Sambuc namespace {
IsSameCharType(QualType T1,QualType T2)8743f4a2713aSLionel Sambuc bool IsSameCharType(QualType T1, QualType T2) {
8744f4a2713aSLionel Sambuc const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8745f4a2713aSLionel Sambuc if (!BT1)
8746f4a2713aSLionel Sambuc return false;
8747f4a2713aSLionel Sambuc
8748f4a2713aSLionel Sambuc const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8749f4a2713aSLionel Sambuc if (!BT2)
8750f4a2713aSLionel Sambuc return false;
8751f4a2713aSLionel Sambuc
8752f4a2713aSLionel Sambuc BuiltinType::Kind T1Kind = BT1->getKind();
8753f4a2713aSLionel Sambuc BuiltinType::Kind T2Kind = BT2->getKind();
8754f4a2713aSLionel Sambuc
8755f4a2713aSLionel Sambuc return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8756f4a2713aSLionel Sambuc (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8757f4a2713aSLionel Sambuc (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8758f4a2713aSLionel Sambuc (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8759f4a2713aSLionel Sambuc }
8760f4a2713aSLionel Sambuc } // unnamed namespace
8761f4a2713aSLionel Sambuc
CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr * Attr,const Expr * const * ExprArgs)8762f4a2713aSLionel Sambuc void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8763f4a2713aSLionel Sambuc const Expr * const *ExprArgs) {
8764f4a2713aSLionel Sambuc const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8765f4a2713aSLionel Sambuc bool IsPointerAttr = Attr->getIsPointer();
8766f4a2713aSLionel Sambuc
8767f4a2713aSLionel Sambuc const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8768f4a2713aSLionel Sambuc bool FoundWrongKind;
8769f4a2713aSLionel Sambuc TypeTagData TypeInfo;
8770f4a2713aSLionel Sambuc if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8771f4a2713aSLionel Sambuc TypeTagForDatatypeMagicValues.get(),
8772f4a2713aSLionel Sambuc FoundWrongKind, TypeInfo)) {
8773f4a2713aSLionel Sambuc if (FoundWrongKind)
8774f4a2713aSLionel Sambuc Diag(TypeTagExpr->getExprLoc(),
8775f4a2713aSLionel Sambuc diag::warn_type_tag_for_datatype_wrong_kind)
8776f4a2713aSLionel Sambuc << TypeTagExpr->getSourceRange();
8777f4a2713aSLionel Sambuc return;
8778f4a2713aSLionel Sambuc }
8779f4a2713aSLionel Sambuc
8780f4a2713aSLionel Sambuc const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8781f4a2713aSLionel Sambuc if (IsPointerAttr) {
8782f4a2713aSLionel Sambuc // Skip implicit cast of pointer to `void *' (as a function argument).
8783f4a2713aSLionel Sambuc if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
8784f4a2713aSLionel Sambuc if (ICE->getType()->isVoidPointerType() &&
8785f4a2713aSLionel Sambuc ICE->getCastKind() == CK_BitCast)
8786f4a2713aSLionel Sambuc ArgumentExpr = ICE->getSubExpr();
8787f4a2713aSLionel Sambuc }
8788f4a2713aSLionel Sambuc QualType ArgumentType = ArgumentExpr->getType();
8789f4a2713aSLionel Sambuc
8790f4a2713aSLionel Sambuc // Passing a `void*' pointer shouldn't trigger a warning.
8791f4a2713aSLionel Sambuc if (IsPointerAttr && ArgumentType->isVoidPointerType())
8792f4a2713aSLionel Sambuc return;
8793f4a2713aSLionel Sambuc
8794f4a2713aSLionel Sambuc if (TypeInfo.MustBeNull) {
8795f4a2713aSLionel Sambuc // Type tag with matching void type requires a null pointer.
8796f4a2713aSLionel Sambuc if (!ArgumentExpr->isNullPointerConstant(Context,
8797f4a2713aSLionel Sambuc Expr::NPC_ValueDependentIsNotNull)) {
8798f4a2713aSLionel Sambuc Diag(ArgumentExpr->getExprLoc(),
8799f4a2713aSLionel Sambuc diag::warn_type_safety_null_pointer_required)
8800f4a2713aSLionel Sambuc << ArgumentKind->getName()
8801f4a2713aSLionel Sambuc << ArgumentExpr->getSourceRange()
8802f4a2713aSLionel Sambuc << TypeTagExpr->getSourceRange();
8803f4a2713aSLionel Sambuc }
8804f4a2713aSLionel Sambuc return;
8805f4a2713aSLionel Sambuc }
8806f4a2713aSLionel Sambuc
8807f4a2713aSLionel Sambuc QualType RequiredType = TypeInfo.Type;
8808f4a2713aSLionel Sambuc if (IsPointerAttr)
8809f4a2713aSLionel Sambuc RequiredType = Context.getPointerType(RequiredType);
8810f4a2713aSLionel Sambuc
8811f4a2713aSLionel Sambuc bool mismatch = false;
8812f4a2713aSLionel Sambuc if (!TypeInfo.LayoutCompatible) {
8813f4a2713aSLionel Sambuc mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8814f4a2713aSLionel Sambuc
8815f4a2713aSLionel Sambuc // C++11 [basic.fundamental] p1:
8816f4a2713aSLionel Sambuc // Plain char, signed char, and unsigned char are three distinct types.
8817f4a2713aSLionel Sambuc //
8818f4a2713aSLionel Sambuc // But we treat plain `char' as equivalent to `signed char' or `unsigned
8819f4a2713aSLionel Sambuc // char' depending on the current char signedness mode.
8820f4a2713aSLionel Sambuc if (mismatch)
8821f4a2713aSLionel Sambuc if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8822f4a2713aSLionel Sambuc RequiredType->getPointeeType())) ||
8823f4a2713aSLionel Sambuc (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8824f4a2713aSLionel Sambuc mismatch = false;
8825f4a2713aSLionel Sambuc } else
8826f4a2713aSLionel Sambuc if (IsPointerAttr)
8827f4a2713aSLionel Sambuc mismatch = !isLayoutCompatible(Context,
8828f4a2713aSLionel Sambuc ArgumentType->getPointeeType(),
8829f4a2713aSLionel Sambuc RequiredType->getPointeeType());
8830f4a2713aSLionel Sambuc else
8831f4a2713aSLionel Sambuc mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8832f4a2713aSLionel Sambuc
8833f4a2713aSLionel Sambuc if (mismatch)
8834f4a2713aSLionel Sambuc Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
8835*0a6a1f1dSLionel Sambuc << ArgumentType << ArgumentKind
8836f4a2713aSLionel Sambuc << TypeInfo.LayoutCompatible << RequiredType
8837f4a2713aSLionel Sambuc << ArgumentExpr->getSourceRange()
8838f4a2713aSLionel Sambuc << TypeTagExpr->getSourceRange();
8839f4a2713aSLionel Sambuc }
8840*0a6a1f1dSLionel Sambuc
8841