blob: edb5a494665ee74e541e8f82d92da08cf6fd91fc [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 Lattner719e6152009-02-18 19:21:10 +000020#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/Lex/Preprocessor.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022using namespace clang;
23
Chris Lattner60800082009-02-18 17:49:48 +000024/// getLocationOfStringLiteralByte - Return a source location that points to the
25/// specified byte of the specified string literal.
26///
27/// Strings are amazingly complex. They can be formed from multiple tokens and
28/// can have escape sequences in them in addition to the usual trigraph and
29/// escaped newline business. This routine handles this complexity.
30///
31SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
32 unsigned ByteNo) const {
33 assert(!SL->isWide() && "This doesn't work for wide strings yet");
34
35 // Loop over all of the tokens in this string until we find the one that
36 // contains the byte we're looking for.
37 unsigned TokNo = 0;
38 while (1) {
39 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
40 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
41
42 // Get the spelling of the string so that we can get the data that makes up
43 // the string literal, not the identifier for the macro it is potentially
44 // expanded through.
45 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
46
47 // Re-lex the token to get its length and original spelling.
48 std::pair<FileID, unsigned> LocInfo =
49 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
50 std::pair<const char *,const char *> Buffer =
51 SourceMgr.getBufferData(LocInfo.first);
52 const char *StrData = Buffer.first+LocInfo.second;
53
54 // Create a langops struct and enable trigraphs. This is sufficient for
55 // relexing tokens.
56 LangOptions LangOpts;
57 LangOpts.Trigraphs = true;
58
59 // Create a lexer starting at the beginning of this token.
60 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
61 Buffer.second);
62 Token TheTok;
63 TheLexer.LexFromRawLexer(TheTok);
64
Chris Lattner443e53c2009-02-18 19:26:42 +000065 // Use the StringLiteralParser to compute the length of the string in bytes.
66 StringLiteralParser SLP(&TheTok, 1, PP);
67 unsigned TokNumBytes = SLP.GetStringLength();
Chris Lattnerd0d082f2009-02-18 18:34:12 +000068
Chris Lattner2197c962009-02-18 18:52:52 +000069 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000070 if (ByteNo < TokNumBytes ||
71 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Chris Lattner719e6152009-02-18 19:21:10 +000072 unsigned Offset =
73 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
74
75 // Now that we know the offset of the token in the spelling, use the
76 // preprocessor to get the offset in the original source.
77 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000078 }
79
80 // Move to the next string token.
81 ++TokNo;
82 ByteNo -= TokNumBytes;
83 }
84}
85
86
Chris Lattner59907c42007-08-10 20:18:51 +000087/// CheckFunctionCall - Check a direct function call for various correctness
88/// and safety properties not strictly enforced by the C type system.
Sebastian Redl0eb23302009-01-19 00:08:26 +000089Action::OwningExprResult
90Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
91 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +000092 // Get the IdentifierInfo* for the called function.
93 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +000094
95 // None of the checks below are needed for functions that don't have
96 // simple names (e.g., C++ conversion functions).
97 if (!FnInfo)
Sebastian Redl0eb23302009-01-19 00:08:26 +000098 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +000099
Douglas Gregor3c385e52009-02-14 18:57:46 +0000100 switch (FDecl->getBuiltinID(Context)) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000101 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000102 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000103 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000104 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000105 return ExprError();
106 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000107 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000108 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000109 if (SemaBuiltinVAStart(TheCall))
110 return ExprError();
111 return move(TheCallResult);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000112 case Builtin::BI__builtin_isgreater:
113 case Builtin::BI__builtin_isgreaterequal:
114 case Builtin::BI__builtin_isless:
115 case Builtin::BI__builtin_islessequal:
116 case Builtin::BI__builtin_islessgreater:
117 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000118 if (SemaBuiltinUnorderedCompare(TheCall))
119 return ExprError();
120 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +0000121 case Builtin::BI__builtin_return_address:
122 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000123 if (SemaBuiltinStackAddress(TheCall))
124 return ExprError();
125 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +0000126 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000127 return SemaBuiltinShuffleVector(TheCall);
128 // TheCall will be freed by the smart pointer here, but that's fine, since
129 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000130 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000131 if (SemaBuiltinPrefetch(TheCall))
132 return ExprError();
133 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000134 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000135 if (SemaBuiltinObjectSize(TheCall))
136 return ExprError();
Eli Friedman586d6a82009-05-03 06:04:26 +0000137 return move(TheCallResult);
Eli Friedmand875fed2009-05-03 04:46:36 +0000138 case Builtin::BI__builtin_longjmp:
139 if (SemaBuiltinLongjmp(TheCall))
140 return ExprError();
Eli Friedman586d6a82009-05-03 06:04:26 +0000141 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000142 case Builtin::BI__sync_fetch_and_add:
143 case Builtin::BI__sync_fetch_and_sub:
144 case Builtin::BI__sync_fetch_and_or:
145 case Builtin::BI__sync_fetch_and_and:
146 case Builtin::BI__sync_fetch_and_xor:
147 case Builtin::BI__sync_add_and_fetch:
148 case Builtin::BI__sync_sub_and_fetch:
149 case Builtin::BI__sync_and_and_fetch:
150 case Builtin::BI__sync_or_and_fetch:
151 case Builtin::BI__sync_xor_and_fetch:
152 case Builtin::BI__sync_val_compare_and_swap:
153 case Builtin::BI__sync_bool_compare_and_swap:
154 case Builtin::BI__sync_lock_test_and_set:
155 case Builtin::BI__sync_lock_release:
156 if (SemaBuiltinAtomicOverloaded(TheCall))
157 return ExprError();
158 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000159 }
Daniel Dunbarde454282008-10-02 18:44:07 +0000160
161 // FIXME: This mechanism should be abstracted to be less fragile and
162 // more efficient. For example, just map function ids to custom
163 // handlers.
164
Chris Lattner59907c42007-08-10 20:18:51 +0000165 // Printf checking.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000166 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
167 if (Format->getType() == "printf") {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000168 bool HasVAListArg = Format->getFirstArg() == 0;
169 if (!HasVAListArg) {
170 if (const FunctionProtoType *Proto
171 = FDecl->getType()->getAsFunctionProtoType())
Douglas Gregor3c385e52009-02-14 18:57:46 +0000172 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000173 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000174 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000175 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000176 }
Chris Lattner59907c42007-08-10 20:18:51 +0000177 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000178
179 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000180}
181
Chris Lattner5caa3702009-05-08 06:58:22 +0000182/// SemaBuiltinAtomicOverloaded - We have a call to a function like
183/// __sync_fetch_and_add, which is an overloaded function based on the pointer
184/// type of its first argument. The main ActOnCallExpr routines have already
185/// promoted the types of arguments because all of these calls are prototyped as
186/// void(...).
187///
188/// This function goes through and does final semantic checking for these
189/// builtins,
190bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
191 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
192 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
193
194 // Ensure that we have at least one argument to do type inference from.
195 if (TheCall->getNumArgs() < 1)
196 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
197 << 0 << TheCall->getCallee()->getSourceRange();
198
199 // Inspect the first argument of the atomic builtin. This should always be
200 // a pointer type, whose element is an integral scalar or pointer type.
201 // Because it is a pointer type, we don't have to worry about any implicit
202 // casts here.
203 Expr *FirstArg = TheCall->getArg(0);
204 if (!FirstArg->getType()->isPointerType())
205 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
206 << FirstArg->getType() << FirstArg->getSourceRange();
207
208 QualType ValType = FirstArg->getType()->getAsPointerType()->getPointeeType();
209 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
210 !ValType->isBlockPointerType())
211 return Diag(DRE->getLocStart(),
212 diag::err_atomic_builtin_must_be_pointer_intptr)
213 << FirstArg->getType() << FirstArg->getSourceRange();
214
215 // We need to figure out which concrete builtin this maps onto. For example,
216 // __sync_fetch_and_add with a 2 byte object turns into
217 // __sync_fetch_and_add_2.
218#define BUILTIN_ROW(x) \
219 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
220 Builtin::BI##x##_8, Builtin::BI##x##_16 }
221
222 static const unsigned BuiltinIndices[][5] = {
223 BUILTIN_ROW(__sync_fetch_and_add),
224 BUILTIN_ROW(__sync_fetch_and_sub),
225 BUILTIN_ROW(__sync_fetch_and_or),
226 BUILTIN_ROW(__sync_fetch_and_and),
227 BUILTIN_ROW(__sync_fetch_and_xor),
228
229 BUILTIN_ROW(__sync_add_and_fetch),
230 BUILTIN_ROW(__sync_sub_and_fetch),
231 BUILTIN_ROW(__sync_and_and_fetch),
232 BUILTIN_ROW(__sync_or_and_fetch),
233 BUILTIN_ROW(__sync_xor_and_fetch),
234
235 BUILTIN_ROW(__sync_val_compare_and_swap),
236 BUILTIN_ROW(__sync_bool_compare_and_swap),
237 BUILTIN_ROW(__sync_lock_test_and_set),
238 BUILTIN_ROW(__sync_lock_release)
239 };
240#undef BUILTIN_ROW
241
242 // Determine the index of the size.
243 unsigned SizeIndex;
244 switch (Context.getTypeSize(ValType)/8) {
245 case 1: SizeIndex = 0; break;
246 case 2: SizeIndex = 1; break;
247 case 4: SizeIndex = 2; break;
248 case 8: SizeIndex = 3; break;
249 case 16: SizeIndex = 4; break;
250 default:
251 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
252 << FirstArg->getType() << FirstArg->getSourceRange();
253 }
254
255 // Each of these builtins has one pointer argument, followed by some number of
256 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
257 // that we ignore. Find out which row of BuiltinIndices to read from as well
258 // as the number of fixed args.
259 unsigned BuiltinID = FDecl->getBuiltinID(Context);
260 unsigned BuiltinIndex, NumFixed = 1;
261 switch (BuiltinID) {
262 default: assert(0 && "Unknown overloaded atomic builtin!");
263 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
264 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
265 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
266 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
267 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
268
269 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
270 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
271 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
272 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
273 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
274
275 case Builtin::BI__sync_val_compare_and_swap:
276 BuiltinIndex = 10;
277 NumFixed = 2;
278 break;
279 case Builtin::BI__sync_bool_compare_and_swap:
280 BuiltinIndex = 11;
281 NumFixed = 2;
282 break;
283 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
284 case Builtin::BI__sync_lock_release:
285 BuiltinIndex = 13;
286 NumFixed = 0;
287 break;
288 }
289
290 // Now that we know how many fixed arguments we expect, first check that we
291 // have at least that many.
292 if (TheCall->getNumArgs() < 1+NumFixed)
293 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
294 << 0 << TheCall->getCallee()->getSourceRange();
295
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000296
297 // Get the decl for the concrete builtin from this, we can tell what the
298 // concrete integer type we should convert to is.
299 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
300 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
301 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
302 FunctionDecl *NewBuiltinDecl =
303 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
304 TUScope, false, DRE->getLocStart()));
305 const FunctionProtoType *BuiltinFT =
306 NewBuiltinDecl->getType()->getAsFunctionProtoType();
307 ValType = BuiltinFT->getArgType(0)->getAsPointerType()->getPointeeType();
308
309 // If the first type needs to be converted (e.g. void** -> int*), do it now.
310 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
311 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), false);
312 TheCall->setArg(0, FirstArg);
313 }
314
Chris Lattner5caa3702009-05-08 06:58:22 +0000315 // Next, walk the valid ones promoting to the right type.
316 for (unsigned i = 0; i != NumFixed; ++i) {
317 Expr *Arg = TheCall->getArg(i+1);
318
319 // If the argument is an implicit cast, then there was a promotion due to
320 // "...", just remove it now.
321 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
322 Arg = ICE->getSubExpr();
323 ICE->setSubExpr(0);
324 ICE->Destroy(Context);
325 TheCall->setArg(i+1, Arg);
326 }
327
328 // GCC does an implicit conversion to the pointer or integer ValType. This
329 // can fail in some cases (1i -> int**), check for this error case now.
330 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg))
331 return true;
332
333 // Okay, we have something that *can* be converted to the right type. Check
334 // to see if there is a potentially weird extension going on here. This can
335 // happen when you do an atomic operation on something like an char* and
336 // pass in 42. The 42 gets converted to char. This is even more strange
337 // for things like 45.123 -> char, etc.
338 // FIXME: Do this check.
339 ImpCastExprToType(Arg, ValType, false);
340 TheCall->setArg(i+1, Arg);
341 }
342
Chris Lattner5caa3702009-05-08 06:58:22 +0000343 // Switch the DeclRefExpr to refer to the new decl.
344 DRE->setDecl(NewBuiltinDecl);
345 DRE->setType(NewBuiltinDecl->getType());
346
347 // Set the callee in the CallExpr.
348 // FIXME: This leaks the original parens and implicit casts.
349 Expr *PromotedCall = DRE;
350 UsualUnaryConversions(PromotedCall);
351 TheCall->setCallee(PromotedCall);
352
353
354 // Change the result type of the call to match the result type of the decl.
355 TheCall->setType(NewBuiltinDecl->getResultType());
356 return false;
357}
358
359
Chris Lattner69039812009-02-18 06:01:06 +0000360/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000361/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000362/// FIXME: GCC currently emits the following warning:
363/// "warning: input conversion stopped due to an input byte that does not
364/// belong to the input codeset UTF-8"
365/// Note: It might also make sense to do the UTF-16 conversion here (would
366/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000367bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000368 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000369 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
370
371 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000372 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
373 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000374 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000375 }
376
377 const char *Data = Literal->getStrData();
378 unsigned Length = Literal->getByteLength();
379
380 for (unsigned i = 0; i < Length; ++i) {
Anders Carlsson71993dd2007-08-17 05:31:46 +0000381 if (!Data[i]) {
Chris Lattner60800082009-02-18 17:49:48 +0000382 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000383 diag::warn_cfstring_literal_contains_nul_character)
384 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000385 break;
386 }
387 }
388
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000389 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000390}
391
Chris Lattnerc27c6652007-12-20 00:05:45 +0000392/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
393/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000394bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
395 Expr *Fn = TheCall->getCallee();
396 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000397 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000398 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000399 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000400 << SourceRange(TheCall->getArg(2)->getLocStart(),
401 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000402 return true;
403 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000404
405 if (TheCall->getNumArgs() < 2) {
406 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
407 << 0 /*function call*/;
408 }
409
Chris Lattnerc27c6652007-12-20 00:05:45 +0000410 // Determine whether the current function is variadic or not.
411 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000412 if (CurBlock)
413 isVariadic = CurBlock->isVariadic;
414 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000415 if (FunctionProtoType* FTP =
416 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000417 isVariadic = FTP->isVariadic();
418 else
419 isVariadic = false;
420 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000421 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000422 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000423
Chris Lattnerc27c6652007-12-20 00:05:45 +0000424 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000425 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
426 return true;
427 }
428
429 // Verify that the second argument to the builtin is the last argument of the
430 // current function or method.
431 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000432 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000433
434 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
435 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000436 // FIXME: This isn't correct for methods (results in bogus warning).
437 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000438 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000439 if (CurBlock)
440 LastArg = *(CurBlock->TheDecl->param_end()-1);
441 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000442 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000443 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000444 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000445 SecondArgIsLastNamedArgument = PV == LastArg;
446 }
447 }
448
449 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000450 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000451 diag::warn_second_parameter_of_va_start_not_last_named_argument);
452 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000453}
Chris Lattner30ce3442007-12-19 23:59:04 +0000454
Chris Lattner1b9a0792007-12-20 00:26:33 +0000455/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
456/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000457bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
458 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000459 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
460 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000461 if (TheCall->getNumArgs() > 2)
462 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000463 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000464 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000465 << SourceRange(TheCall->getArg(2)->getLocStart(),
466 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000467
Chris Lattner925e60d2007-12-28 05:29:59 +0000468 Expr *OrigArg0 = TheCall->getArg(0);
469 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000470
471 // Do standard promotions between the two arguments, returning their common
472 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000473 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000474
475 // Make sure any conversions are pushed back into the call; this is
476 // type safe since unordered compare builtins are declared as "_Bool
477 // foo(...)".
478 TheCall->setArg(0, OrigArg0);
479 TheCall->setArg(1, OrigArg1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000480
481 // If the common type isn't a real floating type, then the arguments were
482 // invalid for this operation.
483 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000484 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000485 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000486 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000487 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000488
489 return false;
490}
491
Eli Friedman6cfda232008-05-20 08:23:37 +0000492bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
493 // The signature for these builtins is exact; the only thing we need
494 // to check is that the argument is a constant.
495 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000496 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000497 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000498
Eli Friedman6cfda232008-05-20 08:23:37 +0000499 return false;
500}
501
Eli Friedmand38617c2008-05-14 19:38:39 +0000502/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
503// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000504Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000505 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000506 return ExprError(Diag(TheCall->getLocEnd(),
507 diag::err_typecheck_call_too_few_args)
508 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000509
510 QualType FAType = TheCall->getArg(0)->getType();
511 QualType SAType = TheCall->getArg(1)->getType();
512
513 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000514 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
515 << SourceRange(TheCall->getArg(0)->getLocStart(),
516 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000517 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000518 }
519
Chris Lattnerb77792e2008-07-26 22:17:49 +0000520 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
521 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000522 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
523 << SourceRange(TheCall->getArg(0)->getLocStart(),
524 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000525 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000526 }
527
528 unsigned numElements = FAType->getAsVectorType()->getNumElements();
529 if (TheCall->getNumArgs() != numElements+2) {
530 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000531 return ExprError(Diag(TheCall->getLocEnd(),
532 diag::err_typecheck_call_too_few_args)
533 << 0 /*function call*/ << TheCall->getSourceRange());
534 return ExprError(Diag(TheCall->getLocEnd(),
535 diag::err_typecheck_call_too_many_args)
536 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000537 }
538
539 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
540 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000541 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000542 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000543 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000544 << TheCall->getArg(i)->getSourceRange());
545
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000546 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000547 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000548 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000549 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000550 }
551
552 llvm::SmallVector<Expr*, 32> exprs;
553
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000554 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000555 exprs.push_back(TheCall->getArg(i));
556 TheCall->setArg(i, 0);
557 }
558
Ted Kremenek8189cde2009-02-07 01:47:29 +0000559 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
560 FAType,
561 TheCall->getCallee()->getLocStart(),
562 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000563}
Chris Lattner30ce3442007-12-19 23:59:04 +0000564
Daniel Dunbar4493f792008-07-21 22:59:13 +0000565/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
566// This is declared to take (const void*, ...) and can take two
567// optional constant int args.
568bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000569 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000570
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000571 if (NumArgs > 3)
572 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000573 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000574
575 // Argument 0 is checked for us and the remaining arguments must be
576 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000577 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000578 Expr *Arg = TheCall->getArg(i);
579 QualType RWType = Arg->getType();
580
581 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000582 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000583 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000584 !Arg->isIntegerConstantExpr(Result, Context))
585 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
586 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000587
588 // FIXME: gcc issues a warning and rewrites these to 0. These
589 // seems especially odd for the third argument since the default
590 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000591 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000592 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000593 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
594 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000595 } else {
596 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000597 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
598 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000599 }
600 }
601
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000602 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000603}
604
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000605/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
606/// int type). This simply type checks that type is one of the defined
607/// constants (0-3).
608bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
609 Expr *Arg = TheCall->getArg(1);
610 QualType ArgType = Arg->getType();
611 const BuiltinType *BT = ArgType->getAsBuiltinType();
612 llvm::APSInt Result(32);
613 if (!BT || BT->getKind() != BuiltinType::Int ||
614 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000615 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
616 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000617 }
618
619 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000620 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
621 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000622 }
623
624 return false;
625}
626
Eli Friedman586d6a82009-05-03 06:04:26 +0000627/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000628/// This checks that val is a constant 1.
629bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
630 Expr *Arg = TheCall->getArg(1);
631 llvm::APSInt Result(32);
632 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
633 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
634 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
635
636 return false;
637}
638
Ted Kremenekd30ef872009-01-12 23:09:09 +0000639// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000640bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
641 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000642 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000643
644 switch (E->getStmtClass()) {
645 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000646 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000647 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000648 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000649 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000650 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000651 }
652
653 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000654 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000655 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000656 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000657 }
658
659 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000660 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000661 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000662 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000663 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000664
665 case Stmt::DeclRefExprClass: {
666 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
667
668 // As an exception, do not flag errors for variables binding to
669 // const string literals.
670 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
671 bool isConstant = false;
672 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000673
Ted Kremenek082d9362009-03-20 21:35:28 +0000674 if (const ArrayType *AT = Context.getAsArrayType(T)) {
675 isConstant = AT->getElementType().isConstant(Context);
676 }
677 else if (const PointerType *PT = T->getAsPointerType()) {
678 isConstant = T.isConstant(Context) &&
679 PT->getPointeeType().isConstant(Context);
680 }
681
682 if (isConstant) {
683 const VarDecl *Def = 0;
684 if (const Expr *Init = VD->getDefinition(Def))
685 return SemaCheckStringLiteral(Init, TheCall,
686 HasVAListArg, format_idx, firstDataArg);
687 }
688 }
689
690 return false;
691 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000692
Ted Kremenek082d9362009-03-20 21:35:28 +0000693 case Stmt::ObjCStringLiteralClass:
694 case Stmt::StringLiteralClass: {
695 const StringLiteral *StrE = NULL;
696
697 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000698 StrE = ObjCFExpr->getString();
699 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000700 StrE = cast<StringLiteral>(E);
701
Ted Kremenekd30ef872009-01-12 23:09:09 +0000702 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000703 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
704 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000705 return true;
706 }
707
708 return false;
709 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000710
711 default:
712 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000713 }
714}
715
716
Chris Lattner59907c42007-08-10 20:18:51 +0000717/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000718/// correct use of format strings.
719///
720/// HasVAListArg - A predicate indicating whether the printf-like
721/// function is passed an explicit va_arg argument (e.g., vprintf)
722///
723/// format_idx - The index into Args for the format string.
724///
725/// Improper format strings to functions in the printf family can be
726/// the source of bizarre bugs and very serious security holes. A
727/// good source of information is available in the following paper
728/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000729///
730/// FormatGuard: Automatic Protection From printf Format String
731/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000732///
733/// Functionality implemented:
734///
735/// We can statically check the following properties for string
736/// literal format strings for non v.*printf functions (where the
737/// arguments are passed directly):
738//
739/// (1) Are the number of format conversions equal to the number of
740/// data arguments?
741///
742/// (2) Does each format conversion correctly match the type of the
743/// corresponding data argument? (TODO)
744///
745/// Moreover, for all printf functions we can:
746///
747/// (3) Check for a missing format string (when not caught by type checking).
748///
749/// (4) Check for no-operation flags; e.g. using "#" with format
750/// conversion 'c' (TODO)
751///
752/// (5) Check the use of '%n', a major source of security holes.
753///
754/// (6) Check for malformed format conversions that don't specify anything.
755///
756/// (7) Check for empty format strings. e.g: printf("");
757///
758/// (8) Check that the format string is a wide literal.
759///
Ted Kremenek6d439592008-03-03 16:50:00 +0000760/// (9) Also check the arguments of functions with the __format__ attribute.
761/// (TODO).
762///
Ted Kremenek71895b92007-08-14 17:39:48 +0000763/// All of these checks can be done by parsing the format string.
764///
765/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000766void
Ted Kremenek082d9362009-03-20 21:35:28 +0000767Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000768 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000769 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000770
Ted Kremenek71895b92007-08-14 17:39:48 +0000771 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000772 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000773 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
774 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000775 return;
776 }
777
Ted Kremenek082d9362009-03-20 21:35:28 +0000778 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000779
Chris Lattner59907c42007-08-10 20:18:51 +0000780 // CHECK: format string is not a string literal.
781 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000782 // Dynamically generated format strings are difficult to
783 // automatically vet at compile time. Requiring that format strings
784 // are string literals: (1) permits the checking of format strings by
785 // the compiler and thereby (2) can practically remove the source of
786 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000787
788 // Format string can be either ObjC string (e.g. @"%d") or
789 // C string (e.g. "%d")
790 // ObjC string uses the same format specifiers as C string, so we can use
791 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000792 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
793 firstDataArg))
794 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000795
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000796 // For vprintf* functions (i.e., HasVAListArg==true), we add a
797 // special check to see if the format string is a function parameter
798 // of the function calling the printf function. If the function
799 // has an attribute indicating it is a printf-like function, then we
800 // should suppress warnings concerning non-literals being used in a call
801 // to a vprintf function. For example:
802 //
803 // void
804 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
805 // va_list ap;
806 // va_start(ap, fmt);
807 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
808 // ...
809 //
810 //
811 // FIXME: We don't have full attribute support yet, so just check to see
812 // if the argument is a DeclRefExpr that references a parameter. We'll
813 // add proper support for checking the attribute later.
814 if (HasVAListArg)
815 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
816 if (isa<ParmVarDecl>(DR->getDecl()))
817 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000818
Chris Lattner655f1412009-04-29 04:59:47 +0000819 // If there are no arguments specified, warn with -Wformat-security, otherwise
820 // warn only with -Wformat-nonliteral.
821 if (TheCall->getNumArgs() == format_idx+1)
822 Diag(TheCall->getArg(format_idx)->getLocStart(),
823 diag::warn_printf_nonliteral_noargs)
824 << OrigFormatExpr->getSourceRange();
825 else
826 Diag(TheCall->getArg(format_idx)->getLocStart(),
827 diag::warn_printf_nonliteral)
828 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000829}
Ted Kremenek71895b92007-08-14 17:39:48 +0000830
Ted Kremenek082d9362009-03-20 21:35:28 +0000831void Sema::CheckPrintfString(const StringLiteral *FExpr,
832 const Expr *OrigFormatExpr,
833 const CallExpr *TheCall, bool HasVAListArg,
834 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000835
Ted Kremenek082d9362009-03-20 21:35:28 +0000836 const ObjCStringLiteral *ObjCFExpr =
837 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
838
Ted Kremenek71895b92007-08-14 17:39:48 +0000839 // CHECK: is the format string a wide literal?
840 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000841 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000842 diag::warn_printf_format_string_is_wide_literal)
843 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000844 return;
845 }
846
847 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000848 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +0000849
850 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000851 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek71895b92007-08-14 17:39:48 +0000852
853 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000854 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
855 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000856 return;
857 }
858
859 // We process the format string using a binary state machine. The
860 // current state is stored in CurrentState.
861 enum {
862 state_OrdChr,
863 state_Conversion
864 } CurrentState = state_OrdChr;
865
866 // numConversions - The number of conversions seen so far. This is
867 // incremented as we traverse the format string.
868 unsigned numConversions = 0;
869
870 // numDataArgs - The number of data arguments after the format
871 // string. This can only be determined for non vprintf-like
872 // functions. For those functions, this value is 1 (the sole
873 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000874 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000875
876 // Inspect the format string.
877 unsigned StrIdx = 0;
878
879 // LastConversionIdx - Index within the format string where we last saw
880 // a '%' character that starts a new format conversion.
881 unsigned LastConversionIdx = 0;
882
Chris Lattner925e60d2007-12-28 05:29:59 +0000883 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000884
Ted Kremenek71895b92007-08-14 17:39:48 +0000885 // Is the number of detected conversion conversions greater than
886 // the number of matching data arguments? If so, stop.
887 if (!HasVAListArg && numConversions > numDataArgs) break;
888
889 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000890 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000891 // The string returned by getStrData() is not null-terminated,
892 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +0000893 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000894 diag::warn_printf_format_string_contains_null_char)
895 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000896 return;
897 }
898
899 // Ordinary characters (not processing a format conversion).
900 if (CurrentState == state_OrdChr) {
901 if (Str[StrIdx] == '%') {
902 CurrentState = state_Conversion;
903 LastConversionIdx = StrIdx;
904 }
905 continue;
906 }
907
908 // Seen '%'. Now processing a format conversion.
909 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000910 // Handle dynamic precision or width specifier.
911 case '*': {
912 ++numConversions;
913
914 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000915 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +0000916
Ted Kremenek580b6642007-10-12 20:51:52 +0000917 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000918 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
919 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000920 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000921 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
922 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000923
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000924 // Don't do any more checking. We'll just emit spurious errors.
925 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000926 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000927
928 // Perform type checking on width/precision specifier.
Ted Kremenek082d9362009-03-20 21:35:28 +0000929 const Expr *E = TheCall->getArg(format_idx+numConversions);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000930 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
931 if (BT->getKind() == BuiltinType::Int)
932 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000933
Chris Lattner60800082009-02-18 17:49:48 +0000934 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000935
936 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000937 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000938 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000939 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000940 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000941 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000942
943 break;
944 }
945
946 // Characters which can terminate a format conversion
947 // (e.g. "%d"). Characters that specify length modifiers or
948 // other flags are handled by the default case below.
949 //
950 // FIXME: additional checks will go into the following cases.
951 case 'i':
952 case 'd':
953 case 'o':
954 case 'u':
955 case 'x':
956 case 'X':
957 case 'D':
958 case 'O':
959 case 'U':
960 case 'e':
961 case 'E':
962 case 'f':
963 case 'F':
964 case 'g':
965 case 'G':
966 case 'a':
967 case 'A':
968 case 'c':
969 case 'C':
970 case 'S':
971 case 's':
972 case 'p':
973 ++numConversions;
974 CurrentState = state_OrdChr;
975 break;
976
977 // CHECK: Are we using "%n"? Issue a warning.
978 case 'n': {
979 ++numConversions;
980 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +0000981 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
982 LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000983
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000984 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000985 break;
986 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000987
988 // Handle "%@"
989 case '@':
990 // %@ is allowed in ObjC format strings only.
991 if(ObjCFExpr != NULL)
992 CurrentState = state_OrdChr;
993 else {
994 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000995 SourceLocation Loc =
996 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000997
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000998 Diag(Loc, diag::warn_printf_invalid_conversion)
999 << std::string(Str+LastConversionIdx,
1000 Str+std::min(LastConversionIdx+2, StrLen))
1001 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001002 }
1003 ++numConversions;
1004 break;
1005
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001006 // Handle "%%"
1007 case '%':
1008 // Sanity check: Was the first "%" character the previous one?
1009 // If not, we will assume that we have a malformed format
1010 // conversion, and that the current "%" character is the start
1011 // of a new conversion.
1012 if (StrIdx - LastConversionIdx == 1)
1013 CurrentState = state_OrdChr;
1014 else {
1015 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001016 SourceLocation Loc =
1017 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001018
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001019 Diag(Loc, diag::warn_printf_invalid_conversion)
1020 << std::string(Str+LastConversionIdx, Str+StrIdx)
1021 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001022
1023 // This conversion is broken. Advance to the next format
1024 // conversion.
1025 LastConversionIdx = StrIdx;
1026 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +00001027 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001028 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001029
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001030 default:
1031 // This case catches all other characters: flags, widths, etc.
1032 // We should eventually process those as well.
1033 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001034 }
1035 }
1036
1037 if (CurrentState == state_Conversion) {
1038 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001039 SourceLocation Loc =
1040 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +00001041
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001042 Diag(Loc, diag::warn_printf_invalid_conversion)
1043 << std::string(Str+LastConversionIdx,
1044 Str+std::min(LastConversionIdx+2, StrLen))
1045 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001046 return;
1047 }
1048
1049 if (!HasVAListArg) {
1050 // CHECK: Does the number of format conversions exceed the number
1051 // of data arguments?
1052 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +00001053 SourceLocation Loc =
1054 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +00001055
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001056 Diag(Loc, diag::warn_printf_insufficient_data_args)
1057 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001058 }
1059 // CHECK: Does the number of data arguments exceed the number of
1060 // format conversions in the format string?
1061 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +00001062 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001063 diag::warn_printf_too_many_data_args)
1064 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001065 }
1066}
Ted Kremenek06de2762007-08-17 16:46:58 +00001067
1068//===--- CHECK: Return Address of Stack Variable --------------------------===//
1069
1070static DeclRefExpr* EvalVal(Expr *E);
1071static DeclRefExpr* EvalAddr(Expr* E);
1072
1073/// CheckReturnStackAddr - Check if a return statement returns the address
1074/// of a stack variable.
1075void
1076Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1077 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +00001078
Ted Kremenek06de2762007-08-17 16:46:58 +00001079 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001080 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001081 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001082 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001083 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001084
1085 // Skip over implicit cast expressions when checking for block expressions.
1086 if (ImplicitCastExpr *IcExpr =
1087 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
1088 RetValExp = IcExpr->getSubExpr();
1089
Steve Naroff61f40a22008-09-10 19:17:48 +00001090 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001091 if (C->hasBlockDeclRefExprs())
1092 Diag(C->getLocStart(), diag::err_ret_local_block)
1093 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001094 }
1095 // Perform checking for stack values returned by reference.
1096 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +00001097 // Check for a reference to the stack
1098 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001099 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001100 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001101 }
1102}
1103
1104/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1105/// check if the expression in a return statement evaluates to an address
1106/// to a location on the stack. The recursion is used to traverse the
1107/// AST of the return expression, with recursion backtracking when we
1108/// encounter a subexpression that (1) clearly does not lead to the address
1109/// of a stack variable or (2) is something we cannot determine leads to
1110/// the address of a stack variable based on such local checking.
1111///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001112/// EvalAddr processes expressions that are pointers that are used as
1113/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +00001114/// At the base case of the recursion is a check for a DeclRefExpr* in
1115/// the refers to a stack variable.
1116///
1117/// This implementation handles:
1118///
1119/// * pointer-to-pointer casts
1120/// * implicit conversions from array references to pointers
1121/// * taking the address of fields
1122/// * arbitrary interplay between "&" and "*" operators
1123/// * pointer arithmetic from an address of a stack variable
1124/// * taking the address of an array element where the array is on the stack
1125static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001126 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +00001127 assert((E->getType()->isPointerType() ||
1128 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001129 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001130 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +00001131
1132 // Our "symbolic interpreter" is just a dispatch off the currently
1133 // viewed AST node. We then recursively traverse the AST by calling
1134 // EvalAddr and EvalVal appropriately.
1135 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001136 case Stmt::ParenExprClass:
1137 // Ignore parentheses.
1138 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001139
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001140 case Stmt::UnaryOperatorClass: {
1141 // The only unary operator that make sense to handle here
1142 // is AddrOf. All others don't make sense as pointers.
1143 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +00001144
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001145 if (U->getOpcode() == UnaryOperator::AddrOf)
1146 return EvalVal(U->getSubExpr());
1147 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001148 return NULL;
1149 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001150
1151 case Stmt::BinaryOperatorClass: {
1152 // Handle pointer arithmetic. All other binary operators are not valid
1153 // in this context.
1154 BinaryOperator *B = cast<BinaryOperator>(E);
1155 BinaryOperator::Opcode op = B->getOpcode();
1156
1157 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1158 return NULL;
1159
1160 Expr *Base = B->getLHS();
1161
1162 // Determine which argument is the real pointer base. It could be
1163 // the RHS argument instead of the LHS.
1164 if (!Base->getType()->isPointerType()) Base = B->getRHS();
1165
1166 assert (Base->getType()->isPointerType());
1167 return EvalAddr(Base);
1168 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001169
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001170 // For conditional operators we need to see if either the LHS or RHS are
1171 // valid DeclRefExpr*s. If one of them is valid, we return it.
1172 case Stmt::ConditionalOperatorClass: {
1173 ConditionalOperator *C = cast<ConditionalOperator>(E);
1174
1175 // Handle the GNU extension for missing LHS.
1176 if (Expr *lhsExpr = C->getLHS())
1177 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1178 return LHS;
1179
1180 return EvalAddr(C->getRHS());
1181 }
1182
Ted Kremenek54b52742008-08-07 00:49:01 +00001183 // For casts, we need to handle conversions from arrays to
1184 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001185 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001186 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001187 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001188 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001189 QualType T = SubExpr->getType();
1190
Steve Naroffdd972f22008-09-05 22:11:13 +00001191 if (SubExpr->getType()->isPointerType() ||
1192 SubExpr->getType()->isBlockPointerType() ||
1193 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001194 return EvalAddr(SubExpr);
1195 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001196 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001197 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001198 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001199 }
1200
1201 // C++ casts. For dynamic casts, static casts, and const casts, we
1202 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001203 // through the cast. In the case the dynamic cast doesn't fail (and
1204 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001205 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001206 // FIXME: The comment about is wrong; we're not always converting
1207 // from pointer to pointer. I'm guessing that this code should also
1208 // handle references to objects.
1209 case Stmt::CXXStaticCastExprClass:
1210 case Stmt::CXXDynamicCastExprClass:
1211 case Stmt::CXXConstCastExprClass:
1212 case Stmt::CXXReinterpretCastExprClass: {
1213 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001214 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001215 return EvalAddr(S);
1216 else
1217 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001218 }
1219
1220 // Everything else: we simply don't reason about them.
1221 default:
1222 return NULL;
1223 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001224}
1225
1226
1227/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1228/// See the comments for EvalAddr for more details.
1229static DeclRefExpr* EvalVal(Expr *E) {
1230
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001231 // We should only be called for evaluating non-pointer expressions, or
1232 // expressions with a pointer type that are not used as references but instead
1233 // are l-values (e.g., DeclRefExpr with a pointer type).
1234
Ted Kremenek06de2762007-08-17 16:46:58 +00001235 // Our "symbolic interpreter" is just a dispatch off the currently
1236 // viewed AST node. We then recursively traverse the AST by calling
1237 // EvalAddr and EvalVal appropriately.
1238 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +00001239 case Stmt::DeclRefExprClass:
1240 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001241 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1242 // at code that refers to a variable's name. We check if it has local
1243 // storage within the function, and if so, return the expression.
1244 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1245
1246 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001247 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +00001248
1249 return NULL;
1250 }
1251
1252 case Stmt::ParenExprClass:
1253 // Ignore parentheses.
1254 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1255
1256 case Stmt::UnaryOperatorClass: {
1257 // The only unary operator that make sense to handle here
1258 // is Deref. All others don't resolve to a "name." This includes
1259 // handling all sorts of rvalues passed to a unary operator.
1260 UnaryOperator *U = cast<UnaryOperator>(E);
1261
1262 if (U->getOpcode() == UnaryOperator::Deref)
1263 return EvalAddr(U->getSubExpr());
1264
1265 return NULL;
1266 }
1267
1268 case Stmt::ArraySubscriptExprClass: {
1269 // Array subscripts are potential references to data on the stack. We
1270 // retrieve the DeclRefExpr* for the array variable if it indeed
1271 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001272 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001273 }
1274
1275 case Stmt::ConditionalOperatorClass: {
1276 // For conditional operators we need to see if either the LHS or RHS are
1277 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1278 ConditionalOperator *C = cast<ConditionalOperator>(E);
1279
Anders Carlsson39073232007-11-30 19:04:31 +00001280 // Handle the GNU extension for missing LHS.
1281 if (Expr *lhsExpr = C->getLHS())
1282 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1283 return LHS;
1284
1285 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001286 }
1287
1288 // Accesses to members are potential references to data on the stack.
1289 case Stmt::MemberExprClass: {
1290 MemberExpr *M = cast<MemberExpr>(E);
1291
1292 // Check for indirect access. We only want direct field accesses.
1293 if (!M->isArrow())
1294 return EvalVal(M->getBase());
1295 else
1296 return NULL;
1297 }
1298
1299 // Everything else: we simply don't reason about them.
1300 default:
1301 return NULL;
1302 }
1303}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001304
1305//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1306
1307/// Check for comparisons of floating point operands using != and ==.
1308/// Issue a warning if these are no self-comparisons, as they are not likely
1309/// to do what the programmer intended.
1310void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1311 bool EmitWarning = true;
1312
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001313 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001314 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001315
1316 // Special case: check for x == x (which is OK).
1317 // Do not emit warnings for such cases.
1318 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1319 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1320 if (DRL->getDecl() == DRR->getDecl())
1321 EmitWarning = false;
1322
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001323
1324 // Special case: check for comparisons against literals that can be exactly
1325 // represented by APFloat. In such cases, do not emit a warning. This
1326 // is a heuristic: often comparison against such literals are used to
1327 // detect if a value in a variable has not changed. This clearly can
1328 // lead to false negatives.
1329 if (EmitWarning) {
1330 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1331 if (FLL->isExact())
1332 EmitWarning = false;
1333 }
1334 else
1335 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1336 if (FLR->isExact())
1337 EmitWarning = false;
1338 }
1339 }
1340
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001341 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001342 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001343 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001344 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001345 EmitWarning = false;
1346
Sebastian Redl0eb23302009-01-19 00:08:26 +00001347 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001348 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001349 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001350 EmitWarning = false;
1351
1352 // Emit the diagnostic.
1353 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001354 Diag(loc, diag::warn_floatingpoint_eq)
1355 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001356}