blob: 949c33dfff806b0b115149f281b8752e844e8b14 [file] [log] [blame]
Chris Lattner2e64c072007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner2e64c072007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements extra semantic analysis beyond what is enforced
11// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek1c1700f2007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek225a14c2008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattnerbe93e792009-02-18 19:21:10 +000020#include "clang/Lex/LiteralSupport.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000021#include "clang/Lex/Preprocessor.h"
Zhongxing Xufedea7e2009-05-20 01:55:10 +000022#include <limits>
Chris Lattner2e64c072007-08-10 20:18:51 +000023using namespace clang;
24
Chris Lattnerf17cb362009-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 Lattnerf6d44722009-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 Lattner30183b02009-02-18 18:34:12 +000069
Chris Lattner81df8462009-02-18 18:52:52 +000070 // If the byte is in this token, return the location of the byte.
Chris Lattnerf17cb362009-02-18 17:49:48 +000071 if (ByteNo < TokNumBytes ||
72 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Chris Lattnerbe93e792009-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 Lattnerf17cb362009-02-18 17:49:48 +000079 }
80
81 // Move to the next string token.
82 ++TokNo;
83 ByteNo -= TokNumBytes;
84 }
85}
86
Ryan Flynnb692ec42009-08-06 03:00:50 +000087/// CheckablePrintfAttr - does a function call have a "printf" attribute
88/// and arguments that merit checking?
89bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
90 if (Format->getType() == "printf") return true;
91 if (Format->getType() == "printf0") {
92 // printf0 allows null "format" string; if so don't check format/args
93 unsigned format_idx = Format->getFormatIdx() - 1;
94 if (format_idx < TheCall->getNumArgs()) {
95 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
96 if (!Format->isNullPointerConstant(Context))
97 return true;
98 }
99 }
100 return false;
101}
Chris Lattnerf17cb362009-02-18 17:49:48 +0000102
Chris Lattner2e64c072007-08-10 20:18:51 +0000103/// CheckFunctionCall - Check a direct function call for various correctness
104/// and safety properties not strictly enforced by the C type system.
Sebastian Redl8b769972009-01-19 00:08:26 +0000105Action::OwningExprResult
106Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
107 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner2e64c072007-08-10 20:18:51 +0000108 // Get the IdentifierInfo* for the called function.
109 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000110
111 // None of the checks below are needed for functions that don't have
112 // simple names (e.g., C++ conversion functions).
113 if (!FnInfo)
Sebastian Redl8b769972009-01-19 00:08:26 +0000114 return move(TheCallResult);
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000115
Douglas Gregorb5af7382009-02-14 18:57:46 +0000116 switch (FDecl->getBuiltinID(Context)) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000117 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000118 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000119 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner81f5be22009-02-18 06:01:06 +0000120 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl8b769972009-01-19 00:08:26 +0000121 return ExprError();
122 return move(TheCallResult);
Ted Kremenek7a0654c2008-07-09 17:58:53 +0000123 case Builtin::BI__builtin_stdarg_start:
Chris Lattnerf22a8502007-12-19 23:59:04 +0000124 case Builtin::BI__builtin_va_start:
Sebastian Redl8b769972009-01-19 00:08:26 +0000125 if (SemaBuiltinVAStart(TheCall))
126 return ExprError();
127 return move(TheCallResult);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000128 case Builtin::BI__builtin_isgreater:
129 case Builtin::BI__builtin_isgreaterequal:
130 case Builtin::BI__builtin_isless:
131 case Builtin::BI__builtin_islessequal:
132 case Builtin::BI__builtin_islessgreater:
133 case Builtin::BI__builtin_isunordered:
Sebastian Redl8b769972009-01-19 00:08:26 +0000134 if (SemaBuiltinUnorderedCompare(TheCall))
135 return ExprError();
136 return move(TheCallResult);
Eli Friedman8c50c622008-05-20 08:23:37 +0000137 case Builtin::BI__builtin_return_address:
138 case Builtin::BI__builtin_frame_address:
Sebastian Redl8b769972009-01-19 00:08:26 +0000139 if (SemaBuiltinStackAddress(TheCall))
140 return ExprError();
141 return move(TheCallResult);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000142 case Builtin::BI__builtin_shufflevector:
Sebastian Redl8b769972009-01-19 00:08:26 +0000143 return SemaBuiltinShuffleVector(TheCall);
144 // TheCall will be freed by the smart pointer here, but that's fine, since
145 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000146 case Builtin::BI__builtin_prefetch:
Sebastian Redl8b769972009-01-19 00:08:26 +0000147 if (SemaBuiltinPrefetch(TheCall))
148 return ExprError();
149 return move(TheCallResult);
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000150 case Builtin::BI__builtin_object_size:
Sebastian Redl8b769972009-01-19 00:08:26 +0000151 if (SemaBuiltinObjectSize(TheCall))
152 return ExprError();
Eli Friedman5e0ae472009-05-03 06:04:26 +0000153 return move(TheCallResult);
Eli Friedman6277e402009-05-03 04:46:36 +0000154 case Builtin::BI__builtin_longjmp:
155 if (SemaBuiltinLongjmp(TheCall))
156 return ExprError();
Eli Friedman5e0ae472009-05-03 06:04:26 +0000157 return move(TheCallResult);
Chris Lattner822adfe2009-05-08 06:58:22 +0000158 case Builtin::BI__sync_fetch_and_add:
159 case Builtin::BI__sync_fetch_and_sub:
160 case Builtin::BI__sync_fetch_and_or:
161 case Builtin::BI__sync_fetch_and_and:
162 case Builtin::BI__sync_fetch_and_xor:
Chris Lattner33615252009-05-13 04:37:52 +0000163 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner822adfe2009-05-08 06:58:22 +0000164 case Builtin::BI__sync_add_and_fetch:
165 case Builtin::BI__sync_sub_and_fetch:
166 case Builtin::BI__sync_and_and_fetch:
167 case Builtin::BI__sync_or_and_fetch:
168 case Builtin::BI__sync_xor_and_fetch:
Chris Lattner33615252009-05-13 04:37:52 +0000169 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner822adfe2009-05-08 06:58:22 +0000170 case Builtin::BI__sync_val_compare_and_swap:
171 case Builtin::BI__sync_bool_compare_and_swap:
172 case Builtin::BI__sync_lock_test_and_set:
173 case Builtin::BI__sync_lock_release:
174 if (SemaBuiltinAtomicOverloaded(TheCall))
175 return ExprError();
176 return move(TheCallResult);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000177 }
Daniel Dunbar0ab03e62008-10-02 18:44:07 +0000178
179 // FIXME: This mechanism should be abstracted to be less fragile and
180 // more efficient. For example, just map function ids to custom
181 // handlers.
182
Chris Lattner2e64c072007-08-10 20:18:51 +0000183 // Printf checking.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +0000184 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynnb692ec42009-08-06 03:00:50 +0000185 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenekfec9c152009-02-27 17:58:43 +0000186 bool HasVAListArg = Format->getFirstArg() == 0;
187 if (!HasVAListArg) {
188 if (const FunctionProtoType *Proto
189 = FDecl->getType()->getAsFunctionProtoType())
Douglas Gregorb5af7382009-02-14 18:57:46 +0000190 HasVAListArg = !Proto->isVariadic();
Ted Kremenekfec9c152009-02-27 17:58:43 +0000191 }
Douglas Gregorb5af7382009-02-14 18:57:46 +0000192 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenekfec9c152009-02-27 17:58:43 +0000193 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregorb5af7382009-02-14 18:57:46 +0000194 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000195 }
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +0000196 for (const Attr *attr = FDecl->getAttrs();
Douglas Gregor98da6ae2009-06-18 16:11:24 +0000197 attr; attr = attr->getNext()) {
Fariborz Jahanian5440d2f2009-05-21 18:48:51 +0000198 if (const NonNullAttr *NonNull = dyn_cast<NonNullAttr>(attr))
199 CheckNonNullArguments(NonNull, TheCall);
200 }
Sebastian Redl8b769972009-01-19 00:08:26 +0000201
202 return move(TheCallResult);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000203}
204
Fariborz Jahanianf83c85f2009-05-18 21:05:18 +0000205Action::OwningExprResult
206Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
207
208 OwningExprResult TheCallResult(Owned(TheCall));
209 // Printf checking.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +0000210 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanianf83c85f2009-05-18 21:05:18 +0000211 if (!Format)
212 return move(TheCallResult);
213 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
214 if (!V)
215 return move(TheCallResult);
216 QualType Ty = V->getType();
217 if (!Ty->isBlockPointerType())
218 return move(TheCallResult);
Ryan Flynnb692ec42009-08-06 03:00:50 +0000219 if (CheckablePrintfAttr(Format, TheCall)) {
Fariborz Jahanianf83c85f2009-05-18 21:05:18 +0000220 bool HasVAListArg = Format->getFirstArg() == 0;
221 if (!HasVAListArg) {
222 const FunctionType *FT =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000223 Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianf83c85f2009-05-18 21:05:18 +0000224 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
225 HasVAListArg = !Proto->isVariadic();
226 }
227 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
228 HasVAListArg ? 0 : Format->getFirstArg() - 1);
229 }
230 return move(TheCallResult);
231}
232
Chris Lattner822adfe2009-05-08 06:58:22 +0000233/// SemaBuiltinAtomicOverloaded - We have a call to a function like
234/// __sync_fetch_and_add, which is an overloaded function based on the pointer
235/// type of its first argument. The main ActOnCallExpr routines have already
236/// promoted the types of arguments because all of these calls are prototyped as
237/// void(...).
238///
239/// This function goes through and does final semantic checking for these
240/// builtins,
241bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
242 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
243 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
244
245 // Ensure that we have at least one argument to do type inference from.
246 if (TheCall->getNumArgs() < 1)
247 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
248 << 0 << TheCall->getCallee()->getSourceRange();
249
250 // Inspect the first argument of the atomic builtin. This should always be
251 // a pointer type, whose element is an integral scalar or pointer type.
252 // Because it is a pointer type, we don't have to worry about any implicit
253 // casts here.
254 Expr *FirstArg = TheCall->getArg(0);
255 if (!FirstArg->getType()->isPointerType())
256 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
257 << FirstArg->getType() << FirstArg->getSourceRange();
258
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000259 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattner822adfe2009-05-08 06:58:22 +0000260 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
261 !ValType->isBlockPointerType())
262 return Diag(DRE->getLocStart(),
263 diag::err_atomic_builtin_must_be_pointer_intptr)
264 << FirstArg->getType() << FirstArg->getSourceRange();
265
266 // We need to figure out which concrete builtin this maps onto. For example,
267 // __sync_fetch_and_add with a 2 byte object turns into
268 // __sync_fetch_and_add_2.
269#define BUILTIN_ROW(x) \
270 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
271 Builtin::BI##x##_8, Builtin::BI##x##_16 }
272
273 static const unsigned BuiltinIndices[][5] = {
274 BUILTIN_ROW(__sync_fetch_and_add),
275 BUILTIN_ROW(__sync_fetch_and_sub),
276 BUILTIN_ROW(__sync_fetch_and_or),
277 BUILTIN_ROW(__sync_fetch_and_and),
278 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattner33615252009-05-13 04:37:52 +0000279 BUILTIN_ROW(__sync_fetch_and_nand),
Chris Lattner822adfe2009-05-08 06:58:22 +0000280
281 BUILTIN_ROW(__sync_add_and_fetch),
282 BUILTIN_ROW(__sync_sub_and_fetch),
283 BUILTIN_ROW(__sync_and_and_fetch),
284 BUILTIN_ROW(__sync_or_and_fetch),
285 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattner33615252009-05-13 04:37:52 +0000286 BUILTIN_ROW(__sync_nand_and_fetch),
Chris Lattner822adfe2009-05-08 06:58:22 +0000287
288 BUILTIN_ROW(__sync_val_compare_and_swap),
289 BUILTIN_ROW(__sync_bool_compare_and_swap),
290 BUILTIN_ROW(__sync_lock_test_and_set),
291 BUILTIN_ROW(__sync_lock_release)
292 };
293#undef BUILTIN_ROW
294
295 // Determine the index of the size.
296 unsigned SizeIndex;
297 switch (Context.getTypeSize(ValType)/8) {
298 case 1: SizeIndex = 0; break;
299 case 2: SizeIndex = 1; break;
300 case 4: SizeIndex = 2; break;
301 case 8: SizeIndex = 3; break;
302 case 16: SizeIndex = 4; break;
303 default:
304 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
305 << FirstArg->getType() << FirstArg->getSourceRange();
306 }
307
308 // Each of these builtins has one pointer argument, followed by some number of
309 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
310 // that we ignore. Find out which row of BuiltinIndices to read from as well
311 // as the number of fixed args.
312 unsigned BuiltinID = FDecl->getBuiltinID(Context);
313 unsigned BuiltinIndex, NumFixed = 1;
314 switch (BuiltinID) {
315 default: assert(0 && "Unknown overloaded atomic builtin!");
316 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
317 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
318 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
319 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
320 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattner33615252009-05-13 04:37:52 +0000321 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Chris Lattner822adfe2009-05-08 06:58:22 +0000322
Chris Lattner33615252009-05-13 04:37:52 +0000323 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
324 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
325 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
326 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
327 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
328 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Chris Lattner822adfe2009-05-08 06:58:22 +0000329
330 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattner33615252009-05-13 04:37:52 +0000331 BuiltinIndex = 12;
Chris Lattner822adfe2009-05-08 06:58:22 +0000332 NumFixed = 2;
333 break;
334 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattner33615252009-05-13 04:37:52 +0000335 BuiltinIndex = 13;
Chris Lattner822adfe2009-05-08 06:58:22 +0000336 NumFixed = 2;
337 break;
Chris Lattner33615252009-05-13 04:37:52 +0000338 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner822adfe2009-05-08 06:58:22 +0000339 case Builtin::BI__sync_lock_release:
Chris Lattner33615252009-05-13 04:37:52 +0000340 BuiltinIndex = 15;
Chris Lattner822adfe2009-05-08 06:58:22 +0000341 NumFixed = 0;
342 break;
343 }
344
345 // Now that we know how many fixed arguments we expect, first check that we
346 // have at least that many.
347 if (TheCall->getNumArgs() < 1+NumFixed)
348 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
349 << 0 << TheCall->getCallee()->getSourceRange();
350
Chris Lattner5e8eb1f2009-05-08 15:36:58 +0000351
352 // Get the decl for the concrete builtin from this, we can tell what the
353 // concrete integer type we should convert to is.
354 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
355 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
356 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
357 FunctionDecl *NewBuiltinDecl =
358 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
359 TUScope, false, DRE->getLocStart()));
360 const FunctionProtoType *BuiltinFT =
361 NewBuiltinDecl->getType()->getAsFunctionProtoType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000362 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Chris Lattner5e8eb1f2009-05-08 15:36:58 +0000363
364 // If the first type needs to be converted (e.g. void** -> int*), do it now.
365 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Anders Carlsson85186942009-07-31 01:23:52 +0000366 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_Unknown,
367 /*isLvalue=*/false);
Chris Lattner5e8eb1f2009-05-08 15:36:58 +0000368 TheCall->setArg(0, FirstArg);
369 }
370
Chris Lattner822adfe2009-05-08 06:58:22 +0000371 // Next, walk the valid ones promoting to the right type.
372 for (unsigned i = 0; i != NumFixed; ++i) {
373 Expr *Arg = TheCall->getArg(i+1);
374
375 // If the argument is an implicit cast, then there was a promotion due to
376 // "...", just remove it now.
377 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
378 Arg = ICE->getSubExpr();
379 ICE->setSubExpr(0);
380 ICE->Destroy(Context);
381 TheCall->setArg(i+1, Arg);
382 }
383
384 // GCC does an implicit conversion to the pointer or integer ValType. This
385 // can fail in some cases (1i -> int**), check for this error case now.
386 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg))
387 return true;
388
389 // Okay, we have something that *can* be converted to the right type. Check
390 // to see if there is a potentially weird extension going on here. This can
391 // happen when you do an atomic operation on something like an char* and
392 // pass in 42. The 42 gets converted to char. This is even more strange
393 // for things like 45.123 -> char, etc.
394 // FIXME: Do this check.
Anders Carlsson85186942009-07-31 01:23:52 +0000395 ImpCastExprToType(Arg, ValType, CastExpr::CK_Unknown,
396 /*isLvalue=*/false);
Chris Lattner822adfe2009-05-08 06:58:22 +0000397 TheCall->setArg(i+1, Arg);
398 }
399
Chris Lattner822adfe2009-05-08 06:58:22 +0000400 // Switch the DeclRefExpr to refer to the new decl.
401 DRE->setDecl(NewBuiltinDecl);
402 DRE->setType(NewBuiltinDecl->getType());
403
404 // Set the callee in the CallExpr.
405 // FIXME: This leaks the original parens and implicit casts.
406 Expr *PromotedCall = DRE;
407 UsualUnaryConversions(PromotedCall);
408 TheCall->setCallee(PromotedCall);
409
410
411 // Change the result type of the call to match the result type of the decl.
412 TheCall->setType(NewBuiltinDecl->getResultType());
413 return false;
414}
415
416
Chris Lattner81f5be22009-02-18 06:01:06 +0000417/// CheckObjCString - Checks that the argument to the builtin
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000418/// CFString constructor is correct
Steve Naroff9c9dc522009-04-13 20:26:29 +0000419/// FIXME: GCC currently emits the following warning:
420/// "warning: input conversion stopped due to an input byte that does not
421/// belong to the input codeset UTF-8"
422/// Note: It might also make sense to do the UTF-16 conversion here (would
423/// simplify the backend).
Chris Lattner81f5be22009-02-18 06:01:06 +0000424bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000425 Arg = Arg->IgnoreParenCasts();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000426 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
427
428 if (!Literal || Literal->isWide()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000429 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
430 << Arg->getSourceRange();
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000431 return true;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000432 }
433
434 const char *Data = Literal->getStrData();
435 unsigned Length = Literal->getByteLength();
436
437 for (unsigned i = 0; i < Length; ++i) {
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000438 if (!Data[i]) {
Chris Lattnerf17cb362009-02-18 17:49:48 +0000439 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000440 diag::warn_cfstring_literal_contains_nul_character)
441 << Arg->getSourceRange();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000442 break;
443 }
444 }
445
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000446 return false;
Chris Lattner2e64c072007-08-10 20:18:51 +0000447}
448
Chris Lattner3b933692007-12-20 00:05:45 +0000449/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
450/// Emit an error and return true on failure, return false on success.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000451bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
452 Expr *Fn = TheCall->getCallee();
453 if (TheCall->getNumArgs() > 2) {
Chris Lattner66beaba2008-11-21 18:44:24 +0000454 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000455 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000456 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000457 << SourceRange(TheCall->getArg(2)->getLocStart(),
458 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattnerf22a8502007-12-19 23:59:04 +0000459 return true;
460 }
Eli Friedman6422de62008-12-15 22:05:35 +0000461
462 if (TheCall->getNumArgs() < 2) {
463 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
464 << 0 /*function call*/;
465 }
466
Chris Lattner3b933692007-12-20 00:05:45 +0000467 // Determine whether the current function is variadic or not.
468 bool isVariadic;
Steve Naroffe06a81e2009-04-15 19:33:47 +0000469 if (CurBlock)
470 isVariadic = CurBlock->isVariadic;
471 else if (getCurFunctionDecl()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000472 if (FunctionProtoType* FTP =
473 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman6422de62008-12-15 22:05:35 +0000474 isVariadic = FTP->isVariadic();
475 else
476 isVariadic = false;
477 } else {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000478 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman6422de62008-12-15 22:05:35 +0000479 }
Chris Lattnerf22a8502007-12-19 23:59:04 +0000480
Chris Lattner3b933692007-12-20 00:05:45 +0000481 if (!isVariadic) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000482 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
483 return true;
484 }
485
486 // Verify that the second argument to the builtin is the last argument of the
487 // current function or method.
488 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson924556e2008-02-13 01:22:59 +0000489 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlssonc27156b2008-02-11 04:20:54 +0000490
491 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
492 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000493 // FIXME: This isn't correct for methods (results in bogus warning).
494 // Get the last formal in the current function.
Anders Carlssonc27156b2008-02-11 04:20:54 +0000495 const ParmVarDecl *LastArg;
Steve Naroffe06a81e2009-04-15 19:33:47 +0000496 if (CurBlock)
497 LastArg = *(CurBlock->TheDecl->param_end()-1);
498 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere5cb5862008-12-04 23:50:19 +0000499 LastArg = *(FD->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000500 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000501 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000502 SecondArgIsLastNamedArgument = PV == LastArg;
503 }
504 }
505
506 if (!SecondArgIsLastNamedArgument)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000507 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000508 diag::warn_second_parameter_of_va_start_not_last_named_argument);
509 return false;
Eli Friedman8c50c622008-05-20 08:23:37 +0000510}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000511
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000512/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
513/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000514bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
515 if (TheCall->getNumArgs() < 2)
Chris Lattner66beaba2008-11-21 18:44:24 +0000516 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
517 << 0 /*function call*/;
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000518 if (TheCall->getNumArgs() > 2)
519 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000520 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000521 << 0 /*function call*/
Chris Lattner8ba580c2008-11-19 05:08:23 +0000522 << SourceRange(TheCall->getArg(2)->getLocStart(),
523 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000524
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000525 Expr *OrigArg0 = TheCall->getArg(0);
526 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregor602173d2009-05-19 22:10:17 +0000527
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000528 // Do standard promotions between the two arguments, returning their common
529 // type.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000530 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar5ac4dff2009-02-19 19:28:43 +0000531
532 // Make sure any conversions are pushed back into the call; this is
533 // type safe since unordered compare builtins are declared as "_Bool
534 // foo(...)".
535 TheCall->setArg(0, OrigArg0);
536 TheCall->setArg(1, OrigArg1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000537
Douglas Gregor602173d2009-05-19 22:10:17 +0000538 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
539 return false;
540
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000541 // If the common type isn't a real floating type, then the arguments were
542 // invalid for this operation.
543 if (!Res->isRealFloatingType())
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000544 return Diag(OrigArg0->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000545 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000546 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000547 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000548
549 return false;
550}
551
Eli Friedman8c50c622008-05-20 08:23:37 +0000552bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
553 // The signature for these builtins is exact; the only thing we need
554 // to check is that the argument is a constant.
555 SourceLocation Loc;
Douglas Gregor602173d2009-05-19 22:10:17 +0000556 if (!TheCall->getArg(0)->isTypeDependent() &&
557 !TheCall->getArg(0)->isValueDependent() &&
558 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000559 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattner941c0102008-08-10 02:05:13 +0000560
Eli Friedman8c50c622008-05-20 08:23:37 +0000561 return false;
562}
563
Eli Friedmand0e9d092008-05-14 19:38:39 +0000564/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
565// This is declared to take (...), so we have to check everything.
Sebastian Redl8b769972009-01-19 00:08:26 +0000566Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000567 if (TheCall->getNumArgs() < 3)
Sebastian Redl8b769972009-01-19 00:08:26 +0000568 return ExprError(Diag(TheCall->getLocEnd(),
569 diag::err_typecheck_call_too_few_args)
570 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000571
Douglas Gregor602173d2009-05-19 22:10:17 +0000572 unsigned numElements = std::numeric_limits<unsigned>::max();
573 if (!TheCall->getArg(0)->isTypeDependent() &&
574 !TheCall->getArg(1)->isTypeDependent()) {
575 QualType FAType = TheCall->getArg(0)->getType();
576 QualType SAType = TheCall->getArg(1)->getType();
577
578 if (!FAType->isVectorType() || !SAType->isVectorType()) {
579 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
580 << SourceRange(TheCall->getArg(0)->getLocStart(),
581 TheCall->getArg(1)->getLocEnd());
582 return ExprError();
583 }
584
585 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
586 Context.getCanonicalType(SAType).getUnqualifiedType()) {
587 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
588 << SourceRange(TheCall->getArg(0)->getLocStart(),
589 TheCall->getArg(1)->getLocEnd());
590 return ExprError();
591 }
Eli Friedmand0e9d092008-05-14 19:38:39 +0000592
Douglas Gregor602173d2009-05-19 22:10:17 +0000593 numElements = FAType->getAsVectorType()->getNumElements();
594 if (TheCall->getNumArgs() != numElements+2) {
595 if (TheCall->getNumArgs() < numElements+2)
596 return ExprError(Diag(TheCall->getLocEnd(),
597 diag::err_typecheck_call_too_few_args)
598 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +0000599 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregor602173d2009-05-19 22:10:17 +0000600 diag::err_typecheck_call_too_many_args)
601 << 0 /*function call*/ << TheCall->getSourceRange());
602 }
Eli Friedmand0e9d092008-05-14 19:38:39 +0000603 }
604
605 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregor602173d2009-05-19 22:10:17 +0000606 if (TheCall->getArg(i)->isTypeDependent() ||
607 TheCall->getArg(i)->isValueDependent())
608 continue;
609
Eli Friedmand0e9d092008-05-14 19:38:39 +0000610 llvm::APSInt Result(32);
Chris Lattner941c0102008-08-10 02:05:13 +0000611 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl8b769972009-01-19 00:08:26 +0000612 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000613 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl8b769972009-01-19 00:08:26 +0000614 << TheCall->getArg(i)->getSourceRange());
615
Chris Lattner941c0102008-08-10 02:05:13 +0000616 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000617 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000618 diag::err_shufflevector_argument_too_large)
Sebastian Redl8b769972009-01-19 00:08:26 +0000619 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000620 }
621
622 llvm::SmallVector<Expr*, 32> exprs;
623
Chris Lattner941c0102008-08-10 02:05:13 +0000624 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000625 exprs.push_back(TheCall->getArg(i));
626 TheCall->setArg(i, 0);
627 }
628
Douglas Gregor602173d2009-05-19 22:10:17 +0000629 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), exprs.size(),
630 exprs[0]->getType(),
Ted Kremenek0c97e042009-02-07 01:47:29 +0000631 TheCall->getCallee()->getLocStart(),
632 TheCall->getRParenLoc()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000633}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000634
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000635/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
636// This is declared to take (const void*, ...) and can take two
637// optional constant int args.
638bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000639 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000640
Chris Lattner8ba580c2008-11-19 05:08:23 +0000641 if (NumArgs > 3)
642 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000643 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000644
645 // Argument 0 is checked for us and the remaining arguments must be
646 // constant integers.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000647 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000648 Expr *Arg = TheCall->getArg(i);
Douglas Gregor602173d2009-05-19 22:10:17 +0000649 if (Arg->isTypeDependent())
650 continue;
651
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000652 QualType RWType = Arg->getType();
653
654 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000655 llvm::APSInt Result;
Douglas Gregor602173d2009-05-19 22:10:17 +0000656 if (!BT || BT->getKind() != BuiltinType::Int)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000657 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
658 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Douglas Gregor602173d2009-05-19 22:10:17 +0000659
660 if (Arg->isValueDependent())
661 continue;
662
663 if (!Arg->isIntegerConstantExpr(Result, Context))
664 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
665 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000666
667 // FIXME: gcc issues a warning and rewrites these to 0. These
668 // seems especially odd for the third argument since the default
669 // is 3.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000670 if (i == 1) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000671 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000672 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
673 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000674 } else {
675 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000676 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
677 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000678 }
679 }
680
Chris Lattner8ba580c2008-11-19 05:08:23 +0000681 return false;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000682}
683
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000684/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
685/// int type). This simply type checks that type is one of the defined
686/// constants (0-3).
687bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
688 Expr *Arg = TheCall->getArg(1);
Douglas Gregor602173d2009-05-19 22:10:17 +0000689 if (Arg->isTypeDependent())
690 return false;
691
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000692 QualType ArgType = Arg->getType();
693 const BuiltinType *BT = ArgType->getAsBuiltinType();
694 llvm::APSInt Result(32);
Douglas Gregor602173d2009-05-19 22:10:17 +0000695 if (!BT || BT->getKind() != BuiltinType::Int)
696 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
697 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
698
699 if (Arg->isValueDependent())
700 return false;
701
702 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000703 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
704 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000705 }
706
707 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000708 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
709 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000710 }
711
712 return false;
713}
714
Eli Friedman5e0ae472009-05-03 06:04:26 +0000715/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedman6277e402009-05-03 04:46:36 +0000716/// This checks that val is a constant 1.
717bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
718 Expr *Arg = TheCall->getArg(1);
Douglas Gregor602173d2009-05-19 22:10:17 +0000719 if (Arg->isTypeDependent() || Arg->isValueDependent())
720 return false;
721
Eli Friedman6277e402009-05-03 04:46:36 +0000722 llvm::APSInt Result(32);
723 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
724 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
725 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
726
727 return false;
728}
729
Ted Kremenek8c797c02009-01-12 23:09:09 +0000730// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek51787c72009-03-20 21:35:28 +0000731bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
732 bool HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000733 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregor602173d2009-05-19 22:10:17 +0000734 if (E->isTypeDependent() || E->isValueDependent())
735 return false;
Ted Kremenek8c797c02009-01-12 23:09:09 +0000736
737 switch (E->getStmtClass()) {
738 case Stmt::ConditionalOperatorClass: {
Ted Kremenek51787c72009-03-20 21:35:28 +0000739 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000740 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000741 HasVAListArg, format_idx, firstDataArg)
Ted Kremenek8c797c02009-01-12 23:09:09 +0000742 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000743 HasVAListArg, format_idx, firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000744 }
745
746 case Stmt::ImplicitCastExprClass: {
Ted Kremenek51787c72009-03-20 21:35:28 +0000747 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000748 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000749 format_idx, firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000750 }
751
752 case Stmt::ParenExprClass: {
Ted Kremenek51787c72009-03-20 21:35:28 +0000753 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000754 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000755 format_idx, firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000756 }
Ted Kremenek51787c72009-03-20 21:35:28 +0000757
758 case Stmt::DeclRefExprClass: {
759 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
760
761 // As an exception, do not flag errors for variables binding to
762 // const string literals.
763 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
764 bool isConstant = false;
765 QualType T = DR->getType();
Ted Kremenek8c797c02009-01-12 23:09:09 +0000766
Ted Kremenek51787c72009-03-20 21:35:28 +0000767 if (const ArrayType *AT = Context.getAsArrayType(T)) {
768 isConstant = AT->getElementType().isConstant(Context);
Mike Stump90fc78e2009-08-04 21:02:39 +0000769 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Ted Kremenek51787c72009-03-20 21:35:28 +0000770 isConstant = T.isConstant(Context) &&
771 PT->getPointeeType().isConstant(Context);
772 }
773
774 if (isConstant) {
775 const VarDecl *Def = 0;
776 if (const Expr *Init = VD->getDefinition(Def))
777 return SemaCheckStringLiteral(Init, TheCall,
778 HasVAListArg, format_idx, firstDataArg);
779 }
Anders Carlsson50d279d2009-06-28 19:55:58 +0000780
781 // For vprintf* functions (i.e., HasVAListArg==true), we add a
782 // special check to see if the format string is a function parameter
783 // of the function calling the printf function. If the function
784 // has an attribute indicating it is a printf-like function, then we
785 // should suppress warnings concerning non-literals being used in a call
786 // to a vprintf function. For example:
787 //
788 // void
789 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
790 // va_list ap;
791 // va_start(ap, fmt);
792 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
793 // ...
794 //
795 //
796 // FIXME: We don't have full attribute support yet, so just check to see
797 // if the argument is a DeclRefExpr that references a parameter. We'll
798 // add proper support for checking the attribute later.
799 if (HasVAListArg)
800 if (isa<ParmVarDecl>(VD))
801 return true;
Ted Kremenek51787c72009-03-20 21:35:28 +0000802 }
803
804 return false;
805 }
Ted Kremenek8c797c02009-01-12 23:09:09 +0000806
Anders Carlsson71d5f682009-06-27 04:05:33 +0000807 case Stmt::CallExprClass: {
808 const CallExpr *CE = cast<CallExpr>(E);
809 if (const ImplicitCastExpr *ICE
810 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
811 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
812 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +0000813 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson71d5f682009-06-27 04:05:33 +0000814 unsigned ArgIndex = FA->getFormatIdx();
815 const Expr *Arg = CE->getArg(ArgIndex - 1);
816
817 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
818 format_idx, firstDataArg);
819 }
820 }
821 }
822 }
823
824 return false;
825 }
Ted Kremenek51787c72009-03-20 21:35:28 +0000826 case Stmt::ObjCStringLiteralClass:
827 case Stmt::StringLiteralClass: {
828 const StringLiteral *StrE = NULL;
829
830 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek8c797c02009-01-12 23:09:09 +0000831 StrE = ObjCFExpr->getString();
832 else
Ted Kremenek51787c72009-03-20 21:35:28 +0000833 StrE = cast<StringLiteral>(E);
834
Ted Kremenek8c797c02009-01-12 23:09:09 +0000835 if (StrE) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000836 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
837 firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000838 return true;
839 }
840
841 return false;
842 }
Ted Kremenek51787c72009-03-20 21:35:28 +0000843
844 default:
845 return false;
Ted Kremenek8c797c02009-01-12 23:09:09 +0000846 }
847}
848
Fariborz Jahanian5440d2f2009-05-21 18:48:51 +0000849void
850Sema::CheckNonNullArguments(const NonNullAttr *NonNull, const CallExpr *TheCall)
851{
852 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
853 i != e; ++i) {
Chris Lattnerbf89b302009-05-25 18:23:36 +0000854 const Expr *ArgExpr = TheCall->getArg(*i);
Fariborz Jahanian5440d2f2009-05-21 18:48:51 +0000855 if (ArgExpr->isNullPointerConstant(Context))
Chris Lattnerbf89b302009-05-25 18:23:36 +0000856 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
857 << ArgExpr->getSourceRange();
Fariborz Jahanian5440d2f2009-05-21 18:48:51 +0000858 }
859}
Ted Kremenek8c797c02009-01-12 23:09:09 +0000860
Chris Lattner2e64c072007-08-10 20:18:51 +0000861/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek081ed872007-08-14 17:39:48 +0000862/// correct use of format strings.
863///
864/// HasVAListArg - A predicate indicating whether the printf-like
865/// function is passed an explicit va_arg argument (e.g., vprintf)
866///
867/// format_idx - The index into Args for the format string.
868///
869/// Improper format strings to functions in the printf family can be
870/// the source of bizarre bugs and very serious security holes. A
871/// good source of information is available in the following paper
872/// (which includes additional references):
Chris Lattner2e64c072007-08-10 20:18:51 +0000873///
874/// FormatGuard: Automatic Protection From printf Format String
875/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek081ed872007-08-14 17:39:48 +0000876///
877/// Functionality implemented:
878///
879/// We can statically check the following properties for string
880/// literal format strings for non v.*printf functions (where the
881/// arguments are passed directly):
882//
883/// (1) Are the number of format conversions equal to the number of
884/// data arguments?
885///
886/// (2) Does each format conversion correctly match the type of the
887/// corresponding data argument? (TODO)
888///
889/// Moreover, for all printf functions we can:
890///
891/// (3) Check for a missing format string (when not caught by type checking).
892///
893/// (4) Check for no-operation flags; e.g. using "#" with format
894/// conversion 'c' (TODO)
895///
896/// (5) Check the use of '%n', a major source of security holes.
897///
898/// (6) Check for malformed format conversions that don't specify anything.
899///
900/// (7) Check for empty format strings. e.g: printf("");
901///
902/// (8) Check that the format string is a wide literal.
903///
Ted Kremenekc2804c22008-03-03 16:50:00 +0000904/// (9) Also check the arguments of functions with the __format__ attribute.
905/// (TODO).
906///
Ted Kremenek081ed872007-08-14 17:39:48 +0000907/// All of these checks can be done by parsing the format string.
908///
909/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner2e64c072007-08-10 20:18:51 +0000910void
Ted Kremenek51787c72009-03-20 21:35:28 +0000911Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000912 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek51787c72009-03-20 21:35:28 +0000913 const Expr *Fn = TheCall->getCallee();
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000914
Ted Kremenek081ed872007-08-14 17:39:48 +0000915 // CHECK: printf-like function is called with no format string.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000916 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000917 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
918 << Fn->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000919 return;
920 }
921
Ted Kremenek51787c72009-03-20 21:35:28 +0000922 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattnere65acc12007-08-25 05:36:18 +0000923
Chris Lattner2e64c072007-08-10 20:18:51 +0000924 // CHECK: format string is not a string literal.
925 //
Ted Kremenek081ed872007-08-14 17:39:48 +0000926 // Dynamically generated format strings are difficult to
927 // automatically vet at compile time. Requiring that format strings
928 // are string literals: (1) permits the checking of format strings by
929 // the compiler and thereby (2) can practically remove the source of
930 // many format string exploits.
Ted Kremenek225a14c2008-06-16 18:00:42 +0000931
932 // Format string can be either ObjC string (e.g. @"%d") or
933 // C string (e.g. "%d")
934 // ObjC string uses the same format specifiers as C string, so we can use
935 // the same format string checking logic for both ObjC and C strings.
Chris Lattner153b4eb2009-04-29 04:49:34 +0000936 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
937 firstDataArg))
938 return; // Literal format string found, check done!
Ted Kremenek225a14c2008-06-16 18:00:42 +0000939
Chris Lattner8ba7cc72009-04-29 04:59:47 +0000940 // If there are no arguments specified, warn with -Wformat-security, otherwise
941 // warn only with -Wformat-nonliteral.
942 if (TheCall->getNumArgs() == format_idx+1)
943 Diag(TheCall->getArg(format_idx)->getLocStart(),
944 diag::warn_printf_nonliteral_noargs)
945 << OrigFormatExpr->getSourceRange();
946 else
947 Diag(TheCall->getArg(format_idx)->getLocStart(),
948 diag::warn_printf_nonliteral)
949 << OrigFormatExpr->getSourceRange();
Ted Kremenek8c797c02009-01-12 23:09:09 +0000950}
Ted Kremenek081ed872007-08-14 17:39:48 +0000951
Ted Kremenek51787c72009-03-20 21:35:28 +0000952void Sema::CheckPrintfString(const StringLiteral *FExpr,
953 const Expr *OrigFormatExpr,
954 const CallExpr *TheCall, bool HasVAListArg,
955 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek8c797c02009-01-12 23:09:09 +0000956
Ted Kremenek51787c72009-03-20 21:35:28 +0000957 const ObjCStringLiteral *ObjCFExpr =
958 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
959
Ted Kremenek081ed872007-08-14 17:39:48 +0000960 // CHECK: is the format string a wide literal?
961 if (FExpr->isWide()) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000962 Diag(FExpr->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000963 diag::warn_printf_format_string_is_wide_literal)
964 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000965 return;
966 }
967
968 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner44c5c012009-04-29 04:12:34 +0000969 const char *Str = FExpr->getStrData();
Ted Kremenek081ed872007-08-14 17:39:48 +0000970
971 // CHECK: empty format string?
Chris Lattner44c5c012009-04-29 04:12:34 +0000972 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek081ed872007-08-14 17:39:48 +0000973
974 if (StrLen == 0) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000975 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
976 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000977 return;
978 }
979
980 // We process the format string using a binary state machine. The
981 // current state is stored in CurrentState.
982 enum {
983 state_OrdChr,
984 state_Conversion
985 } CurrentState = state_OrdChr;
986
987 // numConversions - The number of conversions seen so far. This is
988 // incremented as we traverse the format string.
989 unsigned numConversions = 0;
990
991 // numDataArgs - The number of data arguments after the format
992 // string. This can only be determined for non vprintf-like
993 // functions. For those functions, this value is 1 (the sole
994 // va_arg argument).
Douglas Gregorb5af7382009-02-14 18:57:46 +0000995 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek081ed872007-08-14 17:39:48 +0000996
997 // Inspect the format string.
998 unsigned StrIdx = 0;
999
1000 // LastConversionIdx - Index within the format string where we last saw
1001 // a '%' character that starts a new format conversion.
1002 unsigned LastConversionIdx = 0;
1003
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001004 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner3d5a8f32007-12-28 05:38:24 +00001005
Ted Kremenek081ed872007-08-14 17:39:48 +00001006 // Is the number of detected conversion conversions greater than
1007 // the number of matching data arguments? If so, stop.
1008 if (!HasVAListArg && numConversions > numDataArgs) break;
1009
1010 // Handle "\0"
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001011 if (Str[StrIdx] == '\0') {
Ted Kremenek081ed872007-08-14 17:39:48 +00001012 // The string returned by getStrData() is not null-terminated,
1013 // so the presence of a null character is likely an error.
Chris Lattnerf17cb362009-02-18 17:49:48 +00001014 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001015 diag::warn_printf_format_string_contains_null_char)
1016 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +00001017 return;
1018 }
1019
1020 // Ordinary characters (not processing a format conversion).
1021 if (CurrentState == state_OrdChr) {
1022 if (Str[StrIdx] == '%') {
1023 CurrentState = state_Conversion;
1024 LastConversionIdx = StrIdx;
1025 }
1026 continue;
1027 }
1028
1029 // Seen '%'. Now processing a format conversion.
1030 switch (Str[StrIdx]) {
Chris Lattner68d88f02007-12-28 05:31:15 +00001031 // Handle dynamic precision or width specifier.
1032 case '*': {
1033 ++numConversions;
1034
Ted Kremenek4ff8a152009-05-13 16:06:05 +00001035 if (!HasVAListArg) {
1036 if (numConversions > numDataArgs) {
1037 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek035d8792007-10-12 20:51:52 +00001038
Ted Kremenek4ff8a152009-05-13 16:06:05 +00001039 if (Str[StrIdx-1] == '.')
1040 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
1041 << OrigFormatExpr->getSourceRange();
1042 else
1043 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
1044 << OrigFormatExpr->getSourceRange();
1045
1046 // Don't do any more checking. We'll just emit spurious errors.
1047 return;
1048 }
1049
1050 // Perform type checking on width/precision specifier.
1051 const Expr *E = TheCall->getArg(format_idx+numConversions);
1052 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
1053 if (BT->getKind() == BuiltinType::Int)
1054 break;
Ted Kremenek035d8792007-10-12 20:51:52 +00001055
Ted Kremenek4ff8a152009-05-13 16:06:05 +00001056 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
1057
1058 if (Str[StrIdx-1] == '.')
1059 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1060 << E->getType() << E->getSourceRange();
1061 else
1062 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1063 << E->getType() << E->getSourceRange();
1064
1065 break;
Ted Kremenek035d8792007-10-12 20:51:52 +00001066 }
Chris Lattner68d88f02007-12-28 05:31:15 +00001067 }
1068
1069 // Characters which can terminate a format conversion
1070 // (e.g. "%d"). Characters that specify length modifiers or
1071 // other flags are handled by the default case below.
1072 //
1073 // FIXME: additional checks will go into the following cases.
1074 case 'i':
1075 case 'd':
1076 case 'o':
1077 case 'u':
1078 case 'x':
1079 case 'X':
1080 case 'D':
1081 case 'O':
1082 case 'U':
1083 case 'e':
1084 case 'E':
1085 case 'f':
1086 case 'F':
1087 case 'g':
1088 case 'G':
1089 case 'a':
1090 case 'A':
1091 case 'c':
1092 case 'C':
1093 case 'S':
1094 case 's':
1095 case 'p':
1096 ++numConversions;
1097 CurrentState = state_OrdChr;
1098 break;
1099
Eli Friedmanb53dbd02009-06-02 08:36:19 +00001100 case 'm':
1101 // FIXME: Warn in situations where this isn't supported!
1102 CurrentState = state_OrdChr;
1103 break;
1104
Chris Lattner68d88f02007-12-28 05:31:15 +00001105 // CHECK: Are we using "%n"? Issue a warning.
1106 case 'n': {
1107 ++numConversions;
1108 CurrentState = state_OrdChr;
Chris Lattnerf17cb362009-02-18 17:49:48 +00001109 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1110 LastConversionIdx);
Chris Lattner68d88f02007-12-28 05:31:15 +00001111
Chris Lattner9d2cf082008-11-19 05:27:50 +00001112 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +00001113 break;
1114 }
Ted Kremenek225a14c2008-06-16 18:00:42 +00001115
1116 // Handle "%@"
1117 case '@':
1118 // %@ is allowed in ObjC format strings only.
1119 if(ObjCFExpr != NULL)
1120 CurrentState = state_OrdChr;
1121 else {
1122 // Issue a warning: invalid format conversion.
Chris Lattnerf17cb362009-02-18 17:49:48 +00001123 SourceLocation Loc =
1124 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek225a14c2008-06-16 18:00:42 +00001125
Chris Lattner77d52da2008-11-20 06:06:08 +00001126 Diag(Loc, diag::warn_printf_invalid_conversion)
1127 << std::string(Str+LastConversionIdx,
1128 Str+std::min(LastConversionIdx+2, StrLen))
1129 << OrigFormatExpr->getSourceRange();
Ted Kremenek225a14c2008-06-16 18:00:42 +00001130 }
1131 ++numConversions;
1132 break;
1133
Chris Lattner68d88f02007-12-28 05:31:15 +00001134 // Handle "%%"
1135 case '%':
1136 // Sanity check: Was the first "%" character the previous one?
1137 // If not, we will assume that we have a malformed format
1138 // conversion, and that the current "%" character is the start
1139 // of a new conversion.
1140 if (StrIdx - LastConversionIdx == 1)
1141 CurrentState = state_OrdChr;
1142 else {
1143 // Issue a warning: invalid format conversion.
Chris Lattnerf17cb362009-02-18 17:49:48 +00001144 SourceLocation Loc =
1145 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattner68d88f02007-12-28 05:31:15 +00001146
Chris Lattner77d52da2008-11-20 06:06:08 +00001147 Diag(Loc, diag::warn_printf_invalid_conversion)
1148 << std::string(Str+LastConversionIdx, Str+StrIdx)
1149 << OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +00001150
1151 // This conversion is broken. Advance to the next format
1152 // conversion.
1153 LastConversionIdx = StrIdx;
1154 ++numConversions;
Ted Kremenek081ed872007-08-14 17:39:48 +00001155 }
Chris Lattner68d88f02007-12-28 05:31:15 +00001156 break;
Ted Kremenek081ed872007-08-14 17:39:48 +00001157
Chris Lattner68d88f02007-12-28 05:31:15 +00001158 default:
1159 // This case catches all other characters: flags, widths, etc.
1160 // We should eventually process those as well.
1161 break;
Ted Kremenek081ed872007-08-14 17:39:48 +00001162 }
1163 }
1164
1165 if (CurrentState == state_Conversion) {
1166 // Issue a warning: invalid format conversion.
Chris Lattnerf17cb362009-02-18 17:49:48 +00001167 SourceLocation Loc =
1168 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +00001169
Chris Lattner77d52da2008-11-20 06:06:08 +00001170 Diag(Loc, diag::warn_printf_invalid_conversion)
1171 << std::string(Str+LastConversionIdx,
1172 Str+std::min(LastConversionIdx+2, StrLen))
1173 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +00001174 return;
1175 }
1176
1177 if (!HasVAListArg) {
1178 // CHECK: Does the number of format conversions exceed the number
1179 // of data arguments?
1180 if (numConversions > numDataArgs) {
Chris Lattnerf17cb362009-02-18 17:49:48 +00001181 SourceLocation Loc =
1182 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +00001183
Chris Lattner9d2cf082008-11-19 05:27:50 +00001184 Diag(Loc, diag::warn_printf_insufficient_data_args)
1185 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +00001186 }
1187 // CHECK: Does the number of data arguments exceed the number of
1188 // format conversions in the format string?
1189 else if (numConversions < numDataArgs)
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001190 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001191 diag::warn_printf_too_many_data_args)
1192 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +00001193 }
1194}
Ted Kremenek45925ab2007-08-17 16:46:58 +00001195
1196//===--- CHECK: Return Address of Stack Variable --------------------------===//
1197
1198static DeclRefExpr* EvalVal(Expr *E);
1199static DeclRefExpr* EvalAddr(Expr* E);
1200
1201/// CheckReturnStackAddr - Check if a return statement returns the address
1202/// of a stack variable.
1203void
1204Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1205 SourceLocation ReturnLoc) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +00001206
Ted Kremenek45925ab2007-08-17 16:46:58 +00001207 // Perform checking for returned stack addresses.
Steve Naroffd6163f32008-09-05 22:11:13 +00001208 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek45925ab2007-08-17 16:46:58 +00001209 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner65cae292008-11-19 08:23:25 +00001210 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattnerb1753422008-11-23 21:45:46 +00001211 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroff503996b2008-09-16 22:25:10 +00001212
1213 // Skip over implicit cast expressions when checking for block expressions.
1214 if (ImplicitCastExpr *IcExpr =
1215 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
1216 RetValExp = IcExpr->getSubExpr();
1217
Steve Naroff3eac7692008-09-10 19:17:48 +00001218 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Mike Stumpb1a2aab2009-04-17 00:09:41 +00001219 if (C->hasBlockDeclRefExprs())
1220 Diag(C->getLocStart(), diag::err_ret_local_block)
1221 << C->getSourceRange();
Mike Stump90fc78e2009-08-04 21:02:39 +00001222 } else if (lhsType->isReferenceType()) {
1223 // Perform checking for stack values returned by reference.
Douglas Gregor21a04f32008-10-27 19:41:14 +00001224 // Check for a reference to the stack
1225 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001226 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattnerb1753422008-11-23 21:45:46 +00001227 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +00001228 }
1229}
1230
1231/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1232/// check if the expression in a return statement evaluates to an address
1233/// to a location on the stack. The recursion is used to traverse the
1234/// AST of the return expression, with recursion backtracking when we
1235/// encounter a subexpression that (1) clearly does not lead to the address
1236/// of a stack variable or (2) is something we cannot determine leads to
1237/// the address of a stack variable based on such local checking.
1238///
Ted Kremenekda1300a2007-08-28 17:02:55 +00001239/// EvalAddr processes expressions that are pointers that are used as
1240/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek45925ab2007-08-17 16:46:58 +00001241/// At the base case of the recursion is a check for a DeclRefExpr* in
1242/// the refers to a stack variable.
1243///
1244/// This implementation handles:
1245///
1246/// * pointer-to-pointer casts
1247/// * implicit conversions from array references to pointers
1248/// * taking the address of fields
1249/// * arbitrary interplay between "&" and "*" operators
1250/// * pointer arithmetic from an address of a stack variable
1251/// * taking the address of an array element where the array is on the stack
1252static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek45925ab2007-08-17 16:46:58 +00001253 // We should only be called for evaluating pointer expressions.
Steve Naroffd6163f32008-09-05 22:11:13 +00001254 assert((E->getType()->isPointerType() ||
1255 E->getType()->isBlockPointerType() ||
Ted Kremenek42730c52008-01-07 19:49:32 +00001256 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner68d88f02007-12-28 05:31:15 +00001257 "EvalAddr only works on pointers");
Ted Kremenek45925ab2007-08-17 16:46:58 +00001258
1259 // Our "symbolic interpreter" is just a dispatch off the currently
1260 // viewed AST node. We then recursively traverse the AST by calling
1261 // EvalAddr and EvalVal appropriately.
1262 switch (E->getStmtClass()) {
Chris Lattner68d88f02007-12-28 05:31:15 +00001263 case Stmt::ParenExprClass:
1264 // Ignore parentheses.
1265 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek45925ab2007-08-17 16:46:58 +00001266
Chris Lattner68d88f02007-12-28 05:31:15 +00001267 case Stmt::UnaryOperatorClass: {
1268 // The only unary operator that make sense to handle here
1269 // is AddrOf. All others don't make sense as pointers.
1270 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek45925ab2007-08-17 16:46:58 +00001271
Chris Lattner68d88f02007-12-28 05:31:15 +00001272 if (U->getOpcode() == UnaryOperator::AddrOf)
1273 return EvalVal(U->getSubExpr());
1274 else
Ted Kremenek45925ab2007-08-17 16:46:58 +00001275 return NULL;
1276 }
Chris Lattner68d88f02007-12-28 05:31:15 +00001277
1278 case Stmt::BinaryOperatorClass: {
1279 // Handle pointer arithmetic. All other binary operators are not valid
1280 // in this context.
1281 BinaryOperator *B = cast<BinaryOperator>(E);
1282 BinaryOperator::Opcode op = B->getOpcode();
1283
1284 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1285 return NULL;
1286
1287 Expr *Base = B->getLHS();
1288
1289 // Determine which argument is the real pointer base. It could be
1290 // the RHS argument instead of the LHS.
1291 if (!Base->getType()->isPointerType()) Base = B->getRHS();
1292
1293 assert (Base->getType()->isPointerType());
1294 return EvalAddr(Base);
1295 }
Steve Naroff3eac7692008-09-10 19:17:48 +00001296
Chris Lattner68d88f02007-12-28 05:31:15 +00001297 // For conditional operators we need to see if either the LHS or RHS are
1298 // valid DeclRefExpr*s. If one of them is valid, we return it.
1299 case Stmt::ConditionalOperatorClass: {
1300 ConditionalOperator *C = cast<ConditionalOperator>(E);
1301
1302 // Handle the GNU extension for missing LHS.
1303 if (Expr *lhsExpr = C->getLHS())
1304 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1305 return LHS;
1306
1307 return EvalAddr(C->getRHS());
1308 }
1309
Ted Kremenekea19edd2008-08-07 00:49:01 +00001310 // For casts, we need to handle conversions from arrays to
1311 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor21a04f32008-10-27 19:41:14 +00001312 case Stmt::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001313 case Stmt::CStyleCastExprClass:
Douglas Gregor21a04f32008-10-27 19:41:14 +00001314 case Stmt::CXXFunctionalCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001315 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekea19edd2008-08-07 00:49:01 +00001316 QualType T = SubExpr->getType();
1317
Steve Naroffd6163f32008-09-05 22:11:13 +00001318 if (SubExpr->getType()->isPointerType() ||
1319 SubExpr->getType()->isBlockPointerType() ||
1320 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenekea19edd2008-08-07 00:49:01 +00001321 return EvalAddr(SubExpr);
1322 else if (T->isArrayType())
Chris Lattner68d88f02007-12-28 05:31:15 +00001323 return EvalVal(SubExpr);
Chris Lattner68d88f02007-12-28 05:31:15 +00001324 else
Ted Kremenekea19edd2008-08-07 00:49:01 +00001325 return 0;
Chris Lattner68d88f02007-12-28 05:31:15 +00001326 }
1327
1328 // C++ casts. For dynamic casts, static casts, and const casts, we
1329 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor21a04f32008-10-27 19:41:14 +00001330 // through the cast. In the case the dynamic cast doesn't fail (and
1331 // return NULL), we take the conservative route and report cases
Chris Lattner68d88f02007-12-28 05:31:15 +00001332 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor21a04f32008-10-27 19:41:14 +00001333 // FIXME: The comment about is wrong; we're not always converting
1334 // from pointer to pointer. I'm guessing that this code should also
1335 // handle references to objects.
1336 case Stmt::CXXStaticCastExprClass:
1337 case Stmt::CXXDynamicCastExprClass:
1338 case Stmt::CXXConstCastExprClass:
1339 case Stmt::CXXReinterpretCastExprClass: {
1340 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffd6163f32008-09-05 22:11:13 +00001341 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattner68d88f02007-12-28 05:31:15 +00001342 return EvalAddr(S);
1343 else
1344 return NULL;
Chris Lattner68d88f02007-12-28 05:31:15 +00001345 }
1346
1347 // Everything else: we simply don't reason about them.
1348 default:
1349 return NULL;
1350 }
Ted Kremenek45925ab2007-08-17 16:46:58 +00001351}
1352
1353
1354/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1355/// See the comments for EvalAddr for more details.
1356static DeclRefExpr* EvalVal(Expr *E) {
1357
Ted Kremenekda1300a2007-08-28 17:02:55 +00001358 // We should only be called for evaluating non-pointer expressions, or
1359 // expressions with a pointer type that are not used as references but instead
1360 // are l-values (e.g., DeclRefExpr with a pointer type).
1361
Ted Kremenek45925ab2007-08-17 16:46:58 +00001362 // Our "symbolic interpreter" is just a dispatch off the currently
1363 // viewed AST node. We then recursively traverse the AST by calling
1364 // EvalAddr and EvalVal appropriately.
1365 switch (E->getStmtClass()) {
Douglas Gregor566782a2009-01-06 05:10:23 +00001366 case Stmt::DeclRefExprClass:
1367 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek45925ab2007-08-17 16:46:58 +00001368 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1369 // at code that refers to a variable's name. We check if it has local
1370 // storage within the function, and if so, return the expression.
1371 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1372
1373 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor81c29152008-10-29 00:13:59 +00001374 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek45925ab2007-08-17 16:46:58 +00001375
1376 return NULL;
1377 }
1378
1379 case Stmt::ParenExprClass:
1380 // Ignore parentheses.
1381 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1382
1383 case Stmt::UnaryOperatorClass: {
1384 // The only unary operator that make sense to handle here
1385 // is Deref. All others don't resolve to a "name." This includes
1386 // handling all sorts of rvalues passed to a unary operator.
1387 UnaryOperator *U = cast<UnaryOperator>(E);
1388
1389 if (U->getOpcode() == UnaryOperator::Deref)
1390 return EvalAddr(U->getSubExpr());
1391
1392 return NULL;
1393 }
1394
1395 case Stmt::ArraySubscriptExprClass: {
1396 // Array subscripts are potential references to data on the stack. We
1397 // retrieve the DeclRefExpr* for the array variable if it indeed
1398 // has local storage.
Ted Kremenek1c1700f2007-08-20 16:18:38 +00001399 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek45925ab2007-08-17 16:46:58 +00001400 }
1401
1402 case Stmt::ConditionalOperatorClass: {
1403 // For conditional operators we need to see if either the LHS or RHS are
1404 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1405 ConditionalOperator *C = cast<ConditionalOperator>(E);
1406
Anders Carlsson37365fc2007-11-30 19:04:31 +00001407 // Handle the GNU extension for missing LHS.
1408 if (Expr *lhsExpr = C->getLHS())
1409 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1410 return LHS;
1411
1412 return EvalVal(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +00001413 }
1414
1415 // Accesses to members are potential references to data on the stack.
1416 case Stmt::MemberExprClass: {
1417 MemberExpr *M = cast<MemberExpr>(E);
1418
1419 // Check for indirect access. We only want direct field accesses.
1420 if (!M->isArrow())
1421 return EvalVal(M->getBase());
1422 else
1423 return NULL;
1424 }
1425
1426 // Everything else: we simply don't reason about them.
1427 default:
1428 return NULL;
1429 }
1430}
Ted Kremenek30c66752007-11-25 00:58:00 +00001431
1432//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1433
1434/// Check for comparisons of floating point operands using != and ==.
1435/// Issue a warning if these are no self-comparisons, as they are not likely
1436/// to do what the programmer intended.
1437void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1438 bool EmitWarning = true;
1439
Ted Kremenek87e30c52008-01-17 16:57:34 +00001440 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek24c61682008-01-17 17:55:13 +00001441 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek30c66752007-11-25 00:58:00 +00001442
1443 // Special case: check for x == x (which is OK).
1444 // Do not emit warnings for such cases.
1445 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1446 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1447 if (DRL->getDecl() == DRR->getDecl())
1448 EmitWarning = false;
1449
Ted Kremenek33159832007-11-29 00:59:04 +00001450
1451 // Special case: check for comparisons against literals that can be exactly
1452 // represented by APFloat. In such cases, do not emit a warning. This
1453 // is a heuristic: often comparison against such literals are used to
1454 // detect if a value in a variable has not changed. This clearly can
1455 // lead to false negatives.
1456 if (EmitWarning) {
1457 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1458 if (FLL->isExact())
1459 EmitWarning = false;
Mike Stump90fc78e2009-08-04 21:02:39 +00001460 } else
Ted Kremenek33159832007-11-29 00:59:04 +00001461 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1462 if (FLR->isExact())
1463 EmitWarning = false;
1464 }
1465 }
1466
Ted Kremenek30c66752007-11-25 00:58:00 +00001467 // Check for comparisons with builtin types.
Sebastian Redl8b769972009-01-19 00:08:26 +00001468 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001469 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregorb5af7382009-02-14 18:57:46 +00001470 if (CL->isBuiltinCall(Context))
Ted Kremenek30c66752007-11-25 00:58:00 +00001471 EmitWarning = false;
1472
Sebastian Redl8b769972009-01-19 00:08:26 +00001473 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001474 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregorb5af7382009-02-14 18:57:46 +00001475 if (CR->isBuiltinCall(Context))
Ted Kremenek30c66752007-11-25 00:58:00 +00001476 EmitWarning = false;
1477
1478 // Emit the diagnostic.
1479 if (EmitWarning)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001480 Diag(loc, diag::warn_floatingpoint_eq)
1481 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek30c66752007-11-25 00:58:00 +00001482}