blob: e9ddce33ce4271615240ab4771007dc53ab7f7b1 [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"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000022#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000023using namespace clang;
24
Chris Lattner60800082009-02-18 17:49:48 +000025/// getLocationOfStringLiteralByte - Return a source location that points to the
26/// specified byte of the specified string literal.
27///
28/// Strings are amazingly complex. They can be formed from multiple tokens and
29/// can have escape sequences in them in addition to the usual trigraph and
30/// escaped newline business. This routine handles this complexity.
31///
32SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
33 unsigned ByteNo) const {
34 assert(!SL->isWide() && "This doesn't work for wide strings yet");
35
36 // Loop over all of the tokens in this string until we find the one that
37 // contains the byte we're looking for.
38 unsigned TokNo = 0;
39 while (1) {
40 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
41 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
42
43 // Get the spelling of the string so that we can get the data that makes up
44 // the string literal, not the identifier for the macro it is potentially
45 // expanded through.
46 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
47
48 // Re-lex the token to get its length and original spelling.
49 std::pair<FileID, unsigned> LocInfo =
50 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
51 std::pair<const char *,const char *> Buffer =
52 SourceMgr.getBufferData(LocInfo.first);
53 const char *StrData = Buffer.first+LocInfo.second;
54
55 // Create a langops struct and enable trigraphs. This is sufficient for
56 // relexing tokens.
57 LangOptions LangOpts;
58 LangOpts.Trigraphs = true;
59
60 // Create a lexer starting at the beginning of this token.
61 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
62 Buffer.second);
63 Token TheTok;
64 TheLexer.LexFromRawLexer(TheTok);
65
Chris Lattner443e53c2009-02-18 19:26:42 +000066 // Use the StringLiteralParser to compute the length of the string in bytes.
67 StringLiteralParser SLP(&TheTok, 1, PP);
68 unsigned TokNumBytes = SLP.GetStringLength();
Chris Lattnerd0d082f2009-02-18 18:34:12 +000069
Chris Lattner2197c962009-02-18 18:52:52 +000070 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000071 if (ByteNo < TokNumBytes ||
72 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Chris Lattner719e6152009-02-18 19:21:10 +000073 unsigned Offset =
74 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
75
76 // Now that we know the offset of the token in the spelling, use the
77 // preprocessor to get the offset in the original source.
78 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000079 }
80
81 // Move to the next string token.
82 ++TokNo;
83 ByteNo -= TokNumBytes;
84 }
85}
86
87
Chris Lattner59907c42007-08-10 20:18:51 +000088/// CheckFunctionCall - Check a direct function call for various correctness
89/// and safety properties not strictly enforced by the C type system.
Sebastian Redl0eb23302009-01-19 00:08:26 +000090Action::OwningExprResult
91Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
92 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +000093 // Get the IdentifierInfo* for the called function.
94 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +000095
96 // None of the checks below are needed for functions that don't have
97 // simple names (e.g., C++ conversion functions).
98 if (!FnInfo)
Sebastian Redl0eb23302009-01-19 00:08:26 +000099 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +0000100
Douglas Gregor3c385e52009-02-14 18:57:46 +0000101 switch (FDecl->getBuiltinID(Context)) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000102 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000103 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000104 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000105 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000106 return ExprError();
107 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000108 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000109 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000110 if (SemaBuiltinVAStart(TheCall))
111 return ExprError();
112 return move(TheCallResult);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000113 case Builtin::BI__builtin_isgreater:
114 case Builtin::BI__builtin_isgreaterequal:
115 case Builtin::BI__builtin_isless:
116 case Builtin::BI__builtin_islessequal:
117 case Builtin::BI__builtin_islessgreater:
118 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000119 if (SemaBuiltinUnorderedCompare(TheCall))
120 return ExprError();
121 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +0000122 case Builtin::BI__builtin_return_address:
123 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000124 if (SemaBuiltinStackAddress(TheCall))
125 return ExprError();
126 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +0000127 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000128 return SemaBuiltinShuffleVector(TheCall);
129 // TheCall will be freed by the smart pointer here, but that's fine, since
130 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000131 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 if (SemaBuiltinPrefetch(TheCall))
133 return ExprError();
134 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000135 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinObjectSize(TheCall))
137 return ExprError();
Eli Friedman586d6a82009-05-03 06:04:26 +0000138 return move(TheCallResult);
Eli Friedmand875fed2009-05-03 04:46:36 +0000139 case Builtin::BI__builtin_longjmp:
140 if (SemaBuiltinLongjmp(TheCall))
141 return ExprError();
Eli Friedman586d6a82009-05-03 06:04:26 +0000142 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000143 case Builtin::BI__sync_fetch_and_add:
144 case Builtin::BI__sync_fetch_and_sub:
145 case Builtin::BI__sync_fetch_and_or:
146 case Builtin::BI__sync_fetch_and_and:
147 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000148 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000149 case Builtin::BI__sync_add_and_fetch:
150 case Builtin::BI__sync_sub_and_fetch:
151 case Builtin::BI__sync_and_and_fetch:
152 case Builtin::BI__sync_or_and_fetch:
153 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000154 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000155 case Builtin::BI__sync_val_compare_and_swap:
156 case Builtin::BI__sync_bool_compare_and_swap:
157 case Builtin::BI__sync_lock_test_and_set:
158 case Builtin::BI__sync_lock_release:
159 if (SemaBuiltinAtomicOverloaded(TheCall))
160 return ExprError();
161 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000162 }
Daniel Dunbarde454282008-10-02 18:44:07 +0000163
164 // FIXME: This mechanism should be abstracted to be less fragile and
165 // more efficient. For example, just map function ids to custom
166 // handlers.
167
Chris Lattner59907c42007-08-10 20:18:51 +0000168 // Printf checking.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000169 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
170 if (Format->getType() == "printf") {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000171 bool HasVAListArg = Format->getFirstArg() == 0;
172 if (!HasVAListArg) {
173 if (const FunctionProtoType *Proto
174 = FDecl->getType()->getAsFunctionProtoType())
Douglas Gregor3c385e52009-02-14 18:57:46 +0000175 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000176 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000177 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000178 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000179 }
Chris Lattner59907c42007-08-10 20:18:51 +0000180 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000181
182 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000183}
184
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000185Action::OwningExprResult
186Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
187
188 OwningExprResult TheCallResult(Owned(TheCall));
189 // Printf checking.
190 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
191 if (!Format)
192 return move(TheCallResult);
193 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
194 if (!V)
195 return move(TheCallResult);
196 QualType Ty = V->getType();
197 if (!Ty->isBlockPointerType())
198 return move(TheCallResult);
199 if (Format->getType() == "printf") {
200 bool HasVAListArg = Format->getFirstArg() == 0;
201 if (!HasVAListArg) {
202 const FunctionType *FT =
203 Ty->getAsBlockPointerType()->getPointeeType()->getAsFunctionType();
204 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
205 HasVAListArg = !Proto->isVariadic();
206 }
207 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
208 HasVAListArg ? 0 : Format->getFirstArg() - 1);
209 }
210 return move(TheCallResult);
211}
212
Chris Lattner5caa3702009-05-08 06:58:22 +0000213/// SemaBuiltinAtomicOverloaded - We have a call to a function like
214/// __sync_fetch_and_add, which is an overloaded function based on the pointer
215/// type of its first argument. The main ActOnCallExpr routines have already
216/// promoted the types of arguments because all of these calls are prototyped as
217/// void(...).
218///
219/// This function goes through and does final semantic checking for these
220/// builtins,
221bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
222 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
223 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
224
225 // Ensure that we have at least one argument to do type inference from.
226 if (TheCall->getNumArgs() < 1)
227 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
228 << 0 << TheCall->getCallee()->getSourceRange();
229
230 // Inspect the first argument of the atomic builtin. This should always be
231 // a pointer type, whose element is an integral scalar or pointer type.
232 // Because it is a pointer type, we don't have to worry about any implicit
233 // casts here.
234 Expr *FirstArg = TheCall->getArg(0);
235 if (!FirstArg->getType()->isPointerType())
236 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
237 << FirstArg->getType() << FirstArg->getSourceRange();
238
239 QualType ValType = FirstArg->getType()->getAsPointerType()->getPointeeType();
240 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
241 !ValType->isBlockPointerType())
242 return Diag(DRE->getLocStart(),
243 diag::err_atomic_builtin_must_be_pointer_intptr)
244 << FirstArg->getType() << FirstArg->getSourceRange();
245
246 // We need to figure out which concrete builtin this maps onto. For example,
247 // __sync_fetch_and_add with a 2 byte object turns into
248 // __sync_fetch_and_add_2.
249#define BUILTIN_ROW(x) \
250 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
251 Builtin::BI##x##_8, Builtin::BI##x##_16 }
252
253 static const unsigned BuiltinIndices[][5] = {
254 BUILTIN_ROW(__sync_fetch_and_add),
255 BUILTIN_ROW(__sync_fetch_and_sub),
256 BUILTIN_ROW(__sync_fetch_and_or),
257 BUILTIN_ROW(__sync_fetch_and_and),
258 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000259 BUILTIN_ROW(__sync_fetch_and_nand),
Chris Lattner5caa3702009-05-08 06:58:22 +0000260
261 BUILTIN_ROW(__sync_add_and_fetch),
262 BUILTIN_ROW(__sync_sub_and_fetch),
263 BUILTIN_ROW(__sync_and_and_fetch),
264 BUILTIN_ROW(__sync_or_and_fetch),
265 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000266 BUILTIN_ROW(__sync_nand_and_fetch),
Chris Lattner5caa3702009-05-08 06:58:22 +0000267
268 BUILTIN_ROW(__sync_val_compare_and_swap),
269 BUILTIN_ROW(__sync_bool_compare_and_swap),
270 BUILTIN_ROW(__sync_lock_test_and_set),
271 BUILTIN_ROW(__sync_lock_release)
272 };
273#undef BUILTIN_ROW
274
275 // Determine the index of the size.
276 unsigned SizeIndex;
277 switch (Context.getTypeSize(ValType)/8) {
278 case 1: SizeIndex = 0; break;
279 case 2: SizeIndex = 1; break;
280 case 4: SizeIndex = 2; break;
281 case 8: SizeIndex = 3; break;
282 case 16: SizeIndex = 4; break;
283 default:
284 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
285 << FirstArg->getType() << FirstArg->getSourceRange();
286 }
287
288 // Each of these builtins has one pointer argument, followed by some number of
289 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
290 // that we ignore. Find out which row of BuiltinIndices to read from as well
291 // as the number of fixed args.
292 unsigned BuiltinID = FDecl->getBuiltinID(Context);
293 unsigned BuiltinIndex, NumFixed = 1;
294 switch (BuiltinID) {
295 default: assert(0 && "Unknown overloaded atomic builtin!");
296 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
297 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
298 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
299 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
300 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000301 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000302
Chris Lattnereebd9d22009-05-13 04:37:52 +0000303 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
304 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
305 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
306 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
307 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
308 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000309
310 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000311 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000312 NumFixed = 2;
313 break;
314 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000315 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000316 NumFixed = 2;
317 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000318 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000319 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000320 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000321 NumFixed = 0;
322 break;
323 }
324
325 // Now that we know how many fixed arguments we expect, first check that we
326 // have at least that many.
327 if (TheCall->getNumArgs() < 1+NumFixed)
328 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
329 << 0 << TheCall->getCallee()->getSourceRange();
330
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000331
332 // Get the decl for the concrete builtin from this, we can tell what the
333 // concrete integer type we should convert to is.
334 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
335 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
336 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
337 FunctionDecl *NewBuiltinDecl =
338 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
339 TUScope, false, DRE->getLocStart()));
340 const FunctionProtoType *BuiltinFT =
341 NewBuiltinDecl->getType()->getAsFunctionProtoType();
342 ValType = BuiltinFT->getArgType(0)->getAsPointerType()->getPointeeType();
343
344 // If the first type needs to be converted (e.g. void** -> int*), do it now.
345 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
346 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), false);
347 TheCall->setArg(0, FirstArg);
348 }
349
Chris Lattner5caa3702009-05-08 06:58:22 +0000350 // Next, walk the valid ones promoting to the right type.
351 for (unsigned i = 0; i != NumFixed; ++i) {
352 Expr *Arg = TheCall->getArg(i+1);
353
354 // If the argument is an implicit cast, then there was a promotion due to
355 // "...", just remove it now.
356 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
357 Arg = ICE->getSubExpr();
358 ICE->setSubExpr(0);
359 ICE->Destroy(Context);
360 TheCall->setArg(i+1, Arg);
361 }
362
363 // GCC does an implicit conversion to the pointer or integer ValType. This
364 // can fail in some cases (1i -> int**), check for this error case now.
365 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg))
366 return true;
367
368 // Okay, we have something that *can* be converted to the right type. Check
369 // to see if there is a potentially weird extension going on here. This can
370 // happen when you do an atomic operation on something like an char* and
371 // pass in 42. The 42 gets converted to char. This is even more strange
372 // for things like 45.123 -> char, etc.
373 // FIXME: Do this check.
374 ImpCastExprToType(Arg, ValType, false);
375 TheCall->setArg(i+1, Arg);
376 }
377
Chris Lattner5caa3702009-05-08 06:58:22 +0000378 // Switch the DeclRefExpr to refer to the new decl.
379 DRE->setDecl(NewBuiltinDecl);
380 DRE->setType(NewBuiltinDecl->getType());
381
382 // Set the callee in the CallExpr.
383 // FIXME: This leaks the original parens and implicit casts.
384 Expr *PromotedCall = DRE;
385 UsualUnaryConversions(PromotedCall);
386 TheCall->setCallee(PromotedCall);
387
388
389 // Change the result type of the call to match the result type of the decl.
390 TheCall->setType(NewBuiltinDecl->getResultType());
391 return false;
392}
393
394
Chris Lattner69039812009-02-18 06:01:06 +0000395/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000396/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000397/// FIXME: GCC currently emits the following warning:
398/// "warning: input conversion stopped due to an input byte that does not
399/// belong to the input codeset UTF-8"
400/// Note: It might also make sense to do the UTF-16 conversion here (would
401/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000402bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000403 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000404 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
405
406 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000407 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
408 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000409 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000410 }
411
412 const char *Data = Literal->getStrData();
413 unsigned Length = Literal->getByteLength();
414
415 for (unsigned i = 0; i < Length; ++i) {
Anders Carlsson71993dd2007-08-17 05:31:46 +0000416 if (!Data[i]) {
Chris Lattner60800082009-02-18 17:49:48 +0000417 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000418 diag::warn_cfstring_literal_contains_nul_character)
419 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000420 break;
421 }
422 }
423
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000424 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000425}
426
Chris Lattnerc27c6652007-12-20 00:05:45 +0000427/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
428/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000429bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
430 Expr *Fn = TheCall->getCallee();
431 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000432 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000433 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000434 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000435 << SourceRange(TheCall->getArg(2)->getLocStart(),
436 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000437 return true;
438 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000439
440 if (TheCall->getNumArgs() < 2) {
441 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
442 << 0 /*function call*/;
443 }
444
Chris Lattnerc27c6652007-12-20 00:05:45 +0000445 // Determine whether the current function is variadic or not.
446 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000447 if (CurBlock)
448 isVariadic = CurBlock->isVariadic;
449 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000450 if (FunctionProtoType* FTP =
451 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000452 isVariadic = FTP->isVariadic();
453 else
454 isVariadic = false;
455 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000456 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000457 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000458
Chris Lattnerc27c6652007-12-20 00:05:45 +0000459 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000460 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
461 return true;
462 }
463
464 // Verify that the second argument to the builtin is the last argument of the
465 // current function or method.
466 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000467 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000468
469 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
470 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000471 // FIXME: This isn't correct for methods (results in bogus warning).
472 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000473 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000474 if (CurBlock)
475 LastArg = *(CurBlock->TheDecl->param_end()-1);
476 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000477 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000478 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000479 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000480 SecondArgIsLastNamedArgument = PV == LastArg;
481 }
482 }
483
484 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000485 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000486 diag::warn_second_parameter_of_va_start_not_last_named_argument);
487 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000488}
Chris Lattner30ce3442007-12-19 23:59:04 +0000489
Chris Lattner1b9a0792007-12-20 00:26:33 +0000490/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
491/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000492bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
493 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000494 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
495 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000496 if (TheCall->getNumArgs() > 2)
497 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000498 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000499 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000500 << SourceRange(TheCall->getArg(2)->getLocStart(),
501 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000502
Chris Lattner925e60d2007-12-28 05:29:59 +0000503 Expr *OrigArg0 = TheCall->getArg(0);
504 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000505
Chris Lattner1b9a0792007-12-20 00:26:33 +0000506 // Do standard promotions between the two arguments, returning their common
507 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000508 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000509
510 // Make sure any conversions are pushed back into the call; this is
511 // type safe since unordered compare builtins are declared as "_Bool
512 // foo(...)".
513 TheCall->setArg(0, OrigArg0);
514 TheCall->setArg(1, OrigArg1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000515
Douglas Gregorcde01732009-05-19 22:10:17 +0000516 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
517 return false;
518
Chris Lattner1b9a0792007-12-20 00:26:33 +0000519 // If the common type isn't a real floating type, then the arguments were
520 // invalid for this operation.
521 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000522 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000523 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000524 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000525 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000526
527 return false;
528}
529
Eli Friedman6cfda232008-05-20 08:23:37 +0000530bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
531 // The signature for these builtins is exact; the only thing we need
532 // to check is that the argument is a constant.
533 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000534 if (!TheCall->getArg(0)->isTypeDependent() &&
535 !TheCall->getArg(0)->isValueDependent() &&
536 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000537 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000538
Eli Friedman6cfda232008-05-20 08:23:37 +0000539 return false;
540}
541
Eli Friedmand38617c2008-05-14 19:38:39 +0000542/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
543// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000544Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000545 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000546 return ExprError(Diag(TheCall->getLocEnd(),
547 diag::err_typecheck_call_too_few_args)
548 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000549
Douglas Gregorcde01732009-05-19 22:10:17 +0000550 unsigned numElements = std::numeric_limits<unsigned>::max();
551 if (!TheCall->getArg(0)->isTypeDependent() &&
552 !TheCall->getArg(1)->isTypeDependent()) {
553 QualType FAType = TheCall->getArg(0)->getType();
554 QualType SAType = TheCall->getArg(1)->getType();
555
556 if (!FAType->isVectorType() || !SAType->isVectorType()) {
557 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
558 << SourceRange(TheCall->getArg(0)->getLocStart(),
559 TheCall->getArg(1)->getLocEnd());
560 return ExprError();
561 }
562
563 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
564 Context.getCanonicalType(SAType).getUnqualifiedType()) {
565 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
566 << SourceRange(TheCall->getArg(0)->getLocStart(),
567 TheCall->getArg(1)->getLocEnd());
568 return ExprError();
569 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000570
Douglas Gregorcde01732009-05-19 22:10:17 +0000571 numElements = FAType->getAsVectorType()->getNumElements();
572 if (TheCall->getNumArgs() != numElements+2) {
573 if (TheCall->getNumArgs() < numElements+2)
574 return ExprError(Diag(TheCall->getLocEnd(),
575 diag::err_typecheck_call_too_few_args)
576 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000577 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000578 diag::err_typecheck_call_too_many_args)
579 << 0 /*function call*/ << TheCall->getSourceRange());
580 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000581 }
582
583 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000584 if (TheCall->getArg(i)->isTypeDependent() ||
585 TheCall->getArg(i)->isValueDependent())
586 continue;
587
Eli Friedmand38617c2008-05-14 19:38:39 +0000588 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000589 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000590 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000591 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000592 << TheCall->getArg(i)->getSourceRange());
593
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000594 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000595 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000596 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000597 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000598 }
599
600 llvm::SmallVector<Expr*, 32> exprs;
601
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000602 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000603 exprs.push_back(TheCall->getArg(i));
604 TheCall->setArg(i, 0);
605 }
606
Douglas Gregorcde01732009-05-19 22:10:17 +0000607 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), exprs.size(),
608 exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000609 TheCall->getCallee()->getLocStart(),
610 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000611}
Chris Lattner30ce3442007-12-19 23:59:04 +0000612
Daniel Dunbar4493f792008-07-21 22:59:13 +0000613/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
614// This is declared to take (const void*, ...) and can take two
615// optional constant int args.
616bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000617 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000618
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000619 if (NumArgs > 3)
620 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000621 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000622
623 // Argument 0 is checked for us and the remaining arguments must be
624 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000625 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000626 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000627 if (Arg->isTypeDependent())
628 continue;
629
Daniel Dunbar4493f792008-07-21 22:59:13 +0000630 QualType RWType = Arg->getType();
631
632 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000633 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000634 if (!BT || BT->getKind() != BuiltinType::Int)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000635 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
636 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Douglas Gregorcde01732009-05-19 22:10:17 +0000637
638 if (Arg->isValueDependent())
639 continue;
640
641 if (!Arg->isIntegerConstantExpr(Result, Context))
642 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
643 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000644
645 // FIXME: gcc issues a warning and rewrites these to 0. These
646 // seems especially odd for the third argument since the default
647 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000648 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000649 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000650 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
651 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000652 } else {
653 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000654 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
655 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000656 }
657 }
658
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000659 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000660}
661
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000662/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
663/// int type). This simply type checks that type is one of the defined
664/// constants (0-3).
665bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
666 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000667 if (Arg->isTypeDependent())
668 return false;
669
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000670 QualType ArgType = Arg->getType();
671 const BuiltinType *BT = ArgType->getAsBuiltinType();
672 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000673 if (!BT || BT->getKind() != BuiltinType::Int)
674 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
675 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
676
677 if (Arg->isValueDependent())
678 return false;
679
680 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000681 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
682 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000683 }
684
685 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000686 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
687 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000688 }
689
690 return false;
691}
692
Eli Friedman586d6a82009-05-03 06:04:26 +0000693/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000694/// This checks that val is a constant 1.
695bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
696 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000697 if (Arg->isTypeDependent() || Arg->isValueDependent())
698 return false;
699
Eli Friedmand875fed2009-05-03 04:46:36 +0000700 llvm::APSInt Result(32);
701 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
702 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
703 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
704
705 return false;
706}
707
Ted Kremenekd30ef872009-01-12 23:09:09 +0000708// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000709bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
710 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000711 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000712 if (E->isTypeDependent() || E->isValueDependent())
713 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000714
715 switch (E->getStmtClass()) {
716 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000717 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000718 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000719 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000720 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000721 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000722 }
723
724 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000725 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000726 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000727 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000728 }
729
730 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000731 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000732 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000733 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000734 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000735
736 case Stmt::DeclRefExprClass: {
737 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
738
739 // As an exception, do not flag errors for variables binding to
740 // const string literals.
741 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
742 bool isConstant = false;
743 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000744
Ted Kremenek082d9362009-03-20 21:35:28 +0000745 if (const ArrayType *AT = Context.getAsArrayType(T)) {
746 isConstant = AT->getElementType().isConstant(Context);
747 }
748 else if (const PointerType *PT = T->getAsPointerType()) {
749 isConstant = T.isConstant(Context) &&
750 PT->getPointeeType().isConstant(Context);
751 }
752
753 if (isConstant) {
754 const VarDecl *Def = 0;
755 if (const Expr *Init = VD->getDefinition(Def))
756 return SemaCheckStringLiteral(Init, TheCall,
757 HasVAListArg, format_idx, firstDataArg);
758 }
759 }
760
761 return false;
762 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000763
Ted Kremenek082d9362009-03-20 21:35:28 +0000764 case Stmt::ObjCStringLiteralClass:
765 case Stmt::StringLiteralClass: {
766 const StringLiteral *StrE = NULL;
767
768 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000769 StrE = ObjCFExpr->getString();
770 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000771 StrE = cast<StringLiteral>(E);
772
Ted Kremenekd30ef872009-01-12 23:09:09 +0000773 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000774 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
775 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000776 return true;
777 }
778
779 return false;
780 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000781
782 default:
783 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000784 }
785}
786
787
Chris Lattner59907c42007-08-10 20:18:51 +0000788/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000789/// correct use of format strings.
790///
791/// HasVAListArg - A predicate indicating whether the printf-like
792/// function is passed an explicit va_arg argument (e.g., vprintf)
793///
794/// format_idx - The index into Args for the format string.
795///
796/// Improper format strings to functions in the printf family can be
797/// the source of bizarre bugs and very serious security holes. A
798/// good source of information is available in the following paper
799/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000800///
801/// FormatGuard: Automatic Protection From printf Format String
802/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000803///
804/// Functionality implemented:
805///
806/// We can statically check the following properties for string
807/// literal format strings for non v.*printf functions (where the
808/// arguments are passed directly):
809//
810/// (1) Are the number of format conversions equal to the number of
811/// data arguments?
812///
813/// (2) Does each format conversion correctly match the type of the
814/// corresponding data argument? (TODO)
815///
816/// Moreover, for all printf functions we can:
817///
818/// (3) Check for a missing format string (when not caught by type checking).
819///
820/// (4) Check for no-operation flags; e.g. using "#" with format
821/// conversion 'c' (TODO)
822///
823/// (5) Check the use of '%n', a major source of security holes.
824///
825/// (6) Check for malformed format conversions that don't specify anything.
826///
827/// (7) Check for empty format strings. e.g: printf("");
828///
829/// (8) Check that the format string is a wide literal.
830///
Ted Kremenek6d439592008-03-03 16:50:00 +0000831/// (9) Also check the arguments of functions with the __format__ attribute.
832/// (TODO).
833///
Ted Kremenek71895b92007-08-14 17:39:48 +0000834/// All of these checks can be done by parsing the format string.
835///
836/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000837void
Ted Kremenek082d9362009-03-20 21:35:28 +0000838Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000839 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000840 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000841
Ted Kremenek71895b92007-08-14 17:39:48 +0000842 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000843 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000844 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
845 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000846 return;
847 }
848
Ted Kremenek082d9362009-03-20 21:35:28 +0000849 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000850
Chris Lattner59907c42007-08-10 20:18:51 +0000851 // CHECK: format string is not a string literal.
852 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000853 // Dynamically generated format strings are difficult to
854 // automatically vet at compile time. Requiring that format strings
855 // are string literals: (1) permits the checking of format strings by
856 // the compiler and thereby (2) can practically remove the source of
857 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000858
859 // Format string can be either ObjC string (e.g. @"%d") or
860 // C string (e.g. "%d")
861 // ObjC string uses the same format specifiers as C string, so we can use
862 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000863 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
864 firstDataArg))
865 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000866
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000867 // For vprintf* functions (i.e., HasVAListArg==true), we add a
868 // special check to see if the format string is a function parameter
869 // of the function calling the printf function. If the function
870 // has an attribute indicating it is a printf-like function, then we
871 // should suppress warnings concerning non-literals being used in a call
872 // to a vprintf function. For example:
873 //
874 // void
875 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
876 // va_list ap;
877 // va_start(ap, fmt);
878 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
879 // ...
880 //
881 //
882 // FIXME: We don't have full attribute support yet, so just check to see
883 // if the argument is a DeclRefExpr that references a parameter. We'll
884 // add proper support for checking the attribute later.
885 if (HasVAListArg)
886 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
887 if (isa<ParmVarDecl>(DR->getDecl()))
888 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000889
Chris Lattner655f1412009-04-29 04:59:47 +0000890 // If there are no arguments specified, warn with -Wformat-security, otherwise
891 // warn only with -Wformat-nonliteral.
892 if (TheCall->getNumArgs() == format_idx+1)
893 Diag(TheCall->getArg(format_idx)->getLocStart(),
894 diag::warn_printf_nonliteral_noargs)
895 << OrigFormatExpr->getSourceRange();
896 else
897 Diag(TheCall->getArg(format_idx)->getLocStart(),
898 diag::warn_printf_nonliteral)
899 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000900}
Ted Kremenek71895b92007-08-14 17:39:48 +0000901
Ted Kremenek082d9362009-03-20 21:35:28 +0000902void Sema::CheckPrintfString(const StringLiteral *FExpr,
903 const Expr *OrigFormatExpr,
904 const CallExpr *TheCall, bool HasVAListArg,
905 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000906
Ted Kremenek082d9362009-03-20 21:35:28 +0000907 const ObjCStringLiteral *ObjCFExpr =
908 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
909
Ted Kremenek71895b92007-08-14 17:39:48 +0000910 // CHECK: is the format string a wide literal?
911 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000912 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000913 diag::warn_printf_format_string_is_wide_literal)
914 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000915 return;
916 }
917
918 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000919 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +0000920
921 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000922 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek71895b92007-08-14 17:39:48 +0000923
924 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000925 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
926 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000927 return;
928 }
929
930 // We process the format string using a binary state machine. The
931 // current state is stored in CurrentState.
932 enum {
933 state_OrdChr,
934 state_Conversion
935 } CurrentState = state_OrdChr;
936
937 // numConversions - The number of conversions seen so far. This is
938 // incremented as we traverse the format string.
939 unsigned numConversions = 0;
940
941 // numDataArgs - The number of data arguments after the format
942 // string. This can only be determined for non vprintf-like
943 // functions. For those functions, this value is 1 (the sole
944 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000945 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000946
947 // Inspect the format string.
948 unsigned StrIdx = 0;
949
950 // LastConversionIdx - Index within the format string where we last saw
951 // a '%' character that starts a new format conversion.
952 unsigned LastConversionIdx = 0;
953
Chris Lattner925e60d2007-12-28 05:29:59 +0000954 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000955
Ted Kremenek71895b92007-08-14 17:39:48 +0000956 // Is the number of detected conversion conversions greater than
957 // the number of matching data arguments? If so, stop.
958 if (!HasVAListArg && numConversions > numDataArgs) break;
959
960 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000961 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000962 // The string returned by getStrData() is not null-terminated,
963 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +0000964 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000965 diag::warn_printf_format_string_contains_null_char)
966 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000967 return;
968 }
969
970 // Ordinary characters (not processing a format conversion).
971 if (CurrentState == state_OrdChr) {
972 if (Str[StrIdx] == '%') {
973 CurrentState = state_Conversion;
974 LastConversionIdx = StrIdx;
975 }
976 continue;
977 }
978
979 // Seen '%'. Now processing a format conversion.
980 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000981 // Handle dynamic precision or width specifier.
982 case '*': {
983 ++numConversions;
984
Ted Kremenek42ae3e82009-05-13 16:06:05 +0000985 if (!HasVAListArg) {
986 if (numConversions > numDataArgs) {
987 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +0000988
Ted Kremenek42ae3e82009-05-13 16:06:05 +0000989 if (Str[StrIdx-1] == '.')
990 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
991 << OrigFormatExpr->getSourceRange();
992 else
993 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
994 << OrigFormatExpr->getSourceRange();
995
996 // Don't do any more checking. We'll just emit spurious errors.
997 return;
998 }
999
1000 // Perform type checking on width/precision specifier.
1001 const Expr *E = TheCall->getArg(format_idx+numConversions);
1002 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
1003 if (BT->getKind() == BuiltinType::Int)
1004 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001005
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001006 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
1007
1008 if (Str[StrIdx-1] == '.')
1009 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1010 << E->getType() << E->getSourceRange();
1011 else
1012 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1013 << E->getType() << E->getSourceRange();
1014
1015 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001016 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001017 }
1018
1019 // Characters which can terminate a format conversion
1020 // (e.g. "%d"). Characters that specify length modifiers or
1021 // other flags are handled by the default case below.
1022 //
1023 // FIXME: additional checks will go into the following cases.
1024 case 'i':
1025 case 'd':
1026 case 'o':
1027 case 'u':
1028 case 'x':
1029 case 'X':
1030 case 'D':
1031 case 'O':
1032 case 'U':
1033 case 'e':
1034 case 'E':
1035 case 'f':
1036 case 'F':
1037 case 'g':
1038 case 'G':
1039 case 'a':
1040 case 'A':
1041 case 'c':
1042 case 'C':
1043 case 'S':
1044 case 's':
1045 case 'p':
1046 ++numConversions;
1047 CurrentState = state_OrdChr;
1048 break;
1049
1050 // CHECK: Are we using "%n"? Issue a warning.
1051 case 'n': {
1052 ++numConversions;
1053 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +00001054 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1055 LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001056
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001057 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001058 break;
1059 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001060
1061 // Handle "%@"
1062 case '@':
1063 // %@ is allowed in ObjC format strings only.
1064 if(ObjCFExpr != NULL)
1065 CurrentState = state_OrdChr;
1066 else {
1067 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001068 SourceLocation Loc =
1069 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001070
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001071 Diag(Loc, diag::warn_printf_invalid_conversion)
1072 << std::string(Str+LastConversionIdx,
1073 Str+std::min(LastConversionIdx+2, StrLen))
1074 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001075 }
1076 ++numConversions;
1077 break;
1078
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001079 // Handle "%%"
1080 case '%':
1081 // Sanity check: Was the first "%" character the previous one?
1082 // If not, we will assume that we have a malformed format
1083 // conversion, and that the current "%" character is the start
1084 // of a new conversion.
1085 if (StrIdx - LastConversionIdx == 1)
1086 CurrentState = state_OrdChr;
1087 else {
1088 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001089 SourceLocation Loc =
1090 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001091
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001092 Diag(Loc, diag::warn_printf_invalid_conversion)
1093 << std::string(Str+LastConversionIdx, Str+StrIdx)
1094 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001095
1096 // This conversion is broken. Advance to the next format
1097 // conversion.
1098 LastConversionIdx = StrIdx;
1099 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +00001100 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001101 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001102
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001103 default:
1104 // This case catches all other characters: flags, widths, etc.
1105 // We should eventually process those as well.
1106 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001107 }
1108 }
1109
1110 if (CurrentState == state_Conversion) {
1111 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001112 SourceLocation Loc =
1113 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +00001114
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001115 Diag(Loc, diag::warn_printf_invalid_conversion)
1116 << std::string(Str+LastConversionIdx,
1117 Str+std::min(LastConversionIdx+2, StrLen))
1118 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001119 return;
1120 }
1121
1122 if (!HasVAListArg) {
1123 // CHECK: Does the number of format conversions exceed the number
1124 // of data arguments?
1125 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +00001126 SourceLocation Loc =
1127 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +00001128
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001129 Diag(Loc, diag::warn_printf_insufficient_data_args)
1130 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001131 }
1132 // CHECK: Does the number of data arguments exceed the number of
1133 // format conversions in the format string?
1134 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +00001135 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001136 diag::warn_printf_too_many_data_args)
1137 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001138 }
1139}
Ted Kremenek06de2762007-08-17 16:46:58 +00001140
1141//===--- CHECK: Return Address of Stack Variable --------------------------===//
1142
1143static DeclRefExpr* EvalVal(Expr *E);
1144static DeclRefExpr* EvalAddr(Expr* E);
1145
1146/// CheckReturnStackAddr - Check if a return statement returns the address
1147/// of a stack variable.
1148void
1149Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1150 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +00001151
Ted Kremenek06de2762007-08-17 16:46:58 +00001152 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001153 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001154 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001155 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001156 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001157
1158 // Skip over implicit cast expressions when checking for block expressions.
1159 if (ImplicitCastExpr *IcExpr =
1160 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
1161 RetValExp = IcExpr->getSubExpr();
1162
Steve Naroff61f40a22008-09-10 19:17:48 +00001163 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001164 if (C->hasBlockDeclRefExprs())
1165 Diag(C->getLocStart(), diag::err_ret_local_block)
1166 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001167 }
1168 // Perform checking for stack values returned by reference.
1169 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +00001170 // Check for a reference to the stack
1171 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001172 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001173 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001174 }
1175}
1176
1177/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1178/// check if the expression in a return statement evaluates to an address
1179/// to a location on the stack. The recursion is used to traverse the
1180/// AST of the return expression, with recursion backtracking when we
1181/// encounter a subexpression that (1) clearly does not lead to the address
1182/// of a stack variable or (2) is something we cannot determine leads to
1183/// the address of a stack variable based on such local checking.
1184///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001185/// EvalAddr processes expressions that are pointers that are used as
1186/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +00001187/// At the base case of the recursion is a check for a DeclRefExpr* in
1188/// the refers to a stack variable.
1189///
1190/// This implementation handles:
1191///
1192/// * pointer-to-pointer casts
1193/// * implicit conversions from array references to pointers
1194/// * taking the address of fields
1195/// * arbitrary interplay between "&" and "*" operators
1196/// * pointer arithmetic from an address of a stack variable
1197/// * taking the address of an array element where the array is on the stack
1198static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001199 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +00001200 assert((E->getType()->isPointerType() ||
1201 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001202 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001203 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +00001204
1205 // Our "symbolic interpreter" is just a dispatch off the currently
1206 // viewed AST node. We then recursively traverse the AST by calling
1207 // EvalAddr and EvalVal appropriately.
1208 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001209 case Stmt::ParenExprClass:
1210 // Ignore parentheses.
1211 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001212
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001213 case Stmt::UnaryOperatorClass: {
1214 // The only unary operator that make sense to handle here
1215 // is AddrOf. All others don't make sense as pointers.
1216 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +00001217
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001218 if (U->getOpcode() == UnaryOperator::AddrOf)
1219 return EvalVal(U->getSubExpr());
1220 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001221 return NULL;
1222 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001223
1224 case Stmt::BinaryOperatorClass: {
1225 // Handle pointer arithmetic. All other binary operators are not valid
1226 // in this context.
1227 BinaryOperator *B = cast<BinaryOperator>(E);
1228 BinaryOperator::Opcode op = B->getOpcode();
1229
1230 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1231 return NULL;
1232
1233 Expr *Base = B->getLHS();
1234
1235 // Determine which argument is the real pointer base. It could be
1236 // the RHS argument instead of the LHS.
1237 if (!Base->getType()->isPointerType()) Base = B->getRHS();
1238
1239 assert (Base->getType()->isPointerType());
1240 return EvalAddr(Base);
1241 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001242
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001243 // For conditional operators we need to see if either the LHS or RHS are
1244 // valid DeclRefExpr*s. If one of them is valid, we return it.
1245 case Stmt::ConditionalOperatorClass: {
1246 ConditionalOperator *C = cast<ConditionalOperator>(E);
1247
1248 // Handle the GNU extension for missing LHS.
1249 if (Expr *lhsExpr = C->getLHS())
1250 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1251 return LHS;
1252
1253 return EvalAddr(C->getRHS());
1254 }
1255
Ted Kremenek54b52742008-08-07 00:49:01 +00001256 // For casts, we need to handle conversions from arrays to
1257 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001258 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001259 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001260 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001261 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001262 QualType T = SubExpr->getType();
1263
Steve Naroffdd972f22008-09-05 22:11:13 +00001264 if (SubExpr->getType()->isPointerType() ||
1265 SubExpr->getType()->isBlockPointerType() ||
1266 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001267 return EvalAddr(SubExpr);
1268 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001269 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001270 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001271 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001272 }
1273
1274 // C++ casts. For dynamic casts, static casts, and const casts, we
1275 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001276 // through the cast. In the case the dynamic cast doesn't fail (and
1277 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001278 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001279 // FIXME: The comment about is wrong; we're not always converting
1280 // from pointer to pointer. I'm guessing that this code should also
1281 // handle references to objects.
1282 case Stmt::CXXStaticCastExprClass:
1283 case Stmt::CXXDynamicCastExprClass:
1284 case Stmt::CXXConstCastExprClass:
1285 case Stmt::CXXReinterpretCastExprClass: {
1286 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001287 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001288 return EvalAddr(S);
1289 else
1290 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001291 }
1292
1293 // Everything else: we simply don't reason about them.
1294 default:
1295 return NULL;
1296 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001297}
1298
1299
1300/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1301/// See the comments for EvalAddr for more details.
1302static DeclRefExpr* EvalVal(Expr *E) {
1303
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001304 // We should only be called for evaluating non-pointer expressions, or
1305 // expressions with a pointer type that are not used as references but instead
1306 // are l-values (e.g., DeclRefExpr with a pointer type).
1307
Ted Kremenek06de2762007-08-17 16:46:58 +00001308 // Our "symbolic interpreter" is just a dispatch off the currently
1309 // viewed AST node. We then recursively traverse the AST by calling
1310 // EvalAddr and EvalVal appropriately.
1311 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +00001312 case Stmt::DeclRefExprClass:
1313 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001314 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1315 // at code that refers to a variable's name. We check if it has local
1316 // storage within the function, and if so, return the expression.
1317 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1318
1319 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001320 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +00001321
1322 return NULL;
1323 }
1324
1325 case Stmt::ParenExprClass:
1326 // Ignore parentheses.
1327 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1328
1329 case Stmt::UnaryOperatorClass: {
1330 // The only unary operator that make sense to handle here
1331 // is Deref. All others don't resolve to a "name." This includes
1332 // handling all sorts of rvalues passed to a unary operator.
1333 UnaryOperator *U = cast<UnaryOperator>(E);
1334
1335 if (U->getOpcode() == UnaryOperator::Deref)
1336 return EvalAddr(U->getSubExpr());
1337
1338 return NULL;
1339 }
1340
1341 case Stmt::ArraySubscriptExprClass: {
1342 // Array subscripts are potential references to data on the stack. We
1343 // retrieve the DeclRefExpr* for the array variable if it indeed
1344 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001345 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001346 }
1347
1348 case Stmt::ConditionalOperatorClass: {
1349 // For conditional operators we need to see if either the LHS or RHS are
1350 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1351 ConditionalOperator *C = cast<ConditionalOperator>(E);
1352
Anders Carlsson39073232007-11-30 19:04:31 +00001353 // Handle the GNU extension for missing LHS.
1354 if (Expr *lhsExpr = C->getLHS())
1355 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1356 return LHS;
1357
1358 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001359 }
1360
1361 // Accesses to members are potential references to data on the stack.
1362 case Stmt::MemberExprClass: {
1363 MemberExpr *M = cast<MemberExpr>(E);
1364
1365 // Check for indirect access. We only want direct field accesses.
1366 if (!M->isArrow())
1367 return EvalVal(M->getBase());
1368 else
1369 return NULL;
1370 }
1371
1372 // Everything else: we simply don't reason about them.
1373 default:
1374 return NULL;
1375 }
1376}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001377
1378//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1379
1380/// Check for comparisons of floating point operands using != and ==.
1381/// Issue a warning if these are no self-comparisons, as they are not likely
1382/// to do what the programmer intended.
1383void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1384 bool EmitWarning = true;
1385
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001386 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001387 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001388
1389 // Special case: check for x == x (which is OK).
1390 // Do not emit warnings for such cases.
1391 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1392 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1393 if (DRL->getDecl() == DRR->getDecl())
1394 EmitWarning = false;
1395
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001396
1397 // Special case: check for comparisons against literals that can be exactly
1398 // represented by APFloat. In such cases, do not emit a warning. This
1399 // is a heuristic: often comparison against such literals are used to
1400 // detect if a value in a variable has not changed. This clearly can
1401 // lead to false negatives.
1402 if (EmitWarning) {
1403 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1404 if (FLL->isExact())
1405 EmitWarning = false;
1406 }
1407 else
1408 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1409 if (FLR->isExact())
1410 EmitWarning = false;
1411 }
1412 }
1413
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001414 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001415 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001416 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001417 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001418 EmitWarning = false;
1419
Sebastian Redl0eb23302009-01-19 00:08:26 +00001420 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001421 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001422 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001423 EmitWarning = false;
1424
1425 // Emit the diagnostic.
1426 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001427 Diag(loc, diag::warn_floatingpoint_eq)
1428 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001429}