blob: 92f1ba5d6ad0fa25903cd957bf244be90eead310 [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//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000020#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/Lex/Preprocessor.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000022#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000023using namespace clang;
24
Chris Lattner60800082009-02-18 17:49:48 +000025/// getLocationOfStringLiteralByte - Return a source location that points to the
26/// specified byte of the specified string literal.
27///
28/// Strings are amazingly complex. They can be formed from multiple tokens and
29/// can have escape sequences in them in addition to the usual trigraph and
30/// escaped newline business. This routine handles this complexity.
31///
32SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
33 unsigned ByteNo) const {
34 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000035
Chris Lattner60800082009-02-18 17:49:48 +000036 // 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);
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner60800082009-02-18 17:49:48 +000043 // 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;
Mike Stump1eb44332009-09-09 15:08:12 +000054
Chris Lattner60800082009-02-18 17:49:48 +000055 // Create a langops struct and enable trigraphs. This is sufficient for
56 // relexing tokens.
57 LangOptions LangOpts;
58 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000059
Chris Lattner60800082009-02-18 17:49:48 +000060 // 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);
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner443e53c2009-02-18 19:26:42 +000066 // Use the StringLiteralParser to compute the length of the string in bytes.
67 StringLiteralParser SLP(&TheTok, 1, PP);
68 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner2197c962009-02-18 18:52:52 +000070 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000071 if (ByteNo < TokNumBytes ||
72 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000073 unsigned Offset =
Chris Lattner719e6152009-02-18 19:21:10 +000074 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner719e6152009-02-18 19:21:10 +000076 // Now that we know the offset of the token in the spelling, use the
77 // preprocessor to get the offset in the original source.
78 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000079 }
Mike Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattner60800082009-02-18 17:49:48 +000081 // Move to the next string token.
82 ++TokNo;
83 ByteNo -= TokNumBytes;
84 }
85}
86
Ryan Flynn4403a5e2009-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();
Douglas Gregorce940492009-09-25 04:25:58 +000096 if (!Format->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000097 return true;
98 }
99 }
100 return false;
101}
Chris Lattner60800082009-02-18 17:49:48 +0000102
Sebastian Redl0eb23302009-01-19 00:08:26 +0000103Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000104Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000105 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000106
Anders Carlssond406bf02009-08-16 01:56:34 +0000107 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000108 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000109 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000110 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000111 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000112 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000113 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000114 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000115 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000116 if (SemaBuiltinVAStart(TheCall))
117 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000118 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000119 case Builtin::BI__builtin_isgreater:
120 case Builtin::BI__builtin_isgreaterequal:
121 case Builtin::BI__builtin_isless:
122 case Builtin::BI__builtin_islessequal:
123 case Builtin::BI__builtin_islessgreater:
124 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125 if (SemaBuiltinUnorderedCompare(TheCall))
126 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000128 case Builtin::BI__builtin_isfinite:
129 case Builtin::BI__builtin_isinf:
130 case Builtin::BI__builtin_isinf_sign:
131 case Builtin::BI__builtin_isnan:
132 case Builtin::BI__builtin_isnormal:
133 if (SemaBuiltinUnaryFP(TheCall))
134 return ExprError();
135 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000136 case Builtin::BI__builtin_return_address:
137 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 if (SemaBuiltinStackAddress(TheCall))
139 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000140 break;
Chris Lattner21fb98e2009-09-23 06:06:36 +0000141 case Builtin::BI__builtin_eh_return_data_regno:
142 if (SemaBuiltinEHReturnDataRegNo(TheCall))
143 return ExprError();
144 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000145 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000146 return SemaBuiltinShuffleVector(TheCall);
147 // TheCall will be freed by the smart pointer here, but that's fine, since
148 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000149 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000150 if (SemaBuiltinPrefetch(TheCall))
151 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000152 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000153 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 if (SemaBuiltinObjectSize(TheCall))
155 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000156 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000157 case Builtin::BI__builtin_longjmp:
158 if (SemaBuiltinLongjmp(TheCall))
159 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000160 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000161 case Builtin::BI__sync_fetch_and_add:
162 case Builtin::BI__sync_fetch_and_sub:
163 case Builtin::BI__sync_fetch_and_or:
164 case Builtin::BI__sync_fetch_and_and:
165 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000166 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000167 case Builtin::BI__sync_add_and_fetch:
168 case Builtin::BI__sync_sub_and_fetch:
169 case Builtin::BI__sync_and_and_fetch:
170 case Builtin::BI__sync_or_and_fetch:
171 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000172 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000173 case Builtin::BI__sync_val_compare_and_swap:
174 case Builtin::BI__sync_bool_compare_and_swap:
175 case Builtin::BI__sync_lock_test_and_set:
176 case Builtin::BI__sync_lock_release:
177 if (SemaBuiltinAtomicOverloaded(TheCall))
178 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000179 break;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000180 }
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Anders Carlssond406bf02009-08-16 01:56:34 +0000182 return move(TheCallResult);
183}
Daniel Dunbarde454282008-10-02 18:44:07 +0000184
Anders Carlssond406bf02009-08-16 01:56:34 +0000185/// CheckFunctionCall - Check a direct function call for various correctness
186/// and safety properties not strictly enforced by the C type system.
187bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
188 // Get the IdentifierInfo* for the called function.
189 IdentifierInfo *FnInfo = FDecl->getIdentifier();
190
191 // None of the checks below are needed for functions that don't have
192 // simple names (e.g., C++ conversion functions).
193 if (!FnInfo)
194 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Daniel Dunbarde454282008-10-02 18:44:07 +0000196 // FIXME: This mechanism should be abstracted to be less fragile and
197 // more efficient. For example, just map function ids to custom
198 // handlers.
199
Chris Lattner59907c42007-08-10 20:18:51 +0000200 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000201 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000202 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000203 bool HasVAListArg = Format->getFirstArg() == 0;
204 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000205 if (const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +0000206 = FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregor3c385e52009-02-14 18:57:46 +0000207 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000208 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000209 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000210 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000211 }
Chris Lattner59907c42007-08-10 20:18:51 +0000212 }
Mike Stump1eb44332009-09-09 15:08:12 +0000213
214 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000215 NonNull = NonNull->getNext<NonNullAttr>())
216 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000217
Anders Carlssond406bf02009-08-16 01:56:34 +0000218 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000219}
220
Anders Carlssond406bf02009-08-16 01:56:34 +0000221bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000222 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000223 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000224 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000225 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000227 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
228 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000229 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000231 QualType Ty = V->getType();
232 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000233 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Anders Carlssond406bf02009-08-16 01:56:34 +0000235 if (!CheckablePrintfAttr(Format, TheCall))
236 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Anders Carlssond406bf02009-08-16 01:56:34 +0000238 bool HasVAListArg = Format->getFirstArg() == 0;
239 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000240 const FunctionType *FT =
John McCall183700f2009-09-21 23:43:11 +0000241 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Anders Carlssond406bf02009-08-16 01:56:34 +0000242 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
243 HasVAListArg = !Proto->isVariadic();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000244 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000245 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
246 HasVAListArg ? 0 : Format->getFirstArg() - 1);
247
248 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000249}
250
Chris Lattner5caa3702009-05-08 06:58:22 +0000251/// SemaBuiltinAtomicOverloaded - We have a call to a function like
252/// __sync_fetch_and_add, which is an overloaded function based on the pointer
253/// type of its first argument. The main ActOnCallExpr routines have already
254/// promoted the types of arguments because all of these calls are prototyped as
255/// void(...).
256///
257/// This function goes through and does final semantic checking for these
258/// builtins,
259bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
260 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
261 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
262
263 // Ensure that we have at least one argument to do type inference from.
264 if (TheCall->getNumArgs() < 1)
265 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
266 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattner5caa3702009-05-08 06:58:22 +0000268 // Inspect the first argument of the atomic builtin. This should always be
269 // a pointer type, whose element is an integral scalar or pointer type.
270 // Because it is a pointer type, we don't have to worry about any implicit
271 // casts here.
272 Expr *FirstArg = TheCall->getArg(0);
273 if (!FirstArg->getType()->isPointerType())
274 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
275 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Ted Kremenek6217b802009-07-29 21:53:49 +0000277 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000278 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000279 !ValType->isBlockPointerType())
280 return Diag(DRE->getLocStart(),
281 diag::err_atomic_builtin_must_be_pointer_intptr)
282 << FirstArg->getType() << FirstArg->getSourceRange();
283
284 // We need to figure out which concrete builtin this maps onto. For example,
285 // __sync_fetch_and_add with a 2 byte object turns into
286 // __sync_fetch_and_add_2.
287#define BUILTIN_ROW(x) \
288 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
289 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattner5caa3702009-05-08 06:58:22 +0000291 static const unsigned BuiltinIndices[][5] = {
292 BUILTIN_ROW(__sync_fetch_and_add),
293 BUILTIN_ROW(__sync_fetch_and_sub),
294 BUILTIN_ROW(__sync_fetch_and_or),
295 BUILTIN_ROW(__sync_fetch_and_and),
296 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000297 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattner5caa3702009-05-08 06:58:22 +0000299 BUILTIN_ROW(__sync_add_and_fetch),
300 BUILTIN_ROW(__sync_sub_and_fetch),
301 BUILTIN_ROW(__sync_and_and_fetch),
302 BUILTIN_ROW(__sync_or_and_fetch),
303 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000304 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattner5caa3702009-05-08 06:58:22 +0000306 BUILTIN_ROW(__sync_val_compare_and_swap),
307 BUILTIN_ROW(__sync_bool_compare_and_swap),
308 BUILTIN_ROW(__sync_lock_test_and_set),
309 BUILTIN_ROW(__sync_lock_release)
310 };
Mike Stump1eb44332009-09-09 15:08:12 +0000311#undef BUILTIN_ROW
312
Chris Lattner5caa3702009-05-08 06:58:22 +0000313 // Determine the index of the size.
314 unsigned SizeIndex;
315 switch (Context.getTypeSize(ValType)/8) {
316 case 1: SizeIndex = 0; break;
317 case 2: SizeIndex = 1; break;
318 case 4: SizeIndex = 2; break;
319 case 8: SizeIndex = 3; break;
320 case 16: SizeIndex = 4; break;
321 default:
322 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
323 << FirstArg->getType() << FirstArg->getSourceRange();
324 }
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Chris Lattner5caa3702009-05-08 06:58:22 +0000326 // Each of these builtins has one pointer argument, followed by some number of
327 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
328 // that we ignore. Find out which row of BuiltinIndices to read from as well
329 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000330 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000331 unsigned BuiltinIndex, NumFixed = 1;
332 switch (BuiltinID) {
333 default: assert(0 && "Unknown overloaded atomic builtin!");
334 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
335 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
336 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
337 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
338 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000339 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Chris Lattnereebd9d22009-05-13 04:37:52 +0000341 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
342 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
343 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
344 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
345 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
346 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Chris Lattner5caa3702009-05-08 06:58:22 +0000348 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000349 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000350 NumFixed = 2;
351 break;
352 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000353 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000354 NumFixed = 2;
355 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000356 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000357 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000358 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000359 NumFixed = 0;
360 break;
361 }
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner5caa3702009-05-08 06:58:22 +0000363 // Now that we know how many fixed arguments we expect, first check that we
364 // have at least that many.
365 if (TheCall->getNumArgs() < 1+NumFixed)
366 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
367 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000368
369
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000370 // Get the decl for the concrete builtin from this, we can tell what the
371 // concrete integer type we should convert to is.
372 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
373 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
374 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000375 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000376 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
377 TUScope, false, DRE->getLocStart()));
378 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000379 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000380 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000382 // If the first type needs to be converted (e.g. void** -> int*), do it now.
383 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000384 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000385 TheCall->setArg(0, FirstArg);
386 }
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Chris Lattner5caa3702009-05-08 06:58:22 +0000388 // Next, walk the valid ones promoting to the right type.
389 for (unsigned i = 0; i != NumFixed; ++i) {
390 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner5caa3702009-05-08 06:58:22 +0000392 // If the argument is an implicit cast, then there was a promotion due to
393 // "...", just remove it now.
394 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
395 Arg = ICE->getSubExpr();
396 ICE->setSubExpr(0);
397 ICE->Destroy(Context);
398 TheCall->setArg(i+1, Arg);
399 }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Chris Lattner5caa3702009-05-08 06:58:22 +0000401 // GCC does an implicit conversion to the pointer or integer ValType. This
402 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000403 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000404 CXXMethodDecl *ConversionDecl = 0;
405 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
406 ConversionDecl))
Chris Lattner5caa3702009-05-08 06:58:22 +0000407 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner5caa3702009-05-08 06:58:22 +0000409 // Okay, we have something that *can* be converted to the right type. Check
410 // to see if there is a potentially weird extension going on here. This can
411 // happen when you do an atomic operation on something like an char* and
412 // pass in 42. The 42 gets converted to char. This is even more strange
413 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000414 // FIXME: Do this check.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000415 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000416 TheCall->setArg(i+1, Arg);
417 }
Mike Stump1eb44332009-09-09 15:08:12 +0000418
Chris Lattner5caa3702009-05-08 06:58:22 +0000419 // Switch the DeclRefExpr to refer to the new decl.
420 DRE->setDecl(NewBuiltinDecl);
421 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Chris Lattner5caa3702009-05-08 06:58:22 +0000423 // Set the callee in the CallExpr.
424 // FIXME: This leaks the original parens and implicit casts.
425 Expr *PromotedCall = DRE;
426 UsualUnaryConversions(PromotedCall);
427 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Chris Lattner5caa3702009-05-08 06:58:22 +0000429
430 // Change the result type of the call to match the result type of the decl.
431 TheCall->setType(NewBuiltinDecl->getResultType());
432 return false;
433}
434
435
Chris Lattner69039812009-02-18 06:01:06 +0000436/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000437/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000438/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000439/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000440/// belong to the input codeset UTF-8"
441/// Note: It might also make sense to do the UTF-16 conversion here (would
442/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000443bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000444 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000445 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
446
447 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000448 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
449 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000450 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000451 }
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Daniel Dunbarf015b032009-09-22 10:03:52 +0000453 const char *Data = Literal->getStrData();
454 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Daniel Dunbarf015b032009-09-22 10:03:52 +0000456 for (unsigned i = 0; i < Length; ++i) {
457 if (!Data[i]) {
458 Diag(getLocationOfStringLiteralByte(Literal, i),
459 diag::warn_cfstring_literal_contains_nul_character)
460 << Arg->getSourceRange();
461 break;
462 }
463 }
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000465 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000466}
467
Chris Lattnerc27c6652007-12-20 00:05:45 +0000468/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
469/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000470bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
471 Expr *Fn = TheCall->getCallee();
472 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000473 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000474 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000475 << 0 /*function call*/ << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000476 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000477 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000478 return true;
479 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000480
481 if (TheCall->getNumArgs() < 2) {
482 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
483 << 0 /*function call*/;
484 }
485
Chris Lattnerc27c6652007-12-20 00:05:45 +0000486 // Determine whether the current function is variadic or not.
487 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000488 if (CurBlock)
489 isVariadic = CurBlock->isVariadic;
490 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000491 if (FunctionProtoType* FTP =
492 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000493 isVariadic = FTP->isVariadic();
494 else
495 isVariadic = false;
496 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000497 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Chris Lattnerc27c6652007-12-20 00:05:45 +0000500 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000501 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
502 return true;
503 }
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Chris Lattner30ce3442007-12-19 23:59:04 +0000505 // Verify that the second argument to the builtin is the last argument of the
506 // current function or method.
507 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000508 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Anders Carlsson88cf2262008-02-11 04:20:54 +0000510 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
511 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000512 // FIXME: This isn't correct for methods (results in bogus warning).
513 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000514 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000515 if (CurBlock)
516 LastArg = *(CurBlock->TheDecl->param_end()-1);
517 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000518 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000519 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000520 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000521 SecondArgIsLastNamedArgument = PV == LastArg;
522 }
523 }
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Chris Lattner30ce3442007-12-19 23:59:04 +0000525 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000526 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000527 diag::warn_second_parameter_of_va_start_not_last_named_argument);
528 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000529}
Chris Lattner30ce3442007-12-19 23:59:04 +0000530
Chris Lattner1b9a0792007-12-20 00:26:33 +0000531/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
532/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000533bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
534 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000535 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
536 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000537 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000538 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000539 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000540 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000541 << SourceRange(TheCall->getArg(2)->getLocStart(),
542 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Chris Lattner925e60d2007-12-28 05:29:59 +0000544 Expr *OrigArg0 = TheCall->getArg(0);
545 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000546
Chris Lattner1b9a0792007-12-20 00:26:33 +0000547 // Do standard promotions between the two arguments, returning their common
548 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000549 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000550
551 // Make sure any conversions are pushed back into the call; this is
552 // type safe since unordered compare builtins are declared as "_Bool
553 // foo(...)".
554 TheCall->setArg(0, OrigArg0);
555 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Douglas Gregorcde01732009-05-19 22:10:17 +0000557 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
558 return false;
559
Chris Lattner1b9a0792007-12-20 00:26:33 +0000560 // If the common type isn't a real floating type, then the arguments were
561 // invalid for this operation.
562 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000563 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000564 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000565 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000566 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000567
Chris Lattner1b9a0792007-12-20 00:26:33 +0000568 return false;
569}
570
Eli Friedman9ac6f622009-08-31 20:06:00 +0000571/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isnan and
572/// friends. This is declared to take (...), so we have to check everything.
573bool Sema::SemaBuiltinUnaryFP(CallExpr *TheCall) {
574 if (TheCall->getNumArgs() < 1)
575 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
576 << 0 /*function call*/;
577 if (TheCall->getNumArgs() > 1)
Mike Stump1eb44332009-09-09 15:08:12 +0000578 return Diag(TheCall->getArg(1)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000579 diag::err_typecheck_call_too_many_args)
580 << 0 /*function call*/
581 << SourceRange(TheCall->getArg(1)->getLocStart(),
582 (*(TheCall->arg_end()-1))->getLocEnd());
583
584 Expr *OrigArg = TheCall->getArg(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Eli Friedman9ac6f622009-08-31 20:06:00 +0000586 if (OrigArg->isTypeDependent())
587 return false;
588
589 // This operation requires a floating-point number
590 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000591 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000592 diag::err_typecheck_call_invalid_unary_fp)
593 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Eli Friedman9ac6f622009-08-31 20:06:00 +0000595 return false;
596}
597
Eli Friedman6cfda232008-05-20 08:23:37 +0000598bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
599 // The signature for these builtins is exact; the only thing we need
600 // to check is that the argument is a constant.
601 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000602 if (!TheCall->getArg(0)->isTypeDependent() &&
603 !TheCall->getArg(0)->isValueDependent() &&
604 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000605 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Eli Friedman6cfda232008-05-20 08:23:37 +0000607 return false;
608}
609
Eli Friedmand38617c2008-05-14 19:38:39 +0000610/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
611// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000612Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000613 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000614 return ExprError(Diag(TheCall->getLocEnd(),
615 diag::err_typecheck_call_too_few_args)
616 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000617
Douglas Gregorcde01732009-05-19 22:10:17 +0000618 unsigned numElements = std::numeric_limits<unsigned>::max();
619 if (!TheCall->getArg(0)->isTypeDependent() &&
620 !TheCall->getArg(1)->isTypeDependent()) {
621 QualType FAType = TheCall->getArg(0)->getType();
622 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Douglas Gregorcde01732009-05-19 22:10:17 +0000624 if (!FAType->isVectorType() || !SAType->isVectorType()) {
625 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000626 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000627 TheCall->getArg(1)->getLocEnd());
628 return ExprError();
629 }
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Douglas Gregora4923eb2009-11-16 21:35:15 +0000631 if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000632 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000633 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000634 TheCall->getArg(1)->getLocEnd());
635 return ExprError();
636 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000637
John McCall183700f2009-09-21 23:43:11 +0000638 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorcde01732009-05-19 22:10:17 +0000639 if (TheCall->getNumArgs() != numElements+2) {
640 if (TheCall->getNumArgs() < numElements+2)
641 return ExprError(Diag(TheCall->getLocEnd(),
642 diag::err_typecheck_call_too_few_args)
643 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000644 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000645 diag::err_typecheck_call_too_many_args)
646 << 0 /*function call*/ << TheCall->getSourceRange());
647 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000648 }
649
650 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000651 if (TheCall->getArg(i)->isTypeDependent() ||
652 TheCall->getArg(i)->isValueDependent())
653 continue;
654
Eli Friedmand38617c2008-05-14 19:38:39 +0000655 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000656 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000657 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000658 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000659 << TheCall->getArg(i)->getSourceRange());
660
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000661 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000662 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000663 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000664 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000665 }
666
667 llvm::SmallVector<Expr*, 32> exprs;
668
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000669 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000670 exprs.push_back(TheCall->getArg(i));
671 TheCall->setArg(i, 0);
672 }
673
Nate Begemana88dc302009-08-12 02:10:25 +0000674 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
675 exprs.size(), exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000676 TheCall->getCallee()->getLocStart(),
677 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000678}
Chris Lattner30ce3442007-12-19 23:59:04 +0000679
Daniel Dunbar4493f792008-07-21 22:59:13 +0000680/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
681// This is declared to take (const void*, ...) and can take two
682// optional constant int args.
683bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000684 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000685
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000686 if (NumArgs > 3)
687 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000688 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000689
690 // Argument 0 is checked for us and the remaining arguments must be
691 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000692 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000693 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000694 if (Arg->isTypeDependent())
695 continue;
696
Daniel Dunbar4493f792008-07-21 22:59:13 +0000697 QualType RWType = Arg->getType();
698
John McCall183700f2009-09-21 23:43:11 +0000699 const BuiltinType *BT = RWType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000700 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000701 if (!BT || BT->getKind() != BuiltinType::Int)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000702 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000703 << Arg->getSourceRange();
Douglas Gregorcde01732009-05-19 22:10:17 +0000704
705 if (Arg->isValueDependent())
706 continue;
707
708 if (!Arg->isIntegerConstantExpr(Result, Context))
709 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
710 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Daniel Dunbar4493f792008-07-21 22:59:13 +0000712 // FIXME: gcc issues a warning and rewrites these to 0. These
713 // seems especially odd for the third argument since the default
714 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000715 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000716 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000717 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000718 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000719 } else {
720 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000721 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000722 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000723 }
724 }
725
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000726 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000727}
728
Chris Lattner21fb98e2009-09-23 06:06:36 +0000729/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
730/// operand must be an integer constant.
731bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
732 llvm::APSInt Result;
733 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
734 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
735 << TheCall->getArg(0)->getSourceRange();
736
737 return false;
738}
739
740
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000741/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
742/// int type). This simply type checks that type is one of the defined
743/// constants (0-3).
744bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
745 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000746 if (Arg->isTypeDependent())
747 return false;
748
Mike Stump1eb44332009-09-09 15:08:12 +0000749 QualType ArgType = Arg->getType();
John McCall183700f2009-09-21 23:43:11 +0000750 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000751 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000752 if (!BT || BT->getKind() != BuiltinType::Int)
753 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
754 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
755
756 if (Arg->isValueDependent())
757 return false;
758
759 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000760 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
761 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000762 }
763
764 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000765 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
766 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000767 }
768
769 return false;
770}
771
Eli Friedman586d6a82009-05-03 06:04:26 +0000772/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000773/// This checks that val is a constant 1.
774bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
775 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000776 if (Arg->isTypeDependent() || Arg->isValueDependent())
777 return false;
778
Eli Friedmand875fed2009-05-03 04:46:36 +0000779 llvm::APSInt Result(32);
780 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
781 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
782 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
783
784 return false;
785}
786
Ted Kremenekd30ef872009-01-12 23:09:09 +0000787// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000788bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
789 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000790 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000791 if (E->isTypeDependent() || E->isValueDependent())
792 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000793
794 switch (E->getStmtClass()) {
795 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000796 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000797 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000798 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000799 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000800 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000801 }
802
803 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000804 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000805 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000806 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000807 }
808
809 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000810 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000811 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000812 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000813 }
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Ted Kremenek082d9362009-03-20 21:35:28 +0000815 case Stmt::DeclRefExprClass: {
816 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Ted Kremenek082d9362009-03-20 21:35:28 +0000818 // As an exception, do not flag errors for variables binding to
819 // const string literals.
820 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
821 bool isConstant = false;
822 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000823
Ted Kremenek082d9362009-03-20 21:35:28 +0000824 if (const ArrayType *AT = Context.getAsArrayType(T)) {
825 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000826 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000827 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000828 PT->getPointeeType().isConstant(Context);
829 }
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Ted Kremenek082d9362009-03-20 21:35:28 +0000831 if (isConstant) {
832 const VarDecl *Def = 0;
833 if (const Expr *Init = VD->getDefinition(Def))
834 return SemaCheckStringLiteral(Init, TheCall,
835 HasVAListArg, format_idx, firstDataArg);
836 }
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Anders Carlssond966a552009-06-28 19:55:58 +0000838 // For vprintf* functions (i.e., HasVAListArg==true), we add a
839 // special check to see if the format string is a function parameter
840 // of the function calling the printf function. If the function
841 // has an attribute indicating it is a printf-like function, then we
842 // should suppress warnings concerning non-literals being used in a call
843 // to a vprintf function. For example:
844 //
845 // void
846 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
847 // va_list ap;
848 // va_start(ap, fmt);
849 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
850 // ...
851 //
852 //
853 // FIXME: We don't have full attribute support yet, so just check to see
854 // if the argument is a DeclRefExpr that references a parameter. We'll
855 // add proper support for checking the attribute later.
856 if (HasVAListArg)
857 if (isa<ParmVarDecl>(VD))
858 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000859 }
Mike Stump1eb44332009-09-09 15:08:12 +0000860
Ted Kremenek082d9362009-03-20 21:35:28 +0000861 return false;
862 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000863
Anders Carlsson8f031b32009-06-27 04:05:33 +0000864 case Stmt::CallExprClass: {
865 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000866 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000867 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
868 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
869 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000870 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000871 unsigned ArgIndex = FA->getFormatIdx();
872 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000873
874 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000875 format_idx, firstDataArg);
876 }
877 }
878 }
879 }
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Anders Carlsson8f031b32009-06-27 04:05:33 +0000881 return false;
882 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000883 case Stmt::ObjCStringLiteralClass:
884 case Stmt::StringLiteralClass: {
885 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Ted Kremenek082d9362009-03-20 21:35:28 +0000887 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000888 StrE = ObjCFExpr->getString();
889 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000890 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
Ted Kremenekd30ef872009-01-12 23:09:09 +0000892 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000893 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000894 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000895 return true;
896 }
Mike Stump1eb44332009-09-09 15:08:12 +0000897
Ted Kremenekd30ef872009-01-12 23:09:09 +0000898 return false;
899 }
Mike Stump1eb44332009-09-09 15:08:12 +0000900
Ted Kremenek082d9362009-03-20 21:35:28 +0000901 default:
902 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000903 }
904}
905
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000906void
Mike Stump1eb44332009-09-09 15:08:12 +0000907Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
908 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000909 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
910 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000911 const Expr *ArgExpr = TheCall->getArg(*i);
Douglas Gregorce940492009-09-25 04:25:58 +0000912 if (ArgExpr->isNullPointerConstant(Context,
913 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000914 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
915 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000916 }
917}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000918
Chris Lattner59907c42007-08-10 20:18:51 +0000919/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000920/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000921///
922/// HasVAListArg - A predicate indicating whether the printf-like
923/// function is passed an explicit va_arg argument (e.g., vprintf)
924///
925/// format_idx - The index into Args for the format string.
926///
927/// Improper format strings to functions in the printf family can be
928/// the source of bizarre bugs and very serious security holes. A
929/// good source of information is available in the following paper
930/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000931///
932/// FormatGuard: Automatic Protection From printf Format String
933/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000934///
935/// Functionality implemented:
936///
937/// We can statically check the following properties for string
938/// literal format strings for non v.*printf functions (where the
939/// arguments are passed directly):
940//
941/// (1) Are the number of format conversions equal to the number of
942/// data arguments?
943///
944/// (2) Does each format conversion correctly match the type of the
945/// corresponding data argument? (TODO)
946///
947/// Moreover, for all printf functions we can:
948///
949/// (3) Check for a missing format string (when not caught by type checking).
950///
951/// (4) Check for no-operation flags; e.g. using "#" with format
952/// conversion 'c' (TODO)
953///
954/// (5) Check the use of '%n', a major source of security holes.
955///
956/// (6) Check for malformed format conversions that don't specify anything.
957///
958/// (7) Check for empty format strings. e.g: printf("");
959///
960/// (8) Check that the format string is a wide literal.
961///
Ted Kremenek6d439592008-03-03 16:50:00 +0000962/// (9) Also check the arguments of functions with the __format__ attribute.
963/// (TODO).
964///
Ted Kremenek71895b92007-08-14 17:39:48 +0000965/// All of these checks can be done by parsing the format string.
966///
967/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000968void
Mike Stump1eb44332009-09-09 15:08:12 +0000969Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000970 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000971 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000972
Mike Stump1eb44332009-09-09 15:08:12 +0000973 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000974 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000975 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
976 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000977 return;
978 }
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Ted Kremenek082d9362009-03-20 21:35:28 +0000980 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Chris Lattner59907c42007-08-10 20:18:51 +0000982 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +0000983 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000984 // Dynamically generated format strings are difficult to
985 // automatically vet at compile time. Requiring that format strings
986 // are string literals: (1) permits the checking of format strings by
987 // the compiler and thereby (2) can practically remove the source of
988 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000989
Mike Stump1eb44332009-09-09 15:08:12 +0000990 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000991 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +0000992 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000993 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000994 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
995 firstDataArg))
996 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000997
Chris Lattner655f1412009-04-29 04:59:47 +0000998 // If there are no arguments specified, warn with -Wformat-security, otherwise
999 // warn only with -Wformat-nonliteral.
1000 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001001 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001002 diag::warn_printf_nonliteral_noargs)
1003 << OrigFormatExpr->getSourceRange();
1004 else
Mike Stump1eb44332009-09-09 15:08:12 +00001005 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001006 diag::warn_printf_nonliteral)
1007 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001008}
Ted Kremenek71895b92007-08-14 17:39:48 +00001009
Ted Kremenek082d9362009-03-20 21:35:28 +00001010void Sema::CheckPrintfString(const StringLiteral *FExpr,
1011 const Expr *OrigFormatExpr,
1012 const CallExpr *TheCall, bool HasVAListArg,
1013 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +00001014
Ted Kremenek082d9362009-03-20 21:35:28 +00001015 const ObjCStringLiteral *ObjCFExpr =
1016 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
1017
Ted Kremenek71895b92007-08-14 17:39:48 +00001018 // CHECK: is the format string a wide literal?
1019 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +00001020 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001021 diag::warn_printf_format_string_is_wide_literal)
1022 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001023 return;
1024 }
1025
1026 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +00001027 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +00001028
1029 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +00001030 unsigned StrLen = FExpr->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Ted Kremenek71895b92007-08-14 17:39:48 +00001032 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001033 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1034 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001035 return;
1036 }
1037
1038 // We process the format string using a binary state machine. The
1039 // current state is stored in CurrentState.
1040 enum {
1041 state_OrdChr,
1042 state_Conversion
1043 } CurrentState = state_OrdChr;
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Ted Kremenek71895b92007-08-14 17:39:48 +00001045 // numConversions - The number of conversions seen so far. This is
1046 // incremented as we traverse the format string.
1047 unsigned numConversions = 0;
1048
1049 // numDataArgs - The number of data arguments after the format
1050 // string. This can only be determined for non vprintf-like
1051 // functions. For those functions, this value is 1 (the sole
1052 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +00001053 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +00001054
1055 // Inspect the format string.
1056 unsigned StrIdx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Ted Kremenek71895b92007-08-14 17:39:48 +00001058 // LastConversionIdx - Index within the format string where we last saw
1059 // a '%' character that starts a new format conversion.
1060 unsigned LastConversionIdx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Chris Lattner925e60d2007-12-28 05:29:59 +00001062 for (; StrIdx < StrLen; ++StrIdx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Ted Kremenek71895b92007-08-14 17:39:48 +00001064 // Is the number of detected conversion conversions greater than
1065 // the number of matching data arguments? If so, stop.
1066 if (!HasVAListArg && numConversions > numDataArgs) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Ted Kremenek71895b92007-08-14 17:39:48 +00001068 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +00001069 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +00001070 // The string returned by getStrData() is not null-terminated,
1071 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +00001072 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001073 diag::warn_printf_format_string_contains_null_char)
1074 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001075 return;
1076 }
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Ted Kremenek71895b92007-08-14 17:39:48 +00001078 // Ordinary characters (not processing a format conversion).
1079 if (CurrentState == state_OrdChr) {
1080 if (Str[StrIdx] == '%') {
1081 CurrentState = state_Conversion;
1082 LastConversionIdx = StrIdx;
1083 }
1084 continue;
1085 }
1086
1087 // Seen '%'. Now processing a format conversion.
1088 switch (Str[StrIdx]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001089 // Handle dynamic precision or width specifier.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001090 case '*': {
1091 ++numConversions;
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001093 if (!HasVAListArg) {
1094 if (numConversions > numDataArgs) {
1095 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +00001096
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001097 if (Str[StrIdx-1] == '.')
1098 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
1099 << OrigFormatExpr->getSourceRange();
1100 else
1101 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
1102 << OrigFormatExpr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001103
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001104 // Don't do any more checking. We'll just emit spurious errors.
1105 return;
1106 }
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001108 // Perform type checking on width/precision specifier.
1109 const Expr *E = TheCall->getArg(format_idx+numConversions);
John McCall183700f2009-09-21 23:43:11 +00001110 if (const BuiltinType *BT = E->getType()->getAs<BuiltinType>())
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001111 if (BT->getKind() == BuiltinType::Int)
1112 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001113
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001114 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001116 if (Str[StrIdx-1] == '.')
1117 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1118 << E->getType() << E->getSourceRange();
1119 else
1120 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1121 << E->getType() << E->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001122
1123 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001124 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001125 }
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001127 // Characters which can terminate a format conversion
1128 // (e.g. "%d"). Characters that specify length modifiers or
1129 // other flags are handled by the default case below.
1130 //
Mike Stump1eb44332009-09-09 15:08:12 +00001131 // FIXME: additional checks will go into the following cases.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001132 case 'i':
1133 case 'd':
Mike Stump1eb44332009-09-09 15:08:12 +00001134 case 'o':
1135 case 'u':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001136 case 'x':
1137 case 'X':
1138 case 'D':
1139 case 'O':
1140 case 'U':
1141 case 'e':
1142 case 'E':
1143 case 'f':
1144 case 'F':
1145 case 'g':
1146 case 'G':
1147 case 'a':
1148 case 'A':
1149 case 'c':
1150 case 'C':
1151 case 'S':
1152 case 's':
Mike Stump1eb44332009-09-09 15:08:12 +00001153 case 'p':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001154 ++numConversions;
1155 CurrentState = state_OrdChr;
1156 break;
1157
Eli Friedmanb92abb42009-06-02 08:36:19 +00001158 case 'm':
1159 // FIXME: Warn in situations where this isn't supported!
1160 CurrentState = state_OrdChr;
1161 break;
1162
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001163 // CHECK: Are we using "%n"? Issue a warning.
1164 case 'n': {
1165 ++numConversions;
1166 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +00001167 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1168 LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001170 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001171 break;
1172 }
Mike Stump1eb44332009-09-09 15:08:12 +00001173
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001174 // Handle "%@"
1175 case '@':
1176 // %@ is allowed in ObjC format strings only.
Mike Stump1eb44332009-09-09 15:08:12 +00001177 if (ObjCFExpr != NULL)
1178 CurrentState = state_OrdChr;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001179 else {
1180 // Issue a warning: invalid format conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00001181 SourceLocation Loc =
Chris Lattner60800082009-02-18 17:49:48 +00001182 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001184 Diag(Loc, diag::warn_printf_invalid_conversion)
1185 << std::string(Str+LastConversionIdx,
1186 Str+std::min(LastConversionIdx+2, StrLen))
1187 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001188 }
1189 ++numConversions;
1190 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001191
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001192 // Handle "%%"
1193 case '%':
1194 // Sanity check: Was the first "%" character the previous one?
1195 // If not, we will assume that we have a malformed format
1196 // conversion, and that the current "%" character is the start
1197 // of a new conversion.
1198 if (StrIdx - LastConversionIdx == 1)
Mike Stump1eb44332009-09-09 15:08:12 +00001199 CurrentState = state_OrdChr;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001200 else {
1201 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001202 SourceLocation Loc =
1203 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001205 Diag(Loc, diag::warn_printf_invalid_conversion)
1206 << std::string(Str+LastConversionIdx, Str+StrIdx)
1207 << OrigFormatExpr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001209 // This conversion is broken. Advance to the next format
1210 // conversion.
1211 LastConversionIdx = StrIdx;
1212 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +00001213 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001214 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001216 default:
1217 // This case catches all other characters: flags, widths, etc.
1218 // We should eventually process those as well.
1219 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001220 }
1221 }
1222
1223 if (CurrentState == state_Conversion) {
1224 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001225 SourceLocation Loc =
1226 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001228 Diag(Loc, diag::warn_printf_invalid_conversion)
1229 << std::string(Str+LastConversionIdx,
1230 Str+std::min(LastConversionIdx+2, StrLen))
1231 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001232 return;
1233 }
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Ted Kremenek71895b92007-08-14 17:39:48 +00001235 if (!HasVAListArg) {
1236 // CHECK: Does the number of format conversions exceed the number
1237 // of data arguments?
1238 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +00001239 SourceLocation Loc =
1240 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001242 Diag(Loc, diag::warn_printf_insufficient_data_args)
1243 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001244 }
1245 // CHECK: Does the number of data arguments exceed the number of
1246 // format conversions in the format string?
1247 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +00001248 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001249 diag::warn_printf_too_many_data_args)
1250 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001251 }
1252}
Ted Kremenek06de2762007-08-17 16:46:58 +00001253
1254//===--- CHECK: Return Address of Stack Variable --------------------------===//
1255
1256static DeclRefExpr* EvalVal(Expr *E);
1257static DeclRefExpr* EvalAddr(Expr* E);
1258
1259/// CheckReturnStackAddr - Check if a return statement returns the address
1260/// of a stack variable.
1261void
1262Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1263 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001264
Ted Kremenek06de2762007-08-17 16:46:58 +00001265 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001266 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001267 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001268 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001269 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Steve Naroffc50a4a52008-09-16 22:25:10 +00001271 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001272 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001273
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001274 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001275 if (C->hasBlockDeclRefExprs())
1276 Diag(C->getLocStart(), diag::err_ret_local_block)
1277 << C->getSourceRange();
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001278
1279 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1280 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1281 << ALE->getSourceRange();
1282
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001283 } else if (lhsType->isReferenceType()) {
1284 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001285 // Check for a reference to the stack
1286 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001287 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001288 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001289 }
1290}
1291
1292/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1293/// check if the expression in a return statement evaluates to an address
1294/// to a location on the stack. The recursion is used to traverse the
1295/// AST of the return expression, with recursion backtracking when we
1296/// encounter a subexpression that (1) clearly does not lead to the address
1297/// of a stack variable or (2) is something we cannot determine leads to
1298/// the address of a stack variable based on such local checking.
1299///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001300/// EvalAddr processes expressions that are pointers that are used as
1301/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001302/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001303/// the refers to a stack variable.
1304///
1305/// This implementation handles:
1306///
1307/// * pointer-to-pointer casts
1308/// * implicit conversions from array references to pointers
1309/// * taking the address of fields
1310/// * arbitrary interplay between "&" and "*" operators
1311/// * pointer arithmetic from an address of a stack variable
1312/// * taking the address of an array element where the array is on the stack
1313static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001314 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001315 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001316 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001317 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001318 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Ted Kremenek06de2762007-08-17 16:46:58 +00001320 // Our "symbolic interpreter" is just a dispatch off the currently
1321 // viewed AST node. We then recursively traverse the AST by calling
1322 // EvalAddr and EvalVal appropriately.
1323 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001324 case Stmt::ParenExprClass:
1325 // Ignore parentheses.
1326 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001327
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001328 case Stmt::UnaryOperatorClass: {
1329 // The only unary operator that make sense to handle here
1330 // is AddrOf. All others don't make sense as pointers.
1331 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001333 if (U->getOpcode() == UnaryOperator::AddrOf)
1334 return EvalVal(U->getSubExpr());
1335 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001336 return NULL;
1337 }
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001339 case Stmt::BinaryOperatorClass: {
1340 // Handle pointer arithmetic. All other binary operators are not valid
1341 // in this context.
1342 BinaryOperator *B = cast<BinaryOperator>(E);
1343 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001345 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1346 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001347
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001348 Expr *Base = B->getLHS();
1349
1350 // Determine which argument is the real pointer base. It could be
1351 // the RHS argument instead of the LHS.
1352 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001353
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001354 assert (Base->getType()->isPointerType());
1355 return EvalAddr(Base);
1356 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001357
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001358 // For conditional operators we need to see if either the LHS or RHS are
1359 // valid DeclRefExpr*s. If one of them is valid, we return it.
1360 case Stmt::ConditionalOperatorClass: {
1361 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001363 // Handle the GNU extension for missing LHS.
1364 if (Expr *lhsExpr = C->getLHS())
1365 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1366 return LHS;
1367
1368 return EvalAddr(C->getRHS());
1369 }
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Ted Kremenek54b52742008-08-07 00:49:01 +00001371 // For casts, we need to handle conversions from arrays to
1372 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001373 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001374 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001375 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001376 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001377 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Steve Naroffdd972f22008-09-05 22:11:13 +00001379 if (SubExpr->getType()->isPointerType() ||
1380 SubExpr->getType()->isBlockPointerType() ||
1381 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001382 return EvalAddr(SubExpr);
1383 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001384 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001385 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001386 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001387 }
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001389 // C++ casts. For dynamic casts, static casts, and const casts, we
1390 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001391 // through the cast. In the case the dynamic cast doesn't fail (and
1392 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001393 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001394 // FIXME: The comment about is wrong; we're not always converting
1395 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001396 // handle references to objects.
1397 case Stmt::CXXStaticCastExprClass:
1398 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001399 case Stmt::CXXConstCastExprClass:
1400 case Stmt::CXXReinterpretCastExprClass: {
1401 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001402 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001403 return EvalAddr(S);
1404 else
1405 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001406 }
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001408 // Everything else: we simply don't reason about them.
1409 default:
1410 return NULL;
1411 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001412}
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Ted Kremenek06de2762007-08-17 16:46:58 +00001414
1415/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1416/// See the comments for EvalAddr for more details.
1417static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001419 // We should only be called for evaluating non-pointer expressions, or
1420 // expressions with a pointer type that are not used as references but instead
1421 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Ted Kremenek06de2762007-08-17 16:46:58 +00001423 // Our "symbolic interpreter" is just a dispatch off the currently
1424 // viewed AST node. We then recursively traverse the AST by calling
1425 // EvalAddr and EvalVal appropriately.
1426 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001427 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001428 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1429 // at code that refers to a variable's name. We check if it has local
1430 // storage within the function, and if so, return the expression.
1431 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Ted Kremenek06de2762007-08-17 16:46:58 +00001433 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001434 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1435
Ted Kremenek06de2762007-08-17 16:46:58 +00001436 return NULL;
1437 }
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Ted Kremenek06de2762007-08-17 16:46:58 +00001439 case Stmt::ParenExprClass:
1440 // Ignore parentheses.
1441 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001442
Ted Kremenek06de2762007-08-17 16:46:58 +00001443 case Stmt::UnaryOperatorClass: {
1444 // The only unary operator that make sense to handle here
1445 // is Deref. All others don't resolve to a "name." This includes
1446 // handling all sorts of rvalues passed to a unary operator.
1447 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Ted Kremenek06de2762007-08-17 16:46:58 +00001449 if (U->getOpcode() == UnaryOperator::Deref)
1450 return EvalAddr(U->getSubExpr());
1451
1452 return NULL;
1453 }
Mike Stump1eb44332009-09-09 15:08:12 +00001454
Ted Kremenek06de2762007-08-17 16:46:58 +00001455 case Stmt::ArraySubscriptExprClass: {
1456 // Array subscripts are potential references to data on the stack. We
1457 // retrieve the DeclRefExpr* for the array variable if it indeed
1458 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001459 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001460 }
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Ted Kremenek06de2762007-08-17 16:46:58 +00001462 case Stmt::ConditionalOperatorClass: {
1463 // For conditional operators we need to see if either the LHS or RHS are
1464 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1465 ConditionalOperator *C = cast<ConditionalOperator>(E);
1466
Anders Carlsson39073232007-11-30 19:04:31 +00001467 // Handle the GNU extension for missing LHS.
1468 if (Expr *lhsExpr = C->getLHS())
1469 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1470 return LHS;
1471
1472 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001473 }
Mike Stump1eb44332009-09-09 15:08:12 +00001474
Ted Kremenek06de2762007-08-17 16:46:58 +00001475 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001476 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001477 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Ted Kremenek06de2762007-08-17 16:46:58 +00001479 // Check for indirect access. We only want direct field accesses.
1480 if (!M->isArrow())
1481 return EvalVal(M->getBase());
1482 else
1483 return NULL;
1484 }
Mike Stump1eb44332009-09-09 15:08:12 +00001485
Ted Kremenek06de2762007-08-17 16:46:58 +00001486 // Everything else: we simply don't reason about them.
1487 default:
1488 return NULL;
1489 }
1490}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001491
1492//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1493
1494/// Check for comparisons of floating point operands using != and ==.
1495/// Issue a warning if these are no self-comparisons, as they are not likely
1496/// to do what the programmer intended.
1497void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1498 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001500 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001501 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001502
1503 // Special case: check for x == x (which is OK).
1504 // Do not emit warnings for such cases.
1505 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1506 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1507 if (DRL->getDecl() == DRR->getDecl())
1508 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001509
1510
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001511 // Special case: check for comparisons against literals that can be exactly
1512 // represented by APFloat. In such cases, do not emit a warning. This
1513 // is a heuristic: often comparison against such literals are used to
1514 // detect if a value in a variable has not changed. This clearly can
1515 // lead to false negatives.
1516 if (EmitWarning) {
1517 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1518 if (FLL->isExact())
1519 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001520 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001521 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1522 if (FLR->isExact())
1523 EmitWarning = false;
1524 }
1525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001527 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001528 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001529 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001530 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001531 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Sebastian Redl0eb23302009-01-19 00:08:26 +00001533 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001534 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001535 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001536 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001538 // Emit the diagnostic.
1539 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001540 Diag(loc, diag::warn_floatingpoint_eq)
1541 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001542}