blob: 7ecc304fc90966f8348ed71125fa7869c841afcf [file] [log] [blame]
Chris Lattner2e64c072007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner2e64c072007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements extra semantic analysis beyond what is enforced
11// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek1c1700f2007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek225a14c2008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000020#include "clang/Lex/Preprocessor.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000021#include "SemaUtil.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000022using namespace clang;
23
24/// CheckFunctionCall - Check a direct function call for various correctness
25/// and safety properties not strictly enforced by the C type system.
Sebastian Redl8b769972009-01-19 00:08:26 +000026Action::OwningExprResult
27Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
28 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner2e64c072007-08-10 20:18:51 +000029 // Get the IdentifierInfo* for the called function.
30 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregorb0212bd2008-11-17 20:34:05 +000031
32 // None of the checks below are needed for functions that don't have
33 // simple names (e.g., C++ conversion functions).
34 if (!FnInfo)
Sebastian Redl8b769972009-01-19 00:08:26 +000035 return move(TheCallResult);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000036
Douglas Gregor411889e2009-02-13 23:20:09 +000037 switch (FDecl->getBuiltinID()) {
Chris Lattnerf22a8502007-12-19 23:59:04 +000038 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner83bd5eb2007-12-28 05:29:59 +000039 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner7c8d1af2007-12-20 00:26:33 +000040 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedman798e4d52008-05-16 17:51:27 +000041 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Sebastian Redl8b769972009-01-19 00:08:26 +000042 return ExprError();
43 return move(TheCallResult);
Ted Kremenek7a0654c2008-07-09 17:58:53 +000044 case Builtin::BI__builtin_stdarg_start:
Chris Lattnerf22a8502007-12-19 23:59:04 +000045 case Builtin::BI__builtin_va_start:
Sebastian Redl8b769972009-01-19 00:08:26 +000046 if (SemaBuiltinVAStart(TheCall))
47 return ExprError();
48 return move(TheCallResult);
Chris Lattner7c8d1af2007-12-20 00:26:33 +000049 case Builtin::BI__builtin_isgreater:
50 case Builtin::BI__builtin_isgreaterequal:
51 case Builtin::BI__builtin_isless:
52 case Builtin::BI__builtin_islessequal:
53 case Builtin::BI__builtin_islessgreater:
54 case Builtin::BI__builtin_isunordered:
Sebastian Redl8b769972009-01-19 00:08:26 +000055 if (SemaBuiltinUnorderedCompare(TheCall))
56 return ExprError();
57 return move(TheCallResult);
Eli Friedman8c50c622008-05-20 08:23:37 +000058 case Builtin::BI__builtin_return_address:
59 case Builtin::BI__builtin_frame_address:
Sebastian Redl8b769972009-01-19 00:08:26 +000060 if (SemaBuiltinStackAddress(TheCall))
61 return ExprError();
62 return move(TheCallResult);
Eli Friedmand0e9d092008-05-14 19:38:39 +000063 case Builtin::BI__builtin_shufflevector:
Sebastian Redl8b769972009-01-19 00:08:26 +000064 return SemaBuiltinShuffleVector(TheCall);
65 // TheCall will be freed by the smart pointer here, but that's fine, since
66 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar5b0de852008-07-21 22:59:13 +000067 case Builtin::BI__builtin_prefetch:
Sebastian Redl8b769972009-01-19 00:08:26 +000068 if (SemaBuiltinPrefetch(TheCall))
69 return ExprError();
70 return move(TheCallResult);
Daniel Dunbar30ad42d2008-09-03 21:13:56 +000071 case Builtin::BI__builtin_object_size:
Sebastian Redl8b769972009-01-19 00:08:26 +000072 if (SemaBuiltinObjectSize(TheCall))
73 return ExprError();
Anders Carlssone7e7aa22007-08-17 05:31:46 +000074 }
Daniel Dunbar0ab03e62008-10-02 18:44:07 +000075
76 // FIXME: This mechanism should be abstracted to be less fragile and
77 // more efficient. For example, just map function ids to custom
78 // handlers.
79
Chris Lattner2e64c072007-08-10 20:18:51 +000080 // Printf checking.
Douglas Gregor17429032009-02-14 00:32:47 +000081 unsigned format_idx = 0;
82 bool HasVAListArg = false;
83 if (FDecl->getBuiltinID() &&
84 Context.BuiltinInfo.isPrintfLike(FDecl->getBuiltinID(), format_idx,
85 HasVAListArg)) {
86 // Found a printf builtin.
87 } else if (FnInfo == KnownFunctionIDs[id_NSLog]) {
88 format_idx = 0;
89 HasVAListArg = false;
Douglas Gregor1fa246d2009-02-14 01:52:53 +000090 } else if (FnInfo == KnownFunctionIDs[id_asprintf]) {
Douglas Gregor17429032009-02-14 00:32:47 +000091 format_idx = 1;
92 HasVAListArg = false;
Douglas Gregor1fa246d2009-02-14 01:52:53 +000093 } else if (FnInfo == KnownFunctionIDs[id_vasprintf]) {
Douglas Gregor17429032009-02-14 00:32:47 +000094 format_idx = 1;
95 HasVAListArg = true;
96 } else {
97 return move(TheCallResult);
Chris Lattner2e64c072007-08-10 20:18:51 +000098 }
Sebastian Redl8b769972009-01-19 00:08:26 +000099
Douglas Gregor17429032009-02-14 00:32:47 +0000100 CheckPrintfArguments(TheCall, HasVAListArg, format_idx);
101
Sebastian Redl8b769972009-01-19 00:08:26 +0000102 return move(TheCallResult);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000103}
104
105/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
106/// CFString constructor is correct
Chris Lattnerda050402007-08-25 05:30:33 +0000107bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000108 Arg = Arg->IgnoreParenCasts();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000109
110 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
111
112 if (!Literal || Literal->isWide()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000113 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
114 << Arg->getSourceRange();
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000115 return true;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000116 }
117
118 const char *Data = Literal->getStrData();
119 unsigned Length = Literal->getByteLength();
120
121 for (unsigned i = 0; i < Length; ++i) {
122 if (!isascii(Data[i])) {
123 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000124 diag::warn_cfstring_literal_contains_non_ascii_character)
125 << Arg->getSourceRange();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000126 break;
127 }
128
129 if (!Data[i]) {
130 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000131 diag::warn_cfstring_literal_contains_nul_character)
132 << Arg->getSourceRange();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000133 break;
134 }
135 }
136
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000137 return false;
Chris Lattner2e64c072007-08-10 20:18:51 +0000138}
139
Chris Lattner3b933692007-12-20 00:05:45 +0000140/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
141/// Emit an error and return true on failure, return false on success.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000142bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
143 Expr *Fn = TheCall->getCallee();
144 if (TheCall->getNumArgs() > 2) {
Chris Lattner66beaba2008-11-21 18:44:24 +0000145 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000146 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000147 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000148 << SourceRange(TheCall->getArg(2)->getLocStart(),
149 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattnerf22a8502007-12-19 23:59:04 +0000150 return true;
151 }
Eli Friedman6422de62008-12-15 22:05:35 +0000152
153 if (TheCall->getNumArgs() < 2) {
154 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
155 << 0 /*function call*/;
156 }
157
Chris Lattner3b933692007-12-20 00:05:45 +0000158 // Determine whether the current function is variadic or not.
159 bool isVariadic;
Eli Friedman6422de62008-12-15 22:05:35 +0000160 if (getCurFunctionDecl()) {
161 if (FunctionTypeProto* FTP =
162 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType()))
163 isVariadic = FTP->isVariadic();
164 else
165 isVariadic = false;
166 } else {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000167 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman6422de62008-12-15 22:05:35 +0000168 }
Chris Lattnerf22a8502007-12-19 23:59:04 +0000169
Chris Lattner3b933692007-12-20 00:05:45 +0000170 if (!isVariadic) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000171 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
172 return true;
173 }
174
175 // Verify that the second argument to the builtin is the last argument of the
176 // current function or method.
177 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson924556e2008-02-13 01:22:59 +0000178 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlssonc27156b2008-02-11 04:20:54 +0000179
180 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
181 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000182 // FIXME: This isn't correct for methods (results in bogus warning).
183 // Get the last formal in the current function.
Anders Carlssonc27156b2008-02-11 04:20:54 +0000184 const ParmVarDecl *LastArg;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000185 if (FunctionDecl *FD = getCurFunctionDecl())
186 LastArg = *(FD->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000187 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000188 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000189 SecondArgIsLastNamedArgument = PV == LastArg;
190 }
191 }
192
193 if (!SecondArgIsLastNamedArgument)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000194 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000195 diag::warn_second_parameter_of_va_start_not_last_named_argument);
196 return false;
Eli Friedman8c50c622008-05-20 08:23:37 +0000197}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000198
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000199/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
200/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000201bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
202 if (TheCall->getNumArgs() < 2)
Chris Lattner66beaba2008-11-21 18:44:24 +0000203 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
204 << 0 /*function call*/;
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000205 if (TheCall->getNumArgs() > 2)
206 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000207 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000208 << 0 /*function call*/
Chris Lattner8ba580c2008-11-19 05:08:23 +0000209 << SourceRange(TheCall->getArg(2)->getLocStart(),
210 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000211
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000212 Expr *OrigArg0 = TheCall->getArg(0);
213 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000214
215 // Do standard promotions between the two arguments, returning their common
216 // type.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000217 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000218
219 // If the common type isn't a real floating type, then the arguments were
220 // invalid for this operation.
221 if (!Res->isRealFloatingType())
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000222 return Diag(OrigArg0->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000223 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000224 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000225 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000226
227 return false;
228}
229
Eli Friedman8c50c622008-05-20 08:23:37 +0000230bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
231 // The signature for these builtins is exact; the only thing we need
232 // to check is that the argument is a constant.
233 SourceLocation Loc;
Chris Lattner941c0102008-08-10 02:05:13 +0000234 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000235 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattner941c0102008-08-10 02:05:13 +0000236
Eli Friedman8c50c622008-05-20 08:23:37 +0000237 return false;
238}
239
Eli Friedmand0e9d092008-05-14 19:38:39 +0000240/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
241// This is declared to take (...), so we have to check everything.
Sebastian Redl8b769972009-01-19 00:08:26 +0000242Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000243 if (TheCall->getNumArgs() < 3)
Sebastian Redl8b769972009-01-19 00:08:26 +0000244 return ExprError(Diag(TheCall->getLocEnd(),
245 diag::err_typecheck_call_too_few_args)
246 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000247
248 QualType FAType = TheCall->getArg(0)->getType();
249 QualType SAType = TheCall->getArg(1)->getType();
250
251 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000252 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
253 << SourceRange(TheCall->getArg(0)->getLocStart(),
254 TheCall->getArg(1)->getLocEnd());
Sebastian Redl8b769972009-01-19 00:08:26 +0000255 return ExprError();
Eli Friedmand0e9d092008-05-14 19:38:39 +0000256 }
257
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000258 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
259 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000260 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
261 << SourceRange(TheCall->getArg(0)->getLocStart(),
262 TheCall->getArg(1)->getLocEnd());
Sebastian Redl8b769972009-01-19 00:08:26 +0000263 return ExprError();
Eli Friedmand0e9d092008-05-14 19:38:39 +0000264 }
265
266 unsigned numElements = FAType->getAsVectorType()->getNumElements();
267 if (TheCall->getNumArgs() != numElements+2) {
268 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000269 return ExprError(Diag(TheCall->getLocEnd(),
270 diag::err_typecheck_call_too_few_args)
271 << 0 /*function call*/ << TheCall->getSourceRange());
272 return ExprError(Diag(TheCall->getLocEnd(),
273 diag::err_typecheck_call_too_many_args)
274 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000275 }
276
277 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
278 llvm::APSInt Result(32);
Chris Lattner941c0102008-08-10 02:05:13 +0000279 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl8b769972009-01-19 00:08:26 +0000280 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000281 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl8b769972009-01-19 00:08:26 +0000282 << TheCall->getArg(i)->getSourceRange());
283
Chris Lattner941c0102008-08-10 02:05:13 +0000284 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000285 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000286 diag::err_shufflevector_argument_too_large)
Sebastian Redl8b769972009-01-19 00:08:26 +0000287 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000288 }
289
290 llvm::SmallVector<Expr*, 32> exprs;
291
Chris Lattner941c0102008-08-10 02:05:13 +0000292 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000293 exprs.push_back(TheCall->getArg(i));
294 TheCall->setArg(i, 0);
295 }
296
Ted Kremenek0c97e042009-02-07 01:47:29 +0000297 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
298 FAType,
299 TheCall->getCallee()->getLocStart(),
300 TheCall->getRParenLoc()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000301}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000302
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000303/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
304// This is declared to take (const void*, ...) and can take two
305// optional constant int args.
306bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000307 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000308
Chris Lattner8ba580c2008-11-19 05:08:23 +0000309 if (NumArgs > 3)
310 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000311 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000312
313 // Argument 0 is checked for us and the remaining arguments must be
314 // constant integers.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000315 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000316 Expr *Arg = TheCall->getArg(i);
317 QualType RWType = Arg->getType();
318
319 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000320 llvm::APSInt Result;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000321 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattner8ba580c2008-11-19 05:08:23 +0000322 !Arg->isIntegerConstantExpr(Result, Context))
323 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
324 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000325
326 // FIXME: gcc issues a warning and rewrites these to 0. These
327 // seems especially odd for the third argument since the default
328 // is 3.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000329 if (i == 1) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000330 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000331 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
332 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000333 } else {
334 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000335 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
336 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000337 }
338 }
339
Chris Lattner8ba580c2008-11-19 05:08:23 +0000340 return false;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000341}
342
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000343/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
344/// int type). This simply type checks that type is one of the defined
345/// constants (0-3).
346bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
347 Expr *Arg = TheCall->getArg(1);
348 QualType ArgType = Arg->getType();
349 const BuiltinType *BT = ArgType->getAsBuiltinType();
350 llvm::APSInt Result(32);
351 if (!BT || BT->getKind() != BuiltinType::Int ||
352 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000353 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
354 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000355 }
356
357 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000358 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
359 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000360 }
361
362 return false;
363}
364
Ted Kremenek8c797c02009-01-12 23:09:09 +0000365// Handle i > 1 ? "x" : "y", recursivelly
366bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
367 unsigned format_idx) {
368
369 switch (E->getStmtClass()) {
370 case Stmt::ConditionalOperatorClass: {
371 ConditionalOperator *C = cast<ConditionalOperator>(E);
372 return SemaCheckStringLiteral(C->getLHS(), TheCall,
373 HasVAListArg, format_idx)
374 && SemaCheckStringLiteral(C->getRHS(), TheCall,
375 HasVAListArg, format_idx);
376 }
377
378 case Stmt::ImplicitCastExprClass: {
379 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
380 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
381 format_idx);
382 }
383
384 case Stmt::ParenExprClass: {
385 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
386 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
387 format_idx);
388 }
389
390 default: {
391 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
392 StringLiteral *StrE = NULL;
393
394 if (ObjCFExpr)
395 StrE = ObjCFExpr->getString();
396 else
397 StrE = dyn_cast<StringLiteral>(E);
398
399 if (StrE) {
400 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx);
401 return true;
402 }
403
404 return false;
405 }
406 }
407}
408
409
Chris Lattner2e64c072007-08-10 20:18:51 +0000410/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek081ed872007-08-14 17:39:48 +0000411/// correct use of format strings.
412///
413/// HasVAListArg - A predicate indicating whether the printf-like
414/// function is passed an explicit va_arg argument (e.g., vprintf)
415///
416/// format_idx - The index into Args for the format string.
417///
418/// Improper format strings to functions in the printf family can be
419/// the source of bizarre bugs and very serious security holes. A
420/// good source of information is available in the following paper
421/// (which includes additional references):
Chris Lattner2e64c072007-08-10 20:18:51 +0000422///
423/// FormatGuard: Automatic Protection From printf Format String
424/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek081ed872007-08-14 17:39:48 +0000425///
426/// Functionality implemented:
427///
428/// We can statically check the following properties for string
429/// literal format strings for non v.*printf functions (where the
430/// arguments are passed directly):
431//
432/// (1) Are the number of format conversions equal to the number of
433/// data arguments?
434///
435/// (2) Does each format conversion correctly match the type of the
436/// corresponding data argument? (TODO)
437///
438/// Moreover, for all printf functions we can:
439///
440/// (3) Check for a missing format string (when not caught by type checking).
441///
442/// (4) Check for no-operation flags; e.g. using "#" with format
443/// conversion 'c' (TODO)
444///
445/// (5) Check the use of '%n', a major source of security holes.
446///
447/// (6) Check for malformed format conversions that don't specify anything.
448///
449/// (7) Check for empty format strings. e.g: printf("");
450///
451/// (8) Check that the format string is a wide literal.
452///
Ted Kremenekc2804c22008-03-03 16:50:00 +0000453/// (9) Also check the arguments of functions with the __format__ attribute.
454/// (TODO).
455///
Ted Kremenek081ed872007-08-14 17:39:48 +0000456/// All of these checks can be done by parsing the format string.
457///
458/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner2e64c072007-08-10 20:18:51 +0000459void
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000460Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
461 unsigned format_idx) {
462 Expr *Fn = TheCall->getCallee();
463
Ted Kremenek081ed872007-08-14 17:39:48 +0000464 // CHECK: printf-like function is called with no format string.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000465 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000466 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
467 << Fn->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000468 return;
469 }
470
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000471 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattnere65acc12007-08-25 05:36:18 +0000472
Chris Lattner2e64c072007-08-10 20:18:51 +0000473 // CHECK: format string is not a string literal.
474 //
Ted Kremenek081ed872007-08-14 17:39:48 +0000475 // Dynamically generated format strings are difficult to
476 // automatically vet at compile time. Requiring that format strings
477 // are string literals: (1) permits the checking of format strings by
478 // the compiler and thereby (2) can practically remove the source of
479 // many format string exploits.
Ted Kremenek225a14c2008-06-16 18:00:42 +0000480
481 // Format string can be either ObjC string (e.g. @"%d") or
482 // C string (e.g. "%d")
483 // ObjC string uses the same format specifiers as C string, so we can use
484 // the same format string checking logic for both ObjC and C strings.
Ted Kremenek8c797c02009-01-12 23:09:09 +0000485 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx);
Ted Kremenek225a14c2008-06-16 18:00:42 +0000486
Ted Kremenek8c797c02009-01-12 23:09:09 +0000487 if (!isFExpr) {
Ted Kremenek19398b62007-12-17 19:03:13 +0000488 // For vprintf* functions (i.e., HasVAListArg==true), we add a
489 // special check to see if the format string is a function parameter
490 // of the function calling the printf function. If the function
491 // has an attribute indicating it is a printf-like function, then we
492 // should suppress warnings concerning non-literals being used in a call
493 // to a vprintf function. For example:
494 //
495 // void
496 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
497 // va_list ap;
498 // va_start(ap, fmt);
499 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
500 // ...
501 //
502 //
503 // FIXME: We don't have full attribute support yet, so just check to see
504 // if the argument is a DeclRefExpr that references a parameter. We'll
505 // add proper support for checking the attribute later.
506 if (HasVAListArg)
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000507 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
508 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek19398b62007-12-17 19:03:13 +0000509 return;
Ted Kremenek8c797c02009-01-12 23:09:09 +0000510
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000511 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000512 diag::warn_printf_not_string_constant)
513 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000514 return;
515 }
Ted Kremenek8c797c02009-01-12 23:09:09 +0000516}
Ted Kremenek081ed872007-08-14 17:39:48 +0000517
Ted Kremenek8c797c02009-01-12 23:09:09 +0000518void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
519 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx) {
520
521 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek081ed872007-08-14 17:39:48 +0000522 // CHECK: is the format string a wide literal?
523 if (FExpr->isWide()) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000524 Diag(FExpr->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000525 diag::warn_printf_format_string_is_wide_literal)
526 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000527 return;
528 }
529
530 // Str - The format string. NOTE: this is NOT null-terminated!
531 const char * const Str = FExpr->getStrData();
532
533 // CHECK: empty format string?
534 const unsigned StrLen = FExpr->getByteLength();
535
536 if (StrLen == 0) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000537 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
538 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000539 return;
540 }
541
542 // We process the format string using a binary state machine. The
543 // current state is stored in CurrentState.
544 enum {
545 state_OrdChr,
546 state_Conversion
547 } CurrentState = state_OrdChr;
548
549 // numConversions - The number of conversions seen so far. This is
550 // incremented as we traverse the format string.
551 unsigned numConversions = 0;
552
553 // numDataArgs - The number of data arguments after the format
554 // string. This can only be determined for non vprintf-like
555 // functions. For those functions, this value is 1 (the sole
556 // va_arg argument).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000557 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000558
559 // Inspect the format string.
560 unsigned StrIdx = 0;
561
562 // LastConversionIdx - Index within the format string where we last saw
563 // a '%' character that starts a new format conversion.
564 unsigned LastConversionIdx = 0;
565
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000566 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000567
Ted Kremenek081ed872007-08-14 17:39:48 +0000568 // Is the number of detected conversion conversions greater than
569 // the number of matching data arguments? If so, stop.
570 if (!HasVAListArg && numConversions > numDataArgs) break;
571
572 // Handle "\0"
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000573 if (Str[StrIdx] == '\0') {
Ted Kremenek081ed872007-08-14 17:39:48 +0000574 // The string returned by getStrData() is not null-terminated,
575 // so the presence of a null character is likely an error.
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000576 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000577 diag::warn_printf_format_string_contains_null_char)
578 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000579 return;
580 }
581
582 // Ordinary characters (not processing a format conversion).
583 if (CurrentState == state_OrdChr) {
584 if (Str[StrIdx] == '%') {
585 CurrentState = state_Conversion;
586 LastConversionIdx = StrIdx;
587 }
588 continue;
589 }
590
591 // Seen '%'. Now processing a format conversion.
592 switch (Str[StrIdx]) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000593 // Handle dynamic precision or width specifier.
594 case '*': {
595 ++numConversions;
596
597 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000598 SourceLocation Loc = FExpr->getLocStart();
599 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek035d8792007-10-12 20:51:52 +0000600
Ted Kremenek035d8792007-10-12 20:51:52 +0000601 if (Str[StrIdx-1] == '.')
Chris Lattner9d2cf082008-11-19 05:27:50 +0000602 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
603 << OrigFormatExpr->getSourceRange();
Ted Kremenek035d8792007-10-12 20:51:52 +0000604 else
Chris Lattner9d2cf082008-11-19 05:27:50 +0000605 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
606 << OrigFormatExpr->getSourceRange();
Ted Kremenek035d8792007-10-12 20:51:52 +0000607
Chris Lattner68d88f02007-12-28 05:31:15 +0000608 // Don't do any more checking. We'll just emit spurious errors.
609 return;
Ted Kremenek035d8792007-10-12 20:51:52 +0000610 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000611
612 // Perform type checking on width/precision specifier.
613 Expr *E = TheCall->getArg(format_idx+numConversions);
614 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
615 if (BT->getKind() == BuiltinType::Int)
616 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000617
Chris Lattner68d88f02007-12-28 05:31:15 +0000618 SourceLocation Loc =
619 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
620
621 if (Str[StrIdx-1] == '.')
Chris Lattner9d2cf082008-11-19 05:27:50 +0000622 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000623 << E->getType() << E->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000624 else
Chris Lattner9d2cf082008-11-19 05:27:50 +0000625 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000626 << E->getType() << E->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000627
628 break;
629 }
630
631 // Characters which can terminate a format conversion
632 // (e.g. "%d"). Characters that specify length modifiers or
633 // other flags are handled by the default case below.
634 //
635 // FIXME: additional checks will go into the following cases.
636 case 'i':
637 case 'd':
638 case 'o':
639 case 'u':
640 case 'x':
641 case 'X':
642 case 'D':
643 case 'O':
644 case 'U':
645 case 'e':
646 case 'E':
647 case 'f':
648 case 'F':
649 case 'g':
650 case 'G':
651 case 'a':
652 case 'A':
653 case 'c':
654 case 'C':
655 case 'S':
656 case 's':
657 case 'p':
658 ++numConversions;
659 CurrentState = state_OrdChr;
660 break;
661
662 // CHECK: Are we using "%n"? Issue a warning.
663 case 'n': {
664 ++numConversions;
665 CurrentState = state_OrdChr;
666 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
667 LastConversionIdx+1);
668
Chris Lattner9d2cf082008-11-19 05:27:50 +0000669 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000670 break;
671 }
Ted Kremenek225a14c2008-06-16 18:00:42 +0000672
673 // Handle "%@"
674 case '@':
675 // %@ is allowed in ObjC format strings only.
676 if(ObjCFExpr != NULL)
677 CurrentState = state_OrdChr;
678 else {
679 // Issue a warning: invalid format conversion.
680 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
681 LastConversionIdx+1);
682
Chris Lattner77d52da2008-11-20 06:06:08 +0000683 Diag(Loc, diag::warn_printf_invalid_conversion)
684 << std::string(Str+LastConversionIdx,
685 Str+std::min(LastConversionIdx+2, StrLen))
686 << OrigFormatExpr->getSourceRange();
Ted Kremenek225a14c2008-06-16 18:00:42 +0000687 }
688 ++numConversions;
689 break;
690
Chris Lattner68d88f02007-12-28 05:31:15 +0000691 // Handle "%%"
692 case '%':
693 // Sanity check: Was the first "%" character the previous one?
694 // If not, we will assume that we have a malformed format
695 // conversion, and that the current "%" character is the start
696 // of a new conversion.
697 if (StrIdx - LastConversionIdx == 1)
698 CurrentState = state_OrdChr;
699 else {
700 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000701 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
702 LastConversionIdx+1);
Chris Lattner68d88f02007-12-28 05:31:15 +0000703
Chris Lattner77d52da2008-11-20 06:06:08 +0000704 Diag(Loc, diag::warn_printf_invalid_conversion)
705 << std::string(Str+LastConversionIdx, Str+StrIdx)
706 << OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000707
708 // This conversion is broken. Advance to the next format
709 // conversion.
710 LastConversionIdx = StrIdx;
711 ++numConversions;
Ted Kremenek081ed872007-08-14 17:39:48 +0000712 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000713 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000714
Chris Lattner68d88f02007-12-28 05:31:15 +0000715 default:
716 // This case catches all other characters: flags, widths, etc.
717 // We should eventually process those as well.
718 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000719 }
720 }
721
722 if (CurrentState == state_Conversion) {
723 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000724 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
725 LastConversionIdx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000726
Chris Lattner77d52da2008-11-20 06:06:08 +0000727 Diag(Loc, diag::warn_printf_invalid_conversion)
728 << std::string(Str+LastConversionIdx,
729 Str+std::min(LastConversionIdx+2, StrLen))
730 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000731 return;
732 }
733
734 if (!HasVAListArg) {
735 // CHECK: Does the number of format conversions exceed the number
736 // of data arguments?
737 if (numConversions > numDataArgs) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000738 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
739 LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +0000740
Chris Lattner9d2cf082008-11-19 05:27:50 +0000741 Diag(Loc, diag::warn_printf_insufficient_data_args)
742 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000743 }
744 // CHECK: Does the number of data arguments exceed the number of
745 // format conversions in the format string?
746 else if (numConversions < numDataArgs)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000747 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000748 diag::warn_printf_too_many_data_args)
749 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000750 }
751}
Ted Kremenek45925ab2007-08-17 16:46:58 +0000752
753//===--- CHECK: Return Address of Stack Variable --------------------------===//
754
755static DeclRefExpr* EvalVal(Expr *E);
756static DeclRefExpr* EvalAddr(Expr* E);
757
758/// CheckReturnStackAddr - Check if a return statement returns the address
759/// of a stack variable.
760void
761Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
762 SourceLocation ReturnLoc) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000763
Ted Kremenek45925ab2007-08-17 16:46:58 +0000764 // Perform checking for returned stack addresses.
Steve Naroffd6163f32008-09-05 22:11:13 +0000765 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000766 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner65cae292008-11-19 08:23:25 +0000767 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattnerb1753422008-11-23 21:45:46 +0000768 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroff503996b2008-09-16 22:25:10 +0000769
770 // Skip over implicit cast expressions when checking for block expressions.
771 if (ImplicitCastExpr *IcExpr =
772 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
773 RetValExp = IcExpr->getSubExpr();
774
Steve Naroff3eac7692008-09-10 19:17:48 +0000775 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000776 Diag(C->getLocStart(), diag::err_ret_local_block)
777 << C->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +0000778 }
779 // Perform checking for stack values returned by reference.
780 else if (lhsType->isReferenceType()) {
Douglas Gregor21a04f32008-10-27 19:41:14 +0000781 // Check for a reference to the stack
782 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000783 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattnerb1753422008-11-23 21:45:46 +0000784 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +0000785 }
786}
787
788/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
789/// check if the expression in a return statement evaluates to an address
790/// to a location on the stack. The recursion is used to traverse the
791/// AST of the return expression, with recursion backtracking when we
792/// encounter a subexpression that (1) clearly does not lead to the address
793/// of a stack variable or (2) is something we cannot determine leads to
794/// the address of a stack variable based on such local checking.
795///
Ted Kremenekda1300a2007-08-28 17:02:55 +0000796/// EvalAddr processes expressions that are pointers that are used as
797/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek45925ab2007-08-17 16:46:58 +0000798/// At the base case of the recursion is a check for a DeclRefExpr* in
799/// the refers to a stack variable.
800///
801/// This implementation handles:
802///
803/// * pointer-to-pointer casts
804/// * implicit conversions from array references to pointers
805/// * taking the address of fields
806/// * arbitrary interplay between "&" and "*" operators
807/// * pointer arithmetic from an address of a stack variable
808/// * taking the address of an array element where the array is on the stack
809static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000810 // We should only be called for evaluating pointer expressions.
Steve Naroffd6163f32008-09-05 22:11:13 +0000811 assert((E->getType()->isPointerType() ||
812 E->getType()->isBlockPointerType() ||
Ted Kremenek42730c52008-01-07 19:49:32 +0000813 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner68d88f02007-12-28 05:31:15 +0000814 "EvalAddr only works on pointers");
Ted Kremenek45925ab2007-08-17 16:46:58 +0000815
816 // Our "symbolic interpreter" is just a dispatch off the currently
817 // viewed AST node. We then recursively traverse the AST by calling
818 // EvalAddr and EvalVal appropriately.
819 switch (E->getStmtClass()) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000820 case Stmt::ParenExprClass:
821 // Ignore parentheses.
822 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000823
Chris Lattner68d88f02007-12-28 05:31:15 +0000824 case Stmt::UnaryOperatorClass: {
825 // The only unary operator that make sense to handle here
826 // is AddrOf. All others don't make sense as pointers.
827 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek45925ab2007-08-17 16:46:58 +0000828
Chris Lattner68d88f02007-12-28 05:31:15 +0000829 if (U->getOpcode() == UnaryOperator::AddrOf)
830 return EvalVal(U->getSubExpr());
831 else
Ted Kremenek45925ab2007-08-17 16:46:58 +0000832 return NULL;
833 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000834
835 case Stmt::BinaryOperatorClass: {
836 // Handle pointer arithmetic. All other binary operators are not valid
837 // in this context.
838 BinaryOperator *B = cast<BinaryOperator>(E);
839 BinaryOperator::Opcode op = B->getOpcode();
840
841 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
842 return NULL;
843
844 Expr *Base = B->getLHS();
845
846 // Determine which argument is the real pointer base. It could be
847 // the RHS argument instead of the LHS.
848 if (!Base->getType()->isPointerType()) Base = B->getRHS();
849
850 assert (Base->getType()->isPointerType());
851 return EvalAddr(Base);
852 }
Steve Naroff3eac7692008-09-10 19:17:48 +0000853
Chris Lattner68d88f02007-12-28 05:31:15 +0000854 // For conditional operators we need to see if either the LHS or RHS are
855 // valid DeclRefExpr*s. If one of them is valid, we return it.
856 case Stmt::ConditionalOperatorClass: {
857 ConditionalOperator *C = cast<ConditionalOperator>(E);
858
859 // Handle the GNU extension for missing LHS.
860 if (Expr *lhsExpr = C->getLHS())
861 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
862 return LHS;
863
864 return EvalAddr(C->getRHS());
865 }
866
Ted Kremenekea19edd2008-08-07 00:49:01 +0000867 // For casts, we need to handle conversions from arrays to
868 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor21a04f32008-10-27 19:41:14 +0000869 case Stmt::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +0000870 case Stmt::CStyleCastExprClass:
Douglas Gregor21a04f32008-10-27 19:41:14 +0000871 case Stmt::CXXFunctionalCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000872 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekea19edd2008-08-07 00:49:01 +0000873 QualType T = SubExpr->getType();
874
Steve Naroffd6163f32008-09-05 22:11:13 +0000875 if (SubExpr->getType()->isPointerType() ||
876 SubExpr->getType()->isBlockPointerType() ||
877 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenekea19edd2008-08-07 00:49:01 +0000878 return EvalAddr(SubExpr);
879 else if (T->isArrayType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000880 return EvalVal(SubExpr);
Chris Lattner68d88f02007-12-28 05:31:15 +0000881 else
Ted Kremenekea19edd2008-08-07 00:49:01 +0000882 return 0;
Chris Lattner68d88f02007-12-28 05:31:15 +0000883 }
884
885 // C++ casts. For dynamic casts, static casts, and const casts, we
886 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor21a04f32008-10-27 19:41:14 +0000887 // through the cast. In the case the dynamic cast doesn't fail (and
888 // return NULL), we take the conservative route and report cases
Chris Lattner68d88f02007-12-28 05:31:15 +0000889 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor21a04f32008-10-27 19:41:14 +0000890 // FIXME: The comment about is wrong; we're not always converting
891 // from pointer to pointer. I'm guessing that this code should also
892 // handle references to objects.
893 case Stmt::CXXStaticCastExprClass:
894 case Stmt::CXXDynamicCastExprClass:
895 case Stmt::CXXConstCastExprClass:
896 case Stmt::CXXReinterpretCastExprClass: {
897 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffd6163f32008-09-05 22:11:13 +0000898 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000899 return EvalAddr(S);
900 else
901 return NULL;
Chris Lattner68d88f02007-12-28 05:31:15 +0000902 }
903
904 // Everything else: we simply don't reason about them.
905 default:
906 return NULL;
907 }
Ted Kremenek45925ab2007-08-17 16:46:58 +0000908}
909
910
911/// EvalVal - This function is complements EvalAddr in the mutual recursion.
912/// See the comments for EvalAddr for more details.
913static DeclRefExpr* EvalVal(Expr *E) {
914
Ted Kremenekda1300a2007-08-28 17:02:55 +0000915 // We should only be called for evaluating non-pointer expressions, or
916 // expressions with a pointer type that are not used as references but instead
917 // are l-values (e.g., DeclRefExpr with a pointer type).
918
Ted Kremenek45925ab2007-08-17 16:46:58 +0000919 // Our "symbolic interpreter" is just a dispatch off the currently
920 // viewed AST node. We then recursively traverse the AST by calling
921 // EvalAddr and EvalVal appropriately.
922 switch (E->getStmtClass()) {
Douglas Gregor566782a2009-01-06 05:10:23 +0000923 case Stmt::DeclRefExprClass:
924 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000925 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
926 // at code that refers to a variable's name. We check if it has local
927 // storage within the function, and if so, return the expression.
928 DeclRefExpr *DR = cast<DeclRefExpr>(E);
929
930 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor81c29152008-10-29 00:13:59 +0000931 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek45925ab2007-08-17 16:46:58 +0000932
933 return NULL;
934 }
935
936 case Stmt::ParenExprClass:
937 // Ignore parentheses.
938 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
939
940 case Stmt::UnaryOperatorClass: {
941 // The only unary operator that make sense to handle here
942 // is Deref. All others don't resolve to a "name." This includes
943 // handling all sorts of rvalues passed to a unary operator.
944 UnaryOperator *U = cast<UnaryOperator>(E);
945
946 if (U->getOpcode() == UnaryOperator::Deref)
947 return EvalAddr(U->getSubExpr());
948
949 return NULL;
950 }
951
952 case Stmt::ArraySubscriptExprClass: {
953 // Array subscripts are potential references to data on the stack. We
954 // retrieve the DeclRefExpr* for the array variable if it indeed
955 // has local storage.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000956 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000957 }
958
959 case Stmt::ConditionalOperatorClass: {
960 // For conditional operators we need to see if either the LHS or RHS are
961 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
962 ConditionalOperator *C = cast<ConditionalOperator>(E);
963
Anders Carlsson37365fc2007-11-30 19:04:31 +0000964 // Handle the GNU extension for missing LHS.
965 if (Expr *lhsExpr = C->getLHS())
966 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
967 return LHS;
968
969 return EvalVal(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000970 }
971
972 // Accesses to members are potential references to data on the stack.
973 case Stmt::MemberExprClass: {
974 MemberExpr *M = cast<MemberExpr>(E);
975
976 // Check for indirect access. We only want direct field accesses.
977 if (!M->isArrow())
978 return EvalVal(M->getBase());
979 else
980 return NULL;
981 }
982
983 // Everything else: we simply don't reason about them.
984 default:
985 return NULL;
986 }
987}
Ted Kremenek30c66752007-11-25 00:58:00 +0000988
989//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
990
991/// Check for comparisons of floating point operands using != and ==.
992/// Issue a warning if these are no self-comparisons, as they are not likely
993/// to do what the programmer intended.
994void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
995 bool EmitWarning = true;
996
Ted Kremenek87e30c52008-01-17 16:57:34 +0000997 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek24c61682008-01-17 17:55:13 +0000998 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek30c66752007-11-25 00:58:00 +0000999
1000 // Special case: check for x == x (which is OK).
1001 // Do not emit warnings for such cases.
1002 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1003 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1004 if (DRL->getDecl() == DRR->getDecl())
1005 EmitWarning = false;
1006
Ted Kremenek33159832007-11-29 00:59:04 +00001007
1008 // Special case: check for comparisons against literals that can be exactly
1009 // represented by APFloat. In such cases, do not emit a warning. This
1010 // is a heuristic: often comparison against such literals are used to
1011 // detect if a value in a variable has not changed. This clearly can
1012 // lead to false negatives.
1013 if (EmitWarning) {
1014 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1015 if (FLL->isExact())
1016 EmitWarning = false;
1017 }
1018 else
1019 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1020 if (FLR->isExact())
1021 EmitWarning = false;
1022 }
1023 }
1024
Ted Kremenek30c66752007-11-25 00:58:00 +00001025 // Check for comparisons with builtin types.
Sebastian Redl8b769972009-01-19 00:08:26 +00001026 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001027 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1028 if (isCallBuiltin(CL))
1029 EmitWarning = false;
1030
Sebastian Redl8b769972009-01-19 00:08:26 +00001031 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001032 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1033 if (isCallBuiltin(CR))
1034 EmitWarning = false;
1035
1036 // Emit the diagnostic.
1037 if (EmitWarning)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001038 Diag(loc, diag::warn_floatingpoint_eq)
1039 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek30c66752007-11-25 00:58:00 +00001040}