blob: 5a68346e0dd82f6ab157c2f41cf619103aa5d655 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements extra semantic analysis beyond what is enforced
11// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000020#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/Lex/Preprocessor.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022using namespace clang;
23
Chris Lattner60800082009-02-18 17:49:48 +000024/// getLocationOfStringLiteralByte - Return a source location that points to the
25/// specified byte of the specified string literal.
26///
27/// Strings are amazingly complex. They can be formed from multiple tokens and
28/// can have escape sequences in them in addition to the usual trigraph and
29/// escaped newline business. This routine handles this complexity.
30///
31SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
32 unsigned ByteNo) const {
33 assert(!SL->isWide() && "This doesn't work for wide strings yet");
34
35 // Loop over all of the tokens in this string until we find the one that
36 // contains the byte we're looking for.
37 unsigned TokNo = 0;
38 while (1) {
39 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
40 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
41
42 // Get the spelling of the string so that we can get the data that makes up
43 // the string literal, not the identifier for the macro it is potentially
44 // expanded through.
45 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
46
47 // Re-lex the token to get its length and original spelling.
48 std::pair<FileID, unsigned> LocInfo =
49 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
50 std::pair<const char *,const char *> Buffer =
51 SourceMgr.getBufferData(LocInfo.first);
52 const char *StrData = Buffer.first+LocInfo.second;
53
54 // Create a langops struct and enable trigraphs. This is sufficient for
55 // relexing tokens.
56 LangOptions LangOpts;
57 LangOpts.Trigraphs = true;
58
59 // Create a lexer starting at the beginning of this token.
60 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
61 Buffer.second);
62 Token TheTok;
63 TheLexer.LexFromRawLexer(TheTok);
64
Chris Lattner443e53c2009-02-18 19:26:42 +000065 // Use the StringLiteralParser to compute the length of the string in bytes.
66 StringLiteralParser SLP(&TheTok, 1, PP);
67 unsigned TokNumBytes = SLP.GetStringLength();
Chris Lattnerd0d082f2009-02-18 18:34:12 +000068
Chris Lattner2197c962009-02-18 18:52:52 +000069 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000070 if (ByteNo < TokNumBytes ||
71 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Chris Lattner719e6152009-02-18 19:21:10 +000072 unsigned Offset =
73 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
74
75 // Now that we know the offset of the token in the spelling, use the
76 // preprocessor to get the offset in the original source.
77 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000078 }
79
80 // Move to the next string token.
81 ++TokNo;
82 ByteNo -= TokNumBytes;
83 }
84}
85
86
Chris Lattner59907c42007-08-10 20:18:51 +000087/// CheckFunctionCall - Check a direct function call for various correctness
88/// and safety properties not strictly enforced by the C type system.
Sebastian Redl0eb23302009-01-19 00:08:26 +000089Action::OwningExprResult
90Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
91 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +000092 // Get the IdentifierInfo* for the called function.
93 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +000094
95 // None of the checks below are needed for functions that don't have
96 // simple names (e.g., C++ conversion functions).
97 if (!FnInfo)
Sebastian Redl0eb23302009-01-19 00:08:26 +000098 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +000099
Douglas Gregor3c385e52009-02-14 18:57:46 +0000100 switch (FDecl->getBuiltinID(Context)) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000101 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000102 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000103 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000104 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000105 return ExprError();
106 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000107 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000108 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000109 if (SemaBuiltinVAStart(TheCall))
110 return ExprError();
111 return move(TheCallResult);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000112 case Builtin::BI__builtin_isgreater:
113 case Builtin::BI__builtin_isgreaterequal:
114 case Builtin::BI__builtin_isless:
115 case Builtin::BI__builtin_islessequal:
116 case Builtin::BI__builtin_islessgreater:
117 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000118 if (SemaBuiltinUnorderedCompare(TheCall))
119 return ExprError();
120 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +0000121 case Builtin::BI__builtin_return_address:
122 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000123 if (SemaBuiltinStackAddress(TheCall))
124 return ExprError();
125 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +0000126 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000127 return SemaBuiltinShuffleVector(TheCall);
128 // TheCall will be freed by the smart pointer here, but that's fine, since
129 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000130 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000131 if (SemaBuiltinPrefetch(TheCall))
132 return ExprError();
133 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000134 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000135 if (SemaBuiltinObjectSize(TheCall))
136 return ExprError();
Eli Friedman586d6a82009-05-03 06:04:26 +0000137 return move(TheCallResult);
Eli Friedmand875fed2009-05-03 04:46:36 +0000138 case Builtin::BI__builtin_longjmp:
139 if (SemaBuiltinLongjmp(TheCall))
140 return ExprError();
Eli Friedman586d6a82009-05-03 06:04:26 +0000141 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000142 case Builtin::BI__sync_fetch_and_add:
143 case Builtin::BI__sync_fetch_and_sub:
144 case Builtin::BI__sync_fetch_and_or:
145 case Builtin::BI__sync_fetch_and_and:
146 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000147 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000148 case Builtin::BI__sync_add_and_fetch:
149 case Builtin::BI__sync_sub_and_fetch:
150 case Builtin::BI__sync_and_and_fetch:
151 case Builtin::BI__sync_or_and_fetch:
152 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000153 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000154 case Builtin::BI__sync_val_compare_and_swap:
155 case Builtin::BI__sync_bool_compare_and_swap:
156 case Builtin::BI__sync_lock_test_and_set:
157 case Builtin::BI__sync_lock_release:
158 if (SemaBuiltinAtomicOverloaded(TheCall))
159 return ExprError();
160 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000161 }
Daniel Dunbarde454282008-10-02 18:44:07 +0000162
163 // FIXME: This mechanism should be abstracted to be less fragile and
164 // more efficient. For example, just map function ids to custom
165 // handlers.
166
Chris Lattner59907c42007-08-10 20:18:51 +0000167 // Printf checking.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000168 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
169 if (Format->getType() == "printf") {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000170 bool HasVAListArg = Format->getFirstArg() == 0;
171 if (!HasVAListArg) {
172 if (const FunctionProtoType *Proto
173 = FDecl->getType()->getAsFunctionProtoType())
Douglas Gregor3c385e52009-02-14 18:57:46 +0000174 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000175 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000176 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000177 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000178 }
Chris Lattner59907c42007-08-10 20:18:51 +0000179 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000180
181 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000182}
183
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000184Action::OwningExprResult
185Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
186
187 OwningExprResult TheCallResult(Owned(TheCall));
188 // Printf checking.
189 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
190 if (!Format)
191 return move(TheCallResult);
192 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
193 if (!V)
194 return move(TheCallResult);
195 QualType Ty = V->getType();
196 if (!Ty->isBlockPointerType())
197 return move(TheCallResult);
198 if (Format->getType() == "printf") {
199 bool HasVAListArg = Format->getFirstArg() == 0;
200 if (!HasVAListArg) {
201 const FunctionType *FT =
202 Ty->getAsBlockPointerType()->getPointeeType()->getAsFunctionType();
203 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
204 HasVAListArg = !Proto->isVariadic();
205 }
206 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
207 HasVAListArg ? 0 : Format->getFirstArg() - 1);
208 }
209 return move(TheCallResult);
210}
211
Chris Lattner5caa3702009-05-08 06:58:22 +0000212/// SemaBuiltinAtomicOverloaded - We have a call to a function like
213/// __sync_fetch_and_add, which is an overloaded function based on the pointer
214/// type of its first argument. The main ActOnCallExpr routines have already
215/// promoted the types of arguments because all of these calls are prototyped as
216/// void(...).
217///
218/// This function goes through and does final semantic checking for these
219/// builtins,
220bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
221 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
222 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
223
224 // Ensure that we have at least one argument to do type inference from.
225 if (TheCall->getNumArgs() < 1)
226 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
227 << 0 << TheCall->getCallee()->getSourceRange();
228
229 // Inspect the first argument of the atomic builtin. This should always be
230 // a pointer type, whose element is an integral scalar or pointer type.
231 // Because it is a pointer type, we don't have to worry about any implicit
232 // casts here.
233 Expr *FirstArg = TheCall->getArg(0);
234 if (!FirstArg->getType()->isPointerType())
235 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
236 << FirstArg->getType() << FirstArg->getSourceRange();
237
238 QualType ValType = FirstArg->getType()->getAsPointerType()->getPointeeType();
239 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
240 !ValType->isBlockPointerType())
241 return Diag(DRE->getLocStart(),
242 diag::err_atomic_builtin_must_be_pointer_intptr)
243 << FirstArg->getType() << FirstArg->getSourceRange();
244
245 // We need to figure out which concrete builtin this maps onto. For example,
246 // __sync_fetch_and_add with a 2 byte object turns into
247 // __sync_fetch_and_add_2.
248#define BUILTIN_ROW(x) \
249 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
250 Builtin::BI##x##_8, Builtin::BI##x##_16 }
251
252 static const unsigned BuiltinIndices[][5] = {
253 BUILTIN_ROW(__sync_fetch_and_add),
254 BUILTIN_ROW(__sync_fetch_and_sub),
255 BUILTIN_ROW(__sync_fetch_and_or),
256 BUILTIN_ROW(__sync_fetch_and_and),
257 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000258 BUILTIN_ROW(__sync_fetch_and_nand),
Chris Lattner5caa3702009-05-08 06:58:22 +0000259
260 BUILTIN_ROW(__sync_add_and_fetch),
261 BUILTIN_ROW(__sync_sub_and_fetch),
262 BUILTIN_ROW(__sync_and_and_fetch),
263 BUILTIN_ROW(__sync_or_and_fetch),
264 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000265 BUILTIN_ROW(__sync_nand_and_fetch),
Chris Lattner5caa3702009-05-08 06:58:22 +0000266
267 BUILTIN_ROW(__sync_val_compare_and_swap),
268 BUILTIN_ROW(__sync_bool_compare_and_swap),
269 BUILTIN_ROW(__sync_lock_test_and_set),
270 BUILTIN_ROW(__sync_lock_release)
271 };
272#undef BUILTIN_ROW
273
274 // Determine the index of the size.
275 unsigned SizeIndex;
276 switch (Context.getTypeSize(ValType)/8) {
277 case 1: SizeIndex = 0; break;
278 case 2: SizeIndex = 1; break;
279 case 4: SizeIndex = 2; break;
280 case 8: SizeIndex = 3; break;
281 case 16: SizeIndex = 4; break;
282 default:
283 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
284 << FirstArg->getType() << FirstArg->getSourceRange();
285 }
286
287 // Each of these builtins has one pointer argument, followed by some number of
288 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
289 // that we ignore. Find out which row of BuiltinIndices to read from as well
290 // as the number of fixed args.
291 unsigned BuiltinID = FDecl->getBuiltinID(Context);
292 unsigned BuiltinIndex, NumFixed = 1;
293 switch (BuiltinID) {
294 default: assert(0 && "Unknown overloaded atomic builtin!");
295 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
296 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
297 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
298 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
299 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000300 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000301
Chris Lattnereebd9d22009-05-13 04:37:52 +0000302 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
303 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
304 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
305 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
306 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
307 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000308
309 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000310 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000311 NumFixed = 2;
312 break;
313 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000314 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000315 NumFixed = 2;
316 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000317 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000318 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000319 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000320 NumFixed = 0;
321 break;
322 }
323
324 // Now that we know how many fixed arguments we expect, first check that we
325 // have at least that many.
326 if (TheCall->getNumArgs() < 1+NumFixed)
327 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
328 << 0 << TheCall->getCallee()->getSourceRange();
329
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000330
331 // Get the decl for the concrete builtin from this, we can tell what the
332 // concrete integer type we should convert to is.
333 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
334 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
335 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
336 FunctionDecl *NewBuiltinDecl =
337 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
338 TUScope, false, DRE->getLocStart()));
339 const FunctionProtoType *BuiltinFT =
340 NewBuiltinDecl->getType()->getAsFunctionProtoType();
341 ValType = BuiltinFT->getArgType(0)->getAsPointerType()->getPointeeType();
342
343 // If the first type needs to be converted (e.g. void** -> int*), do it now.
344 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
345 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), false);
346 TheCall->setArg(0, FirstArg);
347 }
348
Chris Lattner5caa3702009-05-08 06:58:22 +0000349 // Next, walk the valid ones promoting to the right type.
350 for (unsigned i = 0; i != NumFixed; ++i) {
351 Expr *Arg = TheCall->getArg(i+1);
352
353 // If the argument is an implicit cast, then there was a promotion due to
354 // "...", just remove it now.
355 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
356 Arg = ICE->getSubExpr();
357 ICE->setSubExpr(0);
358 ICE->Destroy(Context);
359 TheCall->setArg(i+1, Arg);
360 }
361
362 // GCC does an implicit conversion to the pointer or integer ValType. This
363 // can fail in some cases (1i -> int**), check for this error case now.
364 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg))
365 return true;
366
367 // Okay, we have something that *can* be converted to the right type. Check
368 // to see if there is a potentially weird extension going on here. This can
369 // happen when you do an atomic operation on something like an char* and
370 // pass in 42. The 42 gets converted to char. This is even more strange
371 // for things like 45.123 -> char, etc.
372 // FIXME: Do this check.
373 ImpCastExprToType(Arg, ValType, false);
374 TheCall->setArg(i+1, Arg);
375 }
376
Chris Lattner5caa3702009-05-08 06:58:22 +0000377 // Switch the DeclRefExpr to refer to the new decl.
378 DRE->setDecl(NewBuiltinDecl);
379 DRE->setType(NewBuiltinDecl->getType());
380
381 // Set the callee in the CallExpr.
382 // FIXME: This leaks the original parens and implicit casts.
383 Expr *PromotedCall = DRE;
384 UsualUnaryConversions(PromotedCall);
385 TheCall->setCallee(PromotedCall);
386
387
388 // Change the result type of the call to match the result type of the decl.
389 TheCall->setType(NewBuiltinDecl->getResultType());
390 return false;
391}
392
393
Chris Lattner69039812009-02-18 06:01:06 +0000394/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000395/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000396/// FIXME: GCC currently emits the following warning:
397/// "warning: input conversion stopped due to an input byte that does not
398/// belong to the input codeset UTF-8"
399/// Note: It might also make sense to do the UTF-16 conversion here (would
400/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000401bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000402 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000403 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
404
405 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000406 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
407 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000408 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000409 }
410
411 const char *Data = Literal->getStrData();
412 unsigned Length = Literal->getByteLength();
413
414 for (unsigned i = 0; i < Length; ++i) {
Anders Carlsson71993dd2007-08-17 05:31:46 +0000415 if (!Data[i]) {
Chris Lattner60800082009-02-18 17:49:48 +0000416 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000417 diag::warn_cfstring_literal_contains_nul_character)
418 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000419 break;
420 }
421 }
422
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000423 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000424}
425
Chris Lattnerc27c6652007-12-20 00:05:45 +0000426/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
427/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000428bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
429 Expr *Fn = TheCall->getCallee();
430 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000431 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000432 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000433 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000434 << SourceRange(TheCall->getArg(2)->getLocStart(),
435 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000436 return true;
437 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000438
439 if (TheCall->getNumArgs() < 2) {
440 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
441 << 0 /*function call*/;
442 }
443
Chris Lattnerc27c6652007-12-20 00:05:45 +0000444 // Determine whether the current function is variadic or not.
445 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000446 if (CurBlock)
447 isVariadic = CurBlock->isVariadic;
448 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000449 if (FunctionProtoType* FTP =
450 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000451 isVariadic = FTP->isVariadic();
452 else
453 isVariadic = false;
454 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000455 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000456 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000457
Chris Lattnerc27c6652007-12-20 00:05:45 +0000458 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000459 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
460 return true;
461 }
462
463 // Verify that the second argument to the builtin is the last argument of the
464 // current function or method.
465 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000466 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000467
468 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
469 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000470 // FIXME: This isn't correct for methods (results in bogus warning).
471 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000472 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000473 if (CurBlock)
474 LastArg = *(CurBlock->TheDecl->param_end()-1);
475 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000476 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000477 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000478 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000479 SecondArgIsLastNamedArgument = PV == LastArg;
480 }
481 }
482
483 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000484 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000485 diag::warn_second_parameter_of_va_start_not_last_named_argument);
486 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000487}
Chris Lattner30ce3442007-12-19 23:59:04 +0000488
Chris Lattner1b9a0792007-12-20 00:26:33 +0000489/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
490/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000491bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
492 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000493 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
494 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000495 if (TheCall->getNumArgs() > 2)
496 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000497 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000498 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000499 << SourceRange(TheCall->getArg(2)->getLocStart(),
500 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000501
Chris Lattner925e60d2007-12-28 05:29:59 +0000502 Expr *OrigArg0 = TheCall->getArg(0);
503 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000504
Chris Lattner1b9a0792007-12-20 00:26:33 +0000505 // Do standard promotions between the two arguments, returning their common
506 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000507 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000508
509 // Make sure any conversions are pushed back into the call; this is
510 // type safe since unordered compare builtins are declared as "_Bool
511 // foo(...)".
512 TheCall->setArg(0, OrigArg0);
513 TheCall->setArg(1, OrigArg1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000514
Douglas Gregorcde01732009-05-19 22:10:17 +0000515 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
516 return false;
517
Chris Lattner1b9a0792007-12-20 00:26:33 +0000518 // If the common type isn't a real floating type, then the arguments were
519 // invalid for this operation.
520 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000521 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000522 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000523 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000524 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000525
526 return false;
527}
528
Eli Friedman6cfda232008-05-20 08:23:37 +0000529bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
530 // The signature for these builtins is exact; the only thing we need
531 // to check is that the argument is a constant.
532 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000533 if (!TheCall->getArg(0)->isTypeDependent() &&
534 !TheCall->getArg(0)->isValueDependent() &&
535 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000536 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000537
Eli Friedman6cfda232008-05-20 08:23:37 +0000538 return false;
539}
540
Eli Friedmand38617c2008-05-14 19:38:39 +0000541/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
542// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000543Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000544 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000545 return ExprError(Diag(TheCall->getLocEnd(),
546 diag::err_typecheck_call_too_few_args)
547 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000548
Douglas Gregorcde01732009-05-19 22:10:17 +0000549 unsigned numElements = std::numeric_limits<unsigned>::max();
550 if (!TheCall->getArg(0)->isTypeDependent() &&
551 !TheCall->getArg(1)->isTypeDependent()) {
552 QualType FAType = TheCall->getArg(0)->getType();
553 QualType SAType = TheCall->getArg(1)->getType();
554
555 if (!FAType->isVectorType() || !SAType->isVectorType()) {
556 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
557 << SourceRange(TheCall->getArg(0)->getLocStart(),
558 TheCall->getArg(1)->getLocEnd());
559 return ExprError();
560 }
561
562 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
563 Context.getCanonicalType(SAType).getUnqualifiedType()) {
564 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
565 << SourceRange(TheCall->getArg(0)->getLocStart(),
566 TheCall->getArg(1)->getLocEnd());
567 return ExprError();
568 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000569
Douglas Gregorcde01732009-05-19 22:10:17 +0000570 numElements = FAType->getAsVectorType()->getNumElements();
571 if (TheCall->getNumArgs() != numElements+2) {
572 if (TheCall->getNumArgs() < numElements+2)
573 return ExprError(Diag(TheCall->getLocEnd(),
574 diag::err_typecheck_call_too_few_args)
575 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000576 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000577 diag::err_typecheck_call_too_many_args)
578 << 0 /*function call*/ << TheCall->getSourceRange());
579 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000580 }
581
582 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000583 if (TheCall->getArg(i)->isTypeDependent() ||
584 TheCall->getArg(i)->isValueDependent())
585 continue;
586
Eli Friedmand38617c2008-05-14 19:38:39 +0000587 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000588 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000589 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000590 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000591 << TheCall->getArg(i)->getSourceRange());
592
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000593 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000594 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000595 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000596 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000597 }
598
599 llvm::SmallVector<Expr*, 32> exprs;
600
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000601 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000602 exprs.push_back(TheCall->getArg(i));
603 TheCall->setArg(i, 0);
604 }
605
Douglas Gregorcde01732009-05-19 22:10:17 +0000606 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), exprs.size(),
607 exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000608 TheCall->getCallee()->getLocStart(),
609 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000610}
Chris Lattner30ce3442007-12-19 23:59:04 +0000611
Daniel Dunbar4493f792008-07-21 22:59:13 +0000612/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
613// This is declared to take (const void*, ...) and can take two
614// optional constant int args.
615bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000616 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000617
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000618 if (NumArgs > 3)
619 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000620 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000621
622 // Argument 0 is checked for us and the remaining arguments must be
623 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000624 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000625 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000626 if (Arg->isTypeDependent())
627 continue;
628
Daniel Dunbar4493f792008-07-21 22:59:13 +0000629 QualType RWType = Arg->getType();
630
631 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000632 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000633 if (!BT || BT->getKind() != BuiltinType::Int)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000634 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
635 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Douglas Gregorcde01732009-05-19 22:10:17 +0000636
637 if (Arg->isValueDependent())
638 continue;
639
640 if (!Arg->isIntegerConstantExpr(Result, Context))
641 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
642 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000643
644 // FIXME: gcc issues a warning and rewrites these to 0. These
645 // seems especially odd for the third argument since the default
646 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000647 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000648 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000649 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
650 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000651 } else {
652 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000653 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
654 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000655 }
656 }
657
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000658 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000659}
660
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000661/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
662/// int type). This simply type checks that type is one of the defined
663/// constants (0-3).
664bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
665 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000666 if (Arg->isTypeDependent())
667 return false;
668
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000669 QualType ArgType = Arg->getType();
670 const BuiltinType *BT = ArgType->getAsBuiltinType();
671 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000672 if (!BT || BT->getKind() != BuiltinType::Int)
673 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
674 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
675
676 if (Arg->isValueDependent())
677 return false;
678
679 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000680 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
681 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000682 }
683
684 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000685 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
686 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000687 }
688
689 return false;
690}
691
Eli Friedman586d6a82009-05-03 06:04:26 +0000692/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000693/// This checks that val is a constant 1.
694bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
695 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000696 if (Arg->isTypeDependent() || Arg->isValueDependent())
697 return false;
698
Eli Friedmand875fed2009-05-03 04:46:36 +0000699 llvm::APSInt Result(32);
700 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
701 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
702 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
703
704 return false;
705}
706
Ted Kremenekd30ef872009-01-12 23:09:09 +0000707// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000708bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
709 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000710 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000711 if (E->isTypeDependent() || E->isValueDependent())
712 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000713
714 switch (E->getStmtClass()) {
715 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000716 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000717 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000718 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000719 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000720 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000721 }
722
723 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000724 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000725 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000726 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000727 }
728
729 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000730 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000731 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000732 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000733 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000734
735 case Stmt::DeclRefExprClass: {
736 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
737
738 // As an exception, do not flag errors for variables binding to
739 // const string literals.
740 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
741 bool isConstant = false;
742 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000743
Ted Kremenek082d9362009-03-20 21:35:28 +0000744 if (const ArrayType *AT = Context.getAsArrayType(T)) {
745 isConstant = AT->getElementType().isConstant(Context);
746 }
747 else if (const PointerType *PT = T->getAsPointerType()) {
748 isConstant = T.isConstant(Context) &&
749 PT->getPointeeType().isConstant(Context);
750 }
751
752 if (isConstant) {
753 const VarDecl *Def = 0;
754 if (const Expr *Init = VD->getDefinition(Def))
755 return SemaCheckStringLiteral(Init, TheCall,
756 HasVAListArg, format_idx, firstDataArg);
757 }
758 }
759
760 return false;
761 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000762
Ted Kremenek082d9362009-03-20 21:35:28 +0000763 case Stmt::ObjCStringLiteralClass:
764 case Stmt::StringLiteralClass: {
765 const StringLiteral *StrE = NULL;
766
767 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000768 StrE = ObjCFExpr->getString();
769 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000770 StrE = cast<StringLiteral>(E);
771
Ted Kremenekd30ef872009-01-12 23:09:09 +0000772 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000773 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
774 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000775 return true;
776 }
777
778 return false;
779 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000780
781 default:
782 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000783 }
784}
785
786
Chris Lattner59907c42007-08-10 20:18:51 +0000787/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000788/// correct use of format strings.
789///
790/// HasVAListArg - A predicate indicating whether the printf-like
791/// function is passed an explicit va_arg argument (e.g., vprintf)
792///
793/// format_idx - The index into Args for the format string.
794///
795/// Improper format strings to functions in the printf family can be
796/// the source of bizarre bugs and very serious security holes. A
797/// good source of information is available in the following paper
798/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000799///
800/// FormatGuard: Automatic Protection From printf Format String
801/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000802///
803/// Functionality implemented:
804///
805/// We can statically check the following properties for string
806/// literal format strings for non v.*printf functions (where the
807/// arguments are passed directly):
808//
809/// (1) Are the number of format conversions equal to the number of
810/// data arguments?
811///
812/// (2) Does each format conversion correctly match the type of the
813/// corresponding data argument? (TODO)
814///
815/// Moreover, for all printf functions we can:
816///
817/// (3) Check for a missing format string (when not caught by type checking).
818///
819/// (4) Check for no-operation flags; e.g. using "#" with format
820/// conversion 'c' (TODO)
821///
822/// (5) Check the use of '%n', a major source of security holes.
823///
824/// (6) Check for malformed format conversions that don't specify anything.
825///
826/// (7) Check for empty format strings. e.g: printf("");
827///
828/// (8) Check that the format string is a wide literal.
829///
Ted Kremenek6d439592008-03-03 16:50:00 +0000830/// (9) Also check the arguments of functions with the __format__ attribute.
831/// (TODO).
832///
Ted Kremenek71895b92007-08-14 17:39:48 +0000833/// All of these checks can be done by parsing the format string.
834///
835/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000836void
Ted Kremenek082d9362009-03-20 21:35:28 +0000837Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000838 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000839 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000840
Ted Kremenek71895b92007-08-14 17:39:48 +0000841 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000842 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000843 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
844 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000845 return;
846 }
847
Ted Kremenek082d9362009-03-20 21:35:28 +0000848 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000849
Chris Lattner59907c42007-08-10 20:18:51 +0000850 // CHECK: format string is not a string literal.
851 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000852 // Dynamically generated format strings are difficult to
853 // automatically vet at compile time. Requiring that format strings
854 // are string literals: (1) permits the checking of format strings by
855 // the compiler and thereby (2) can practically remove the source of
856 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000857
858 // Format string can be either ObjC string (e.g. @"%d") or
859 // C string (e.g. "%d")
860 // ObjC string uses the same format specifiers as C string, so we can use
861 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000862 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
863 firstDataArg))
864 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000865
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000866 // For vprintf* functions (i.e., HasVAListArg==true), we add a
867 // special check to see if the format string is a function parameter
868 // of the function calling the printf function. If the function
869 // has an attribute indicating it is a printf-like function, then we
870 // should suppress warnings concerning non-literals being used in a call
871 // to a vprintf function. For example:
872 //
873 // void
874 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
875 // va_list ap;
876 // va_start(ap, fmt);
877 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
878 // ...
879 //
880 //
881 // FIXME: We don't have full attribute support yet, so just check to see
882 // if the argument is a DeclRefExpr that references a parameter. We'll
883 // add proper support for checking the attribute later.
884 if (HasVAListArg)
885 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
886 if (isa<ParmVarDecl>(DR->getDecl()))
887 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000888
Chris Lattner655f1412009-04-29 04:59:47 +0000889 // If there are no arguments specified, warn with -Wformat-security, otherwise
890 // warn only with -Wformat-nonliteral.
891 if (TheCall->getNumArgs() == format_idx+1)
892 Diag(TheCall->getArg(format_idx)->getLocStart(),
893 diag::warn_printf_nonliteral_noargs)
894 << OrigFormatExpr->getSourceRange();
895 else
896 Diag(TheCall->getArg(format_idx)->getLocStart(),
897 diag::warn_printf_nonliteral)
898 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000899}
Ted Kremenek71895b92007-08-14 17:39:48 +0000900
Ted Kremenek082d9362009-03-20 21:35:28 +0000901void Sema::CheckPrintfString(const StringLiteral *FExpr,
902 const Expr *OrigFormatExpr,
903 const CallExpr *TheCall, bool HasVAListArg,
904 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000905
Ted Kremenek082d9362009-03-20 21:35:28 +0000906 const ObjCStringLiteral *ObjCFExpr =
907 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
908
Ted Kremenek71895b92007-08-14 17:39:48 +0000909 // CHECK: is the format string a wide literal?
910 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000911 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000912 diag::warn_printf_format_string_is_wide_literal)
913 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000914 return;
915 }
916
917 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000918 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +0000919
920 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000921 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek71895b92007-08-14 17:39:48 +0000922
923 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000924 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
925 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000926 return;
927 }
928
929 // We process the format string using a binary state machine. The
930 // current state is stored in CurrentState.
931 enum {
932 state_OrdChr,
933 state_Conversion
934 } CurrentState = state_OrdChr;
935
936 // numConversions - The number of conversions seen so far. This is
937 // incremented as we traverse the format string.
938 unsigned numConversions = 0;
939
940 // numDataArgs - The number of data arguments after the format
941 // string. This can only be determined for non vprintf-like
942 // functions. For those functions, this value is 1 (the sole
943 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000944 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000945
946 // Inspect the format string.
947 unsigned StrIdx = 0;
948
949 // LastConversionIdx - Index within the format string where we last saw
950 // a '%' character that starts a new format conversion.
951 unsigned LastConversionIdx = 0;
952
Chris Lattner925e60d2007-12-28 05:29:59 +0000953 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000954
Ted Kremenek71895b92007-08-14 17:39:48 +0000955 // Is the number of detected conversion conversions greater than
956 // the number of matching data arguments? If so, stop.
957 if (!HasVAListArg && numConversions > numDataArgs) break;
958
959 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000960 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000961 // The string returned by getStrData() is not null-terminated,
962 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +0000963 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000964 diag::warn_printf_format_string_contains_null_char)
965 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000966 return;
967 }
968
969 // Ordinary characters (not processing a format conversion).
970 if (CurrentState == state_OrdChr) {
971 if (Str[StrIdx] == '%') {
972 CurrentState = state_Conversion;
973 LastConversionIdx = StrIdx;
974 }
975 continue;
976 }
977
978 // Seen '%'. Now processing a format conversion.
979 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000980 // Handle dynamic precision or width specifier.
981 case '*': {
982 ++numConversions;
983
Ted Kremenek42ae3e82009-05-13 16:06:05 +0000984 if (!HasVAListArg) {
985 if (numConversions > numDataArgs) {
986 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +0000987
Ted Kremenek42ae3e82009-05-13 16:06:05 +0000988 if (Str[StrIdx-1] == '.')
989 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
990 << OrigFormatExpr->getSourceRange();
991 else
992 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
993 << OrigFormatExpr->getSourceRange();
994
995 // Don't do any more checking. We'll just emit spurious errors.
996 return;
997 }
998
999 // Perform type checking on width/precision specifier.
1000 const Expr *E = TheCall->getArg(format_idx+numConversions);
1001 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
1002 if (BT->getKind() == BuiltinType::Int)
1003 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001004
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001005 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
1006
1007 if (Str[StrIdx-1] == '.')
1008 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1009 << E->getType() << E->getSourceRange();
1010 else
1011 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1012 << E->getType() << E->getSourceRange();
1013
1014 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001015 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001016 }
1017
1018 // Characters which can terminate a format conversion
1019 // (e.g. "%d"). Characters that specify length modifiers or
1020 // other flags are handled by the default case below.
1021 //
1022 // FIXME: additional checks will go into the following cases.
1023 case 'i':
1024 case 'd':
1025 case 'o':
1026 case 'u':
1027 case 'x':
1028 case 'X':
1029 case 'D':
1030 case 'O':
1031 case 'U':
1032 case 'e':
1033 case 'E':
1034 case 'f':
1035 case 'F':
1036 case 'g':
1037 case 'G':
1038 case 'a':
1039 case 'A':
1040 case 'c':
1041 case 'C':
1042 case 'S':
1043 case 's':
1044 case 'p':
1045 ++numConversions;
1046 CurrentState = state_OrdChr;
1047 break;
1048
1049 // CHECK: Are we using "%n"? Issue a warning.
1050 case 'n': {
1051 ++numConversions;
1052 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +00001053 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1054 LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001055
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001056 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001057 break;
1058 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001059
1060 // Handle "%@"
1061 case '@':
1062 // %@ is allowed in ObjC format strings only.
1063 if(ObjCFExpr != NULL)
1064 CurrentState = state_OrdChr;
1065 else {
1066 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001067 SourceLocation Loc =
1068 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001069
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001070 Diag(Loc, diag::warn_printf_invalid_conversion)
1071 << std::string(Str+LastConversionIdx,
1072 Str+std::min(LastConversionIdx+2, StrLen))
1073 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001074 }
1075 ++numConversions;
1076 break;
1077
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001078 // Handle "%%"
1079 case '%':
1080 // Sanity check: Was the first "%" character the previous one?
1081 // If not, we will assume that we have a malformed format
1082 // conversion, and that the current "%" character is the start
1083 // of a new conversion.
1084 if (StrIdx - LastConversionIdx == 1)
1085 CurrentState = state_OrdChr;
1086 else {
1087 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001088 SourceLocation Loc =
1089 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001090
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001091 Diag(Loc, diag::warn_printf_invalid_conversion)
1092 << std::string(Str+LastConversionIdx, Str+StrIdx)
1093 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001094
1095 // This conversion is broken. Advance to the next format
1096 // conversion.
1097 LastConversionIdx = StrIdx;
1098 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +00001099 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001100 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001101
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001102 default:
1103 // This case catches all other characters: flags, widths, etc.
1104 // We should eventually process those as well.
1105 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001106 }
1107 }
1108
1109 if (CurrentState == state_Conversion) {
1110 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001111 SourceLocation Loc =
1112 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +00001113
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001114 Diag(Loc, diag::warn_printf_invalid_conversion)
1115 << std::string(Str+LastConversionIdx,
1116 Str+std::min(LastConversionIdx+2, StrLen))
1117 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001118 return;
1119 }
1120
1121 if (!HasVAListArg) {
1122 // CHECK: Does the number of format conversions exceed the number
1123 // of data arguments?
1124 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +00001125 SourceLocation Loc =
1126 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +00001127
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001128 Diag(Loc, diag::warn_printf_insufficient_data_args)
1129 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001130 }
1131 // CHECK: Does the number of data arguments exceed the number of
1132 // format conversions in the format string?
1133 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +00001134 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001135 diag::warn_printf_too_many_data_args)
1136 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001137 }
1138}
Ted Kremenek06de2762007-08-17 16:46:58 +00001139
1140//===--- CHECK: Return Address of Stack Variable --------------------------===//
1141
1142static DeclRefExpr* EvalVal(Expr *E);
1143static DeclRefExpr* EvalAddr(Expr* E);
1144
1145/// CheckReturnStackAddr - Check if a return statement returns the address
1146/// of a stack variable.
1147void
1148Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1149 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +00001150
Ted Kremenek06de2762007-08-17 16:46:58 +00001151 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001152 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001153 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001154 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001155 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001156
1157 // Skip over implicit cast expressions when checking for block expressions.
1158 if (ImplicitCastExpr *IcExpr =
1159 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
1160 RetValExp = IcExpr->getSubExpr();
1161
Steve Naroff61f40a22008-09-10 19:17:48 +00001162 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001163 if (C->hasBlockDeclRefExprs())
1164 Diag(C->getLocStart(), diag::err_ret_local_block)
1165 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001166 }
1167 // Perform checking for stack values returned by reference.
1168 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +00001169 // Check for a reference to the stack
1170 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001171 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001172 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001173 }
1174}
1175
1176/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1177/// check if the expression in a return statement evaluates to an address
1178/// to a location on the stack. The recursion is used to traverse the
1179/// AST of the return expression, with recursion backtracking when we
1180/// encounter a subexpression that (1) clearly does not lead to the address
1181/// of a stack variable or (2) is something we cannot determine leads to
1182/// the address of a stack variable based on such local checking.
1183///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001184/// EvalAddr processes expressions that are pointers that are used as
1185/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +00001186/// At the base case of the recursion is a check for a DeclRefExpr* in
1187/// the refers to a stack variable.
1188///
1189/// This implementation handles:
1190///
1191/// * pointer-to-pointer casts
1192/// * implicit conversions from array references to pointers
1193/// * taking the address of fields
1194/// * arbitrary interplay between "&" and "*" operators
1195/// * pointer arithmetic from an address of a stack variable
1196/// * taking the address of an array element where the array is on the stack
1197static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001198 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +00001199 assert((E->getType()->isPointerType() ||
1200 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001201 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001202 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +00001203
1204 // Our "symbolic interpreter" is just a dispatch off the currently
1205 // viewed AST node. We then recursively traverse the AST by calling
1206 // EvalAddr and EvalVal appropriately.
1207 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001208 case Stmt::ParenExprClass:
1209 // Ignore parentheses.
1210 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001211
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001212 case Stmt::UnaryOperatorClass: {
1213 // The only unary operator that make sense to handle here
1214 // is AddrOf. All others don't make sense as pointers.
1215 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +00001216
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001217 if (U->getOpcode() == UnaryOperator::AddrOf)
1218 return EvalVal(U->getSubExpr());
1219 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001220 return NULL;
1221 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001222
1223 case Stmt::BinaryOperatorClass: {
1224 // Handle pointer arithmetic. All other binary operators are not valid
1225 // in this context.
1226 BinaryOperator *B = cast<BinaryOperator>(E);
1227 BinaryOperator::Opcode op = B->getOpcode();
1228
1229 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1230 return NULL;
1231
1232 Expr *Base = B->getLHS();
1233
1234 // Determine which argument is the real pointer base. It could be
1235 // the RHS argument instead of the LHS.
1236 if (!Base->getType()->isPointerType()) Base = B->getRHS();
1237
1238 assert (Base->getType()->isPointerType());
1239 return EvalAddr(Base);
1240 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001241
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001242 // For conditional operators we need to see if either the LHS or RHS are
1243 // valid DeclRefExpr*s. If one of them is valid, we return it.
1244 case Stmt::ConditionalOperatorClass: {
1245 ConditionalOperator *C = cast<ConditionalOperator>(E);
1246
1247 // Handle the GNU extension for missing LHS.
1248 if (Expr *lhsExpr = C->getLHS())
1249 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1250 return LHS;
1251
1252 return EvalAddr(C->getRHS());
1253 }
1254
Ted Kremenek54b52742008-08-07 00:49:01 +00001255 // For casts, we need to handle conversions from arrays to
1256 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001257 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001258 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001259 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001260 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001261 QualType T = SubExpr->getType();
1262
Steve Naroffdd972f22008-09-05 22:11:13 +00001263 if (SubExpr->getType()->isPointerType() ||
1264 SubExpr->getType()->isBlockPointerType() ||
1265 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001266 return EvalAddr(SubExpr);
1267 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001268 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001269 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001270 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001271 }
1272
1273 // C++ casts. For dynamic casts, static casts, and const casts, we
1274 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001275 // through the cast. In the case the dynamic cast doesn't fail (and
1276 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001277 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001278 // FIXME: The comment about is wrong; we're not always converting
1279 // from pointer to pointer. I'm guessing that this code should also
1280 // handle references to objects.
1281 case Stmt::CXXStaticCastExprClass:
1282 case Stmt::CXXDynamicCastExprClass:
1283 case Stmt::CXXConstCastExprClass:
1284 case Stmt::CXXReinterpretCastExprClass: {
1285 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001286 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001287 return EvalAddr(S);
1288 else
1289 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001290 }
1291
1292 // Everything else: we simply don't reason about them.
1293 default:
1294 return NULL;
1295 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001296}
1297
1298
1299/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1300/// See the comments for EvalAddr for more details.
1301static DeclRefExpr* EvalVal(Expr *E) {
1302
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001303 // We should only be called for evaluating non-pointer expressions, or
1304 // expressions with a pointer type that are not used as references but instead
1305 // are l-values (e.g., DeclRefExpr with a pointer type).
1306
Ted Kremenek06de2762007-08-17 16:46:58 +00001307 // Our "symbolic interpreter" is just a dispatch off the currently
1308 // viewed AST node. We then recursively traverse the AST by calling
1309 // EvalAddr and EvalVal appropriately.
1310 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +00001311 case Stmt::DeclRefExprClass:
1312 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001313 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1314 // at code that refers to a variable's name. We check if it has local
1315 // storage within the function, and if so, return the expression.
1316 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1317
1318 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001319 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +00001320
1321 return NULL;
1322 }
1323
1324 case Stmt::ParenExprClass:
1325 // Ignore parentheses.
1326 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1327
1328 case Stmt::UnaryOperatorClass: {
1329 // The only unary operator that make sense to handle here
1330 // is Deref. All others don't resolve to a "name." This includes
1331 // handling all sorts of rvalues passed to a unary operator.
1332 UnaryOperator *U = cast<UnaryOperator>(E);
1333
1334 if (U->getOpcode() == UnaryOperator::Deref)
1335 return EvalAddr(U->getSubExpr());
1336
1337 return NULL;
1338 }
1339
1340 case Stmt::ArraySubscriptExprClass: {
1341 // Array subscripts are potential references to data on the stack. We
1342 // retrieve the DeclRefExpr* for the array variable if it indeed
1343 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001344 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001345 }
1346
1347 case Stmt::ConditionalOperatorClass: {
1348 // For conditional operators we need to see if either the LHS or RHS are
1349 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1350 ConditionalOperator *C = cast<ConditionalOperator>(E);
1351
Anders Carlsson39073232007-11-30 19:04:31 +00001352 // Handle the GNU extension for missing LHS.
1353 if (Expr *lhsExpr = C->getLHS())
1354 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1355 return LHS;
1356
1357 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001358 }
1359
1360 // Accesses to members are potential references to data on the stack.
1361 case Stmt::MemberExprClass: {
1362 MemberExpr *M = cast<MemberExpr>(E);
1363
1364 // Check for indirect access. We only want direct field accesses.
1365 if (!M->isArrow())
1366 return EvalVal(M->getBase());
1367 else
1368 return NULL;
1369 }
1370
1371 // Everything else: we simply don't reason about them.
1372 default:
1373 return NULL;
1374 }
1375}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001376
1377//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1378
1379/// Check for comparisons of floating point operands using != and ==.
1380/// Issue a warning if these are no self-comparisons, as they are not likely
1381/// to do what the programmer intended.
1382void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1383 bool EmitWarning = true;
1384
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001385 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001386 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001387
1388 // Special case: check for x == x (which is OK).
1389 // Do not emit warnings for such cases.
1390 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1391 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1392 if (DRL->getDecl() == DRR->getDecl())
1393 EmitWarning = false;
1394
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001395
1396 // Special case: check for comparisons against literals that can be exactly
1397 // represented by APFloat. In such cases, do not emit a warning. This
1398 // is a heuristic: often comparison against such literals are used to
1399 // detect if a value in a variable has not changed. This clearly can
1400 // lead to false negatives.
1401 if (EmitWarning) {
1402 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1403 if (FLL->isExact())
1404 EmitWarning = false;
1405 }
1406 else
1407 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1408 if (FLR->isExact())
1409 EmitWarning = false;
1410 }
1411 }
1412
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001413 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001414 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001415 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001416 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001417 EmitWarning = false;
1418
Sebastian Redl0eb23302009-01-19 00:08:26 +00001419 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001420 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001421 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001422 EmitWarning = false;
1423
1424 // Emit the diagnostic.
1425 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001426 Diag(loc, diag::warn_floatingpoint_eq)
1427 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001428}