blob: 9a60861bc28c1169e817374d18f97e1bf032421b [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner59907c42007-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 Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000020#include "clang/Lex/Preprocessor.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/Basic/Diagnostic.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000022#include "SemaUtil.h"
Chris Lattner59907c42007-08-10 20:18:51 +000023using namespace clang;
24
25/// CheckFunctionCall - Check a direct function call for various correctness
26/// and safety properties not strictly enforced by the C type system.
Sebastian Redl0eb23302009-01-19 00:08:26 +000027Action::OwningExprResult
28Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
29 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +000030 // Get the IdentifierInfo* for the called function.
31 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +000032
33 // None of the checks below are needed for functions that don't have
34 // simple names (e.g., C++ conversion functions).
35 if (!FnInfo)
Sebastian Redl0eb23302009-01-19 00:08:26 +000036 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +000037
Chris Lattner30ce3442007-12-19 23:59:04 +000038 switch (FnInfo->getBuiltinID()) {
39 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +000040 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +000041 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedmane8018702008-05-16 17:51:27 +000042 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +000043 return ExprError();
44 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +000045 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +000046 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +000047 if (SemaBuiltinVAStart(TheCall))
48 return ExprError();
49 return move(TheCallResult);
Chris Lattner1b9a0792007-12-20 00:26:33 +000050 case Builtin::BI__builtin_isgreater:
51 case Builtin::BI__builtin_isgreaterequal:
52 case Builtin::BI__builtin_isless:
53 case Builtin::BI__builtin_islessequal:
54 case Builtin::BI__builtin_islessgreater:
55 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +000056 if (SemaBuiltinUnorderedCompare(TheCall))
57 return ExprError();
58 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +000059 case Builtin::BI__builtin_return_address:
60 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +000061 if (SemaBuiltinStackAddress(TheCall))
62 return ExprError();
63 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +000064 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +000065 return SemaBuiltinShuffleVector(TheCall);
66 // TheCall will be freed by the smart pointer here, but that's fine, since
67 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +000068 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +000069 if (SemaBuiltinPrefetch(TheCall))
70 return ExprError();
71 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +000072 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +000073 if (SemaBuiltinObjectSize(TheCall))
74 return ExprError();
Anders Carlsson71993dd2007-08-17 05:31:46 +000075 }
Daniel Dunbarde454282008-10-02 18:44:07 +000076
77 // FIXME: This mechanism should be abstracted to be less fragile and
78 // more efficient. For example, just map function ids to custom
79 // handlers.
80
Chris Lattner59907c42007-08-10 20:18:51 +000081 // Search the KnownFunctionIDs for the identifier.
82 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek71895b92007-08-14 17:39:48 +000083 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Sebastian Redl0eb23302009-01-19 00:08:26 +000084 if (i == e) return move(TheCallResult);
85
Chris Lattner59907c42007-08-10 20:18:51 +000086 // Printf checking.
87 if (i <= id_vprintf) {
Ted Kremenek71895b92007-08-14 17:39:48 +000088 // Retrieve the index of the format string parameter and determine
89 // if the function is passed a va_arg argument.
Chris Lattner59907c42007-08-10 20:18:51 +000090 unsigned format_idx = 0;
Ted Kremenek71895b92007-08-14 17:39:48 +000091 bool HasVAListArg = false;
Sebastian Redl0eb23302009-01-19 00:08:26 +000092
Chris Lattner59907c42007-08-10 20:18:51 +000093 switch (i) {
Chris Lattner30ce3442007-12-19 23:59:04 +000094 default: assert(false && "No format string argument index.");
Daniel Dunbarde454282008-10-02 18:44:07 +000095 case id_NSLog: format_idx = 0; break;
96 case id_asprintf: format_idx = 1; break;
97 case id_fprintf: format_idx = 1; break;
98 case id_printf: format_idx = 0; break;
99 case id_snprintf: format_idx = 2; break;
100 case id_snprintf_chk: format_idx = 4; break;
101 case id_sprintf: format_idx = 1; break;
102 case id_sprintf_chk: format_idx = 3; break;
103 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
104 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
105 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
106 case id_vsnprintf_chk: format_idx = 4; HasVAListArg = true; break;
107 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
108 case id_vsprintf_chk: format_idx = 3; HasVAListArg = true; break;
109 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000110 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000111
112 CheckPrintfArguments(TheCall, HasVAListArg, format_idx);
Chris Lattner59907c42007-08-10 20:18:51 +0000113 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000114
115 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000116}
117
118/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
119/// CFString constructor is correct
Chris Lattnercc6f65d2007-08-25 05:30:33 +0000120bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000121 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000122
123 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
124
125 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000126 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
127 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000128 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000129 }
130
131 const char *Data = Literal->getStrData();
132 unsigned Length = Literal->getByteLength();
133
134 for (unsigned i = 0; i < Length; ++i) {
135 if (!isascii(Data[i])) {
136 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000137 diag::warn_cfstring_literal_contains_non_ascii_character)
138 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000139 break;
140 }
141
142 if (!Data[i]) {
143 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000144 diag::warn_cfstring_literal_contains_nul_character)
145 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000146 break;
147 }
148 }
149
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000150 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000151}
152
Chris Lattnerc27c6652007-12-20 00:05:45 +0000153/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
154/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000155bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
156 Expr *Fn = TheCall->getCallee();
157 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000158 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000159 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000160 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000161 << SourceRange(TheCall->getArg(2)->getLocStart(),
162 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000163 return true;
164 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000165
166 if (TheCall->getNumArgs() < 2) {
167 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
168 << 0 /*function call*/;
169 }
170
Chris Lattnerc27c6652007-12-20 00:05:45 +0000171 // Determine whether the current function is variadic or not.
172 bool isVariadic;
Eli Friedman56f20ae2008-12-15 22:05:35 +0000173 if (getCurFunctionDecl()) {
174 if (FunctionTypeProto* FTP =
175 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType()))
176 isVariadic = FTP->isVariadic();
177 else
178 isVariadic = false;
179 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000180 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000181 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000182
Chris Lattnerc27c6652007-12-20 00:05:45 +0000183 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000184 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
185 return true;
186 }
187
188 // Verify that the second argument to the builtin is the last argument of the
189 // current function or method.
190 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000191 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000192
193 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
194 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000195 // FIXME: This isn't correct for methods (results in bogus warning).
196 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000197 const ParmVarDecl *LastArg;
Chris Lattner371f2582008-12-04 23:50:19 +0000198 if (FunctionDecl *FD = getCurFunctionDecl())
199 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000200 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000201 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000202 SecondArgIsLastNamedArgument = PV == LastArg;
203 }
204 }
205
206 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000207 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000208 diag::warn_second_parameter_of_va_start_not_last_named_argument);
209 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000210}
Chris Lattner30ce3442007-12-19 23:59:04 +0000211
Chris Lattner1b9a0792007-12-20 00:26:33 +0000212/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
213/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000214bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
215 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000216 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
217 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000218 if (TheCall->getNumArgs() > 2)
219 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000220 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000221 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000222 << SourceRange(TheCall->getArg(2)->getLocStart(),
223 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000224
Chris Lattner925e60d2007-12-28 05:29:59 +0000225 Expr *OrigArg0 = TheCall->getArg(0);
226 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000227
228 // Do standard promotions between the two arguments, returning their common
229 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000230 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000231
232 // If the common type isn't a real floating type, then the arguments were
233 // invalid for this operation.
234 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000235 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000236 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000237 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000238 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000239
240 return false;
241}
242
Eli Friedman6cfda232008-05-20 08:23:37 +0000243bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
244 // The signature for these builtins is exact; the only thing we need
245 // to check is that the argument is a constant.
246 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000247 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000248 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000249
Eli Friedman6cfda232008-05-20 08:23:37 +0000250 return false;
251}
252
Eli Friedmand38617c2008-05-14 19:38:39 +0000253/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
254// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000255Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000256 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000257 return ExprError(Diag(TheCall->getLocEnd(),
258 diag::err_typecheck_call_too_few_args)
259 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000260
261 QualType FAType = TheCall->getArg(0)->getType();
262 QualType SAType = TheCall->getArg(1)->getType();
263
264 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000265 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
266 << SourceRange(TheCall->getArg(0)->getLocStart(),
267 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000268 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000269 }
270
Chris Lattnerb77792e2008-07-26 22:17:49 +0000271 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
272 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000273 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
274 << SourceRange(TheCall->getArg(0)->getLocStart(),
275 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000276 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000277 }
278
279 unsigned numElements = FAType->getAsVectorType()->getNumElements();
280 if (TheCall->getNumArgs() != numElements+2) {
281 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000282 return ExprError(Diag(TheCall->getLocEnd(),
283 diag::err_typecheck_call_too_few_args)
284 << 0 /*function call*/ << TheCall->getSourceRange());
285 return ExprError(Diag(TheCall->getLocEnd(),
286 diag::err_typecheck_call_too_many_args)
287 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000288 }
289
290 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
291 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000292 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000293 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000294 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000295 << TheCall->getArg(i)->getSourceRange());
296
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000297 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000298 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000299 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000300 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000301 }
302
303 llvm::SmallVector<Expr*, 32> exprs;
304
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000305 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000306 exprs.push_back(TheCall->getArg(i));
307 TheCall->setArg(i, 0);
308 }
309
Sebastian Redl0eb23302009-01-19 00:08:26 +0000310 return Owned(new ShuffleVectorExpr(exprs.begin(), numElements+2, FAType,
311 TheCall->getCallee()->getLocStart(),
312 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000313}
Chris Lattner30ce3442007-12-19 23:59:04 +0000314
Daniel Dunbar4493f792008-07-21 22:59:13 +0000315/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
316// This is declared to take (const void*, ...) and can take two
317// optional constant int args.
318bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000319 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000320
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000321 if (NumArgs > 3)
322 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000323 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000324
325 // Argument 0 is checked for us and the remaining arguments must be
326 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000327 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000328 Expr *Arg = TheCall->getArg(i);
329 QualType RWType = Arg->getType();
330
331 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000332 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000333 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000334 !Arg->isIntegerConstantExpr(Result, Context))
335 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
336 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000337
338 // FIXME: gcc issues a warning and rewrites these to 0. These
339 // seems especially odd for the third argument since the default
340 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000341 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000342 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000343 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
344 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000345 } else {
346 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000347 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
348 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000349 }
350 }
351
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000352 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000353}
354
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000355/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
356/// int type). This simply type checks that type is one of the defined
357/// constants (0-3).
358bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
359 Expr *Arg = TheCall->getArg(1);
360 QualType ArgType = Arg->getType();
361 const BuiltinType *BT = ArgType->getAsBuiltinType();
362 llvm::APSInt Result(32);
363 if (!BT || BT->getKind() != BuiltinType::Int ||
364 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000365 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
366 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000367 }
368
369 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000370 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
371 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000372 }
373
374 return false;
375}
376
Ted Kremenekd30ef872009-01-12 23:09:09 +0000377// Handle i > 1 ? "x" : "y", recursivelly
378bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
379 unsigned format_idx) {
380
381 switch (E->getStmtClass()) {
382 case Stmt::ConditionalOperatorClass: {
383 ConditionalOperator *C = cast<ConditionalOperator>(E);
384 return SemaCheckStringLiteral(C->getLHS(), TheCall,
385 HasVAListArg, format_idx)
386 && SemaCheckStringLiteral(C->getRHS(), TheCall,
387 HasVAListArg, format_idx);
388 }
389
390 case Stmt::ImplicitCastExprClass: {
391 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
392 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
393 format_idx);
394 }
395
396 case Stmt::ParenExprClass: {
397 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
398 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
399 format_idx);
400 }
401
402 default: {
403 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
404 StringLiteral *StrE = NULL;
405
406 if (ObjCFExpr)
407 StrE = ObjCFExpr->getString();
408 else
409 StrE = dyn_cast<StringLiteral>(E);
410
411 if (StrE) {
412 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx);
413 return true;
414 }
415
416 return false;
417 }
418 }
419}
420
421
Chris Lattner59907c42007-08-10 20:18:51 +0000422/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000423/// correct use of format strings.
424///
425/// HasVAListArg - A predicate indicating whether the printf-like
426/// function is passed an explicit va_arg argument (e.g., vprintf)
427///
428/// format_idx - The index into Args for the format string.
429///
430/// Improper format strings to functions in the printf family can be
431/// the source of bizarre bugs and very serious security holes. A
432/// good source of information is available in the following paper
433/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000434///
435/// FormatGuard: Automatic Protection From printf Format String
436/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000437///
438/// Functionality implemented:
439///
440/// We can statically check the following properties for string
441/// literal format strings for non v.*printf functions (where the
442/// arguments are passed directly):
443//
444/// (1) Are the number of format conversions equal to the number of
445/// data arguments?
446///
447/// (2) Does each format conversion correctly match the type of the
448/// corresponding data argument? (TODO)
449///
450/// Moreover, for all printf functions we can:
451///
452/// (3) Check for a missing format string (when not caught by type checking).
453///
454/// (4) Check for no-operation flags; e.g. using "#" with format
455/// conversion 'c' (TODO)
456///
457/// (5) Check the use of '%n', a major source of security holes.
458///
459/// (6) Check for malformed format conversions that don't specify anything.
460///
461/// (7) Check for empty format strings. e.g: printf("");
462///
463/// (8) Check that the format string is a wide literal.
464///
Ted Kremenek6d439592008-03-03 16:50:00 +0000465/// (9) Also check the arguments of functions with the __format__ attribute.
466/// (TODO).
467///
Ted Kremenek71895b92007-08-14 17:39:48 +0000468/// All of these checks can be done by parsing the format string.
469///
470/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000471void
Chris Lattner925e60d2007-12-28 05:29:59 +0000472Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
473 unsigned format_idx) {
474 Expr *Fn = TheCall->getCallee();
475
Ted Kremenek71895b92007-08-14 17:39:48 +0000476 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000477 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000478 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
479 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000480 return;
481 }
482
Chris Lattner56f34942008-02-13 01:02:39 +0000483 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000484
Chris Lattner59907c42007-08-10 20:18:51 +0000485 // CHECK: format string is not a string literal.
486 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000487 // Dynamically generated format strings are difficult to
488 // automatically vet at compile time. Requiring that format strings
489 // are string literals: (1) permits the checking of format strings by
490 // the compiler and thereby (2) can practically remove the source of
491 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000492
493 // Format string can be either ObjC string (e.g. @"%d") or
494 // C string (e.g. "%d")
495 // ObjC string uses the same format specifiers as C string, so we can use
496 // the same format string checking logic for both ObjC and C strings.
Ted Kremenekd30ef872009-01-12 23:09:09 +0000497 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000498
Ted Kremenekd30ef872009-01-12 23:09:09 +0000499 if (!isFExpr) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000500 // For vprintf* functions (i.e., HasVAListArg==true), we add a
501 // special check to see if the format string is a function parameter
502 // of the function calling the printf function. If the function
503 // has an attribute indicating it is a printf-like function, then we
504 // should suppress warnings concerning non-literals being used in a call
505 // to a vprintf function. For example:
506 //
507 // void
508 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
509 // va_list ap;
510 // va_start(ap, fmt);
511 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
512 // ...
513 //
514 //
515 // FIXME: We don't have full attribute support yet, so just check to see
516 // if the argument is a DeclRefExpr that references a parameter. We'll
517 // add proper support for checking the attribute later.
518 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000519 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
520 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000521 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000522
Chris Lattner925e60d2007-12-28 05:29:59 +0000523 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000524 diag::warn_printf_not_string_constant)
525 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000526 return;
527 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000528}
Ted Kremenek71895b92007-08-14 17:39:48 +0000529
Ted Kremenekd30ef872009-01-12 23:09:09 +0000530void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
531 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx) {
532
533 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000534 // CHECK: is the format string a wide literal?
535 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000536 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000537 diag::warn_printf_format_string_is_wide_literal)
538 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000539 return;
540 }
541
542 // Str - The format string. NOTE: this is NOT null-terminated!
543 const char * const Str = FExpr->getStrData();
544
545 // CHECK: empty format string?
546 const unsigned StrLen = FExpr->getByteLength();
547
548 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000549 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
550 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000551 return;
552 }
553
554 // We process the format string using a binary state machine. The
555 // current state is stored in CurrentState.
556 enum {
557 state_OrdChr,
558 state_Conversion
559 } CurrentState = state_OrdChr;
560
561 // numConversions - The number of conversions seen so far. This is
562 // incremented as we traverse the format string.
563 unsigned numConversions = 0;
564
565 // numDataArgs - The number of data arguments after the format
566 // string. This can only be determined for non vprintf-like
567 // functions. For those functions, this value is 1 (the sole
568 // va_arg argument).
Chris Lattner925e60d2007-12-28 05:29:59 +0000569 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000570
571 // Inspect the format string.
572 unsigned StrIdx = 0;
573
574 // LastConversionIdx - Index within the format string where we last saw
575 // a '%' character that starts a new format conversion.
576 unsigned LastConversionIdx = 0;
577
Chris Lattner925e60d2007-12-28 05:29:59 +0000578 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000579
Ted Kremenek71895b92007-08-14 17:39:48 +0000580 // Is the number of detected conversion conversions greater than
581 // the number of matching data arguments? If so, stop.
582 if (!HasVAListArg && numConversions > numDataArgs) break;
583
584 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000585 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000586 // The string returned by getStrData() is not null-terminated,
587 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000588 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000589 diag::warn_printf_format_string_contains_null_char)
590 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000591 return;
592 }
593
594 // Ordinary characters (not processing a format conversion).
595 if (CurrentState == state_OrdChr) {
596 if (Str[StrIdx] == '%') {
597 CurrentState = state_Conversion;
598 LastConversionIdx = StrIdx;
599 }
600 continue;
601 }
602
603 // Seen '%'. Now processing a format conversion.
604 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000605 // Handle dynamic precision or width specifier.
606 case '*': {
607 ++numConversions;
608
609 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000610 SourceLocation Loc = FExpr->getLocStart();
611 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000612
Ted Kremenek580b6642007-10-12 20:51:52 +0000613 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000614 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
615 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000616 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000617 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
618 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000619
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000620 // Don't do any more checking. We'll just emit spurious errors.
621 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000622 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000623
624 // Perform type checking on width/precision specifier.
625 Expr *E = TheCall->getArg(format_idx+numConversions);
626 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
627 if (BT->getKind() == BuiltinType::Int)
628 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000629
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000630 SourceLocation Loc =
631 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
632
633 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000634 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000635 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000636 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000637 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000638 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000639
640 break;
641 }
642
643 // Characters which can terminate a format conversion
644 // (e.g. "%d"). Characters that specify length modifiers or
645 // other flags are handled by the default case below.
646 //
647 // FIXME: additional checks will go into the following cases.
648 case 'i':
649 case 'd':
650 case 'o':
651 case 'u':
652 case 'x':
653 case 'X':
654 case 'D':
655 case 'O':
656 case 'U':
657 case 'e':
658 case 'E':
659 case 'f':
660 case 'F':
661 case 'g':
662 case 'G':
663 case 'a':
664 case 'A':
665 case 'c':
666 case 'C':
667 case 'S':
668 case 's':
669 case 'p':
670 ++numConversions;
671 CurrentState = state_OrdChr;
672 break;
673
674 // CHECK: Are we using "%n"? Issue a warning.
675 case 'n': {
676 ++numConversions;
677 CurrentState = state_OrdChr;
678 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
679 LastConversionIdx+1);
680
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000681 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000682 break;
683 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000684
685 // Handle "%@"
686 case '@':
687 // %@ is allowed in ObjC format strings only.
688 if(ObjCFExpr != NULL)
689 CurrentState = state_OrdChr;
690 else {
691 // Issue a warning: invalid format conversion.
692 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
693 LastConversionIdx+1);
694
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000695 Diag(Loc, diag::warn_printf_invalid_conversion)
696 << std::string(Str+LastConversionIdx,
697 Str+std::min(LastConversionIdx+2, StrLen))
698 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000699 }
700 ++numConversions;
701 break;
702
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000703 // Handle "%%"
704 case '%':
705 // Sanity check: Was the first "%" character the previous one?
706 // If not, we will assume that we have a malformed format
707 // conversion, and that the current "%" character is the start
708 // of a new conversion.
709 if (StrIdx - LastConversionIdx == 1)
710 CurrentState = state_OrdChr;
711 else {
712 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000713 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
714 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000715
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000716 Diag(Loc, diag::warn_printf_invalid_conversion)
717 << std::string(Str+LastConversionIdx, Str+StrIdx)
718 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000719
720 // This conversion is broken. Advance to the next format
721 // conversion.
722 LastConversionIdx = StrIdx;
723 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000724 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000725 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000726
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000727 default:
728 // This case catches all other characters: flags, widths, etc.
729 // We should eventually process those as well.
730 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000731 }
732 }
733
734 if (CurrentState == state_Conversion) {
735 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000736 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
737 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000738
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000739 Diag(Loc, diag::warn_printf_invalid_conversion)
740 << std::string(Str+LastConversionIdx,
741 Str+std::min(LastConversionIdx+2, StrLen))
742 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000743 return;
744 }
745
746 if (!HasVAListArg) {
747 // CHECK: Does the number of format conversions exceed the number
748 // of data arguments?
749 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000750 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
751 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000752
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000753 Diag(Loc, diag::warn_printf_insufficient_data_args)
754 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000755 }
756 // CHECK: Does the number of data arguments exceed the number of
757 // format conversions in the format string?
758 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000759 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000760 diag::warn_printf_too_many_data_args)
761 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000762 }
763}
Ted Kremenek06de2762007-08-17 16:46:58 +0000764
765//===--- CHECK: Return Address of Stack Variable --------------------------===//
766
767static DeclRefExpr* EvalVal(Expr *E);
768static DeclRefExpr* EvalAddr(Expr* E);
769
770/// CheckReturnStackAddr - Check if a return statement returns the address
771/// of a stack variable.
772void
773Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
774 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000775
Ted Kremenek06de2762007-08-17 16:46:58 +0000776 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000777 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000778 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +0000779 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +0000780 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +0000781
782 // Skip over implicit cast expressions when checking for block expressions.
783 if (ImplicitCastExpr *IcExpr =
784 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
785 RetValExp = IcExpr->getSubExpr();
786
Steve Naroff61f40a22008-09-10 19:17:48 +0000787 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000788 Diag(C->getLocStart(), diag::err_ret_local_block)
789 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000790 }
791 // Perform checking for stack values returned by reference.
792 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000793 // Check for a reference to the stack
794 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000795 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +0000796 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000797 }
798}
799
800/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
801/// check if the expression in a return statement evaluates to an address
802/// to a location on the stack. The recursion is used to traverse the
803/// AST of the return expression, with recursion backtracking when we
804/// encounter a subexpression that (1) clearly does not lead to the address
805/// of a stack variable or (2) is something we cannot determine leads to
806/// the address of a stack variable based on such local checking.
807///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000808/// EvalAddr processes expressions that are pointers that are used as
809/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000810/// At the base case of the recursion is a check for a DeclRefExpr* in
811/// the refers to a stack variable.
812///
813/// This implementation handles:
814///
815/// * pointer-to-pointer casts
816/// * implicit conversions from array references to pointers
817/// * taking the address of fields
818/// * arbitrary interplay between "&" and "*" operators
819/// * pointer arithmetic from an address of a stack variable
820/// * taking the address of an array element where the array is on the stack
821static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000822 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000823 assert((E->getType()->isPointerType() ||
824 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000825 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000826 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000827
828 // Our "symbolic interpreter" is just a dispatch off the currently
829 // viewed AST node. We then recursively traverse the AST by calling
830 // EvalAddr and EvalVal appropriately.
831 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000832 case Stmt::ParenExprClass:
833 // Ignore parentheses.
834 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000835
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000836 case Stmt::UnaryOperatorClass: {
837 // The only unary operator that make sense to handle here
838 // is AddrOf. All others don't make sense as pointers.
839 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000840
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000841 if (U->getOpcode() == UnaryOperator::AddrOf)
842 return EvalVal(U->getSubExpr());
843 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000844 return NULL;
845 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000846
847 case Stmt::BinaryOperatorClass: {
848 // Handle pointer arithmetic. All other binary operators are not valid
849 // in this context.
850 BinaryOperator *B = cast<BinaryOperator>(E);
851 BinaryOperator::Opcode op = B->getOpcode();
852
853 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
854 return NULL;
855
856 Expr *Base = B->getLHS();
857
858 // Determine which argument is the real pointer base. It could be
859 // the RHS argument instead of the LHS.
860 if (!Base->getType()->isPointerType()) Base = B->getRHS();
861
862 assert (Base->getType()->isPointerType());
863 return EvalAddr(Base);
864 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000865
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000866 // For conditional operators we need to see if either the LHS or RHS are
867 // valid DeclRefExpr*s. If one of them is valid, we return it.
868 case Stmt::ConditionalOperatorClass: {
869 ConditionalOperator *C = cast<ConditionalOperator>(E);
870
871 // Handle the GNU extension for missing LHS.
872 if (Expr *lhsExpr = C->getLHS())
873 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
874 return LHS;
875
876 return EvalAddr(C->getRHS());
877 }
878
Ted Kremenek54b52742008-08-07 00:49:01 +0000879 // For casts, we need to handle conversions from arrays to
880 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000881 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000882 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000883 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000884 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000885 QualType T = SubExpr->getType();
886
Steve Naroffdd972f22008-09-05 22:11:13 +0000887 if (SubExpr->getType()->isPointerType() ||
888 SubExpr->getType()->isBlockPointerType() ||
889 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000890 return EvalAddr(SubExpr);
891 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000892 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000893 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000894 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000895 }
896
897 // C++ casts. For dynamic casts, static casts, and const casts, we
898 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +0000899 // through the cast. In the case the dynamic cast doesn't fail (and
900 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000901 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +0000902 // FIXME: The comment about is wrong; we're not always converting
903 // from pointer to pointer. I'm guessing that this code should also
904 // handle references to objects.
905 case Stmt::CXXStaticCastExprClass:
906 case Stmt::CXXDynamicCastExprClass:
907 case Stmt::CXXConstCastExprClass:
908 case Stmt::CXXReinterpretCastExprClass: {
909 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000910 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000911 return EvalAddr(S);
912 else
913 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000914 }
915
916 // Everything else: we simply don't reason about them.
917 default:
918 return NULL;
919 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000920}
921
922
923/// EvalVal - This function is complements EvalAddr in the mutual recursion.
924/// See the comments for EvalAddr for more details.
925static DeclRefExpr* EvalVal(Expr *E) {
926
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000927 // We should only be called for evaluating non-pointer expressions, or
928 // expressions with a pointer type that are not used as references but instead
929 // are l-values (e.g., DeclRefExpr with a pointer type).
930
Ted Kremenek06de2762007-08-17 16:46:58 +0000931 // Our "symbolic interpreter" is just a dispatch off the currently
932 // viewed AST node. We then recursively traverse the AST by calling
933 // EvalAddr and EvalVal appropriately.
934 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +0000935 case Stmt::DeclRefExprClass:
936 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +0000937 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
938 // at code that refers to a variable's name. We check if it has local
939 // storage within the function, and if so, return the expression.
940 DeclRefExpr *DR = cast<DeclRefExpr>(E);
941
942 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000943 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +0000944
945 return NULL;
946 }
947
948 case Stmt::ParenExprClass:
949 // Ignore parentheses.
950 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
951
952 case Stmt::UnaryOperatorClass: {
953 // The only unary operator that make sense to handle here
954 // is Deref. All others don't resolve to a "name." This includes
955 // handling all sorts of rvalues passed to a unary operator.
956 UnaryOperator *U = cast<UnaryOperator>(E);
957
958 if (U->getOpcode() == UnaryOperator::Deref)
959 return EvalAddr(U->getSubExpr());
960
961 return NULL;
962 }
963
964 case Stmt::ArraySubscriptExprClass: {
965 // Array subscripts are potential references to data on the stack. We
966 // retrieve the DeclRefExpr* for the array variable if it indeed
967 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000968 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000969 }
970
971 case Stmt::ConditionalOperatorClass: {
972 // For conditional operators we need to see if either the LHS or RHS are
973 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
974 ConditionalOperator *C = cast<ConditionalOperator>(E);
975
Anders Carlsson39073232007-11-30 19:04:31 +0000976 // Handle the GNU extension for missing LHS.
977 if (Expr *lhsExpr = C->getLHS())
978 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
979 return LHS;
980
981 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000982 }
983
984 // Accesses to members are potential references to data on the stack.
985 case Stmt::MemberExprClass: {
986 MemberExpr *M = cast<MemberExpr>(E);
987
988 // Check for indirect access. We only want direct field accesses.
989 if (!M->isArrow())
990 return EvalVal(M->getBase());
991 else
992 return NULL;
993 }
994
995 // Everything else: we simply don't reason about them.
996 default:
997 return NULL;
998 }
999}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001000
1001//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1002
1003/// Check for comparisons of floating point operands using != and ==.
1004/// Issue a warning if these are no self-comparisons, as they are not likely
1005/// to do what the programmer intended.
1006void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1007 bool EmitWarning = true;
1008
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001009 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001010 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001011
1012 // Special case: check for x == x (which is OK).
1013 // Do not emit warnings for such cases.
1014 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1015 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1016 if (DRL->getDecl() == DRR->getDecl())
1017 EmitWarning = false;
1018
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001019
1020 // Special case: check for comparisons against literals that can be exactly
1021 // represented by APFloat. In such cases, do not emit a warning. This
1022 // is a heuristic: often comparison against such literals are used to
1023 // detect if a value in a variable has not changed. This clearly can
1024 // lead to false negatives.
1025 if (EmitWarning) {
1026 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1027 if (FLL->isExact())
1028 EmitWarning = false;
1029 }
1030 else
1031 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1032 if (FLR->isExact())
1033 EmitWarning = false;
1034 }
1035 }
1036
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001037 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001038 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001039 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1040 if (isCallBuiltin(CL))
1041 EmitWarning = false;
1042
Sebastian Redl0eb23302009-01-19 00:08:26 +00001043 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001044 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1045 if (isCallBuiltin(CR))
1046 EmitWarning = false;
1047
1048 // Emit the diagnostic.
1049 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001050 Diag(loc, diag::warn_floatingpoint_eq)
1051 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001052}