blob: b0d6901953f6245cbe3624e341c20b716eb52db4 [file] [log] [blame]
Chris Lattner2e64c072007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner2e64c072007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements extra semantic analysis beyond what is enforced
11// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek1c1700f2007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek225a14c2008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattnerbe93e792009-02-18 19:21:10 +000020#include "clang/Lex/LiteralSupport.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000021#include "clang/Lex/Preprocessor.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000022using namespace clang;
23
Chris Lattnerf17cb362009-02-18 17:49:48 +000024/// getLocationOfStringLiteralByte - Return a source location that points to the
25/// specified byte of the specified string literal.
26///
27/// Strings are amazingly complex. They can be formed from multiple tokens and
28/// can have escape sequences in them in addition to the usual trigraph and
29/// escaped newline business. This routine handles this complexity.
30///
31SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
32 unsigned ByteNo) const {
33 assert(!SL->isWide() && "This doesn't work for wide strings yet");
34
35 // Loop over all of the tokens in this string until we find the one that
36 // contains the byte we're looking for.
37 unsigned TokNo = 0;
38 while (1) {
39 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
40 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
41
42 // Get the spelling of the string so that we can get the data that makes up
43 // the string literal, not the identifier for the macro it is potentially
44 // expanded through.
45 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
46
47 // Re-lex the token to get its length and original spelling.
48 std::pair<FileID, unsigned> LocInfo =
49 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
50 std::pair<const char *,const char *> Buffer =
51 SourceMgr.getBufferData(LocInfo.first);
52 const char *StrData = Buffer.first+LocInfo.second;
53
54 // Create a langops struct and enable trigraphs. This is sufficient for
55 // relexing tokens.
56 LangOptions LangOpts;
57 LangOpts.Trigraphs = true;
58
59 // Create a lexer starting at the beginning of this token.
60 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
61 Buffer.second);
62 Token TheTok;
63 TheLexer.LexFromRawLexer(TheTok);
64
Chris Lattnerf6d44722009-02-18 19:26:42 +000065 // Use the StringLiteralParser to compute the length of the string in bytes.
66 StringLiteralParser SLP(&TheTok, 1, PP);
67 unsigned TokNumBytes = SLP.GetStringLength();
Chris Lattner30183b02009-02-18 18:34:12 +000068
Chris Lattner81df8462009-02-18 18:52:52 +000069 // If the byte is in this token, return the location of the byte.
Chris Lattnerf17cb362009-02-18 17:49:48 +000070 if (ByteNo < TokNumBytes ||
71 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Chris Lattnerbe93e792009-02-18 19:21:10 +000072 unsigned Offset =
73 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
74
75 // Now that we know the offset of the token in the spelling, use the
76 // preprocessor to get the offset in the original source.
77 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattnerf17cb362009-02-18 17:49:48 +000078 }
79
80 // Move to the next string token.
81 ++TokNo;
82 ByteNo -= TokNumBytes;
83 }
84}
85
86
Chris Lattner2e64c072007-08-10 20:18:51 +000087/// CheckFunctionCall - Check a direct function call for various correctness
88/// and safety properties not strictly enforced by the C type system.
Sebastian Redl8b769972009-01-19 00:08:26 +000089Action::OwningExprResult
90Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
91 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner2e64c072007-08-10 20:18:51 +000092 // Get the IdentifierInfo* for the called function.
93 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregorb0212bd2008-11-17 20:34:05 +000094
95 // None of the checks below are needed for functions that don't have
96 // simple names (e.g., C++ conversion functions).
97 if (!FnInfo)
Sebastian Redl8b769972009-01-19 00:08:26 +000098 return move(TheCallResult);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000099
Douglas Gregorb5af7382009-02-14 18:57:46 +0000100 switch (FDecl->getBuiltinID(Context)) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000101 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000102 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000103 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner81f5be22009-02-18 06:01:06 +0000104 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl8b769972009-01-19 00:08:26 +0000105 return ExprError();
106 return move(TheCallResult);
Ted Kremenek7a0654c2008-07-09 17:58:53 +0000107 case Builtin::BI__builtin_stdarg_start:
Chris Lattnerf22a8502007-12-19 23:59:04 +0000108 case Builtin::BI__builtin_va_start:
Sebastian Redl8b769972009-01-19 00:08:26 +0000109 if (SemaBuiltinVAStart(TheCall))
110 return ExprError();
111 return move(TheCallResult);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000112 case Builtin::BI__builtin_isgreater:
113 case Builtin::BI__builtin_isgreaterequal:
114 case Builtin::BI__builtin_isless:
115 case Builtin::BI__builtin_islessequal:
116 case Builtin::BI__builtin_islessgreater:
117 case Builtin::BI__builtin_isunordered:
Sebastian Redl8b769972009-01-19 00:08:26 +0000118 if (SemaBuiltinUnorderedCompare(TheCall))
119 return ExprError();
120 return move(TheCallResult);
Eli Friedman8c50c622008-05-20 08:23:37 +0000121 case Builtin::BI__builtin_return_address:
122 case Builtin::BI__builtin_frame_address:
Sebastian Redl8b769972009-01-19 00:08:26 +0000123 if (SemaBuiltinStackAddress(TheCall))
124 return ExprError();
125 return move(TheCallResult);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000126 case Builtin::BI__builtin_shufflevector:
Sebastian Redl8b769972009-01-19 00:08:26 +0000127 return SemaBuiltinShuffleVector(TheCall);
128 // TheCall will be freed by the smart pointer here, but that's fine, since
129 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000130 case Builtin::BI__builtin_prefetch:
Sebastian Redl8b769972009-01-19 00:08:26 +0000131 if (SemaBuiltinPrefetch(TheCall))
132 return ExprError();
133 return move(TheCallResult);
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000134 case Builtin::BI__builtin_object_size:
Sebastian Redl8b769972009-01-19 00:08:26 +0000135 if (SemaBuiltinObjectSize(TheCall))
136 return ExprError();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000137 }
Daniel Dunbar0ab03e62008-10-02 18:44:07 +0000138
139 // FIXME: This mechanism should be abstracted to be less fragile and
140 // more efficient. For example, just map function ids to custom
141 // handlers.
142
Chris Lattner2e64c072007-08-10 20:18:51 +0000143 // Printf checking.
Douglas Gregorb5af7382009-02-14 18:57:46 +0000144 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
145 if (Format->getType() == "printf") {
Ted Kremenekfec9c152009-02-27 17:58:43 +0000146 bool HasVAListArg = Format->getFirstArg() == 0;
147 if (!HasVAListArg) {
148 if (const FunctionProtoType *Proto
149 = FDecl->getType()->getAsFunctionProtoType())
Douglas Gregorb5af7382009-02-14 18:57:46 +0000150 HasVAListArg = !Proto->isVariadic();
Ted Kremenekfec9c152009-02-27 17:58:43 +0000151 }
Douglas Gregorb5af7382009-02-14 18:57:46 +0000152 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenekfec9c152009-02-27 17:58:43 +0000153 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregorb5af7382009-02-14 18:57:46 +0000154 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000155 }
Sebastian Redl8b769972009-01-19 00:08:26 +0000156
157 return move(TheCallResult);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000158}
159
Chris Lattner81f5be22009-02-18 06:01:06 +0000160/// CheckObjCString - Checks that the argument to the builtin
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000161/// CFString constructor is correct
Chris Lattner81f5be22009-02-18 06:01:06 +0000162bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000163 Arg = Arg->IgnoreParenCasts();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000164 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
165
166 if (!Literal || Literal->isWide()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000167 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
168 << Arg->getSourceRange();
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000169 return true;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000170 }
171
172 const char *Data = Literal->getStrData();
173 unsigned Length = Literal->getByteLength();
174
175 for (unsigned i = 0; i < Length; ++i) {
176 if (!isascii(Data[i])) {
Chris Lattnerf17cb362009-02-18 17:49:48 +0000177 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000178 diag::warn_cfstring_literal_contains_non_ascii_character)
179 << Arg->getSourceRange();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000180 break;
181 }
182
183 if (!Data[i]) {
Chris Lattnerf17cb362009-02-18 17:49:48 +0000184 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000185 diag::warn_cfstring_literal_contains_nul_character)
186 << Arg->getSourceRange();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000187 break;
188 }
189 }
190
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000191 return false;
Chris Lattner2e64c072007-08-10 20:18:51 +0000192}
193
Chris Lattner3b933692007-12-20 00:05:45 +0000194/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
195/// Emit an error and return true on failure, return false on success.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000196bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
197 Expr *Fn = TheCall->getCallee();
198 if (TheCall->getNumArgs() > 2) {
Chris Lattner66beaba2008-11-21 18:44:24 +0000199 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000200 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000201 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000202 << SourceRange(TheCall->getArg(2)->getLocStart(),
203 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattnerf22a8502007-12-19 23:59:04 +0000204 return true;
205 }
Eli Friedman6422de62008-12-15 22:05:35 +0000206
207 if (TheCall->getNumArgs() < 2) {
208 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
209 << 0 /*function call*/;
210 }
211
Chris Lattner3b933692007-12-20 00:05:45 +0000212 // Determine whether the current function is variadic or not.
213 bool isVariadic;
Eli Friedman6422de62008-12-15 22:05:35 +0000214 if (getCurFunctionDecl()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000215 if (FunctionProtoType* FTP =
216 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman6422de62008-12-15 22:05:35 +0000217 isVariadic = FTP->isVariadic();
218 else
219 isVariadic = false;
220 } else {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000221 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman6422de62008-12-15 22:05:35 +0000222 }
Chris Lattnerf22a8502007-12-19 23:59:04 +0000223
Chris Lattner3b933692007-12-20 00:05:45 +0000224 if (!isVariadic) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000225 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
226 return true;
227 }
228
229 // Verify that the second argument to the builtin is the last argument of the
230 // current function or method.
231 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson924556e2008-02-13 01:22:59 +0000232 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlssonc27156b2008-02-11 04:20:54 +0000233
234 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
235 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000236 // FIXME: This isn't correct for methods (results in bogus warning).
237 // Get the last formal in the current function.
Anders Carlssonc27156b2008-02-11 04:20:54 +0000238 const ParmVarDecl *LastArg;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000239 if (FunctionDecl *FD = getCurFunctionDecl())
240 LastArg = *(FD->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000241 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000242 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000243 SecondArgIsLastNamedArgument = PV == LastArg;
244 }
245 }
246
247 if (!SecondArgIsLastNamedArgument)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000248 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000249 diag::warn_second_parameter_of_va_start_not_last_named_argument);
250 return false;
Eli Friedman8c50c622008-05-20 08:23:37 +0000251}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000252
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000253/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
254/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000255bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
256 if (TheCall->getNumArgs() < 2)
Chris Lattner66beaba2008-11-21 18:44:24 +0000257 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
258 << 0 /*function call*/;
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000259 if (TheCall->getNumArgs() > 2)
260 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000261 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000262 << 0 /*function call*/
Chris Lattner8ba580c2008-11-19 05:08:23 +0000263 << SourceRange(TheCall->getArg(2)->getLocStart(),
264 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000265
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000266 Expr *OrigArg0 = TheCall->getArg(0);
267 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000268
269 // Do standard promotions between the two arguments, returning their common
270 // type.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000271 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar5ac4dff2009-02-19 19:28:43 +0000272
273 // Make sure any conversions are pushed back into the call; this is
274 // type safe since unordered compare builtins are declared as "_Bool
275 // foo(...)".
276 TheCall->setArg(0, OrigArg0);
277 TheCall->setArg(1, OrigArg1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000278
279 // If the common type isn't a real floating type, then the arguments were
280 // invalid for this operation.
281 if (!Res->isRealFloatingType())
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000282 return Diag(OrigArg0->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000283 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000284 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000285 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000286
287 return false;
288}
289
Eli Friedman8c50c622008-05-20 08:23:37 +0000290bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
291 // The signature for these builtins is exact; the only thing we need
292 // to check is that the argument is a constant.
293 SourceLocation Loc;
Chris Lattner941c0102008-08-10 02:05:13 +0000294 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000295 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattner941c0102008-08-10 02:05:13 +0000296
Eli Friedman8c50c622008-05-20 08:23:37 +0000297 return false;
298}
299
Eli Friedmand0e9d092008-05-14 19:38:39 +0000300/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
301// This is declared to take (...), so we have to check everything.
Sebastian Redl8b769972009-01-19 00:08:26 +0000302Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000303 if (TheCall->getNumArgs() < 3)
Sebastian Redl8b769972009-01-19 00:08:26 +0000304 return ExprError(Diag(TheCall->getLocEnd(),
305 diag::err_typecheck_call_too_few_args)
306 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000307
308 QualType FAType = TheCall->getArg(0)->getType();
309 QualType SAType = TheCall->getArg(1)->getType();
310
311 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000312 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
313 << SourceRange(TheCall->getArg(0)->getLocStart(),
314 TheCall->getArg(1)->getLocEnd());
Sebastian Redl8b769972009-01-19 00:08:26 +0000315 return ExprError();
Eli Friedmand0e9d092008-05-14 19:38:39 +0000316 }
317
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000318 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
319 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000320 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
321 << SourceRange(TheCall->getArg(0)->getLocStart(),
322 TheCall->getArg(1)->getLocEnd());
Sebastian Redl8b769972009-01-19 00:08:26 +0000323 return ExprError();
Eli Friedmand0e9d092008-05-14 19:38:39 +0000324 }
325
326 unsigned numElements = FAType->getAsVectorType()->getNumElements();
327 if (TheCall->getNumArgs() != numElements+2) {
328 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000329 return ExprError(Diag(TheCall->getLocEnd(),
330 diag::err_typecheck_call_too_few_args)
331 << 0 /*function call*/ << TheCall->getSourceRange());
332 return ExprError(Diag(TheCall->getLocEnd(),
333 diag::err_typecheck_call_too_many_args)
334 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000335 }
336
337 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
338 llvm::APSInt Result(32);
Chris Lattner941c0102008-08-10 02:05:13 +0000339 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl8b769972009-01-19 00:08:26 +0000340 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000341 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl8b769972009-01-19 00:08:26 +0000342 << TheCall->getArg(i)->getSourceRange());
343
Chris Lattner941c0102008-08-10 02:05:13 +0000344 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000345 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000346 diag::err_shufflevector_argument_too_large)
Sebastian Redl8b769972009-01-19 00:08:26 +0000347 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000348 }
349
350 llvm::SmallVector<Expr*, 32> exprs;
351
Chris Lattner941c0102008-08-10 02:05:13 +0000352 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000353 exprs.push_back(TheCall->getArg(i));
354 TheCall->setArg(i, 0);
355 }
356
Ted Kremenek0c97e042009-02-07 01:47:29 +0000357 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
358 FAType,
359 TheCall->getCallee()->getLocStart(),
360 TheCall->getRParenLoc()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000361}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000362
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000363/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
364// This is declared to take (const void*, ...) and can take two
365// optional constant int args.
366bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000367 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000368
Chris Lattner8ba580c2008-11-19 05:08:23 +0000369 if (NumArgs > 3)
370 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000371 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000372
373 // Argument 0 is checked for us and the remaining arguments must be
374 // constant integers.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000375 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000376 Expr *Arg = TheCall->getArg(i);
377 QualType RWType = Arg->getType();
378
379 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000380 llvm::APSInt Result;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000381 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattner8ba580c2008-11-19 05:08:23 +0000382 !Arg->isIntegerConstantExpr(Result, Context))
383 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
384 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000385
386 // FIXME: gcc issues a warning and rewrites these to 0. These
387 // seems especially odd for the third argument since the default
388 // is 3.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000389 if (i == 1) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000390 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000391 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
392 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000393 } else {
394 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000395 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
396 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000397 }
398 }
399
Chris Lattner8ba580c2008-11-19 05:08:23 +0000400 return false;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000401}
402
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000403/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
404/// int type). This simply type checks that type is one of the defined
405/// constants (0-3).
406bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
407 Expr *Arg = TheCall->getArg(1);
408 QualType ArgType = Arg->getType();
409 const BuiltinType *BT = ArgType->getAsBuiltinType();
410 llvm::APSInt Result(32);
411 if (!BT || BT->getKind() != BuiltinType::Int ||
412 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000413 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
414 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000415 }
416
417 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000418 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
419 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000420 }
421
422 return false;
423}
424
Ted Kremenek8c797c02009-01-12 23:09:09 +0000425// Handle i > 1 ? "x" : "y", recursivelly
426bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000427 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek8c797c02009-01-12 23:09:09 +0000428
429 switch (E->getStmtClass()) {
430 case Stmt::ConditionalOperatorClass: {
431 ConditionalOperator *C = cast<ConditionalOperator>(E);
432 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000433 HasVAListArg, format_idx, firstDataArg)
Ted Kremenek8c797c02009-01-12 23:09:09 +0000434 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000435 HasVAListArg, format_idx, firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000436 }
437
438 case Stmt::ImplicitCastExprClass: {
439 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
440 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000441 format_idx, firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000442 }
443
444 case Stmt::ParenExprClass: {
445 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
446 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000447 format_idx, firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000448 }
449
450 default: {
451 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
452 StringLiteral *StrE = NULL;
453
454 if (ObjCFExpr)
455 StrE = ObjCFExpr->getString();
456 else
457 StrE = dyn_cast<StringLiteral>(E);
458
459 if (StrE) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000460 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
461 firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000462 return true;
463 }
464
465 return false;
466 }
467 }
468}
469
470
Chris Lattner2e64c072007-08-10 20:18:51 +0000471/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek081ed872007-08-14 17:39:48 +0000472/// correct use of format strings.
473///
474/// HasVAListArg - A predicate indicating whether the printf-like
475/// function is passed an explicit va_arg argument (e.g., vprintf)
476///
477/// format_idx - The index into Args for the format string.
478///
479/// Improper format strings to functions in the printf family can be
480/// the source of bizarre bugs and very serious security holes. A
481/// good source of information is available in the following paper
482/// (which includes additional references):
Chris Lattner2e64c072007-08-10 20:18:51 +0000483///
484/// FormatGuard: Automatic Protection From printf Format String
485/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek081ed872007-08-14 17:39:48 +0000486///
487/// Functionality implemented:
488///
489/// We can statically check the following properties for string
490/// literal format strings for non v.*printf functions (where the
491/// arguments are passed directly):
492//
493/// (1) Are the number of format conversions equal to the number of
494/// data arguments?
495///
496/// (2) Does each format conversion correctly match the type of the
497/// corresponding data argument? (TODO)
498///
499/// Moreover, for all printf functions we can:
500///
501/// (3) Check for a missing format string (when not caught by type checking).
502///
503/// (4) Check for no-operation flags; e.g. using "#" with format
504/// conversion 'c' (TODO)
505///
506/// (5) Check the use of '%n', a major source of security holes.
507///
508/// (6) Check for malformed format conversions that don't specify anything.
509///
510/// (7) Check for empty format strings. e.g: printf("");
511///
512/// (8) Check that the format string is a wide literal.
513///
Ted Kremenekc2804c22008-03-03 16:50:00 +0000514/// (9) Also check the arguments of functions with the __format__ attribute.
515/// (TODO).
516///
Ted Kremenek081ed872007-08-14 17:39:48 +0000517/// All of these checks can be done by parsing the format string.
518///
519/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner2e64c072007-08-10 20:18:51 +0000520void
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000521Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000522 unsigned format_idx, unsigned firstDataArg) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000523 Expr *Fn = TheCall->getCallee();
524
Ted Kremenek081ed872007-08-14 17:39:48 +0000525 // CHECK: printf-like function is called with no format string.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000526 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000527 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
528 << Fn->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000529 return;
530 }
531
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000532 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattnere65acc12007-08-25 05:36:18 +0000533
Chris Lattner2e64c072007-08-10 20:18:51 +0000534 // CHECK: format string is not a string literal.
535 //
Ted Kremenek081ed872007-08-14 17:39:48 +0000536 // Dynamically generated format strings are difficult to
537 // automatically vet at compile time. Requiring that format strings
538 // are string literals: (1) permits the checking of format strings by
539 // the compiler and thereby (2) can practically remove the source of
540 // many format string exploits.
Ted Kremenek225a14c2008-06-16 18:00:42 +0000541
542 // Format string can be either ObjC string (e.g. @"%d") or
543 // C string (e.g. "%d")
544 // ObjC string uses the same format specifiers as C string, so we can use
545 // the same format string checking logic for both ObjC and C strings.
Douglas Gregorb5af7382009-02-14 18:57:46 +0000546 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall,
547 HasVAListArg, format_idx,
548 firstDataArg);
Ted Kremenek225a14c2008-06-16 18:00:42 +0000549
Ted Kremenek8c797c02009-01-12 23:09:09 +0000550 if (!isFExpr) {
Ted Kremenek19398b62007-12-17 19:03:13 +0000551 // For vprintf* functions (i.e., HasVAListArg==true), we add a
552 // special check to see if the format string is a function parameter
553 // of the function calling the printf function. If the function
554 // has an attribute indicating it is a printf-like function, then we
555 // should suppress warnings concerning non-literals being used in a call
556 // to a vprintf function. For example:
557 //
558 // void
559 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
560 // va_list ap;
561 // va_start(ap, fmt);
562 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
563 // ...
564 //
565 //
566 // FIXME: We don't have full attribute support yet, so just check to see
567 // if the argument is a DeclRefExpr that references a parameter. We'll
568 // add proper support for checking the attribute later.
569 if (HasVAListArg)
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000570 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
571 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek19398b62007-12-17 19:03:13 +0000572 return;
Ted Kremenek8c797c02009-01-12 23:09:09 +0000573
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000574 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000575 diag::warn_printf_not_string_constant)
576 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000577 return;
578 }
Ted Kremenek8c797c02009-01-12 23:09:09 +0000579}
Ted Kremenek081ed872007-08-14 17:39:48 +0000580
Ted Kremenek8c797c02009-01-12 23:09:09 +0000581void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000582 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx,
583 unsigned firstDataArg) {
Ted Kremenek8c797c02009-01-12 23:09:09 +0000584
585 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek081ed872007-08-14 17:39:48 +0000586 // CHECK: is the format string a wide literal?
587 if (FExpr->isWide()) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000588 Diag(FExpr->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000589 diag::warn_printf_format_string_is_wide_literal)
590 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000591 return;
592 }
593
594 // Str - The format string. NOTE: this is NOT null-terminated!
595 const char * const Str = FExpr->getStrData();
596
597 // CHECK: empty format string?
598 const unsigned StrLen = FExpr->getByteLength();
599
600 if (StrLen == 0) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000601 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
602 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000603 return;
604 }
605
606 // We process the format string using a binary state machine. The
607 // current state is stored in CurrentState.
608 enum {
609 state_OrdChr,
610 state_Conversion
611 } CurrentState = state_OrdChr;
612
613 // numConversions - The number of conversions seen so far. This is
614 // incremented as we traverse the format string.
615 unsigned numConversions = 0;
616
617 // numDataArgs - The number of data arguments after the format
618 // string. This can only be determined for non vprintf-like
619 // functions. For those functions, this value is 1 (the sole
620 // va_arg argument).
Douglas Gregorb5af7382009-02-14 18:57:46 +0000621 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek081ed872007-08-14 17:39:48 +0000622
623 // Inspect the format string.
624 unsigned StrIdx = 0;
625
626 // LastConversionIdx - Index within the format string where we last saw
627 // a '%' character that starts a new format conversion.
628 unsigned LastConversionIdx = 0;
629
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000630 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000631
Ted Kremenek081ed872007-08-14 17:39:48 +0000632 // Is the number of detected conversion conversions greater than
633 // the number of matching data arguments? If so, stop.
634 if (!HasVAListArg && numConversions > numDataArgs) break;
635
636 // Handle "\0"
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000637 if (Str[StrIdx] == '\0') {
Ted Kremenek081ed872007-08-14 17:39:48 +0000638 // The string returned by getStrData() is not null-terminated,
639 // so the presence of a null character is likely an error.
Chris Lattnerf17cb362009-02-18 17:49:48 +0000640 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000641 diag::warn_printf_format_string_contains_null_char)
642 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000643 return;
644 }
645
646 // Ordinary characters (not processing a format conversion).
647 if (CurrentState == state_OrdChr) {
648 if (Str[StrIdx] == '%') {
649 CurrentState = state_Conversion;
650 LastConversionIdx = StrIdx;
651 }
652 continue;
653 }
654
655 // Seen '%'. Now processing a format conversion.
656 switch (Str[StrIdx]) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000657 // Handle dynamic precision or width specifier.
658 case '*': {
659 ++numConversions;
660
661 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerf17cb362009-02-18 17:49:48 +0000662 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek035d8792007-10-12 20:51:52 +0000663
Ted Kremenek035d8792007-10-12 20:51:52 +0000664 if (Str[StrIdx-1] == '.')
Chris Lattner9d2cf082008-11-19 05:27:50 +0000665 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
666 << OrigFormatExpr->getSourceRange();
Ted Kremenek035d8792007-10-12 20:51:52 +0000667 else
Chris Lattner9d2cf082008-11-19 05:27:50 +0000668 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
669 << OrigFormatExpr->getSourceRange();
Ted Kremenek035d8792007-10-12 20:51:52 +0000670
Chris Lattner68d88f02007-12-28 05:31:15 +0000671 // Don't do any more checking. We'll just emit spurious errors.
672 return;
Ted Kremenek035d8792007-10-12 20:51:52 +0000673 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000674
675 // Perform type checking on width/precision specifier.
676 Expr *E = TheCall->getArg(format_idx+numConversions);
677 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
678 if (BT->getKind() == BuiltinType::Int)
679 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000680
Chris Lattnerf17cb362009-02-18 17:49:48 +0000681 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Chris Lattner68d88f02007-12-28 05:31:15 +0000682
683 if (Str[StrIdx-1] == '.')
Chris Lattner9d2cf082008-11-19 05:27:50 +0000684 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000685 << E->getType() << E->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000686 else
Chris Lattner9d2cf082008-11-19 05:27:50 +0000687 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000688 << E->getType() << E->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000689
690 break;
691 }
692
693 // Characters which can terminate a format conversion
694 // (e.g. "%d"). Characters that specify length modifiers or
695 // other flags are handled by the default case below.
696 //
697 // FIXME: additional checks will go into the following cases.
698 case 'i':
699 case 'd':
700 case 'o':
701 case 'u':
702 case 'x':
703 case 'X':
704 case 'D':
705 case 'O':
706 case 'U':
707 case 'e':
708 case 'E':
709 case 'f':
710 case 'F':
711 case 'g':
712 case 'G':
713 case 'a':
714 case 'A':
715 case 'c':
716 case 'C':
717 case 'S':
718 case 's':
719 case 'p':
720 ++numConversions;
721 CurrentState = state_OrdChr;
722 break;
723
724 // CHECK: Are we using "%n"? Issue a warning.
725 case 'n': {
726 ++numConversions;
727 CurrentState = state_OrdChr;
Chris Lattnerf17cb362009-02-18 17:49:48 +0000728 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
729 LastConversionIdx);
Chris Lattner68d88f02007-12-28 05:31:15 +0000730
Chris Lattner9d2cf082008-11-19 05:27:50 +0000731 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000732 break;
733 }
Ted Kremenek225a14c2008-06-16 18:00:42 +0000734
735 // Handle "%@"
736 case '@':
737 // %@ is allowed in ObjC format strings only.
738 if(ObjCFExpr != NULL)
739 CurrentState = state_OrdChr;
740 else {
741 // Issue a warning: invalid format conversion.
Chris Lattnerf17cb362009-02-18 17:49:48 +0000742 SourceLocation Loc =
743 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek225a14c2008-06-16 18:00:42 +0000744
Chris Lattner77d52da2008-11-20 06:06:08 +0000745 Diag(Loc, diag::warn_printf_invalid_conversion)
746 << std::string(Str+LastConversionIdx,
747 Str+std::min(LastConversionIdx+2, StrLen))
748 << OrigFormatExpr->getSourceRange();
Ted Kremenek225a14c2008-06-16 18:00:42 +0000749 }
750 ++numConversions;
751 break;
752
Chris Lattner68d88f02007-12-28 05:31:15 +0000753 // Handle "%%"
754 case '%':
755 // Sanity check: Was the first "%" character the previous one?
756 // If not, we will assume that we have a malformed format
757 // conversion, and that the current "%" character is the start
758 // of a new conversion.
759 if (StrIdx - LastConversionIdx == 1)
760 CurrentState = state_OrdChr;
761 else {
762 // Issue a warning: invalid format conversion.
Chris Lattnerf17cb362009-02-18 17:49:48 +0000763 SourceLocation Loc =
764 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattner68d88f02007-12-28 05:31:15 +0000765
Chris Lattner77d52da2008-11-20 06:06:08 +0000766 Diag(Loc, diag::warn_printf_invalid_conversion)
767 << std::string(Str+LastConversionIdx, Str+StrIdx)
768 << OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000769
770 // This conversion is broken. Advance to the next format
771 // conversion.
772 LastConversionIdx = StrIdx;
773 ++numConversions;
Ted Kremenek081ed872007-08-14 17:39:48 +0000774 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000775 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000776
Chris Lattner68d88f02007-12-28 05:31:15 +0000777 default:
778 // This case catches all other characters: flags, widths, etc.
779 // We should eventually process those as well.
780 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000781 }
782 }
783
784 if (CurrentState == state_Conversion) {
785 // Issue a warning: invalid format conversion.
Chris Lattnerf17cb362009-02-18 17:49:48 +0000786 SourceLocation Loc =
787 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +0000788
Chris Lattner77d52da2008-11-20 06:06:08 +0000789 Diag(Loc, diag::warn_printf_invalid_conversion)
790 << std::string(Str+LastConversionIdx,
791 Str+std::min(LastConversionIdx+2, StrLen))
792 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000793 return;
794 }
795
796 if (!HasVAListArg) {
797 // CHECK: Does the number of format conversions exceed the number
798 // of data arguments?
799 if (numConversions > numDataArgs) {
Chris Lattnerf17cb362009-02-18 17:49:48 +0000800 SourceLocation Loc =
801 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +0000802
Chris Lattner9d2cf082008-11-19 05:27:50 +0000803 Diag(Loc, diag::warn_printf_insufficient_data_args)
804 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000805 }
806 // CHECK: Does the number of data arguments exceed the number of
807 // format conversions in the format string?
808 else if (numConversions < numDataArgs)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000809 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000810 diag::warn_printf_too_many_data_args)
811 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000812 }
813}
Ted Kremenek45925ab2007-08-17 16:46:58 +0000814
815//===--- CHECK: Return Address of Stack Variable --------------------------===//
816
817static DeclRefExpr* EvalVal(Expr *E);
818static DeclRefExpr* EvalAddr(Expr* E);
819
820/// CheckReturnStackAddr - Check if a return statement returns the address
821/// of a stack variable.
822void
823Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
824 SourceLocation ReturnLoc) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000825
Ted Kremenek45925ab2007-08-17 16:46:58 +0000826 // Perform checking for returned stack addresses.
Steve Naroffd6163f32008-09-05 22:11:13 +0000827 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000828 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner65cae292008-11-19 08:23:25 +0000829 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattnerb1753422008-11-23 21:45:46 +0000830 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroff503996b2008-09-16 22:25:10 +0000831
832 // Skip over implicit cast expressions when checking for block expressions.
833 if (ImplicitCastExpr *IcExpr =
834 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
835 RetValExp = IcExpr->getSubExpr();
836
Steve Naroff3eac7692008-09-10 19:17:48 +0000837 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000838 Diag(C->getLocStart(), diag::err_ret_local_block)
839 << C->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +0000840 }
841 // Perform checking for stack values returned by reference.
842 else if (lhsType->isReferenceType()) {
Douglas Gregor21a04f32008-10-27 19:41:14 +0000843 // Check for a reference to the stack
844 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000845 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattnerb1753422008-11-23 21:45:46 +0000846 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +0000847 }
848}
849
850/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
851/// check if the expression in a return statement evaluates to an address
852/// to a location on the stack. The recursion is used to traverse the
853/// AST of the return expression, with recursion backtracking when we
854/// encounter a subexpression that (1) clearly does not lead to the address
855/// of a stack variable or (2) is something we cannot determine leads to
856/// the address of a stack variable based on such local checking.
857///
Ted Kremenekda1300a2007-08-28 17:02:55 +0000858/// EvalAddr processes expressions that are pointers that are used as
859/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek45925ab2007-08-17 16:46:58 +0000860/// At the base case of the recursion is a check for a DeclRefExpr* in
861/// the refers to a stack variable.
862///
863/// This implementation handles:
864///
865/// * pointer-to-pointer casts
866/// * implicit conversions from array references to pointers
867/// * taking the address of fields
868/// * arbitrary interplay between "&" and "*" operators
869/// * pointer arithmetic from an address of a stack variable
870/// * taking the address of an array element where the array is on the stack
871static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000872 // We should only be called for evaluating pointer expressions.
Steve Naroffd6163f32008-09-05 22:11:13 +0000873 assert((E->getType()->isPointerType() ||
874 E->getType()->isBlockPointerType() ||
Ted Kremenek42730c52008-01-07 19:49:32 +0000875 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner68d88f02007-12-28 05:31:15 +0000876 "EvalAddr only works on pointers");
Ted Kremenek45925ab2007-08-17 16:46:58 +0000877
878 // Our "symbolic interpreter" is just a dispatch off the currently
879 // viewed AST node. We then recursively traverse the AST by calling
880 // EvalAddr and EvalVal appropriately.
881 switch (E->getStmtClass()) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000882 case Stmt::ParenExprClass:
883 // Ignore parentheses.
884 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000885
Chris Lattner68d88f02007-12-28 05:31:15 +0000886 case Stmt::UnaryOperatorClass: {
887 // The only unary operator that make sense to handle here
888 // is AddrOf. All others don't make sense as pointers.
889 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek45925ab2007-08-17 16:46:58 +0000890
Chris Lattner68d88f02007-12-28 05:31:15 +0000891 if (U->getOpcode() == UnaryOperator::AddrOf)
892 return EvalVal(U->getSubExpr());
893 else
Ted Kremenek45925ab2007-08-17 16:46:58 +0000894 return NULL;
895 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000896
897 case Stmt::BinaryOperatorClass: {
898 // Handle pointer arithmetic. All other binary operators are not valid
899 // in this context.
900 BinaryOperator *B = cast<BinaryOperator>(E);
901 BinaryOperator::Opcode op = B->getOpcode();
902
903 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
904 return NULL;
905
906 Expr *Base = B->getLHS();
907
908 // Determine which argument is the real pointer base. It could be
909 // the RHS argument instead of the LHS.
910 if (!Base->getType()->isPointerType()) Base = B->getRHS();
911
912 assert (Base->getType()->isPointerType());
913 return EvalAddr(Base);
914 }
Steve Naroff3eac7692008-09-10 19:17:48 +0000915
Chris Lattner68d88f02007-12-28 05:31:15 +0000916 // For conditional operators we need to see if either the LHS or RHS are
917 // valid DeclRefExpr*s. If one of them is valid, we return it.
918 case Stmt::ConditionalOperatorClass: {
919 ConditionalOperator *C = cast<ConditionalOperator>(E);
920
921 // Handle the GNU extension for missing LHS.
922 if (Expr *lhsExpr = C->getLHS())
923 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
924 return LHS;
925
926 return EvalAddr(C->getRHS());
927 }
928
Ted Kremenekea19edd2008-08-07 00:49:01 +0000929 // For casts, we need to handle conversions from arrays to
930 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor21a04f32008-10-27 19:41:14 +0000931 case Stmt::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +0000932 case Stmt::CStyleCastExprClass:
Douglas Gregor21a04f32008-10-27 19:41:14 +0000933 case Stmt::CXXFunctionalCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000934 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekea19edd2008-08-07 00:49:01 +0000935 QualType T = SubExpr->getType();
936
Steve Naroffd6163f32008-09-05 22:11:13 +0000937 if (SubExpr->getType()->isPointerType() ||
938 SubExpr->getType()->isBlockPointerType() ||
939 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenekea19edd2008-08-07 00:49:01 +0000940 return EvalAddr(SubExpr);
941 else if (T->isArrayType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000942 return EvalVal(SubExpr);
Chris Lattner68d88f02007-12-28 05:31:15 +0000943 else
Ted Kremenekea19edd2008-08-07 00:49:01 +0000944 return 0;
Chris Lattner68d88f02007-12-28 05:31:15 +0000945 }
946
947 // C++ casts. For dynamic casts, static casts, and const casts, we
948 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor21a04f32008-10-27 19:41:14 +0000949 // through the cast. In the case the dynamic cast doesn't fail (and
950 // return NULL), we take the conservative route and report cases
Chris Lattner68d88f02007-12-28 05:31:15 +0000951 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor21a04f32008-10-27 19:41:14 +0000952 // FIXME: The comment about is wrong; we're not always converting
953 // from pointer to pointer. I'm guessing that this code should also
954 // handle references to objects.
955 case Stmt::CXXStaticCastExprClass:
956 case Stmt::CXXDynamicCastExprClass:
957 case Stmt::CXXConstCastExprClass:
958 case Stmt::CXXReinterpretCastExprClass: {
959 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffd6163f32008-09-05 22:11:13 +0000960 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000961 return EvalAddr(S);
962 else
963 return NULL;
Chris Lattner68d88f02007-12-28 05:31:15 +0000964 }
965
966 // Everything else: we simply don't reason about them.
967 default:
968 return NULL;
969 }
Ted Kremenek45925ab2007-08-17 16:46:58 +0000970}
971
972
973/// EvalVal - This function is complements EvalAddr in the mutual recursion.
974/// See the comments for EvalAddr for more details.
975static DeclRefExpr* EvalVal(Expr *E) {
976
Ted Kremenekda1300a2007-08-28 17:02:55 +0000977 // We should only be called for evaluating non-pointer expressions, or
978 // expressions with a pointer type that are not used as references but instead
979 // are l-values (e.g., DeclRefExpr with a pointer type).
980
Ted Kremenek45925ab2007-08-17 16:46:58 +0000981 // Our "symbolic interpreter" is just a dispatch off the currently
982 // viewed AST node. We then recursively traverse the AST by calling
983 // EvalAddr and EvalVal appropriately.
984 switch (E->getStmtClass()) {
Douglas Gregor566782a2009-01-06 05:10:23 +0000985 case Stmt::DeclRefExprClass:
986 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000987 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
988 // at code that refers to a variable's name. We check if it has local
989 // storage within the function, and if so, return the expression.
990 DeclRefExpr *DR = cast<DeclRefExpr>(E);
991
992 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor81c29152008-10-29 00:13:59 +0000993 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek45925ab2007-08-17 16:46:58 +0000994
995 return NULL;
996 }
997
998 case Stmt::ParenExprClass:
999 // Ignore parentheses.
1000 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1001
1002 case Stmt::UnaryOperatorClass: {
1003 // The only unary operator that make sense to handle here
1004 // is Deref. All others don't resolve to a "name." This includes
1005 // handling all sorts of rvalues passed to a unary operator.
1006 UnaryOperator *U = cast<UnaryOperator>(E);
1007
1008 if (U->getOpcode() == UnaryOperator::Deref)
1009 return EvalAddr(U->getSubExpr());
1010
1011 return NULL;
1012 }
1013
1014 case Stmt::ArraySubscriptExprClass: {
1015 // Array subscripts are potential references to data on the stack. We
1016 // retrieve the DeclRefExpr* for the array variable if it indeed
1017 // has local storage.
Ted Kremenek1c1700f2007-08-20 16:18:38 +00001018 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek45925ab2007-08-17 16:46:58 +00001019 }
1020
1021 case Stmt::ConditionalOperatorClass: {
1022 // For conditional operators we need to see if either the LHS or RHS are
1023 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1024 ConditionalOperator *C = cast<ConditionalOperator>(E);
1025
Anders Carlsson37365fc2007-11-30 19:04:31 +00001026 // Handle the GNU extension for missing LHS.
1027 if (Expr *lhsExpr = C->getLHS())
1028 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1029 return LHS;
1030
1031 return EvalVal(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +00001032 }
1033
1034 // Accesses to members are potential references to data on the stack.
1035 case Stmt::MemberExprClass: {
1036 MemberExpr *M = cast<MemberExpr>(E);
1037
1038 // Check for indirect access. We only want direct field accesses.
1039 if (!M->isArrow())
1040 return EvalVal(M->getBase());
1041 else
1042 return NULL;
1043 }
1044
1045 // Everything else: we simply don't reason about them.
1046 default:
1047 return NULL;
1048 }
1049}
Ted Kremenek30c66752007-11-25 00:58:00 +00001050
1051//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1052
1053/// Check for comparisons of floating point operands using != and ==.
1054/// Issue a warning if these are no self-comparisons, as they are not likely
1055/// to do what the programmer intended.
1056void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1057 bool EmitWarning = true;
1058
Ted Kremenek87e30c52008-01-17 16:57:34 +00001059 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek24c61682008-01-17 17:55:13 +00001060 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek30c66752007-11-25 00:58:00 +00001061
1062 // Special case: check for x == x (which is OK).
1063 // Do not emit warnings for such cases.
1064 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1065 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1066 if (DRL->getDecl() == DRR->getDecl())
1067 EmitWarning = false;
1068
Ted Kremenek33159832007-11-29 00:59:04 +00001069
1070 // Special case: check for comparisons against literals that can be exactly
1071 // represented by APFloat. In such cases, do not emit a warning. This
1072 // is a heuristic: often comparison against such literals are used to
1073 // detect if a value in a variable has not changed. This clearly can
1074 // lead to false negatives.
1075 if (EmitWarning) {
1076 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1077 if (FLL->isExact())
1078 EmitWarning = false;
1079 }
1080 else
1081 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1082 if (FLR->isExact())
1083 EmitWarning = false;
1084 }
1085 }
1086
Ted Kremenek30c66752007-11-25 00:58:00 +00001087 // Check for comparisons with builtin types.
Sebastian Redl8b769972009-01-19 00:08:26 +00001088 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001089 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregorb5af7382009-02-14 18:57:46 +00001090 if (CL->isBuiltinCall(Context))
Ted Kremenek30c66752007-11-25 00:58:00 +00001091 EmitWarning = false;
1092
Sebastian Redl8b769972009-01-19 00:08:26 +00001093 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001094 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregorb5af7382009-02-14 18:57:46 +00001095 if (CR->isBuiltinCall(Context))
Ted Kremenek30c66752007-11-25 00:58:00 +00001096 EmitWarning = false;
1097
1098 // Emit the diagnostic.
1099 if (EmitWarning)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001100 Diag(loc, diag::warn_floatingpoint_eq)
1101 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek30c66752007-11-25 00:58:00 +00001102}