blob: 5f124e4572239b81a1141fdba20bcdc53cd5d157 [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"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000019#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000020#include "clang/AST/ExprObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000021#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022#include "clang/Lex/Preprocessor.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000023#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000024using namespace clang;
25
Chris Lattner60800082009-02-18 17:49:48 +000026/// getLocationOfStringLiteralByte - Return a source location that points to the
27/// specified byte of the specified string literal.
28///
29/// Strings are amazingly complex. They can be formed from multiple tokens and
30/// can have escape sequences in them in addition to the usual trigraph and
31/// escaped newline business. This routine handles this complexity.
32///
33SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
34 unsigned ByteNo) const {
35 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000036
Chris Lattner60800082009-02-18 17:49:48 +000037 // Loop over all of the tokens in this string until we find the one that
38 // contains the byte we're looking for.
39 unsigned TokNo = 0;
40 while (1) {
41 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
42 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044 // Get the spelling of the string so that we can get the data that makes up
45 // the string literal, not the identifier for the macro it is potentially
46 // expanded through.
47 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
48
49 // Re-lex the token to get its length and original spelling.
50 std::pair<FileID, unsigned> LocInfo =
51 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
52 std::pair<const char *,const char *> Buffer =
53 SourceMgr.getBufferData(LocInfo.first);
54 const char *StrData = Buffer.first+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000055
Chris Lattner60800082009-02-18 17:49:48 +000056 // Create a langops struct and enable trigraphs. This is sufficient for
57 // relexing tokens.
58 LangOptions LangOpts;
59 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner60800082009-02-18 17:49:48 +000061 // Create a lexer starting at the beginning of this token.
62 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
63 Buffer.second);
64 Token TheTok;
65 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattner443e53c2009-02-18 19:26:42 +000067 // Use the StringLiteralParser to compute the length of the string in bytes.
68 StringLiteralParser SLP(&TheTok, 1, PP);
69 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattner2197c962009-02-18 18:52:52 +000071 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000072 if (ByteNo < TokNumBytes ||
73 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000074 unsigned Offset =
Chris Lattner719e6152009-02-18 19:21:10 +000075 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
Mike Stump1eb44332009-09-09 15:08:12 +000076
Chris Lattner719e6152009-02-18 19:21:10 +000077 // Now that we know the offset of the token in the spelling, use the
78 // preprocessor to get the offset in the original source.
79 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000080 }
Mike Stump1eb44332009-09-09 15:08:12 +000081
Chris Lattner60800082009-02-18 17:49:48 +000082 // Move to the next string token.
83 ++TokNo;
84 ByteNo -= TokNumBytes;
85 }
86}
87
Ryan Flynn4403a5e2009-08-06 03:00:50 +000088/// CheckablePrintfAttr - does a function call have a "printf" attribute
89/// and arguments that merit checking?
90bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
91 if (Format->getType() == "printf") return true;
92 if (Format->getType() == "printf0") {
93 // printf0 allows null "format" string; if so don't check format/args
94 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000095 // Does the index refer to the implicit object argument?
96 if (isa<CXXMemberCallExpr>(TheCall)) {
97 if (format_idx == 0)
98 return false;
99 --format_idx;
100 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000101 if (format_idx < TheCall->getNumArgs()) {
102 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Douglas Gregorce940492009-09-25 04:25:58 +0000103 if (!Format->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000104 return true;
105 }
106 }
107 return false;
108}
Chris Lattner60800082009-02-18 17:49:48 +0000109
Sebastian Redl0eb23302009-01-19 00:08:26 +0000110Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000111Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000112 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000113
Anders Carlssond406bf02009-08-16 01:56:34 +0000114 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000115 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000116 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000117 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000118 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000119 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000120 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000121 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000122 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000123 if (SemaBuiltinVAStart(TheCall))
124 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000125 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000126 case Builtin::BI__builtin_isgreater:
127 case Builtin::BI__builtin_isgreaterequal:
128 case Builtin::BI__builtin_isless:
129 case Builtin::BI__builtin_islessequal:
130 case Builtin::BI__builtin_islessgreater:
131 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 if (SemaBuiltinUnorderedCompare(TheCall))
133 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000134 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000135 case Builtin::BI__builtin_isfinite:
136 case Builtin::BI__builtin_isinf:
137 case Builtin::BI__builtin_isinf_sign:
138 case Builtin::BI__builtin_isnan:
139 case Builtin::BI__builtin_isnormal:
140 if (SemaBuiltinUnaryFP(TheCall))
141 return ExprError();
142 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000143 case Builtin::BI__builtin_return_address:
144 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinStackAddress(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Chris Lattner21fb98e2009-09-23 06:06:36 +0000148 case Builtin::BI__builtin_eh_return_data_regno:
149 if (SemaBuiltinEHReturnDataRegNo(TheCall))
150 return ExprError();
151 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000152 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000153 return SemaBuiltinShuffleVector(TheCall);
154 // TheCall will be freed by the smart pointer here, but that's fine, since
155 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000156 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000157 if (SemaBuiltinPrefetch(TheCall))
158 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000159 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000160 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161 if (SemaBuiltinObjectSize(TheCall))
162 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000163 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000164 case Builtin::BI__builtin_longjmp:
165 if (SemaBuiltinLongjmp(TheCall))
166 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000167 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000168 case Builtin::BI__sync_fetch_and_add:
169 case Builtin::BI__sync_fetch_and_sub:
170 case Builtin::BI__sync_fetch_and_or:
171 case Builtin::BI__sync_fetch_and_and:
172 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000173 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000174 case Builtin::BI__sync_add_and_fetch:
175 case Builtin::BI__sync_sub_and_fetch:
176 case Builtin::BI__sync_and_and_fetch:
177 case Builtin::BI__sync_or_and_fetch:
178 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000179 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000180 case Builtin::BI__sync_val_compare_and_swap:
181 case Builtin::BI__sync_bool_compare_and_swap:
182 case Builtin::BI__sync_lock_test_and_set:
183 case Builtin::BI__sync_lock_release:
184 if (SemaBuiltinAtomicOverloaded(TheCall))
185 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000186 break;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000187 }
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Anders Carlssond406bf02009-08-16 01:56:34 +0000189 return move(TheCallResult);
190}
Daniel Dunbarde454282008-10-02 18:44:07 +0000191
Anders Carlssond406bf02009-08-16 01:56:34 +0000192/// CheckFunctionCall - Check a direct function call for various correctness
193/// and safety properties not strictly enforced by the C type system.
194bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
195 // Get the IdentifierInfo* for the called function.
196 IdentifierInfo *FnInfo = FDecl->getIdentifier();
197
198 // None of the checks below are needed for functions that don't have
199 // simple names (e.g., C++ conversion functions).
200 if (!FnInfo)
201 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000202
Daniel Dunbarde454282008-10-02 18:44:07 +0000203 // FIXME: This mechanism should be abstracted to be less fragile and
204 // more efficient. For example, just map function ids to custom
205 // handlers.
206
Chris Lattner59907c42007-08-10 20:18:51 +0000207 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000208 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000209 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000210 bool HasVAListArg = Format->getFirstArg() == 0;
211 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000212 if (const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +0000213 = FDecl->getType()->getAs<FunctionProtoType>())
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000214 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000215 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000216 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000217 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000218 }
Chris Lattner59907c42007-08-10 20:18:51 +0000219 }
Mike Stump1eb44332009-09-09 15:08:12 +0000220
221 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000222 NonNull = NonNull->getNext<NonNullAttr>())
223 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000224
Anders Carlssond406bf02009-08-16 01:56:34 +0000225 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000226}
227
Anders Carlssond406bf02009-08-16 01:56:34 +0000228bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000229 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000230 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000231 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000232 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000234 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
235 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000236 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000238 QualType Ty = V->getType();
239 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000240 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Anders Carlssond406bf02009-08-16 01:56:34 +0000242 if (!CheckablePrintfAttr(Format, TheCall))
243 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Anders Carlssond406bf02009-08-16 01:56:34 +0000245 bool HasVAListArg = Format->getFirstArg() == 0;
246 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000247 const FunctionType *FT =
John McCall183700f2009-09-21 23:43:11 +0000248 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Anders Carlssond406bf02009-08-16 01:56:34 +0000249 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
250 HasVAListArg = !Proto->isVariadic();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000251 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000252 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
253 HasVAListArg ? 0 : Format->getFirstArg() - 1);
254
255 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000256}
257
Chris Lattner5caa3702009-05-08 06:58:22 +0000258/// SemaBuiltinAtomicOverloaded - We have a call to a function like
259/// __sync_fetch_and_add, which is an overloaded function based on the pointer
260/// type of its first argument. The main ActOnCallExpr routines have already
261/// promoted the types of arguments because all of these calls are prototyped as
262/// void(...).
263///
264/// This function goes through and does final semantic checking for these
265/// builtins,
266bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
267 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
268 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
269
270 // Ensure that we have at least one argument to do type inference from.
271 if (TheCall->getNumArgs() < 1)
272 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
273 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000274
Chris Lattner5caa3702009-05-08 06:58:22 +0000275 // Inspect the first argument of the atomic builtin. This should always be
276 // a pointer type, whose element is an integral scalar or pointer type.
277 // Because it is a pointer type, we don't have to worry about any implicit
278 // casts here.
279 Expr *FirstArg = TheCall->getArg(0);
280 if (!FirstArg->getType()->isPointerType())
281 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
282 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000283
Ted Kremenek6217b802009-07-29 21:53:49 +0000284 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000285 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000286 !ValType->isBlockPointerType())
287 return Diag(DRE->getLocStart(),
288 diag::err_atomic_builtin_must_be_pointer_intptr)
289 << FirstArg->getType() << FirstArg->getSourceRange();
290
291 // We need to figure out which concrete builtin this maps onto. For example,
292 // __sync_fetch_and_add with a 2 byte object turns into
293 // __sync_fetch_and_add_2.
294#define BUILTIN_ROW(x) \
295 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
296 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Chris Lattner5caa3702009-05-08 06:58:22 +0000298 static const unsigned BuiltinIndices[][5] = {
299 BUILTIN_ROW(__sync_fetch_and_add),
300 BUILTIN_ROW(__sync_fetch_and_sub),
301 BUILTIN_ROW(__sync_fetch_and_or),
302 BUILTIN_ROW(__sync_fetch_and_and),
303 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000304 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattner5caa3702009-05-08 06:58:22 +0000306 BUILTIN_ROW(__sync_add_and_fetch),
307 BUILTIN_ROW(__sync_sub_and_fetch),
308 BUILTIN_ROW(__sync_and_and_fetch),
309 BUILTIN_ROW(__sync_or_and_fetch),
310 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000311 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Chris Lattner5caa3702009-05-08 06:58:22 +0000313 BUILTIN_ROW(__sync_val_compare_and_swap),
314 BUILTIN_ROW(__sync_bool_compare_and_swap),
315 BUILTIN_ROW(__sync_lock_test_and_set),
316 BUILTIN_ROW(__sync_lock_release)
317 };
Mike Stump1eb44332009-09-09 15:08:12 +0000318#undef BUILTIN_ROW
319
Chris Lattner5caa3702009-05-08 06:58:22 +0000320 // Determine the index of the size.
321 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000322 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000323 case 1: SizeIndex = 0; break;
324 case 2: SizeIndex = 1; break;
325 case 4: SizeIndex = 2; break;
326 case 8: SizeIndex = 3; break;
327 case 16: SizeIndex = 4; break;
328 default:
329 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
330 << FirstArg->getType() << FirstArg->getSourceRange();
331 }
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattner5caa3702009-05-08 06:58:22 +0000333 // Each of these builtins has one pointer argument, followed by some number of
334 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
335 // that we ignore. Find out which row of BuiltinIndices to read from as well
336 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000337 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000338 unsigned BuiltinIndex, NumFixed = 1;
339 switch (BuiltinID) {
340 default: assert(0 && "Unknown overloaded atomic builtin!");
341 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
342 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
343 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
344 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
345 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000346 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Chris Lattnereebd9d22009-05-13 04:37:52 +0000348 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
349 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
350 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
351 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
352 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
353 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Chris Lattner5caa3702009-05-08 06:58:22 +0000355 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000356 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000357 NumFixed = 2;
358 break;
359 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000360 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000361 NumFixed = 2;
362 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000363 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000364 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000365 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000366 NumFixed = 0;
367 break;
368 }
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Chris Lattner5caa3702009-05-08 06:58:22 +0000370 // Now that we know how many fixed arguments we expect, first check that we
371 // have at least that many.
372 if (TheCall->getNumArgs() < 1+NumFixed)
373 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
374 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000375
376
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000377 // Get the decl for the concrete builtin from this, we can tell what the
378 // concrete integer type we should convert to is.
379 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
380 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
381 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000382 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000383 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
384 TUScope, false, DRE->getLocStart()));
385 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000386 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000387 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000389 // If the first type needs to be converted (e.g. void** -> int*), do it now.
390 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000391 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000392 TheCall->setArg(0, FirstArg);
393 }
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattner5caa3702009-05-08 06:58:22 +0000395 // Next, walk the valid ones promoting to the right type.
396 for (unsigned i = 0; i != NumFixed; ++i) {
397 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Chris Lattner5caa3702009-05-08 06:58:22 +0000399 // If the argument is an implicit cast, then there was a promotion due to
400 // "...", just remove it now.
401 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
402 Arg = ICE->getSubExpr();
403 ICE->setSubExpr(0);
404 ICE->Destroy(Context);
405 TheCall->setArg(i+1, Arg);
406 }
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Chris Lattner5caa3702009-05-08 06:58:22 +0000408 // GCC does an implicit conversion to the pointer or integer ValType. This
409 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000410 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000411 CXXMethodDecl *ConversionDecl = 0;
412 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
413 ConversionDecl))
Chris Lattner5caa3702009-05-08 06:58:22 +0000414 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattner5caa3702009-05-08 06:58:22 +0000416 // Okay, we have something that *can* be converted to the right type. Check
417 // to see if there is a potentially weird extension going on here. This can
418 // happen when you do an atomic operation on something like an char* and
419 // pass in 42. The 42 gets converted to char. This is even more strange
420 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000421 // FIXME: Do this check.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000422 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000423 TheCall->setArg(i+1, Arg);
424 }
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Chris Lattner5caa3702009-05-08 06:58:22 +0000426 // Switch the DeclRefExpr to refer to the new decl.
427 DRE->setDecl(NewBuiltinDecl);
428 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Chris Lattner5caa3702009-05-08 06:58:22 +0000430 // Set the callee in the CallExpr.
431 // FIXME: This leaks the original parens and implicit casts.
432 Expr *PromotedCall = DRE;
433 UsualUnaryConversions(PromotedCall);
434 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Chris Lattner5caa3702009-05-08 06:58:22 +0000436
437 // Change the result type of the call to match the result type of the decl.
438 TheCall->setType(NewBuiltinDecl->getResultType());
439 return false;
440}
441
442
Chris Lattner69039812009-02-18 06:01:06 +0000443/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000444/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000445/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000446/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000447/// belong to the input codeset UTF-8"
448/// Note: It might also make sense to do the UTF-16 conversion here (would
449/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000450bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000451 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000452 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
453
454 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000455 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
456 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000457 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000458 }
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Daniel Dunbarf015b032009-09-22 10:03:52 +0000460 const char *Data = Literal->getStrData();
461 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Daniel Dunbarf015b032009-09-22 10:03:52 +0000463 for (unsigned i = 0; i < Length; ++i) {
464 if (!Data[i]) {
465 Diag(getLocationOfStringLiteralByte(Literal, i),
466 diag::warn_cfstring_literal_contains_nul_character)
467 << Arg->getSourceRange();
468 break;
469 }
470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000472 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000473}
474
Chris Lattnerc27c6652007-12-20 00:05:45 +0000475/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
476/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000477bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
478 Expr *Fn = TheCall->getCallee();
479 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000480 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000481 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000482 << 0 /*function call*/ << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000483 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000484 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000485 return true;
486 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000487
488 if (TheCall->getNumArgs() < 2) {
489 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
490 << 0 /*function call*/;
491 }
492
Chris Lattnerc27c6652007-12-20 00:05:45 +0000493 // Determine whether the current function is variadic or not.
494 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000495 if (CurBlock)
496 isVariadic = CurBlock->isVariadic;
497 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000498 if (FunctionProtoType* FTP =
499 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000500 isVariadic = FTP->isVariadic();
501 else
502 isVariadic = false;
503 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000504 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000505 }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Chris Lattnerc27c6652007-12-20 00:05:45 +0000507 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000508 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
509 return true;
510 }
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Chris Lattner30ce3442007-12-19 23:59:04 +0000512 // Verify that the second argument to the builtin is the last argument of the
513 // current function or method.
514 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000515 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Anders Carlsson88cf2262008-02-11 04:20:54 +0000517 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
518 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000519 // FIXME: This isn't correct for methods (results in bogus warning).
520 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000521 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000522 if (CurBlock)
523 LastArg = *(CurBlock->TheDecl->param_end()-1);
524 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000525 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000526 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000527 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000528 SecondArgIsLastNamedArgument = PV == LastArg;
529 }
530 }
Mike Stump1eb44332009-09-09 15:08:12 +0000531
Chris Lattner30ce3442007-12-19 23:59:04 +0000532 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000533 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000534 diag::warn_second_parameter_of_va_start_not_last_named_argument);
535 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000536}
Chris Lattner30ce3442007-12-19 23:59:04 +0000537
Chris Lattner1b9a0792007-12-20 00:26:33 +0000538/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
539/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000540bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
541 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000542 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
543 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000544 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000545 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000546 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000547 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000548 << SourceRange(TheCall->getArg(2)->getLocStart(),
549 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Chris Lattner925e60d2007-12-28 05:29:59 +0000551 Expr *OrigArg0 = TheCall->getArg(0);
552 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000553
Chris Lattner1b9a0792007-12-20 00:26:33 +0000554 // Do standard promotions between the two arguments, returning their common
555 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000556 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000557
558 // Make sure any conversions are pushed back into the call; this is
559 // type safe since unordered compare builtins are declared as "_Bool
560 // foo(...)".
561 TheCall->setArg(0, OrigArg0);
562 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Douglas Gregorcde01732009-05-19 22:10:17 +0000564 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
565 return false;
566
Chris Lattner1b9a0792007-12-20 00:26:33 +0000567 // If the common type isn't a real floating type, then the arguments were
568 // invalid for this operation.
569 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000570 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000571 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000572 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000573 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Chris Lattner1b9a0792007-12-20 00:26:33 +0000575 return false;
576}
577
Eli Friedman9ac6f622009-08-31 20:06:00 +0000578/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isnan and
579/// friends. This is declared to take (...), so we have to check everything.
580bool Sema::SemaBuiltinUnaryFP(CallExpr *TheCall) {
581 if (TheCall->getNumArgs() < 1)
582 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
583 << 0 /*function call*/;
584 if (TheCall->getNumArgs() > 1)
Mike Stump1eb44332009-09-09 15:08:12 +0000585 return Diag(TheCall->getArg(1)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000586 diag::err_typecheck_call_too_many_args)
587 << 0 /*function call*/
588 << SourceRange(TheCall->getArg(1)->getLocStart(),
589 (*(TheCall->arg_end()-1))->getLocEnd());
590
591 Expr *OrigArg = TheCall->getArg(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Eli Friedman9ac6f622009-08-31 20:06:00 +0000593 if (OrigArg->isTypeDependent())
594 return false;
595
596 // This operation requires a floating-point number
597 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000598 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000599 diag::err_typecheck_call_invalid_unary_fp)
600 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Eli Friedman9ac6f622009-08-31 20:06:00 +0000602 return false;
603}
604
Eli Friedman6cfda232008-05-20 08:23:37 +0000605bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
606 // The signature for these builtins is exact; the only thing we need
607 // to check is that the argument is a constant.
608 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000609 if (!TheCall->getArg(0)->isTypeDependent() &&
610 !TheCall->getArg(0)->isValueDependent() &&
611 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000612 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Eli Friedman6cfda232008-05-20 08:23:37 +0000614 return false;
615}
616
Eli Friedmand38617c2008-05-14 19:38:39 +0000617/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
618// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000619Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000620 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000621 return ExprError(Diag(TheCall->getLocEnd(),
622 diag::err_typecheck_call_too_few_args)
623 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000624
Douglas Gregorcde01732009-05-19 22:10:17 +0000625 unsigned numElements = std::numeric_limits<unsigned>::max();
626 if (!TheCall->getArg(0)->isTypeDependent() &&
627 !TheCall->getArg(1)->isTypeDependent()) {
628 QualType FAType = TheCall->getArg(0)->getType();
629 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Douglas Gregorcde01732009-05-19 22:10:17 +0000631 if (!FAType->isVectorType() || !SAType->isVectorType()) {
632 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_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 }
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Douglas Gregora4923eb2009-11-16 21:35:15 +0000638 if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000639 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000640 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000641 TheCall->getArg(1)->getLocEnd());
642 return ExprError();
643 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000644
John McCall183700f2009-09-21 23:43:11 +0000645 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorcde01732009-05-19 22:10:17 +0000646 if (TheCall->getNumArgs() != numElements+2) {
647 if (TheCall->getNumArgs() < numElements+2)
648 return ExprError(Diag(TheCall->getLocEnd(),
649 diag::err_typecheck_call_too_few_args)
650 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000651 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000652 diag::err_typecheck_call_too_many_args)
653 << 0 /*function call*/ << TheCall->getSourceRange());
654 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000655 }
656
657 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000658 if (TheCall->getArg(i)->isTypeDependent() ||
659 TheCall->getArg(i)->isValueDependent())
660 continue;
661
Eli Friedmand38617c2008-05-14 19:38:39 +0000662 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000663 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000664 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000665 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000666 << TheCall->getArg(i)->getSourceRange());
667
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000668 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000669 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000670 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000671 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000672 }
673
674 llvm::SmallVector<Expr*, 32> exprs;
675
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000676 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000677 exprs.push_back(TheCall->getArg(i));
678 TheCall->setArg(i, 0);
679 }
680
Nate Begemana88dc302009-08-12 02:10:25 +0000681 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
682 exprs.size(), exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000683 TheCall->getCallee()->getLocStart(),
684 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000685}
Chris Lattner30ce3442007-12-19 23:59:04 +0000686
Daniel Dunbar4493f792008-07-21 22:59:13 +0000687/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
688// This is declared to take (const void*, ...) and can take two
689// optional constant int args.
690bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000691 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000692
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000693 if (NumArgs > 3)
694 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000695 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000696
697 // Argument 0 is checked for us and the remaining arguments must be
698 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000699 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000700 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000701 if (Arg->isTypeDependent())
702 continue;
703
Eli Friedman9aef7262009-12-04 00:30:06 +0000704 if (!Arg->getType()->isIntegralType())
705 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000706 << Arg->getSourceRange();
Douglas Gregorcde01732009-05-19 22:10:17 +0000707
Eli Friedman9aef7262009-12-04 00:30:06 +0000708 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast);
709 TheCall->setArg(i, Arg);
710
Douglas Gregorcde01732009-05-19 22:10:17 +0000711 if (Arg->isValueDependent())
712 continue;
713
Eli Friedman9aef7262009-12-04 00:30:06 +0000714 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000715 if (!Arg->isIntegerConstantExpr(Result, Context))
Eli Friedman9aef7262009-12-04 00:30:06 +0000716 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice)
Douglas Gregorcde01732009-05-19 22:10:17 +0000717 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Daniel Dunbar4493f792008-07-21 22:59:13 +0000719 // FIXME: gcc issues a warning and rewrites these to 0. These
720 // seems especially odd for the third argument since the default
721 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000722 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000723 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000724 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000725 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000726 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000727 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000728 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000729 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000730 }
731 }
732
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000733 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000734}
735
Chris Lattner21fb98e2009-09-23 06:06:36 +0000736/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
737/// operand must be an integer constant.
738bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
739 llvm::APSInt Result;
740 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
741 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
742 << TheCall->getArg(0)->getSourceRange();
743
744 return false;
745}
746
747
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000748/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
749/// int type). This simply type checks that type is one of the defined
750/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000751// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000752bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
753 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000754 if (Arg->isTypeDependent())
755 return false;
756
Mike Stump1eb44332009-09-09 15:08:12 +0000757 QualType ArgType = Arg->getType();
John McCall183700f2009-09-21 23:43:11 +0000758 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000759 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000760 if (!BT || BT->getKind() != BuiltinType::Int)
761 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
762 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
763
764 if (Arg->isValueDependent())
765 return false;
766
767 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000768 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
769 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000770 }
771
772 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000773 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
774 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000775 }
776
777 return false;
778}
779
Eli Friedman586d6a82009-05-03 06:04:26 +0000780/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000781/// This checks that val is a constant 1.
782bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
783 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000784 if (Arg->isTypeDependent() || Arg->isValueDependent())
785 return false;
786
Eli Friedmand875fed2009-05-03 04:46:36 +0000787 llvm::APSInt Result(32);
788 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
789 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
790 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
791
792 return false;
793}
794
Ted Kremenekd30ef872009-01-12 23:09:09 +0000795// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000796bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
797 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000798 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000799 if (E->isTypeDependent() || E->isValueDependent())
800 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000801
802 switch (E->getStmtClass()) {
803 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000804 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000805 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000806 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000807 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000808 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000809 }
810
811 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000812 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000813 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000814 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000815 }
816
817 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000818 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000819 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000820 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000821 }
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Ted Kremenek082d9362009-03-20 21:35:28 +0000823 case Stmt::DeclRefExprClass: {
824 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Ted Kremenek082d9362009-03-20 21:35:28 +0000826 // As an exception, do not flag errors for variables binding to
827 // const string literals.
828 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
829 bool isConstant = false;
830 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000831
Ted Kremenek082d9362009-03-20 21:35:28 +0000832 if (const ArrayType *AT = Context.getAsArrayType(T)) {
833 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000834 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000835 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000836 PT->getPointeeType().isConstant(Context);
837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Ted Kremenek082d9362009-03-20 21:35:28 +0000839 if (isConstant) {
840 const VarDecl *Def = 0;
841 if (const Expr *Init = VD->getDefinition(Def))
842 return SemaCheckStringLiteral(Init, TheCall,
843 HasVAListArg, format_idx, firstDataArg);
844 }
Mike Stump1eb44332009-09-09 15:08:12 +0000845
Anders Carlssond966a552009-06-28 19:55:58 +0000846 // For vprintf* functions (i.e., HasVAListArg==true), we add a
847 // special check to see if the format string is a function parameter
848 // of the function calling the printf function. If the function
849 // has an attribute indicating it is a printf-like function, then we
850 // should suppress warnings concerning non-literals being used in a call
851 // to a vprintf function. For example:
852 //
853 // void
854 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
855 // va_list ap;
856 // va_start(ap, fmt);
857 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
858 // ...
859 //
860 //
861 // FIXME: We don't have full attribute support yet, so just check to see
862 // if the argument is a DeclRefExpr that references a parameter. We'll
863 // add proper support for checking the attribute later.
864 if (HasVAListArg)
865 if (isa<ParmVarDecl>(VD))
866 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000867 }
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Ted Kremenek082d9362009-03-20 21:35:28 +0000869 return false;
870 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000871
Anders Carlsson8f031b32009-06-27 04:05:33 +0000872 case Stmt::CallExprClass: {
873 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000874 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000875 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
876 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
877 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000878 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000879 unsigned ArgIndex = FA->getFormatIdx();
880 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000881
882 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000883 format_idx, firstDataArg);
884 }
885 }
886 }
887 }
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Anders Carlsson8f031b32009-06-27 04:05:33 +0000889 return false;
890 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000891 case Stmt::ObjCStringLiteralClass:
892 case Stmt::StringLiteralClass: {
893 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000894
Ted Kremenek082d9362009-03-20 21:35:28 +0000895 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000896 StrE = ObjCFExpr->getString();
897 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000898 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Ted Kremenekd30ef872009-01-12 23:09:09 +0000900 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000901 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000902 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000903 return true;
904 }
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Ted Kremenekd30ef872009-01-12 23:09:09 +0000906 return false;
907 }
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Ted Kremenek082d9362009-03-20 21:35:28 +0000909 default:
910 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000911 }
912}
913
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000914void
Mike Stump1eb44332009-09-09 15:08:12 +0000915Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
916 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000917 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
918 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000919 const Expr *ArgExpr = TheCall->getArg(*i);
Douglas Gregorce940492009-09-25 04:25:58 +0000920 if (ArgExpr->isNullPointerConstant(Context,
921 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000922 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
923 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000924 }
925}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000926
Chris Lattner59907c42007-08-10 20:18:51 +0000927/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000928/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000929///
930/// HasVAListArg - A predicate indicating whether the printf-like
931/// function is passed an explicit va_arg argument (e.g., vprintf)
932///
933/// format_idx - The index into Args for the format string.
934///
935/// Improper format strings to functions in the printf family can be
936/// the source of bizarre bugs and very serious security holes. A
937/// good source of information is available in the following paper
938/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000939///
940/// FormatGuard: Automatic Protection From printf Format String
941/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000942///
943/// Functionality implemented:
944///
945/// We can statically check the following properties for string
946/// literal format strings for non v.*printf functions (where the
947/// arguments are passed directly):
948//
949/// (1) Are the number of format conversions equal to the number of
950/// data arguments?
951///
952/// (2) Does each format conversion correctly match the type of the
953/// corresponding data argument? (TODO)
954///
955/// Moreover, for all printf functions we can:
956///
957/// (3) Check for a missing format string (when not caught by type checking).
958///
959/// (4) Check for no-operation flags; e.g. using "#" with format
960/// conversion 'c' (TODO)
961///
962/// (5) Check the use of '%n', a major source of security holes.
963///
964/// (6) Check for malformed format conversions that don't specify anything.
965///
966/// (7) Check for empty format strings. e.g: printf("");
967///
968/// (8) Check that the format string is a wide literal.
969///
970/// All of these checks can be done by parsing the format string.
971///
972/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000973void
Mike Stump1eb44332009-09-09 15:08:12 +0000974Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000975 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000976 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000977
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000978 // The way the format attribute works in GCC, the implicit this argument
979 // of member functions is counted. However, it doesn't appear in our own
980 // lists, so decrement format_idx in that case.
981 if (isa<CXXMemberCallExpr>(TheCall)) {
982 // Catch a format attribute mistakenly referring to the object argument.
983 if (format_idx == 0)
984 return;
985 --format_idx;
986 if(firstDataArg != 0)
987 --firstDataArg;
988 }
989
Mike Stump1eb44332009-09-09 15:08:12 +0000990 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000991 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000992 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
993 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000994 return;
995 }
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Ted Kremenek082d9362009-03-20 21:35:28 +0000997 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Chris Lattner59907c42007-08-10 20:18:51 +0000999 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001000 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001001 // Dynamically generated format strings are difficult to
1002 // automatically vet at compile time. Requiring that format strings
1003 // are string literals: (1) permits the checking of format strings by
1004 // the compiler and thereby (2) can practically remove the source of
1005 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001006
Mike Stump1eb44332009-09-09 15:08:12 +00001007 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001008 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001009 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001010 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001011 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1012 firstDataArg))
1013 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001014
Chris Lattner655f1412009-04-29 04:59:47 +00001015 // If there are no arguments specified, warn with -Wformat-security, otherwise
1016 // warn only with -Wformat-nonliteral.
1017 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001018 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001019 diag::warn_printf_nonliteral_noargs)
1020 << OrigFormatExpr->getSourceRange();
1021 else
Mike Stump1eb44332009-09-09 15:08:12 +00001022 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001023 diag::warn_printf_nonliteral)
1024 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001025}
Ted Kremenek71895b92007-08-14 17:39:48 +00001026
Ted Kremenek082d9362009-03-20 21:35:28 +00001027void Sema::CheckPrintfString(const StringLiteral *FExpr,
1028 const Expr *OrigFormatExpr,
1029 const CallExpr *TheCall, bool HasVAListArg,
1030 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +00001031
Ted Kremenek082d9362009-03-20 21:35:28 +00001032 const ObjCStringLiteral *ObjCFExpr =
1033 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
1034
Ted Kremenek71895b92007-08-14 17:39:48 +00001035 // CHECK: is the format string a wide literal?
1036 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +00001037 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001038 diag::warn_printf_format_string_is_wide_literal)
1039 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001040 return;
1041 }
1042
1043 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +00001044 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +00001045
1046 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +00001047 unsigned StrLen = FExpr->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Ted Kremenek71895b92007-08-14 17:39:48 +00001049 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001050 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1051 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001052 return;
1053 }
1054
1055 // We process the format string using a binary state machine. The
1056 // current state is stored in CurrentState.
1057 enum {
1058 state_OrdChr,
1059 state_Conversion
1060 } CurrentState = state_OrdChr;
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Ted Kremenek71895b92007-08-14 17:39:48 +00001062 // numConversions - The number of conversions seen so far. This is
1063 // incremented as we traverse the format string.
1064 unsigned numConversions = 0;
1065
1066 // numDataArgs - The number of data arguments after the format
1067 // string. This can only be determined for non vprintf-like
1068 // functions. For those functions, this value is 1 (the sole
1069 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +00001070 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +00001071
1072 // Inspect the format string.
1073 unsigned StrIdx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Ted Kremenek71895b92007-08-14 17:39:48 +00001075 // LastConversionIdx - Index within the format string where we last saw
1076 // a '%' character that starts a new format conversion.
1077 unsigned LastConversionIdx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Chris Lattner925e60d2007-12-28 05:29:59 +00001079 for (; StrIdx < StrLen; ++StrIdx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Ted Kremenek71895b92007-08-14 17:39:48 +00001081 // Is the number of detected conversion conversions greater than
1082 // the number of matching data arguments? If so, stop.
1083 if (!HasVAListArg && numConversions > numDataArgs) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001084
Ted Kremenek71895b92007-08-14 17:39:48 +00001085 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +00001086 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +00001087 // The string returned by getStrData() is not null-terminated,
1088 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +00001089 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001090 diag::warn_printf_format_string_contains_null_char)
1091 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001092 return;
1093 }
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Ted Kremenek71895b92007-08-14 17:39:48 +00001095 // Ordinary characters (not processing a format conversion).
1096 if (CurrentState == state_OrdChr) {
1097 if (Str[StrIdx] == '%') {
1098 CurrentState = state_Conversion;
1099 LastConversionIdx = StrIdx;
1100 }
1101 continue;
1102 }
1103
1104 // Seen '%'. Now processing a format conversion.
1105 switch (Str[StrIdx]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001106 // Handle dynamic precision or width specifier.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001107 case '*': {
1108 ++numConversions;
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001110 if (!HasVAListArg) {
1111 if (numConversions > numDataArgs) {
1112 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +00001113
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001114 if (Str[StrIdx-1] == '.')
1115 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
1116 << OrigFormatExpr->getSourceRange();
1117 else
1118 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
1119 << OrigFormatExpr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001121 // Don't do any more checking. We'll just emit spurious errors.
1122 return;
1123 }
Mike Stump1eb44332009-09-09 15:08:12 +00001124
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001125 // Perform type checking on width/precision specifier.
1126 const Expr *E = TheCall->getArg(format_idx+numConversions);
John McCall183700f2009-09-21 23:43:11 +00001127 if (const BuiltinType *BT = E->getType()->getAs<BuiltinType>())
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001128 if (BT->getKind() == BuiltinType::Int)
1129 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001131 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001133 if (Str[StrIdx-1] == '.')
1134 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1135 << E->getType() << E->getSourceRange();
1136 else
1137 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1138 << E->getType() << E->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001139
1140 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001141 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001142 }
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001144 // Characters which can terminate a format conversion
1145 // (e.g. "%d"). Characters that specify length modifiers or
1146 // other flags are handled by the default case below.
1147 //
Mike Stump1eb44332009-09-09 15:08:12 +00001148 // FIXME: additional checks will go into the following cases.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001149 case 'i':
1150 case 'd':
Mike Stump1eb44332009-09-09 15:08:12 +00001151 case 'o':
1152 case 'u':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001153 case 'x':
1154 case 'X':
1155 case 'D':
1156 case 'O':
1157 case 'U':
1158 case 'e':
1159 case 'E':
1160 case 'f':
1161 case 'F':
1162 case 'g':
1163 case 'G':
1164 case 'a':
1165 case 'A':
1166 case 'c':
1167 case 'C':
1168 case 'S':
1169 case 's':
Mike Stump1eb44332009-09-09 15:08:12 +00001170 case 'p':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001171 ++numConversions;
1172 CurrentState = state_OrdChr;
1173 break;
1174
Eli Friedmanb92abb42009-06-02 08:36:19 +00001175 case 'm':
1176 // FIXME: Warn in situations where this isn't supported!
1177 CurrentState = state_OrdChr;
1178 break;
1179
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001180 // CHECK: Are we using "%n"? Issue a warning.
1181 case 'n': {
1182 ++numConversions;
1183 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +00001184 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1185 LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001187 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001188 break;
1189 }
Mike Stump1eb44332009-09-09 15:08:12 +00001190
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001191 // Handle "%@"
1192 case '@':
1193 // %@ is allowed in ObjC format strings only.
Mike Stump1eb44332009-09-09 15:08:12 +00001194 if (ObjCFExpr != NULL)
1195 CurrentState = state_OrdChr;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001196 else {
1197 // Issue a warning: invalid format conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00001198 SourceLocation Loc =
Chris Lattner60800082009-02-18 17:49:48 +00001199 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001201 Diag(Loc, diag::warn_printf_invalid_conversion)
1202 << std::string(Str+LastConversionIdx,
1203 Str+std::min(LastConversionIdx+2, StrLen))
1204 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001205 }
1206 ++numConversions;
1207 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001209 // Handle "%%"
1210 case '%':
1211 // Sanity check: Was the first "%" character the previous one?
1212 // If not, we will assume that we have a malformed format
1213 // conversion, and that the current "%" character is the start
1214 // of a new conversion.
1215 if (StrIdx - LastConversionIdx == 1)
Mike Stump1eb44332009-09-09 15:08:12 +00001216 CurrentState = state_OrdChr;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001217 else {
1218 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001219 SourceLocation Loc =
1220 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001221
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001222 Diag(Loc, diag::warn_printf_invalid_conversion)
1223 << std::string(Str+LastConversionIdx, Str+StrIdx)
1224 << OrigFormatExpr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001226 // This conversion is broken. Advance to the next format
1227 // conversion.
1228 LastConversionIdx = StrIdx;
1229 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +00001230 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001231 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001233 default:
1234 // This case catches all other characters: flags, widths, etc.
1235 // We should eventually process those as well.
1236 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001237 }
1238 }
1239
1240 if (CurrentState == state_Conversion) {
1241 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001242 SourceLocation Loc =
1243 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001245 Diag(Loc, diag::warn_printf_invalid_conversion)
1246 << std::string(Str+LastConversionIdx,
1247 Str+std::min(LastConversionIdx+2, StrLen))
1248 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001249 return;
1250 }
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Ted Kremenek71895b92007-08-14 17:39:48 +00001252 if (!HasVAListArg) {
1253 // CHECK: Does the number of format conversions exceed the number
1254 // of data arguments?
1255 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +00001256 SourceLocation Loc =
1257 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001259 Diag(Loc, diag::warn_printf_insufficient_data_args)
1260 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001261 }
1262 // CHECK: Does the number of data arguments exceed the number of
1263 // format conversions in the format string?
1264 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +00001265 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001266 diag::warn_printf_too_many_data_args)
1267 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001268 }
1269}
Ted Kremenek06de2762007-08-17 16:46:58 +00001270
1271//===--- CHECK: Return Address of Stack Variable --------------------------===//
1272
1273static DeclRefExpr* EvalVal(Expr *E);
1274static DeclRefExpr* EvalAddr(Expr* E);
1275
1276/// CheckReturnStackAddr - Check if a return statement returns the address
1277/// of a stack variable.
1278void
1279Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1280 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Ted Kremenek06de2762007-08-17 16:46:58 +00001282 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001283 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001284 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001285 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001286 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Steve Naroffc50a4a52008-09-16 22:25:10 +00001288 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001289 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001290
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001291 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001292 if (C->hasBlockDeclRefExprs())
1293 Diag(C->getLocStart(), diag::err_ret_local_block)
1294 << C->getSourceRange();
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001295
1296 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1297 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1298 << ALE->getSourceRange();
1299
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001300 } else if (lhsType->isReferenceType()) {
1301 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001302 // Check for a reference to the stack
1303 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001304 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001305 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001306 }
1307}
1308
1309/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1310/// check if the expression in a return statement evaluates to an address
1311/// to a location on the stack. The recursion is used to traverse the
1312/// AST of the return expression, with recursion backtracking when we
1313/// encounter a subexpression that (1) clearly does not lead to the address
1314/// of a stack variable or (2) is something we cannot determine leads to
1315/// the address of a stack variable based on such local checking.
1316///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001317/// EvalAddr processes expressions that are pointers that are used as
1318/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001319/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001320/// the refers to a stack variable.
1321///
1322/// This implementation handles:
1323///
1324/// * pointer-to-pointer casts
1325/// * implicit conversions from array references to pointers
1326/// * taking the address of fields
1327/// * arbitrary interplay between "&" and "*" operators
1328/// * pointer arithmetic from an address of a stack variable
1329/// * taking the address of an array element where the array is on the stack
1330static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001331 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001332 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001333 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001334 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001335 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Ted Kremenek06de2762007-08-17 16:46:58 +00001337 // Our "symbolic interpreter" is just a dispatch off the currently
1338 // viewed AST node. We then recursively traverse the AST by calling
1339 // EvalAddr and EvalVal appropriately.
1340 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001341 case Stmt::ParenExprClass:
1342 // Ignore parentheses.
1343 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001344
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001345 case Stmt::UnaryOperatorClass: {
1346 // The only unary operator that make sense to handle here
1347 // is AddrOf. All others don't make sense as pointers.
1348 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001350 if (U->getOpcode() == UnaryOperator::AddrOf)
1351 return EvalVal(U->getSubExpr());
1352 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001353 return NULL;
1354 }
Mike Stump1eb44332009-09-09 15:08:12 +00001355
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001356 case Stmt::BinaryOperatorClass: {
1357 // Handle pointer arithmetic. All other binary operators are not valid
1358 // in this context.
1359 BinaryOperator *B = cast<BinaryOperator>(E);
1360 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001362 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1363 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001365 Expr *Base = B->getLHS();
1366
1367 // Determine which argument is the real pointer base. It could be
1368 // the RHS argument instead of the LHS.
1369 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001370
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001371 assert (Base->getType()->isPointerType());
1372 return EvalAddr(Base);
1373 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001374
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001375 // For conditional operators we need to see if either the LHS or RHS are
1376 // valid DeclRefExpr*s. If one of them is valid, we return it.
1377 case Stmt::ConditionalOperatorClass: {
1378 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001380 // Handle the GNU extension for missing LHS.
1381 if (Expr *lhsExpr = C->getLHS())
1382 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1383 return LHS;
1384
1385 return EvalAddr(C->getRHS());
1386 }
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Ted Kremenek54b52742008-08-07 00:49:01 +00001388 // For casts, we need to handle conversions from arrays to
1389 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001390 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001391 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001392 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001393 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001394 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Steve Naroffdd972f22008-09-05 22:11:13 +00001396 if (SubExpr->getType()->isPointerType() ||
1397 SubExpr->getType()->isBlockPointerType() ||
1398 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001399 return EvalAddr(SubExpr);
1400 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001401 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001402 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001403 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001404 }
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001406 // C++ casts. For dynamic casts, static casts, and const casts, we
1407 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001408 // through the cast. In the case the dynamic cast doesn't fail (and
1409 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001410 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001411 // FIXME: The comment about is wrong; we're not always converting
1412 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001413 // handle references to objects.
1414 case Stmt::CXXStaticCastExprClass:
1415 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001416 case Stmt::CXXConstCastExprClass:
1417 case Stmt::CXXReinterpretCastExprClass: {
1418 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001419 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001420 return EvalAddr(S);
1421 else
1422 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001423 }
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001425 // Everything else: we simply don't reason about them.
1426 default:
1427 return NULL;
1428 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001429}
Mike Stump1eb44332009-09-09 15:08:12 +00001430
Ted Kremenek06de2762007-08-17 16:46:58 +00001431
1432/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1433/// See the comments for EvalAddr for more details.
1434static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001436 // We should only be called for evaluating non-pointer expressions, or
1437 // expressions with a pointer type that are not used as references but instead
1438 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Ted Kremenek06de2762007-08-17 16:46:58 +00001440 // Our "symbolic interpreter" is just a dispatch off the currently
1441 // viewed AST node. We then recursively traverse the AST by calling
1442 // EvalAddr and EvalVal appropriately.
1443 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001444 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001445 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1446 // at code that refers to a variable's name. We check if it has local
1447 // storage within the function, and if so, return the expression.
1448 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Ted Kremenek06de2762007-08-17 16:46:58 +00001450 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001451 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1452
Ted Kremenek06de2762007-08-17 16:46:58 +00001453 return NULL;
1454 }
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Ted Kremenek06de2762007-08-17 16:46:58 +00001456 case Stmt::ParenExprClass:
1457 // Ignore parentheses.
1458 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Ted Kremenek06de2762007-08-17 16:46:58 +00001460 case Stmt::UnaryOperatorClass: {
1461 // The only unary operator that make sense to handle here
1462 // is Deref. All others don't resolve to a "name." This includes
1463 // handling all sorts of rvalues passed to a unary operator.
1464 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Ted Kremenek06de2762007-08-17 16:46:58 +00001466 if (U->getOpcode() == UnaryOperator::Deref)
1467 return EvalAddr(U->getSubExpr());
1468
1469 return NULL;
1470 }
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Ted Kremenek06de2762007-08-17 16:46:58 +00001472 case Stmt::ArraySubscriptExprClass: {
1473 // Array subscripts are potential references to data on the stack. We
1474 // retrieve the DeclRefExpr* for the array variable if it indeed
1475 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001476 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001477 }
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Ted Kremenek06de2762007-08-17 16:46:58 +00001479 case Stmt::ConditionalOperatorClass: {
1480 // For conditional operators we need to see if either the LHS or RHS are
1481 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1482 ConditionalOperator *C = cast<ConditionalOperator>(E);
1483
Anders Carlsson39073232007-11-30 19:04:31 +00001484 // Handle the GNU extension for missing LHS.
1485 if (Expr *lhsExpr = C->getLHS())
1486 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1487 return LHS;
1488
1489 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001490 }
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Ted Kremenek06de2762007-08-17 16:46:58 +00001492 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001493 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001494 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Ted Kremenek06de2762007-08-17 16:46:58 +00001496 // Check for indirect access. We only want direct field accesses.
1497 if (!M->isArrow())
1498 return EvalVal(M->getBase());
1499 else
1500 return NULL;
1501 }
Mike Stump1eb44332009-09-09 15:08:12 +00001502
Ted Kremenek06de2762007-08-17 16:46:58 +00001503 // Everything else: we simply don't reason about them.
1504 default:
1505 return NULL;
1506 }
1507}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001508
1509//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1510
1511/// Check for comparisons of floating point operands using != and ==.
1512/// Issue a warning if these are no self-comparisons, as they are not likely
1513/// to do what the programmer intended.
1514void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1515 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001517 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001518 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001519
1520 // Special case: check for x == x (which is OK).
1521 // Do not emit warnings for such cases.
1522 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1523 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1524 if (DRL->getDecl() == DRR->getDecl())
1525 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001526
1527
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001528 // Special case: check for comparisons against literals that can be exactly
1529 // represented by APFloat. In such cases, do not emit a warning. This
1530 // is a heuristic: often comparison against such literals are used to
1531 // detect if a value in a variable has not changed. This clearly can
1532 // lead to false negatives.
1533 if (EmitWarning) {
1534 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1535 if (FLL->isExact())
1536 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001537 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001538 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1539 if (FLR->isExact())
1540 EmitWarning = false;
1541 }
1542 }
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001544 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001545 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001546 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001547 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001548 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Sebastian Redl0eb23302009-01-19 00:08:26 +00001550 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001551 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001552 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001553 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001555 // Emit the diagnostic.
1556 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001557 Diag(loc, diag::warn_floatingpoint_eq)
1558 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001559}
John McCallba26e582010-01-04 23:21:16 +00001560
John McCallf2370c92010-01-06 05:24:50 +00001561//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1562//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00001563
John McCallf2370c92010-01-06 05:24:50 +00001564namespace {
John McCallba26e582010-01-04 23:21:16 +00001565
John McCallf2370c92010-01-06 05:24:50 +00001566/// Structure recording the 'active' range of an integer-valued
1567/// expression.
1568struct IntRange {
1569 /// The number of bits active in the int.
1570 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00001571
John McCallf2370c92010-01-06 05:24:50 +00001572 /// True if the int is known not to have negative values.
1573 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00001574
John McCallf2370c92010-01-06 05:24:50 +00001575 IntRange() {}
1576 IntRange(unsigned Width, bool NonNegative)
1577 : Width(Width), NonNegative(NonNegative)
1578 {}
John McCallba26e582010-01-04 23:21:16 +00001579
John McCallf2370c92010-01-06 05:24:50 +00001580 // Returns the range of the bool type.
1581 static IntRange forBoolType() {
1582 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00001583 }
1584
John McCallf2370c92010-01-06 05:24:50 +00001585 // Returns the range of an integral type.
1586 static IntRange forType(ASTContext &C, QualType T) {
1587 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00001588 }
1589
John McCallf2370c92010-01-06 05:24:50 +00001590 // Returns the range of an integeral type based on its canonical
1591 // representation.
1592 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1593 assert(T->isCanonicalUnqualified());
1594
1595 if (const VectorType *VT = dyn_cast<VectorType>(T))
1596 T = VT->getElementType().getTypePtr();
1597 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1598 T = CT->getElementType().getTypePtr();
1599 if (const EnumType *ET = dyn_cast<EnumType>(T))
1600 T = ET->getDecl()->getIntegerType().getTypePtr();
1601
1602 const BuiltinType *BT = cast<BuiltinType>(T);
1603 assert(BT->isInteger());
1604
1605 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1606 }
1607
1608 // Returns the supremum of two ranges: i.e. their conservative merge.
1609 static IntRange join(const IntRange &L, const IntRange &R) {
1610 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00001611 L.NonNegative && R.NonNegative);
1612 }
1613
1614 // Returns the infinum of two ranges: i.e. their aggressive merge.
1615 static IntRange meet(const IntRange &L, const IntRange &R) {
1616 return IntRange(std::min(L.Width, R.Width),
1617 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00001618 }
1619};
1620
1621IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1622 if (value.isSigned() && value.isNegative())
1623 return IntRange(value.getMinSignedBits(), false);
1624
1625 if (value.getBitWidth() > MaxWidth)
1626 value.trunc(MaxWidth);
1627
1628 // isNonNegative() just checks the sign bit without considering
1629 // signedness.
1630 return IntRange(value.getActiveBits(), true);
1631}
1632
John McCall0acc3112010-01-06 22:57:21 +00001633IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00001634 unsigned MaxWidth) {
1635 if (result.isInt())
1636 return GetValueRange(C, result.getInt(), MaxWidth);
1637
1638 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00001639 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1640 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1641 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1642 R = IntRange::join(R, El);
1643 }
John McCallf2370c92010-01-06 05:24:50 +00001644 return R;
1645 }
1646
1647 if (result.isComplexInt()) {
1648 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1649 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1650 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00001651 }
1652
1653 // This can happen with lossless casts to intptr_t of "based" lvalues.
1654 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00001655 // FIXME: The only reason we need to pass the type in here is to get
1656 // the sign right on this one case. It would be nice if APValue
1657 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00001658 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00001659 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00001660}
John McCallf2370c92010-01-06 05:24:50 +00001661
1662/// Pseudo-evaluate the given integer expression, estimating the
1663/// range of values it might take.
1664///
1665/// \param MaxWidth - the width to which the value will be truncated
1666IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1667 E = E->IgnoreParens();
1668
1669 // Try a full evaluation first.
1670 Expr::EvalResult result;
1671 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00001672 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00001673
1674 // I think we only want to look through implicit casts here; if the
1675 // user has an explicit widening cast, we should treat the value as
1676 // being of the new, wider type.
1677 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1678 if (CE->getCastKind() == CastExpr::CK_NoOp)
1679 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1680
1681 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1682
John McCall60fad452010-01-06 22:07:33 +00001683 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1684 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1685 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1686
John McCallf2370c92010-01-06 05:24:50 +00001687 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00001688 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00001689 return OutputTypeRange;
1690
1691 IntRange SubRange
1692 = GetExprRange(C, CE->getSubExpr(),
1693 std::min(MaxWidth, OutputTypeRange.Width));
1694
1695 // Bail out if the subexpr's range is as wide as the cast type.
1696 if (SubRange.Width >= OutputTypeRange.Width)
1697 return OutputTypeRange;
1698
1699 // Otherwise, we take the smaller width, and we're non-negative if
1700 // either the output type or the subexpr is.
1701 return IntRange(SubRange.Width,
1702 SubRange.NonNegative || OutputTypeRange.NonNegative);
1703 }
1704
1705 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1706 // If we can fold the condition, just take that operand.
1707 bool CondResult;
1708 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1709 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1710 : CO->getFalseExpr(),
1711 MaxWidth);
1712
1713 // Otherwise, conservatively merge.
1714 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1715 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1716 return IntRange::join(L, R);
1717 }
1718
1719 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1720 switch (BO->getOpcode()) {
1721
1722 // Boolean-valued operations are single-bit and positive.
1723 case BinaryOperator::LAnd:
1724 case BinaryOperator::LOr:
1725 case BinaryOperator::LT:
1726 case BinaryOperator::GT:
1727 case BinaryOperator::LE:
1728 case BinaryOperator::GE:
1729 case BinaryOperator::EQ:
1730 case BinaryOperator::NE:
1731 return IntRange::forBoolType();
1732
1733 // Operations with opaque sources are black-listed.
1734 case BinaryOperator::PtrMemD:
1735 case BinaryOperator::PtrMemI:
1736 return IntRange::forType(C, E->getType());
1737
John McCall60fad452010-01-06 22:07:33 +00001738 // Bitwise-and uses the *infinum* of the two source ranges.
1739 case BinaryOperator::And:
1740 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1741 GetExprRange(C, BO->getRHS(), MaxWidth));
1742
John McCallf2370c92010-01-06 05:24:50 +00001743 // Left shift gets black-listed based on a judgement call.
1744 case BinaryOperator::Shl:
1745 return IntRange::forType(C, E->getType());
1746
John McCall60fad452010-01-06 22:07:33 +00001747 // Right shift by a constant can narrow its left argument.
1748 case BinaryOperator::Shr: {
1749 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1750
1751 // If the shift amount is a positive constant, drop the width by
1752 // that much.
1753 llvm::APSInt shift;
1754 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1755 shift.isNonNegative()) {
1756 unsigned zext = shift.getZExtValue();
1757 if (zext >= L.Width)
1758 L.Width = (L.NonNegative ? 0 : 1);
1759 else
1760 L.Width -= zext;
1761 }
1762
1763 return L;
1764 }
1765
1766 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00001767 case BinaryOperator::Comma:
1768 return GetExprRange(C, BO->getRHS(), MaxWidth);
1769
John McCall60fad452010-01-06 22:07:33 +00001770 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00001771 case BinaryOperator::Sub:
1772 if (BO->getLHS()->getType()->isPointerType())
1773 return IntRange::forType(C, E->getType());
1774 // fallthrough
1775
1776 default:
1777 break;
1778 }
1779
1780 // Treat every other operator as if it were closed on the
1781 // narrowest type that encompasses both operands.
1782 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1783 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1784 return IntRange::join(L, R);
1785 }
1786
1787 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1788 switch (UO->getOpcode()) {
1789 // Boolean-valued operations are white-listed.
1790 case UnaryOperator::LNot:
1791 return IntRange::forBoolType();
1792
1793 // Operations with opaque sources are black-listed.
1794 case UnaryOperator::Deref:
1795 case UnaryOperator::AddrOf: // should be impossible
1796 case UnaryOperator::OffsetOf:
1797 return IntRange::forType(C, E->getType());
1798
1799 default:
1800 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1801 }
1802 }
1803
1804 FieldDecl *BitField = E->getBitField();
1805 if (BitField) {
1806 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1807 unsigned BitWidth = BitWidthAP.getZExtValue();
1808
1809 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1810 }
1811
1812 return IntRange::forType(C, E->getType());
1813}
John McCall51313c32010-01-04 23:31:57 +00001814
1815/// Checks whether the given value, which currently has the given
1816/// source semantics, has the same value when coerced through the
1817/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00001818bool IsSameFloatAfterCast(const llvm::APFloat &value,
1819 const llvm::fltSemantics &Src,
1820 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001821 llvm::APFloat truncated = value;
1822
1823 bool ignored;
1824 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
1825 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
1826
1827 return truncated.bitwiseIsEqual(value);
1828}
1829
1830/// Checks whether the given value, which currently has the given
1831/// source semantics, has the same value when coerced through the
1832/// target semantics.
1833///
1834/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00001835bool IsSameFloatAfterCast(const APValue &value,
1836 const llvm::fltSemantics &Src,
1837 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001838 if (value.isFloat())
1839 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
1840
1841 if (value.isVector()) {
1842 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
1843 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
1844 return false;
1845 return true;
1846 }
1847
1848 assert(value.isComplexFloat());
1849 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
1850 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
1851}
1852
John McCallf2370c92010-01-06 05:24:50 +00001853} // end anonymous namespace
John McCall51313c32010-01-04 23:31:57 +00001854
John McCallba26e582010-01-04 23:21:16 +00001855/// \brief Implements -Wsign-compare.
1856///
1857/// \param lex the left-hand expression
1858/// \param rex the right-hand expression
1859/// \param OpLoc the location of the joining operator
1860/// \param Equality whether this is an "equality-like" join, which
1861/// suppresses the warning in some cases
1862void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
1863 const PartialDiagnostic &PD, bool Equality) {
1864 // Don't warn if we're in an unevaluated context.
1865 if (ExprEvalContexts.back().Context == Unevaluated)
1866 return;
1867
John McCallf2370c92010-01-06 05:24:50 +00001868 // If either expression is value-dependent, don't warn. We'll get another
1869 // chance at instantiation time.
1870 if (lex->isValueDependent() || rex->isValueDependent())
1871 return;
1872
John McCallba26e582010-01-04 23:21:16 +00001873 QualType lt = lex->getType(), rt = rex->getType();
1874
1875 // Only warn if both operands are integral.
1876 if (!lt->isIntegerType() || !rt->isIntegerType())
1877 return;
1878
John McCallf2370c92010-01-06 05:24:50 +00001879 // In C, the width of a bitfield determines its type, and the
1880 // declared type only contributes the signedness. This duplicates
1881 // the work that will later be done by UsualUnaryConversions.
1882 // Eventually, this check will be reorganized in a way that avoids
1883 // this duplication.
1884 if (!getLangOptions().CPlusPlus) {
1885 QualType tmp;
1886 tmp = Context.isPromotableBitField(lex);
1887 if (!tmp.isNull()) lt = tmp;
1888 tmp = Context.isPromotableBitField(rex);
1889 if (!tmp.isNull()) rt = tmp;
1890 }
John McCallba26e582010-01-04 23:21:16 +00001891
1892 // The rule is that the signed operand becomes unsigned, so isolate the
1893 // signed operand.
John McCallf2370c92010-01-06 05:24:50 +00001894 Expr *signedOperand = lex, *unsignedOperand = rex;
1895 QualType signedType = lt, unsignedType = rt;
John McCallba26e582010-01-04 23:21:16 +00001896 if (lt->isSignedIntegerType()) {
1897 if (rt->isSignedIntegerType()) return;
John McCallba26e582010-01-04 23:21:16 +00001898 } else {
1899 if (!rt->isSignedIntegerType()) return;
John McCallf2370c92010-01-06 05:24:50 +00001900 std::swap(signedOperand, unsignedOperand);
1901 std::swap(signedType, unsignedType);
John McCallba26e582010-01-04 23:21:16 +00001902 }
1903
John McCallf2370c92010-01-06 05:24:50 +00001904 unsigned unsignedWidth = Context.getIntWidth(unsignedType);
1905 unsigned signedWidth = Context.getIntWidth(signedType);
1906
John McCallba26e582010-01-04 23:21:16 +00001907 // If the unsigned type is strictly smaller than the signed type,
1908 // then (1) the result type will be signed and (2) the unsigned
1909 // value will fit fully within the signed type, and thus the result
1910 // of the comparison will be exact.
John McCallf2370c92010-01-06 05:24:50 +00001911 if (signedWidth > unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00001912 return;
1913
John McCallf2370c92010-01-06 05:24:50 +00001914 // Otherwise, calculate the effective ranges.
1915 IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth);
1916 IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth);
1917
1918 // We should never be unable to prove that the unsigned operand is
1919 // non-negative.
1920 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
1921
1922 // If the signed operand is non-negative, then the signed->unsigned
1923 // conversion won't change it.
1924 if (signedRange.NonNegative)
John McCallba26e582010-01-04 23:21:16 +00001925 return;
1926
1927 // For (in)equality comparisons, if the unsigned operand is a
1928 // constant which cannot collide with a overflowed signed operand,
1929 // then reinterpreting the signed operand as unsigned will not
1930 // change the result of the comparison.
John McCallf2370c92010-01-06 05:24:50 +00001931 if (Equality && unsignedRange.Width < unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00001932 return;
1933
1934 Diag(OpLoc, PD)
John McCallf2370c92010-01-06 05:24:50 +00001935 << lt << rt << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00001936}
1937
John McCall51313c32010-01-04 23:31:57 +00001938/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
1939static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
1940 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
1941}
1942
1943/// Implements -Wconversion.
1944void Sema::CheckImplicitConversion(Expr *E, QualType T) {
1945 // Don't diagnose in unevaluated contexts.
1946 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
1947 return;
1948
1949 // Don't diagnose for value-dependent expressions.
1950 if (E->isValueDependent())
1951 return;
1952
1953 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
1954 const Type *Target = Context.getCanonicalType(T).getTypePtr();
1955
1956 // Never diagnose implicit casts to bool.
1957 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
1958 return;
1959
1960 // Strip vector types.
1961 if (isa<VectorType>(Source)) {
1962 if (!isa<VectorType>(Target))
1963 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar);
1964
1965 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
1966 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
1967 }
1968
1969 // Strip complex types.
1970 if (isa<ComplexType>(Source)) {
1971 if (!isa<ComplexType>(Target))
1972 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar);
1973
1974 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
1975 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
1976 }
1977
1978 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
1979 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
1980
1981 // If the source is floating point...
1982 if (SourceBT && SourceBT->isFloatingPoint()) {
1983 // ...and the target is floating point...
1984 if (TargetBT && TargetBT->isFloatingPoint()) {
1985 // ...then warn if we're dropping FP rank.
1986
1987 // Builtin FP kinds are ordered by increasing FP rank.
1988 if (SourceBT->getKind() > TargetBT->getKind()) {
1989 // Don't warn about float constants that are precisely
1990 // representable in the target type.
1991 Expr::EvalResult result;
1992 if (E->Evaluate(result, Context)) {
1993 // Value might be a float, a float vector, or a float complex.
1994 if (IsSameFloatAfterCast(result.Val,
1995 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
1996 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
1997 return;
1998 }
1999
2000 DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision);
2001 }
2002 return;
2003 }
2004
2005 // If the target is integral, always warn.
2006 if ((TargetBT && TargetBT->isInteger()))
2007 // TODO: don't warn for integer values?
2008 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer);
2009
2010 return;
2011 }
2012
John McCallf2370c92010-01-06 05:24:50 +00002013 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002014 return;
2015
John McCallf2370c92010-01-06 05:24:50 +00002016 IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType()));
2017 IntRange TargetRange = IntRange::forCanonicalType(Context, Target);
John McCall51313c32010-01-04 23:31:57 +00002018
John McCallf2370c92010-01-06 05:24:50 +00002019 // FIXME: also signed<->unsigned?
2020
2021 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002022 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2023 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002024 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall51313c32010-01-04 23:31:57 +00002025 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32);
2026 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision);
2027 }
2028
2029 return;
2030}
2031