blob: f03e1f931032996e3ef17d69021b7c3b38a0a255 [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
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000016#include "clang/Sema/SemaInternal.h"
John McCall781472f2010-08-25 08:40:02 +000017#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000018#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000019#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000020#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000021#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000023#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000024#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000025#include "clang/AST/DeclObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000028#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000029#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "llvm/ADT/BitVector.h"
31#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000032#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000033#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000034#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000035#include "clang/Basic/ConvertUTF.h"
36
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000037#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000038using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000039using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000040
Chris Lattner60800082009-02-18 17:49:48 +000041/// getLocationOfStringLiteralByte - Return a source location that points to the
42/// specified byte of the specified string literal.
43///
44/// Strings are amazingly complex. They can be formed from multiple tokens and
45/// can have escape sequences in them in addition to the usual trigraph and
46/// escaped newline business. This routine handles this complexity.
47///
48SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49 unsigned ByteNo) const {
50 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000051
Chris Lattner60800082009-02-18 17:49:48 +000052 // Loop over all of the tokens in this string until we find the one that
53 // contains the byte we're looking for.
54 unsigned TokNo = 0;
55 while (1) {
56 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
57 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000058
Chris Lattner60800082009-02-18 17:49:48 +000059 // Get the spelling of the string so that we can get the data that makes up
60 // the string literal, not the identifier for the macro it is potentially
61 // expanded through.
62 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
63
64 // Re-lex the token to get its length and original spelling.
65 std::pair<FileID, unsigned> LocInfo =
66 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
Douglas Gregorf715ca12010-03-16 00:06:06 +000067 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000068 llvm::StringRef Buffer = SourceMgr.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +000069 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +000070 return StrTokSpellingLoc;
71
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000072 const char *StrData = Buffer.data()+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000073
Chris Lattner60800082009-02-18 17:49:48 +000074 // Create a langops struct and enable trigraphs. This is sufficient for
75 // relexing tokens.
76 LangOptions LangOpts;
77 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000078
Chris Lattner60800082009-02-18 17:49:48 +000079 // Create a lexer starting at the beginning of this token.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000080 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.begin(), StrData,
81 Buffer.end());
Chris Lattner60800082009-02-18 17:49:48 +000082 Token TheTok;
83 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000084
Chris Lattner443e53c2009-02-18 19:26:42 +000085 // Use the StringLiteralParser to compute the length of the string in bytes.
Douglas Gregorb90f4b32010-05-26 05:35:51 +000086 StringLiteralParser SLP(&TheTok, 1, PP, /*Complain=*/false);
Chris Lattner443e53c2009-02-18 19:26:42 +000087 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000088
Chris Lattner2197c962009-02-18 18:52:52 +000089 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000090 if (ByteNo < TokNumBytes ||
91 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000092 unsigned Offset =
Douglas Gregorb90f4b32010-05-26 05:35:51 +000093 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP,
94 /*Complain=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattner719e6152009-02-18 19:21:10 +000096 // Now that we know the offset of the token in the spelling, use the
97 // preprocessor to get the offset in the original source.
98 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000099 }
Mike Stump1eb44332009-09-09 15:08:12 +0000100
Chris Lattner60800082009-02-18 17:49:48 +0000101 // Move to the next string token.
102 ++TokNo;
103 ByteNo -= TokNumBytes;
104 }
105}
106
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000107/// CheckablePrintfAttr - does a function call have a "printf" attribute
108/// and arguments that merit checking?
109bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
110 if (Format->getType() == "printf") return true;
111 if (Format->getType() == "printf0") {
112 // printf0 allows null "format" string; if so don't check format/args
113 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000114 // Does the index refer to the implicit object argument?
115 if (isa<CXXMemberCallExpr>(TheCall)) {
116 if (format_idx == 0)
117 return false;
118 --format_idx;
119 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000120 if (format_idx < TheCall->getNumArgs()) {
121 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +0000122 if (!Format->isNullPointerConstant(Context,
123 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000124 return true;
125 }
126 }
127 return false;
128}
Chris Lattner60800082009-02-18 17:49:48 +0000129
John McCall60d7b3a2010-08-24 06:29:42 +0000130ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000131Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000132 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000133
Chris Lattner946928f2010-10-01 23:23:24 +0000134 // Find out if any arguments are required to be integer constant expressions.
135 unsigned ICEArguments = 0;
136 ASTContext::GetBuiltinTypeError Error;
137 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
138 if (Error != ASTContext::GE_None)
139 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
140
141 // If any arguments are required to be ICE's, check and diagnose.
142 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
143 // Skip arguments not required to be ICE's.
144 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
145
146 llvm::APSInt Result;
147 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
148 return true;
149 ICEArguments &= ~(1 << ArgNo);
150 }
151
Anders Carlssond406bf02009-08-16 01:56:34 +0000152 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000153 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000154 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000155 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000156 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000157 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000158 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000159 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000160 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161 if (SemaBuiltinVAStart(TheCall))
162 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000163 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000164 case Builtin::BI__builtin_isgreater:
165 case Builtin::BI__builtin_isgreaterequal:
166 case Builtin::BI__builtin_isless:
167 case Builtin::BI__builtin_islessequal:
168 case Builtin::BI__builtin_islessgreater:
169 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 if (SemaBuiltinUnorderedCompare(TheCall))
171 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000172 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000173 case Builtin::BI__builtin_fpclassify:
174 if (SemaBuiltinFPClassification(TheCall, 6))
175 return ExprError();
176 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000177 case Builtin::BI__builtin_isfinite:
178 case Builtin::BI__builtin_isinf:
179 case Builtin::BI__builtin_isinf_sign:
180 case Builtin::BI__builtin_isnan:
181 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000182 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000183 return ExprError();
184 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000185 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000186 return SemaBuiltinShuffleVector(TheCall);
187 // TheCall will be freed by the smart pointer here, but that's fine, since
188 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000189 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000190 if (SemaBuiltinPrefetch(TheCall))
191 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000192 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000193 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000194 if (SemaBuiltinObjectSize(TheCall))
195 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000196 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000197 case Builtin::BI__builtin_longjmp:
198 if (SemaBuiltinLongjmp(TheCall))
199 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000200 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000201 case Builtin::BI__sync_fetch_and_add:
202 case Builtin::BI__sync_fetch_and_sub:
203 case Builtin::BI__sync_fetch_and_or:
204 case Builtin::BI__sync_fetch_and_and:
205 case Builtin::BI__sync_fetch_and_xor:
206 case Builtin::BI__sync_add_and_fetch:
207 case Builtin::BI__sync_sub_and_fetch:
208 case Builtin::BI__sync_and_and_fetch:
209 case Builtin::BI__sync_or_and_fetch:
210 case Builtin::BI__sync_xor_and_fetch:
211 case Builtin::BI__sync_val_compare_and_swap:
212 case Builtin::BI__sync_bool_compare_and_swap:
213 case Builtin::BI__sync_lock_test_and_set:
214 case Builtin::BI__sync_lock_release:
Chandler Carruthd2014572010-07-09 18:59:35 +0000215 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000216 }
217
218 // Since the target specific builtins for each arch overlap, only check those
219 // of the arch we are compiling for.
220 if (BuiltinID >= Builtin::FirstTSBuiltin) {
221 switch (Context.Target.getTriple().getArch()) {
222 case llvm::Triple::arm:
223 case llvm::Triple::thumb:
224 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
225 return ExprError();
226 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000227 default:
228 break;
229 }
230 }
231
232 return move(TheCallResult);
233}
234
Nate Begeman61eecf52010-06-14 05:21:25 +0000235// Get the valid immediate range for the specified NEON type code.
236static unsigned RFT(unsigned t, bool shift = false) {
237 bool quad = t & 0x10;
238
239 switch (t & 0x7) {
240 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000241 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000242 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000243 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000244 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000245 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000246 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000247 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000248 case 4: // f32
249 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000250 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000251 case 5: // poly8
252 assert(!shift && "cannot shift polynomial types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000253 return (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000254 case 6: // poly16
255 assert(!shift && "cannot shift polynomial types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000256 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000257 case 7: // float16
258 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000259 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000260 }
261 return 0;
262}
263
Nate Begeman26a31422010-06-08 02:47:44 +0000264bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000265 llvm::APSInt Result;
266
Nate Begeman0d15c532010-06-13 04:47:52 +0000267 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000268 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000269 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000270#define GET_NEON_OVERLOAD_CHECK
271#include "clang/Basic/arm_neon.inc"
272#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000273 }
274
Nate Begeman0d15c532010-06-13 04:47:52 +0000275 // For NEON intrinsics which are overloaded on vector element type, validate
276 // the immediate which specifies which variant to emit.
277 if (mask) {
278 unsigned ArgNo = TheCall->getNumArgs()-1;
279 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
280 return true;
281
Nate Begeman61eecf52010-06-14 05:21:25 +0000282 TV = Result.getLimitedValue(32);
283 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000284 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
285 << TheCall->getArg(ArgNo)->getSourceRange();
286 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000287
Nate Begeman0d15c532010-06-13 04:47:52 +0000288 // For NEON intrinsics which take an immediate value as part of the
289 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000290 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000291 switch (BuiltinID) {
292 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000293 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
294 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000295 case ARM::BI__builtin_arm_vcvtr_f:
296 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000297#define GET_NEON_IMMEDIATE_CHECK
298#include "clang/Basic/arm_neon.inc"
299#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000300 };
301
Nate Begeman61eecf52010-06-14 05:21:25 +0000302 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000303 if (SemaBuiltinConstantArg(TheCall, i, Result))
304 return true;
305
Nate Begeman61eecf52010-06-14 05:21:25 +0000306 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000307 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000308 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000309 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000310 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000311
Nate Begeman99c40bb2010-08-03 21:32:34 +0000312 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000313 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000314}
Daniel Dunbarde454282008-10-02 18:44:07 +0000315
Anders Carlssond406bf02009-08-16 01:56:34 +0000316/// CheckFunctionCall - Check a direct function call for various correctness
317/// and safety properties not strictly enforced by the C type system.
318bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
319 // Get the IdentifierInfo* for the called function.
320 IdentifierInfo *FnInfo = FDecl->getIdentifier();
321
322 // None of the checks below are needed for functions that don't have
323 // simple names (e.g., C++ conversion functions).
324 if (!FnInfo)
325 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Daniel Dunbarde454282008-10-02 18:44:07 +0000327 // FIXME: This mechanism should be abstracted to be less fragile and
328 // more efficient. For example, just map function ids to custom
329 // handlers.
330
Ted Kremenekc82faca2010-09-09 04:33:05 +0000331 // Printf and scanf checking.
332 for (specific_attr_iterator<FormatAttr>
333 i = FDecl->specific_attr_begin<FormatAttr>(),
334 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
335
336 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000337 const bool b = Format->getType() == "scanf";
338 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000339 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000340 CheckPrintfScanfArguments(TheCall, HasVAListArg,
341 Format->getFormatIdx() - 1,
342 HasVAListArg ? 0 : Format->getFirstArg() - 1,
343 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000344 }
Chris Lattner59907c42007-08-10 20:18:51 +0000345 }
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Ted Kremenekc82faca2010-09-09 04:33:05 +0000347 for (specific_attr_iterator<NonNullAttr>
348 i = FDecl->specific_attr_begin<NonNullAttr>(),
349 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Sean Huntcf807c42010-08-18 23:23:40 +0000350 CheckNonNullArguments(*i, TheCall);
Ted Kremenekc82faca2010-09-09 04:33:05 +0000351 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000352
Anders Carlssond406bf02009-08-16 01:56:34 +0000353 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000354}
355
Anders Carlssond406bf02009-08-16 01:56:34 +0000356bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000357 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000358 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000359 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000360 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000362 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
363 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000364 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000366 QualType Ty = V->getType();
367 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000368 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Ted Kremenek826a3452010-07-16 02:11:22 +0000370 const bool b = Format->getType() == "scanf";
371 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000372 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Anders Carlssond406bf02009-08-16 01:56:34 +0000374 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000375 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
376 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000377
378 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000379}
380
Chris Lattner5caa3702009-05-08 06:58:22 +0000381/// SemaBuiltinAtomicOverloaded - We have a call to a function like
382/// __sync_fetch_and_add, which is an overloaded function based on the pointer
383/// type of its first argument. The main ActOnCallExpr routines have already
384/// promoted the types of arguments because all of these calls are prototyped as
385/// void(...).
386///
387/// This function goes through and does final semantic checking for these
388/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000389ExprResult
390Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000391 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000392 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
393 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
394
395 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000396 if (TheCall->getNumArgs() < 1) {
397 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
398 << 0 << 1 << TheCall->getNumArgs()
399 << TheCall->getCallee()->getSourceRange();
400 return ExprError();
401 }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chris Lattner5caa3702009-05-08 06:58:22 +0000403 // Inspect the first argument of the atomic builtin. This should always be
404 // a pointer type, whose element is an integral scalar or pointer type.
405 // Because it is a pointer type, we don't have to worry about any implicit
406 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000407 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000408 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruthd2014572010-07-09 18:59:35 +0000409 if (!FirstArg->getType()->isPointerType()) {
410 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
411 << FirstArg->getType() << FirstArg->getSourceRange();
412 return ExprError();
413 }
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chandler Carruthd2014572010-07-09 18:59:35 +0000415 QualType ValType =
416 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000417 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000418 !ValType->isBlockPointerType()) {
419 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
420 << FirstArg->getType() << FirstArg->getSourceRange();
421 return ExprError();
422 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000423
Chandler Carruth8d13d222010-07-18 20:54:12 +0000424 // The majority of builtins return a value, but a few have special return
425 // types, so allow them to override appropriately below.
426 QualType ResultType = ValType;
427
Chris Lattner5caa3702009-05-08 06:58:22 +0000428 // We need to figure out which concrete builtin this maps onto. For example,
429 // __sync_fetch_and_add with a 2 byte object turns into
430 // __sync_fetch_and_add_2.
431#define BUILTIN_ROW(x) \
432 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
433 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner5caa3702009-05-08 06:58:22 +0000435 static const unsigned BuiltinIndices[][5] = {
436 BUILTIN_ROW(__sync_fetch_and_add),
437 BUILTIN_ROW(__sync_fetch_and_sub),
438 BUILTIN_ROW(__sync_fetch_and_or),
439 BUILTIN_ROW(__sync_fetch_and_and),
440 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner5caa3702009-05-08 06:58:22 +0000442 BUILTIN_ROW(__sync_add_and_fetch),
443 BUILTIN_ROW(__sync_sub_and_fetch),
444 BUILTIN_ROW(__sync_and_and_fetch),
445 BUILTIN_ROW(__sync_or_and_fetch),
446 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattner5caa3702009-05-08 06:58:22 +0000448 BUILTIN_ROW(__sync_val_compare_and_swap),
449 BUILTIN_ROW(__sync_bool_compare_and_swap),
450 BUILTIN_ROW(__sync_lock_test_and_set),
451 BUILTIN_ROW(__sync_lock_release)
452 };
Mike Stump1eb44332009-09-09 15:08:12 +0000453#undef BUILTIN_ROW
454
Chris Lattner5caa3702009-05-08 06:58:22 +0000455 // Determine the index of the size.
456 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000457 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000458 case 1: SizeIndex = 0; break;
459 case 2: SizeIndex = 1; break;
460 case 4: SizeIndex = 2; break;
461 case 8: SizeIndex = 3; break;
462 case 16: SizeIndex = 4; break;
463 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000464 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
465 << FirstArg->getType() << FirstArg->getSourceRange();
466 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Chris Lattner5caa3702009-05-08 06:58:22 +0000469 // Each of these builtins has one pointer argument, followed by some number of
470 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
471 // that we ignore. Find out which row of BuiltinIndices to read from as well
472 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000473 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000474 unsigned BuiltinIndex, NumFixed = 1;
475 switch (BuiltinID) {
476 default: assert(0 && "Unknown overloaded atomic builtin!");
477 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
478 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
479 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
480 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
481 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000483 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
484 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
485 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
486 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
487 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Chris Lattner5caa3702009-05-08 06:58:22 +0000489 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000490 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000491 NumFixed = 2;
492 break;
493 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000494 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000495 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000496 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000497 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000498 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000499 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000500 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000501 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000502 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000503 break;
504 }
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Chris Lattner5caa3702009-05-08 06:58:22 +0000506 // Now that we know how many fixed arguments we expect, first check that we
507 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000508 if (TheCall->getNumArgs() < 1+NumFixed) {
509 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
510 << 0 << 1+NumFixed << TheCall->getNumArgs()
511 << TheCall->getCallee()->getSourceRange();
512 return ExprError();
513 }
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000515 // Get the decl for the concrete builtin from this, we can tell what the
516 // concrete integer type we should convert to is.
517 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
518 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
519 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000520 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000521 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
522 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000523
John McCallf871d0c2010-08-07 06:22:56 +0000524 // The first argument --- the pointer --- has a fixed type; we
525 // deduce the types of the rest of the arguments accordingly. Walk
526 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000527 for (unsigned i = 0; i != NumFixed; ++i) {
528 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Chris Lattner5caa3702009-05-08 06:58:22 +0000530 // If the argument is an implicit cast, then there was a promotion due to
531 // "...", just remove it now.
532 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
533 Arg = ICE->getSubExpr();
534 ICE->setSubExpr(0);
Chris Lattner5caa3702009-05-08 06:58:22 +0000535 TheCall->setArg(i+1, Arg);
536 }
Mike Stump1eb44332009-09-09 15:08:12 +0000537
Chris Lattner5caa3702009-05-08 06:58:22 +0000538 // GCC does an implicit conversion to the pointer or integer ValType. This
539 // can fail in some cases (1i -> int**), check for this error case now.
John McCall2de56d12010-08-25 11:45:40 +0000540 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +0000541 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000542 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, BasePath))
Chandler Carruthd2014572010-07-09 18:59:35 +0000543 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner5caa3702009-05-08 06:58:22 +0000545 // Okay, we have something that *can* be converted to the right type. Check
546 // to see if there is a potentially weird extension going on here. This can
547 // happen when you do an atomic operation on something like an char* and
548 // pass in 42. The 42 gets converted to char. This is even more strange
549 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000550 // FIXME: Do this check.
John McCall5baba9d2010-08-25 10:28:54 +0000551 ImpCastExprToType(Arg, ValType, Kind, VK_RValue, &BasePath);
Chris Lattner5caa3702009-05-08 06:58:22 +0000552 TheCall->setArg(i+1, Arg);
553 }
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Chris Lattner5caa3702009-05-08 06:58:22 +0000555 // Switch the DeclRefExpr to refer to the new decl.
556 DRE->setDecl(NewBuiltinDecl);
557 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000558
Chris Lattner5caa3702009-05-08 06:58:22 +0000559 // Set the callee in the CallExpr.
560 // FIXME: This leaks the original parens and implicit casts.
561 Expr *PromotedCall = DRE;
562 UsualUnaryConversions(PromotedCall);
563 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000565 // Change the result type of the call to match the original value type. This
566 // is arbitrary, but the codegen for these builtins ins design to handle it
567 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000568 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000569
570 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000571}
572
573
Chris Lattner69039812009-02-18 06:01:06 +0000574/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000575/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000576/// Note: It might also make sense to do the UTF-16 conversion here (would
577/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000578bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000579 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000580 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
581
582 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000583 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
584 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000585 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000586 }
Mike Stump1eb44332009-09-09 15:08:12 +0000587
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000588 size_t NulPos = Literal->getString().find('\0');
589 if (NulPos != llvm::StringRef::npos) {
590 Diag(getLocationOfStringLiteralByte(Literal, NulPos),
591 diag::warn_cfstring_literal_contains_nul_character)
592 << Arg->getSourceRange();
Daniel Dunbarf015b032009-09-22 10:03:52 +0000593 }
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000594 if (Literal->containsNonAsciiOrNull()) {
595 llvm::StringRef String = Literal->getString();
596 unsigned NumBytes = String.size();
597 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
598 const UTF8 *FromPtr = (UTF8 *)String.data();
599 UTF16 *ToPtr = &ToBuf[0];
600
601 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
602 &ToPtr, ToPtr + NumBytes,
603 strictConversion);
604 // Check for conversion failure.
605 if (Result != conversionOK)
606 Diag(Arg->getLocStart(),
607 diag::warn_cfstring_truncated) << Arg->getSourceRange();
608 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000609 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000610}
611
Chris Lattnerc27c6652007-12-20 00:05:45 +0000612/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
613/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000614bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
615 Expr *Fn = TheCall->getCallee();
616 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000617 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000618 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000619 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
620 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000621 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000622 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000623 return true;
624 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000625
626 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000627 return Diag(TheCall->getLocEnd(),
628 diag::err_typecheck_call_too_few_args_at_least)
629 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000630 }
631
Chris Lattnerc27c6652007-12-20 00:05:45 +0000632 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000633 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000634 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000635 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000636 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000637 else if (FunctionDecl *FD = getCurFunctionDecl())
638 isVariadic = FD->isVariadic();
639 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000640 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Chris Lattnerc27c6652007-12-20 00:05:45 +0000642 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000643 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
644 return true;
645 }
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Chris Lattner30ce3442007-12-19 23:59:04 +0000647 // Verify that the second argument to the builtin is the last argument of the
648 // current function or method.
649 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000650 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000651
Anders Carlsson88cf2262008-02-11 04:20:54 +0000652 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
653 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000654 // FIXME: This isn't correct for methods (results in bogus warning).
655 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000656 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000657 if (CurBlock)
658 LastArg = *(CurBlock->TheDecl->param_end()-1);
659 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000660 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000661 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000662 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000663 SecondArgIsLastNamedArgument = PV == LastArg;
664 }
665 }
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattner30ce3442007-12-19 23:59:04 +0000667 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000668 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000669 diag::warn_second_parameter_of_va_start_not_last_named_argument);
670 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000671}
Chris Lattner30ce3442007-12-19 23:59:04 +0000672
Chris Lattner1b9a0792007-12-20 00:26:33 +0000673/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
674/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000675bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
676 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000677 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000678 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000679 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000680 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000681 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000682 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000683 << SourceRange(TheCall->getArg(2)->getLocStart(),
684 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Chris Lattner925e60d2007-12-28 05:29:59 +0000686 Expr *OrigArg0 = TheCall->getArg(0);
687 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000688
Chris Lattner1b9a0792007-12-20 00:26:33 +0000689 // Do standard promotions between the two arguments, returning their common
690 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000691 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000692
693 // Make sure any conversions are pushed back into the call; this is
694 // type safe since unordered compare builtins are declared as "_Bool
695 // foo(...)".
696 TheCall->setArg(0, OrigArg0);
697 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Douglas Gregorcde01732009-05-19 22:10:17 +0000699 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
700 return false;
701
Chris Lattner1b9a0792007-12-20 00:26:33 +0000702 // If the common type isn't a real floating type, then the arguments were
703 // invalid for this operation.
704 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000705 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000706 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000707 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000708 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Chris Lattner1b9a0792007-12-20 00:26:33 +0000710 return false;
711}
712
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000713/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
714/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000715/// to check everything. We expect the last argument to be a floating point
716/// value.
717bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
718 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000719 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000720 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000721 if (TheCall->getNumArgs() > NumArgs)
722 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000723 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000724 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000725 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000726 (*(TheCall->arg_end()-1))->getLocEnd());
727
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000728 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Eli Friedman9ac6f622009-08-31 20:06:00 +0000730 if (OrigArg->isTypeDependent())
731 return false;
732
Chris Lattner81368fb2010-05-06 05:50:07 +0000733 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000734 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000735 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000736 diag::err_typecheck_call_invalid_unary_fp)
737 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000738
Chris Lattner81368fb2010-05-06 05:50:07 +0000739 // If this is an implicit conversion from float -> double, remove it.
740 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
741 Expr *CastArg = Cast->getSubExpr();
742 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
743 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
744 "promotion from float to double is the only expected cast here");
745 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000746 TheCall->setArg(NumArgs-1, CastArg);
747 OrigArg = CastArg;
748 }
749 }
750
Eli Friedman9ac6f622009-08-31 20:06:00 +0000751 return false;
752}
753
Eli Friedmand38617c2008-05-14 19:38:39 +0000754/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
755// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000756ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000757 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000758 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000759 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000760 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000761 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000762
Nate Begeman37b6a572010-06-08 00:16:34 +0000763 // Determine which of the following types of shufflevector we're checking:
764 // 1) unary, vector mask: (lhs, mask)
765 // 2) binary, vector mask: (lhs, rhs, mask)
766 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
767 QualType resType = TheCall->getArg(0)->getType();
768 unsigned numElements = 0;
769
Douglas Gregorcde01732009-05-19 22:10:17 +0000770 if (!TheCall->getArg(0)->isTypeDependent() &&
771 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000772 QualType LHSType = TheCall->getArg(0)->getType();
773 QualType RHSType = TheCall->getArg(1)->getType();
774
775 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000776 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000777 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000778 TheCall->getArg(1)->getLocEnd());
779 return ExprError();
780 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000781
782 numElements = LHSType->getAs<VectorType>()->getNumElements();
783 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Nate Begeman37b6a572010-06-08 00:16:34 +0000785 // Check to see if we have a call with 2 vector arguments, the unary shuffle
786 // with mask. If so, verify that RHS is an integer vector type with the
787 // same number of elts as lhs.
788 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000789 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000790 RHSType->getAs<VectorType>()->getNumElements() != numElements)
791 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
792 << SourceRange(TheCall->getArg(1)->getLocStart(),
793 TheCall->getArg(1)->getLocEnd());
794 numResElements = numElements;
795 }
796 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000797 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000798 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000799 TheCall->getArg(1)->getLocEnd());
800 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000801 } else if (numElements != numResElements) {
802 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000803 resType = Context.getVectorType(eltType, numResElements,
804 VectorType::NotAltiVec);
Douglas Gregorcde01732009-05-19 22:10:17 +0000805 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000806 }
807
808 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000809 if (TheCall->getArg(i)->isTypeDependent() ||
810 TheCall->getArg(i)->isValueDependent())
811 continue;
812
Nate Begeman37b6a572010-06-08 00:16:34 +0000813 llvm::APSInt Result(32);
814 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
815 return ExprError(Diag(TheCall->getLocStart(),
816 diag::err_shufflevector_nonconstant_argument)
817 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000818
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000819 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000820 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000821 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000822 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000823 }
824
825 llvm::SmallVector<Expr*, 32> exprs;
826
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000827 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000828 exprs.push_back(TheCall->getArg(i));
829 TheCall->setArg(i, 0);
830 }
831
Nate Begemana88dc302009-08-12 02:10:25 +0000832 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000833 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000834 TheCall->getCallee()->getLocStart(),
835 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000836}
Chris Lattner30ce3442007-12-19 23:59:04 +0000837
Daniel Dunbar4493f792008-07-21 22:59:13 +0000838/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
839// This is declared to take (const void*, ...) and can take two
840// optional constant int args.
841bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000842 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000843
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000844 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000845 return Diag(TheCall->getLocEnd(),
846 diag::err_typecheck_call_too_many_args_at_most)
847 << 0 /*function call*/ << 3 << NumArgs
848 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000849
850 // Argument 0 is checked for us and the remaining arguments must be
851 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000852 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000853 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000854
Eli Friedman9aef7262009-12-04 00:30:06 +0000855 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000856 if (SemaBuiltinConstantArg(TheCall, i, Result))
857 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Daniel Dunbar4493f792008-07-21 22:59:13 +0000859 // FIXME: gcc issues a warning and rewrites these to 0. These
860 // seems especially odd for the third argument since the default
861 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000862 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000863 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000864 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000865 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000866 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000867 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000868 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000869 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000870 }
871 }
872
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000873 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000874}
875
Eric Christopher691ebc32010-04-17 02:26:23 +0000876/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
877/// TheCall is a constant expression.
878bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
879 llvm::APSInt &Result) {
880 Expr *Arg = TheCall->getArg(ArgNum);
881 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
882 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
883
884 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
885
886 if (!Arg->isIntegerConstantExpr(Result, Context))
887 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000888 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000889
Chris Lattner21fb98e2009-09-23 06:06:36 +0000890 return false;
891}
892
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000893/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
894/// int type). This simply type checks that type is one of the defined
895/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000896// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000897bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000898 llvm::APSInt Result;
899
900 // Check constant-ness first.
901 if (SemaBuiltinConstantArg(TheCall, 1, Result))
902 return true;
903
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000904 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000905 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000906 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
907 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000908 }
909
910 return false;
911}
912
Eli Friedman586d6a82009-05-03 06:04:26 +0000913/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000914/// This checks that val is a constant 1.
915bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
916 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000917 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000918
Eric Christopher691ebc32010-04-17 02:26:23 +0000919 // TODO: This is less than ideal. Overload this to take a value.
920 if (SemaBuiltinConstantArg(TheCall, 1, Result))
921 return true;
922
923 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000924 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
925 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
926
927 return false;
928}
929
Ted Kremenekd30ef872009-01-12 23:09:09 +0000930// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000931bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
932 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000933 unsigned format_idx, unsigned firstDataArg,
934 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000935 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000936 if (E->isTypeDependent() || E->isValueDependent())
937 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000938
939 switch (E->getStmtClass()) {
940 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000941 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000942 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
943 format_idx, firstDataArg, isPrintf)
944 && SemaCheckStringLiteral(C->getRHS(), TheCall, HasVAListArg,
945 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000946 }
947
Ted Kremenek95355bb2010-09-09 03:51:42 +0000948 case Stmt::IntegerLiteralClass:
949 // Technically -Wformat-nonliteral does not warn about this case.
950 // The behavior of printf and friends in this case is implementation
951 // dependent. Ideally if the format string cannot be null then
952 // it should have a 'nonnull' attribute in the function prototype.
953 return true;
954
Ted Kremenekd30ef872009-01-12 23:09:09 +0000955 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000956 E = cast<ImplicitCastExpr>(E)->getSubExpr();
957 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000958 }
959
960 case Stmt::ParenExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000961 E = cast<ParenExpr>(E)->getSubExpr();
962 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000963 }
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Ted Kremenek082d9362009-03-20 21:35:28 +0000965 case Stmt::DeclRefExprClass: {
966 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Ted Kremenek082d9362009-03-20 21:35:28 +0000968 // As an exception, do not flag errors for variables binding to
969 // const string literals.
970 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
971 bool isConstant = false;
972 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000973
Ted Kremenek082d9362009-03-20 21:35:28 +0000974 if (const ArrayType *AT = Context.getAsArrayType(T)) {
975 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000976 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000977 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000978 PT->getPointeeType().isConstant(Context);
979 }
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Ted Kremenek082d9362009-03-20 21:35:28 +0000981 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000982 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000983 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000984 HasVAListArg, format_idx, firstDataArg,
985 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000986 }
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Anders Carlssond966a552009-06-28 19:55:58 +0000988 // For vprintf* functions (i.e., HasVAListArg==true), we add a
989 // special check to see if the format string is a function parameter
990 // of the function calling the printf function. If the function
991 // has an attribute indicating it is a printf-like function, then we
992 // should suppress warnings concerning non-literals being used in a call
993 // to a vprintf function. For example:
994 //
995 // void
996 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
997 // va_list ap;
998 // va_start(ap, fmt);
999 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1000 // ...
1001 //
1002 //
1003 // FIXME: We don't have full attribute support yet, so just check to see
1004 // if the argument is a DeclRefExpr that references a parameter. We'll
1005 // add proper support for checking the attribute later.
1006 if (HasVAListArg)
1007 if (isa<ParmVarDecl>(VD))
1008 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001009 }
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Ted Kremenek082d9362009-03-20 21:35:28 +00001011 return false;
1012 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001013
Anders Carlsson8f031b32009-06-27 04:05:33 +00001014 case Stmt::CallExprClass: {
1015 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001016 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001017 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1018 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1019 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001020 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001021 unsigned ArgIndex = FA->getFormatIdx();
1022 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001023
1024 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001025 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001026 }
1027 }
1028 }
1029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Anders Carlsson8f031b32009-06-27 04:05:33 +00001031 return false;
1032 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001033 case Stmt::ObjCStringLiteralClass:
1034 case Stmt::StringLiteralClass: {
1035 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Ted Kremenek082d9362009-03-20 21:35:28 +00001037 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001038 StrE = ObjCFExpr->getString();
1039 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001040 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Ted Kremenekd30ef872009-01-12 23:09:09 +00001042 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001043 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1044 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001045 return true;
1046 }
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Ted Kremenekd30ef872009-01-12 23:09:09 +00001048 return false;
1049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Ted Kremenek082d9362009-03-20 21:35:28 +00001051 default:
1052 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001053 }
1054}
1055
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001056void
Mike Stump1eb44332009-09-09 15:08:12 +00001057Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1058 const CallExpr *TheCall) {
Sean Huntcf807c42010-08-18 23:23:40 +00001059 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1060 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001061 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +00001062 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001063 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001064 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +00001065 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1066 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001067 }
1068}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001069
Ted Kremenek826a3452010-07-16 02:11:22 +00001070/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1071/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001072void
Ted Kremenek826a3452010-07-16 02:11:22 +00001073Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1074 unsigned format_idx, unsigned firstDataArg,
1075 bool isPrintf) {
1076
Ted Kremenek082d9362009-03-20 21:35:28 +00001077 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001078
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001079 // The way the format attribute works in GCC, the implicit this argument
1080 // of member functions is counted. However, it doesn't appear in our own
1081 // lists, so decrement format_idx in that case.
1082 if (isa<CXXMemberCallExpr>(TheCall)) {
1083 // Catch a format attribute mistakenly referring to the object argument.
1084 if (format_idx == 0)
1085 return;
1086 --format_idx;
1087 if(firstDataArg != 0)
1088 --firstDataArg;
1089 }
1090
Ted Kremenek826a3452010-07-16 02:11:22 +00001091 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001092 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001093 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001094 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001095 return;
1096 }
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Ted Kremenek082d9362009-03-20 21:35:28 +00001098 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Chris Lattner59907c42007-08-10 20:18:51 +00001100 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001101 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001102 // Dynamically generated format strings are difficult to
1103 // automatically vet at compile time. Requiring that format strings
1104 // are string literals: (1) permits the checking of format strings by
1105 // the compiler and thereby (2) can practically remove the source of
1106 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001107
Mike Stump1eb44332009-09-09 15:08:12 +00001108 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001109 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001110 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001111 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001112 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001113 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001114 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001115
Chris Lattner655f1412009-04-29 04:59:47 +00001116 // If there are no arguments specified, warn with -Wformat-security, otherwise
1117 // warn only with -Wformat-nonliteral.
1118 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001119 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001120 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001121 << OrigFormatExpr->getSourceRange();
1122 else
Mike Stump1eb44332009-09-09 15:08:12 +00001123 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001124 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001125 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001126}
Ted Kremenek71895b92007-08-14 17:39:48 +00001127
Ted Kremeneke0e53132010-01-28 23:39:18 +00001128namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001129class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1130protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001131 Sema &S;
1132 const StringLiteral *FExpr;
1133 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001134 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001135 const unsigned NumDataArgs;
1136 const bool IsObjCLiteral;
1137 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001138 const bool HasVAListArg;
1139 const CallExpr *TheCall;
1140 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001141 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001142 bool usesPositionalArgs;
1143 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001144public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001145 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001146 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001147 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001148 const char *beg, bool hasVAListArg,
1149 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001150 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001151 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001152 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001153 IsObjCLiteral(isObjCLiteral), Beg(beg),
1154 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001155 TheCall(theCall), FormatIdx(formatIdx),
1156 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001157 CoveredArgs.resize(numDataArgs);
1158 CoveredArgs.reset();
1159 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001160
Ted Kremenek07d161f2010-01-29 01:50:07 +00001161 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001162
Ted Kremenek826a3452010-07-16 02:11:22 +00001163 void HandleIncompleteSpecifier(const char *startSpecifier,
1164 unsigned specifierLen);
1165
Ted Kremenekefaff192010-02-27 01:41:03 +00001166 virtual void HandleInvalidPosition(const char *startSpecifier,
1167 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001168 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001169
1170 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1171
Ted Kremeneke0e53132010-01-28 23:39:18 +00001172 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001173
Ted Kremenek826a3452010-07-16 02:11:22 +00001174protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001175 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1176 const char *startSpec,
1177 unsigned specifierLen,
1178 const char *csStart, unsigned csLen);
1179
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001180 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001181 CharSourceRange getSpecifierRange(const char *startSpecifier,
1182 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001183 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001184
Ted Kremenek0d277352010-01-29 01:06:55 +00001185 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001186
1187 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1188 const analyze_format_string::ConversionSpecifier &CS,
1189 const char *startSpecifier, unsigned specifierLen,
1190 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001191};
1192}
1193
Ted Kremenek826a3452010-07-16 02:11:22 +00001194SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001195 return OrigFormatExpr->getSourceRange();
1196}
1197
Ted Kremenek826a3452010-07-16 02:11:22 +00001198CharSourceRange CheckFormatHandler::
1199getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001200 SourceLocation Start = getLocationOfByte(startSpecifier);
1201 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1202
1203 // Advance the end SourceLocation by one due to half-open ranges.
1204 End = End.getFileLocWithOffset(1);
1205
1206 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001207}
1208
Ted Kremenek826a3452010-07-16 02:11:22 +00001209SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001210 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001211}
1212
Ted Kremenek826a3452010-07-16 02:11:22 +00001213void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1214 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001215 SourceLocation Loc = getLocationOfByte(startSpecifier);
1216 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001217 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001218}
1219
Ted Kremenekefaff192010-02-27 01:41:03 +00001220void
Ted Kremenek826a3452010-07-16 02:11:22 +00001221CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1222 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001223 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001224 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1225 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001226}
1227
Ted Kremenek826a3452010-07-16 02:11:22 +00001228void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001229 unsigned posLen) {
1230 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001231 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1232 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001233}
1234
Ted Kremenek826a3452010-07-16 02:11:22 +00001235void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1236 // The presence of a null character is likely an error.
1237 S.Diag(getLocationOfByte(nullCharacter),
1238 diag::warn_printf_format_string_contains_null_char)
1239 << getFormatStringRange();
1240}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001241
Ted Kremenek826a3452010-07-16 02:11:22 +00001242const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1243 return TheCall->getArg(FirstDataArg + i);
1244}
1245
1246void CheckFormatHandler::DoneProcessing() {
1247 // Does the number of data arguments exceed the number of
1248 // format conversions in the format string?
1249 if (!HasVAListArg) {
1250 // Find any arguments that weren't covered.
1251 CoveredArgs.flip();
1252 signed notCoveredArg = CoveredArgs.find_first();
1253 if (notCoveredArg >= 0) {
1254 assert((unsigned)notCoveredArg < NumDataArgs);
1255 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1256 diag::warn_printf_data_arg_not_used)
1257 << getFormatStringRange();
1258 }
1259 }
1260}
1261
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001262bool
1263CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1264 SourceLocation Loc,
1265 const char *startSpec,
1266 unsigned specifierLen,
1267 const char *csStart,
1268 unsigned csLen) {
1269
1270 bool keepGoing = true;
1271 if (argIndex < NumDataArgs) {
1272 // Consider the argument coverered, even though the specifier doesn't
1273 // make sense.
1274 CoveredArgs.set(argIndex);
1275 }
1276 else {
1277 // If argIndex exceeds the number of data arguments we
1278 // don't issue a warning because that is just a cascade of warnings (and
1279 // they may have intended '%%' anyway). We don't want to continue processing
1280 // the format string after this point, however, as we will like just get
1281 // gibberish when trying to match arguments.
1282 keepGoing = false;
1283 }
1284
1285 S.Diag(Loc, diag::warn_format_invalid_conversion)
1286 << llvm::StringRef(csStart, csLen)
1287 << getSpecifierRange(startSpec, specifierLen);
1288
1289 return keepGoing;
1290}
1291
Ted Kremenek666a1972010-07-26 19:45:42 +00001292bool
1293CheckFormatHandler::CheckNumArgs(
1294 const analyze_format_string::FormatSpecifier &FS,
1295 const analyze_format_string::ConversionSpecifier &CS,
1296 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1297
1298 if (argIndex >= NumDataArgs) {
1299 if (FS.usesPositionalArg()) {
1300 S.Diag(getLocationOfByte(CS.getStart()),
1301 diag::warn_printf_positional_arg_exceeds_data_args)
1302 << (argIndex+1) << NumDataArgs
1303 << getSpecifierRange(startSpecifier, specifierLen);
1304 }
1305 else {
1306 S.Diag(getLocationOfByte(CS.getStart()),
1307 diag::warn_printf_insufficient_data_args)
1308 << getSpecifierRange(startSpecifier, specifierLen);
1309 }
1310
1311 return false;
1312 }
1313 return true;
1314}
1315
Ted Kremenek826a3452010-07-16 02:11:22 +00001316//===--- CHECK: Printf format string checking ------------------------------===//
1317
1318namespace {
1319class CheckPrintfHandler : public CheckFormatHandler {
1320public:
1321 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1322 const Expr *origFormatExpr, unsigned firstDataArg,
1323 unsigned numDataArgs, bool isObjCLiteral,
1324 const char *beg, bool hasVAListArg,
1325 const CallExpr *theCall, unsigned formatIdx)
1326 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1327 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1328 theCall, formatIdx) {}
1329
1330
1331 bool HandleInvalidPrintfConversionSpecifier(
1332 const analyze_printf::PrintfSpecifier &FS,
1333 const char *startSpecifier,
1334 unsigned specifierLen);
1335
1336 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1337 const char *startSpecifier,
1338 unsigned specifierLen);
1339
1340 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1341 const char *startSpecifier, unsigned specifierLen);
1342 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1343 const analyze_printf::OptionalAmount &Amt,
1344 unsigned type,
1345 const char *startSpecifier, unsigned specifierLen);
1346 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1347 const analyze_printf::OptionalFlag &flag,
1348 const char *startSpecifier, unsigned specifierLen);
1349 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1350 const analyze_printf::OptionalFlag &ignoredFlag,
1351 const analyze_printf::OptionalFlag &flag,
1352 const char *startSpecifier, unsigned specifierLen);
1353};
1354}
1355
1356bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1357 const analyze_printf::PrintfSpecifier &FS,
1358 const char *startSpecifier,
1359 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001360 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001361 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001362
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001363 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1364 getLocationOfByte(CS.getStart()),
1365 startSpecifier, specifierLen,
1366 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001367}
1368
Ted Kremenek826a3452010-07-16 02:11:22 +00001369bool CheckPrintfHandler::HandleAmount(
1370 const analyze_format_string::OptionalAmount &Amt,
1371 unsigned k, const char *startSpecifier,
1372 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001373
1374 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001375 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001376 unsigned argIndex = Amt.getArgIndex();
1377 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001378 S.Diag(getLocationOfByte(Amt.getStart()),
1379 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001380 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001381 // Don't do any more checking. We will just emit
1382 // spurious errors.
1383 return false;
1384 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001385
Ted Kremenek0d277352010-01-29 01:06:55 +00001386 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001387 // Although not in conformance with C99, we also allow the argument to be
1388 // an 'unsigned int' as that is a reasonably safe case. GCC also
1389 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001390 CoveredArgs.set(argIndex);
1391 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001392 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001393
1394 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1395 assert(ATR.isValid());
1396
1397 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001398 S.Diag(getLocationOfByte(Amt.getStart()),
1399 diag::warn_printf_asterisk_wrong_type)
1400 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001401 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001402 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001403 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001404 // Don't do any more checking. We will just emit
1405 // spurious errors.
1406 return false;
1407 }
1408 }
1409 }
1410 return true;
1411}
Ted Kremenek0d277352010-01-29 01:06:55 +00001412
Tom Caree4ee9662010-06-17 19:00:27 +00001413void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001414 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001415 const analyze_printf::OptionalAmount &Amt,
1416 unsigned type,
1417 const char *startSpecifier,
1418 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001419 const analyze_printf::PrintfConversionSpecifier &CS =
1420 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001421 switch (Amt.getHowSpecified()) {
1422 case analyze_printf::OptionalAmount::Constant:
1423 S.Diag(getLocationOfByte(Amt.getStart()),
1424 diag::warn_printf_nonsensical_optional_amount)
1425 << type
1426 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001427 << getSpecifierRange(startSpecifier, specifierLen)
1428 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001429 Amt.getConstantLength()));
1430 break;
1431
1432 default:
1433 S.Diag(getLocationOfByte(Amt.getStart()),
1434 diag::warn_printf_nonsensical_optional_amount)
1435 << type
1436 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001437 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001438 break;
1439 }
1440}
1441
Ted Kremenek826a3452010-07-16 02:11:22 +00001442void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001443 const analyze_printf::OptionalFlag &flag,
1444 const char *startSpecifier,
1445 unsigned specifierLen) {
1446 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001447 const analyze_printf::PrintfConversionSpecifier &CS =
1448 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001449 S.Diag(getLocationOfByte(flag.getPosition()),
1450 diag::warn_printf_nonsensical_flag)
1451 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001452 << getSpecifierRange(startSpecifier, specifierLen)
1453 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001454}
1455
1456void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001457 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001458 const analyze_printf::OptionalFlag &ignoredFlag,
1459 const analyze_printf::OptionalFlag &flag,
1460 const char *startSpecifier,
1461 unsigned specifierLen) {
1462 // Warn about ignored flag with a fixit removal.
1463 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1464 diag::warn_printf_ignored_flag)
1465 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001466 << getSpecifierRange(startSpecifier, specifierLen)
1467 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001468 ignoredFlag.getPosition(), 1));
1469}
1470
Ted Kremeneke0e53132010-01-28 23:39:18 +00001471bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001472CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001473 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001474 const char *startSpecifier,
1475 unsigned specifierLen) {
1476
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001477 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001478 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001479 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001480
Ted Kremenekbaa40062010-07-19 22:01:06 +00001481 if (FS.consumesDataArgument()) {
1482 if (atFirstArg) {
1483 atFirstArg = false;
1484 usesPositionalArgs = FS.usesPositionalArg();
1485 }
1486 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1487 // Cannot mix-and-match positional and non-positional arguments.
1488 S.Diag(getLocationOfByte(CS.getStart()),
1489 diag::warn_format_mix_positional_nonpositional_args)
1490 << getSpecifierRange(startSpecifier, specifierLen);
1491 return false;
1492 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001493 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001494
Ted Kremenekefaff192010-02-27 01:41:03 +00001495 // First check if the field width, precision, and conversion specifier
1496 // have matching data arguments.
1497 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1498 startSpecifier, specifierLen)) {
1499 return false;
1500 }
1501
1502 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1503 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001504 return false;
1505 }
1506
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001507 if (!CS.consumesDataArgument()) {
1508 // FIXME: Technically specifying a precision or field width here
1509 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001510 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001511 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001512
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001513 // Consume the argument.
1514 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001515 if (argIndex < NumDataArgs) {
1516 // The check to see if the argIndex is valid will come later.
1517 // We set the bit here because we may exit early from this
1518 // function if we encounter some other error.
1519 CoveredArgs.set(argIndex);
1520 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001521
1522 // Check for using an Objective-C specific conversion specifier
1523 // in a non-ObjC literal.
1524 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001525 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1526 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001527 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001528
Tom Caree4ee9662010-06-17 19:00:27 +00001529 // Check for invalid use of field width
1530 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001531 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001532 startSpecifier, specifierLen);
1533 }
1534
1535 // Check for invalid use of precision
1536 if (!FS.hasValidPrecision()) {
1537 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1538 startSpecifier, specifierLen);
1539 }
1540
1541 // Check each flag does not conflict with any other component.
1542 if (!FS.hasValidLeadingZeros())
1543 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1544 if (!FS.hasValidPlusPrefix())
1545 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001546 if (!FS.hasValidSpacePrefix())
1547 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001548 if (!FS.hasValidAlternativeForm())
1549 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1550 if (!FS.hasValidLeftJustified())
1551 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1552
1553 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001554 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1555 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1556 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001557 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1558 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1559 startSpecifier, specifierLen);
1560
1561 // Check the length modifier is valid with the given conversion specifier.
1562 const LengthModifier &LM = FS.getLengthModifier();
1563 if (!FS.hasValidLengthModifier())
1564 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001565 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001566 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001567 << getSpecifierRange(startSpecifier, specifierLen)
1568 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001569 LM.getLength()));
1570
1571 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001572 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001573 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001574 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001575 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001576 // Continue checking the other format specifiers.
1577 return true;
1578 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001579
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001580 // The remaining checks depend on the data arguments.
1581 if (HasVAListArg)
1582 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001583
Ted Kremenek666a1972010-07-26 19:45:42 +00001584 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001585 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001586
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001587 // Now type check the data expression that matches the
1588 // format specifier.
1589 const Expr *Ex = getDataArg(argIndex);
1590 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1591 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1592 // Check if we didn't match because of an implicit cast from a 'char'
1593 // or 'short' to an 'int'. This is done because printf is a varargs
1594 // function.
1595 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1596 if (ICE->getType() == S.Context.IntTy)
1597 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1598 return true;
1599
1600 // We may be able to offer a FixItHint if it is a supported type.
1601 PrintfSpecifier fixedFS = FS;
1602 bool success = fixedFS.fixType(Ex->getType());
1603
1604 if (success) {
1605 // Get the fix string from the fixed format specifier
1606 llvm::SmallString<128> buf;
1607 llvm::raw_svector_ostream os(buf);
1608 fixedFS.toString(os);
1609
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001610 // FIXME: getRepresentativeType() perhaps should return a string
1611 // instead of a QualType to better handle when the representative
1612 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001613 S.Diag(getLocationOfByte(CS.getStart()),
1614 diag::warn_printf_conversion_argument_type_mismatch)
1615 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1616 << getSpecifierRange(startSpecifier, specifierLen)
1617 << Ex->getSourceRange()
1618 << FixItHint::CreateReplacement(
1619 getSpecifierRange(startSpecifier, specifierLen),
1620 os.str());
1621 }
1622 else {
1623 S.Diag(getLocationOfByte(CS.getStart()),
1624 diag::warn_printf_conversion_argument_type_mismatch)
1625 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1626 << getSpecifierRange(startSpecifier, specifierLen)
1627 << Ex->getSourceRange();
1628 }
1629 }
1630
Ted Kremeneke0e53132010-01-28 23:39:18 +00001631 return true;
1632}
1633
Ted Kremenek826a3452010-07-16 02:11:22 +00001634//===--- CHECK: Scanf format string checking ------------------------------===//
1635
1636namespace {
1637class CheckScanfHandler : public CheckFormatHandler {
1638public:
1639 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1640 const Expr *origFormatExpr, unsigned firstDataArg,
1641 unsigned numDataArgs, bool isObjCLiteral,
1642 const char *beg, bool hasVAListArg,
1643 const CallExpr *theCall, unsigned formatIdx)
1644 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1645 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1646 theCall, formatIdx) {}
1647
1648 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1649 const char *startSpecifier,
1650 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001651
1652 bool HandleInvalidScanfConversionSpecifier(
1653 const analyze_scanf::ScanfSpecifier &FS,
1654 const char *startSpecifier,
1655 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001656
1657 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001658};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001659}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001660
Ted Kremenekb7c21012010-07-16 18:28:03 +00001661void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1662 const char *end) {
1663 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1664 << getSpecifierRange(start, end - start);
1665}
1666
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001667bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1668 const analyze_scanf::ScanfSpecifier &FS,
1669 const char *startSpecifier,
1670 unsigned specifierLen) {
1671
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001672 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001673 FS.getConversionSpecifier();
1674
1675 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1676 getLocationOfByte(CS.getStart()),
1677 startSpecifier, specifierLen,
1678 CS.getStart(), CS.getLength());
1679}
1680
Ted Kremenek826a3452010-07-16 02:11:22 +00001681bool CheckScanfHandler::HandleScanfSpecifier(
1682 const analyze_scanf::ScanfSpecifier &FS,
1683 const char *startSpecifier,
1684 unsigned specifierLen) {
1685
1686 using namespace analyze_scanf;
1687 using namespace analyze_format_string;
1688
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001689 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001690
Ted Kremenekbaa40062010-07-19 22:01:06 +00001691 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1692 // be used to decide if we are using positional arguments consistently.
1693 if (FS.consumesDataArgument()) {
1694 if (atFirstArg) {
1695 atFirstArg = false;
1696 usesPositionalArgs = FS.usesPositionalArg();
1697 }
1698 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1699 // Cannot mix-and-match positional and non-positional arguments.
1700 S.Diag(getLocationOfByte(CS.getStart()),
1701 diag::warn_format_mix_positional_nonpositional_args)
1702 << getSpecifierRange(startSpecifier, specifierLen);
1703 return false;
1704 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001705 }
1706
1707 // Check if the field with is non-zero.
1708 const OptionalAmount &Amt = FS.getFieldWidth();
1709 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1710 if (Amt.getConstantAmount() == 0) {
1711 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1712 Amt.getConstantLength());
1713 S.Diag(getLocationOfByte(Amt.getStart()),
1714 diag::warn_scanf_nonzero_width)
1715 << R << FixItHint::CreateRemoval(R);
1716 }
1717 }
1718
1719 if (!FS.consumesDataArgument()) {
1720 // FIXME: Technically specifying a precision or field width here
1721 // makes no sense. Worth issuing a warning at some point.
1722 return true;
1723 }
1724
1725 // Consume the argument.
1726 unsigned argIndex = FS.getArgIndex();
1727 if (argIndex < NumDataArgs) {
1728 // The check to see if the argIndex is valid will come later.
1729 // We set the bit here because we may exit early from this
1730 // function if we encounter some other error.
1731 CoveredArgs.set(argIndex);
1732 }
1733
Ted Kremenek1e51c202010-07-20 20:04:47 +00001734 // Check the length modifier is valid with the given conversion specifier.
1735 const LengthModifier &LM = FS.getLengthModifier();
1736 if (!FS.hasValidLengthModifier()) {
1737 S.Diag(getLocationOfByte(LM.getStart()),
1738 diag::warn_format_nonsensical_length)
1739 << LM.toString() << CS.toString()
1740 << getSpecifierRange(startSpecifier, specifierLen)
1741 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1742 LM.getLength()));
1743 }
1744
Ted Kremenek826a3452010-07-16 02:11:22 +00001745 // The remaining checks depend on the data arguments.
1746 if (HasVAListArg)
1747 return true;
1748
Ted Kremenek666a1972010-07-26 19:45:42 +00001749 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001750 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001751
1752 // FIXME: Check that the argument type matches the format specifier.
1753
1754 return true;
1755}
1756
1757void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001758 const Expr *OrigFormatExpr,
1759 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001760 unsigned format_idx, unsigned firstDataArg,
1761 bool isPrintf) {
1762
Ted Kremeneke0e53132010-01-28 23:39:18 +00001763 // CHECK: is the format string a wide literal?
1764 if (FExpr->isWide()) {
1765 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001766 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001767 << OrigFormatExpr->getSourceRange();
1768 return;
1769 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001770
Ted Kremeneke0e53132010-01-28 23:39:18 +00001771 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001772 llvm::StringRef StrRef = FExpr->getString();
1773 const char *Str = StrRef.data();
1774 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001775
Ted Kremeneke0e53132010-01-28 23:39:18 +00001776 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001777 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001778 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001779 << OrigFormatExpr->getSourceRange();
1780 return;
1781 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001782
1783 if (isPrintf) {
1784 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1785 TheCall->getNumArgs() - firstDataArg,
1786 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1787 HasVAListArg, TheCall, format_idx);
1788
1789 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1790 H.DoneProcessing();
1791 }
1792 else {
1793 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1794 TheCall->getNumArgs() - firstDataArg,
1795 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1796 HasVAListArg, TheCall, format_idx);
1797
1798 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1799 H.DoneProcessing();
1800 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001801}
1802
Ted Kremenek06de2762007-08-17 16:46:58 +00001803//===--- CHECK: Return Address of Stack Variable --------------------------===//
1804
1805static DeclRefExpr* EvalVal(Expr *E);
1806static DeclRefExpr* EvalAddr(Expr* E);
1807
1808/// CheckReturnStackAddr - Check if a return statement returns the address
1809/// of a stack variable.
1810void
1811Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1812 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Ted Kremenek06de2762007-08-17 16:46:58 +00001814 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001815 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001816 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001817 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001818 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001819
Steve Naroffc50a4a52008-09-16 22:25:10 +00001820 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001821 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001822
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001823 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001824 if (C->hasBlockDeclRefExprs())
1825 Diag(C->getLocStart(), diag::err_ret_local_block)
1826 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001827
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001828 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1829 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1830 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001831
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001832 } else if (lhsType->isReferenceType()) {
1833 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001834 // Check for a reference to the stack
1835 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001836 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001837 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001838 }
1839}
1840
1841/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1842/// check if the expression in a return statement evaluates to an address
1843/// to a location on the stack. The recursion is used to traverse the
1844/// AST of the return expression, with recursion backtracking when we
1845/// encounter a subexpression that (1) clearly does not lead to the address
1846/// of a stack variable or (2) is something we cannot determine leads to
1847/// the address of a stack variable based on such local checking.
1848///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001849/// EvalAddr processes expressions that are pointers that are used as
1850/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001851/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001852/// the refers to a stack variable.
1853///
1854/// This implementation handles:
1855///
1856/// * pointer-to-pointer casts
1857/// * implicit conversions from array references to pointers
1858/// * taking the address of fields
1859/// * arbitrary interplay between "&" and "*" operators
1860/// * pointer arithmetic from an address of a stack variable
1861/// * taking the address of an array element where the array is on the stack
1862static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001863 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001864 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001865 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001866 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001867 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Ted Kremenek06de2762007-08-17 16:46:58 +00001869 // Our "symbolic interpreter" is just a dispatch off the currently
1870 // viewed AST node. We then recursively traverse the AST by calling
1871 // EvalAddr and EvalVal appropriately.
1872 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001873 case Stmt::ParenExprClass:
1874 // Ignore parentheses.
1875 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001876
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001877 case Stmt::UnaryOperatorClass: {
1878 // The only unary operator that make sense to handle here
1879 // is AddrOf. All others don't make sense as pointers.
1880 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001881
John McCall2de56d12010-08-25 11:45:40 +00001882 if (U->getOpcode() == UO_AddrOf)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001883 return EvalVal(U->getSubExpr());
1884 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001885 return NULL;
1886 }
Mike Stump1eb44332009-09-09 15:08:12 +00001887
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001888 case Stmt::BinaryOperatorClass: {
1889 // Handle pointer arithmetic. All other binary operators are not valid
1890 // in this context.
1891 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001892 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001893
John McCall2de56d12010-08-25 11:45:40 +00001894 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001895 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001896
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001897 Expr *Base = B->getLHS();
1898
1899 // Determine which argument is the real pointer base. It could be
1900 // the RHS argument instead of the LHS.
1901 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001902
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001903 assert (Base->getType()->isPointerType());
1904 return EvalAddr(Base);
1905 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001906
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001907 // For conditional operators we need to see if either the LHS or RHS are
1908 // valid DeclRefExpr*s. If one of them is valid, we return it.
1909 case Stmt::ConditionalOperatorClass: {
1910 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001912 // Handle the GNU extension for missing LHS.
1913 if (Expr *lhsExpr = C->getLHS())
1914 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1915 return LHS;
1916
1917 return EvalAddr(C->getRHS());
1918 }
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Ted Kremenek54b52742008-08-07 00:49:01 +00001920 // For casts, we need to handle conversions from arrays to
1921 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001922 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001923 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001924 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001925 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001926 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Steve Naroffdd972f22008-09-05 22:11:13 +00001928 if (SubExpr->getType()->isPointerType() ||
1929 SubExpr->getType()->isBlockPointerType() ||
1930 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001931 return EvalAddr(SubExpr);
1932 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001933 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001934 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001935 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001936 }
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001938 // C++ casts. For dynamic casts, static casts, and const casts, we
1939 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001940 // through the cast. In the case the dynamic cast doesn't fail (and
1941 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001942 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001943 // FIXME: The comment about is wrong; we're not always converting
1944 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001945 // handle references to objects.
1946 case Stmt::CXXStaticCastExprClass:
1947 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001948 case Stmt::CXXConstCastExprClass:
1949 case Stmt::CXXReinterpretCastExprClass: {
1950 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001951 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001952 return EvalAddr(S);
1953 else
1954 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001955 }
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001957 // Everything else: we simply don't reason about them.
1958 default:
1959 return NULL;
1960 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001961}
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Ted Kremenek06de2762007-08-17 16:46:58 +00001963
1964/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1965/// See the comments for EvalAddr for more details.
1966static DeclRefExpr* EvalVal(Expr *E) {
Ted Kremenek68957a92010-08-04 20:01:07 +00001967do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001968 // We should only be called for evaluating non-pointer expressions, or
1969 // expressions with a pointer type that are not used as references but instead
1970 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Ted Kremenek06de2762007-08-17 16:46:58 +00001972 // Our "symbolic interpreter" is just a dispatch off the currently
1973 // viewed AST node. We then recursively traverse the AST by calling
1974 // EvalAddr and EvalVal appropriately.
1975 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00001976 case Stmt::ImplicitCastExprClass: {
1977 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00001978 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00001979 E = IE->getSubExpr();
1980 continue;
1981 }
1982 return NULL;
1983 }
1984
Douglas Gregora2813ce2009-10-23 18:54:35 +00001985 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001986 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1987 // at code that refers to a variable's name. We check if it has local
1988 // storage within the function, and if so, return the expression.
1989 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001990
Ted Kremenek06de2762007-08-17 16:46:58 +00001991 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001992 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1993
Ted Kremenek06de2762007-08-17 16:46:58 +00001994 return NULL;
1995 }
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Ted Kremenek68957a92010-08-04 20:01:07 +00001997 case Stmt::ParenExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001998 // Ignore parentheses.
Ted Kremenek68957a92010-08-04 20:01:07 +00001999 E = cast<ParenExpr>(E)->getSubExpr();
2000 continue;
2001 }
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Ted Kremenek06de2762007-08-17 16:46:58 +00002003 case Stmt::UnaryOperatorClass: {
2004 // The only unary operator that make sense to handle here
2005 // is Deref. All others don't resolve to a "name." This includes
2006 // handling all sorts of rvalues passed to a unary operator.
2007 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002008
John McCall2de56d12010-08-25 11:45:40 +00002009 if (U->getOpcode() == UO_Deref)
Ted Kremenek06de2762007-08-17 16:46:58 +00002010 return EvalAddr(U->getSubExpr());
2011
2012 return NULL;
2013 }
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Ted Kremenek06de2762007-08-17 16:46:58 +00002015 case Stmt::ArraySubscriptExprClass: {
2016 // Array subscripts are potential references to data on the stack. We
2017 // retrieve the DeclRefExpr* for the array variable if it indeed
2018 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00002019 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00002020 }
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Ted Kremenek06de2762007-08-17 16:46:58 +00002022 case Stmt::ConditionalOperatorClass: {
2023 // For conditional operators we need to see if either the LHS or RHS are
2024 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
2025 ConditionalOperator *C = cast<ConditionalOperator>(E);
2026
Anders Carlsson39073232007-11-30 19:04:31 +00002027 // Handle the GNU extension for missing LHS.
2028 if (Expr *lhsExpr = C->getLHS())
2029 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
2030 return LHS;
2031
2032 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00002033 }
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Ted Kremenek06de2762007-08-17 16:46:58 +00002035 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002036 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002037 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Ted Kremenek06de2762007-08-17 16:46:58 +00002039 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002040 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002041 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002042
2043 // Check whether the member type is itself a reference, in which case
2044 // we're not going to refer to the member, but to what the member refers to.
2045 if (M->getMemberDecl()->getType()->isReferenceType())
2046 return NULL;
2047
2048 return EvalVal(M->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00002049 }
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Ted Kremenek06de2762007-08-17 16:46:58 +00002051 // Everything else: we simply don't reason about them.
2052 default:
2053 return NULL;
2054 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002055} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002056}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002057
2058//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2059
2060/// Check for comparisons of floating point operands using != and ==.
2061/// Issue a warning if these are no self-comparisons, as they are not likely
2062/// to do what the programmer intended.
2063void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2064 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002066 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00002067 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002068
2069 // Special case: check for x == x (which is OK).
2070 // Do not emit warnings for such cases.
2071 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2072 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2073 if (DRL->getDecl() == DRR->getDecl())
2074 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002075
2076
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002077 // Special case: check for comparisons against literals that can be exactly
2078 // represented by APFloat. In such cases, do not emit a warning. This
2079 // is a heuristic: often comparison against such literals are used to
2080 // detect if a value in a variable has not changed. This clearly can
2081 // lead to false negatives.
2082 if (EmitWarning) {
2083 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2084 if (FLL->isExact())
2085 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002086 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002087 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2088 if (FLR->isExact())
2089 EmitWarning = false;
2090 }
2091 }
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002093 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002094 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002095 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002096 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002097 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Sebastian Redl0eb23302009-01-19 00:08:26 +00002099 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002100 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002101 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002102 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002104 // Emit the diagnostic.
2105 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002106 Diag(loc, diag::warn_floatingpoint_eq)
2107 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002108}
John McCallba26e582010-01-04 23:21:16 +00002109
John McCallf2370c92010-01-06 05:24:50 +00002110//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2111//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002112
John McCallf2370c92010-01-06 05:24:50 +00002113namespace {
John McCallba26e582010-01-04 23:21:16 +00002114
John McCallf2370c92010-01-06 05:24:50 +00002115/// Structure recording the 'active' range of an integer-valued
2116/// expression.
2117struct IntRange {
2118 /// The number of bits active in the int.
2119 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002120
John McCallf2370c92010-01-06 05:24:50 +00002121 /// True if the int is known not to have negative values.
2122 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002123
John McCallf2370c92010-01-06 05:24:50 +00002124 IntRange(unsigned Width, bool NonNegative)
2125 : Width(Width), NonNegative(NonNegative)
2126 {}
John McCallba26e582010-01-04 23:21:16 +00002127
John McCallf2370c92010-01-06 05:24:50 +00002128 // Returns the range of the bool type.
2129 static IntRange forBoolType() {
2130 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002131 }
2132
John McCallf2370c92010-01-06 05:24:50 +00002133 // Returns the range of an integral type.
2134 static IntRange forType(ASTContext &C, QualType T) {
2135 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002136 }
2137
John McCallf2370c92010-01-06 05:24:50 +00002138 // Returns the range of an integeral type based on its canonical
2139 // representation.
2140 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
2141 assert(T->isCanonicalUnqualified());
2142
2143 if (const VectorType *VT = dyn_cast<VectorType>(T))
2144 T = VT->getElementType().getTypePtr();
2145 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2146 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002147
2148 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2149 EnumDecl *Enum = ET->getDecl();
2150 unsigned NumPositive = Enum->getNumPositiveBits();
2151 unsigned NumNegative = Enum->getNumNegativeBits();
2152
2153 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2154 }
John McCallf2370c92010-01-06 05:24:50 +00002155
2156 const BuiltinType *BT = cast<BuiltinType>(T);
2157 assert(BT->isInteger());
2158
2159 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2160 }
2161
2162 // Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002163 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002164 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002165 L.NonNegative && R.NonNegative);
2166 }
2167
2168 // Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002169 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002170 return IntRange(std::min(L.Width, R.Width),
2171 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002172 }
2173};
2174
2175IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2176 if (value.isSigned() && value.isNegative())
2177 return IntRange(value.getMinSignedBits(), false);
2178
2179 if (value.getBitWidth() > MaxWidth)
2180 value.trunc(MaxWidth);
2181
2182 // isNonNegative() just checks the sign bit without considering
2183 // signedness.
2184 return IntRange(value.getActiveBits(), true);
2185}
2186
John McCall0acc3112010-01-06 22:57:21 +00002187IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002188 unsigned MaxWidth) {
2189 if (result.isInt())
2190 return GetValueRange(C, result.getInt(), MaxWidth);
2191
2192 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002193 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2194 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2195 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2196 R = IntRange::join(R, El);
2197 }
John McCallf2370c92010-01-06 05:24:50 +00002198 return R;
2199 }
2200
2201 if (result.isComplexInt()) {
2202 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2203 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2204 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002205 }
2206
2207 // This can happen with lossless casts to intptr_t of "based" lvalues.
2208 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002209 // FIXME: The only reason we need to pass the type in here is to get
2210 // the sign right on this one case. It would be nice if APValue
2211 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002212 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002213 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002214}
John McCallf2370c92010-01-06 05:24:50 +00002215
2216/// Pseudo-evaluate the given integer expression, estimating the
2217/// range of values it might take.
2218///
2219/// \param MaxWidth - the width to which the value will be truncated
2220IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2221 E = E->IgnoreParens();
2222
2223 // Try a full evaluation first.
2224 Expr::EvalResult result;
2225 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002226 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002227
2228 // I think we only want to look through implicit casts here; if the
2229 // user has an explicit widening cast, we should treat the value as
2230 // being of the new, wider type.
2231 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002232 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002233 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2234
2235 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
2236
John McCall2de56d12010-08-25 11:45:40 +00002237 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
2238 if (!isIntegerCast && CE->getCastKind() == CK_Unknown)
John McCall60fad452010-01-06 22:07:33 +00002239 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
2240
John McCallf2370c92010-01-06 05:24:50 +00002241 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002242 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002243 return OutputTypeRange;
2244
2245 IntRange SubRange
2246 = GetExprRange(C, CE->getSubExpr(),
2247 std::min(MaxWidth, OutputTypeRange.Width));
2248
2249 // Bail out if the subexpr's range is as wide as the cast type.
2250 if (SubRange.Width >= OutputTypeRange.Width)
2251 return OutputTypeRange;
2252
2253 // Otherwise, we take the smaller width, and we're non-negative if
2254 // either the output type or the subexpr is.
2255 return IntRange(SubRange.Width,
2256 SubRange.NonNegative || OutputTypeRange.NonNegative);
2257 }
2258
2259 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2260 // If we can fold the condition, just take that operand.
2261 bool CondResult;
2262 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2263 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2264 : CO->getFalseExpr(),
2265 MaxWidth);
2266
2267 // Otherwise, conservatively merge.
2268 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2269 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2270 return IntRange::join(L, R);
2271 }
2272
2273 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2274 switch (BO->getOpcode()) {
2275
2276 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002277 case BO_LAnd:
2278 case BO_LOr:
2279 case BO_LT:
2280 case BO_GT:
2281 case BO_LE:
2282 case BO_GE:
2283 case BO_EQ:
2284 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002285 return IntRange::forBoolType();
2286
John McCallc0cd21d2010-02-23 19:22:29 +00002287 // The type of these compound assignments is the type of the LHS,
2288 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002289 case BO_MulAssign:
2290 case BO_DivAssign:
2291 case BO_RemAssign:
2292 case BO_AddAssign:
2293 case BO_SubAssign:
John McCallc0cd21d2010-02-23 19:22:29 +00002294 return IntRange::forType(C, E->getType());
2295
John McCallf2370c92010-01-06 05:24:50 +00002296 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002297 case BO_PtrMemD:
2298 case BO_PtrMemI:
John McCallf2370c92010-01-06 05:24:50 +00002299 return IntRange::forType(C, E->getType());
2300
John McCall60fad452010-01-06 22:07:33 +00002301 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002302 case BO_And:
2303 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002304 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2305 GetExprRange(C, BO->getRHS(), MaxWidth));
2306
John McCallf2370c92010-01-06 05:24:50 +00002307 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002308 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002309 // ...except that we want to treat '1 << (blah)' as logically
2310 // positive. It's an important idiom.
2311 if (IntegerLiteral *I
2312 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2313 if (I->getValue() == 1) {
2314 IntRange R = IntRange::forType(C, E->getType());
2315 return IntRange(R.Width, /*NonNegative*/ true);
2316 }
2317 }
2318 // fallthrough
2319
John McCall2de56d12010-08-25 11:45:40 +00002320 case BO_ShlAssign:
John McCallf2370c92010-01-06 05:24:50 +00002321 return IntRange::forType(C, E->getType());
2322
John McCall60fad452010-01-06 22:07:33 +00002323 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002324 case BO_Shr:
2325 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002326 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2327
2328 // If the shift amount is a positive constant, drop the width by
2329 // that much.
2330 llvm::APSInt shift;
2331 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2332 shift.isNonNegative()) {
2333 unsigned zext = shift.getZExtValue();
2334 if (zext >= L.Width)
2335 L.Width = (L.NonNegative ? 0 : 1);
2336 else
2337 L.Width -= zext;
2338 }
2339
2340 return L;
2341 }
2342
2343 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002344 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002345 return GetExprRange(C, BO->getRHS(), MaxWidth);
2346
John McCall60fad452010-01-06 22:07:33 +00002347 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002348 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002349 if (BO->getLHS()->getType()->isPointerType())
2350 return IntRange::forType(C, E->getType());
2351 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002352
John McCallf2370c92010-01-06 05:24:50 +00002353 default:
2354 break;
2355 }
2356
2357 // Treat every other operator as if it were closed on the
2358 // narrowest type that encompasses both operands.
2359 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2360 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2361 return IntRange::join(L, R);
2362 }
2363
2364 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2365 switch (UO->getOpcode()) {
2366 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002367 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002368 return IntRange::forBoolType();
2369
2370 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002371 case UO_Deref:
2372 case UO_AddrOf: // should be impossible
John McCallf2370c92010-01-06 05:24:50 +00002373 return IntRange::forType(C, E->getType());
2374
2375 default:
2376 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2377 }
2378 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002379
2380 if (dyn_cast<OffsetOfExpr>(E)) {
2381 IntRange::forType(C, E->getType());
2382 }
John McCallf2370c92010-01-06 05:24:50 +00002383
2384 FieldDecl *BitField = E->getBitField();
2385 if (BitField) {
2386 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2387 unsigned BitWidth = BitWidthAP.getZExtValue();
2388
2389 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2390 }
2391
2392 return IntRange::forType(C, E->getType());
2393}
John McCall51313c32010-01-04 23:31:57 +00002394
John McCall323ed742010-05-06 08:58:33 +00002395IntRange GetExprRange(ASTContext &C, Expr *E) {
2396 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2397}
2398
John McCall51313c32010-01-04 23:31:57 +00002399/// Checks whether the given value, which currently has the given
2400/// source semantics, has the same value when coerced through the
2401/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002402bool IsSameFloatAfterCast(const llvm::APFloat &value,
2403 const llvm::fltSemantics &Src,
2404 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002405 llvm::APFloat truncated = value;
2406
2407 bool ignored;
2408 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2409 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2410
2411 return truncated.bitwiseIsEqual(value);
2412}
2413
2414/// Checks whether the given value, which currently has the given
2415/// source semantics, has the same value when coerced through the
2416/// target semantics.
2417///
2418/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002419bool IsSameFloatAfterCast(const APValue &value,
2420 const llvm::fltSemantics &Src,
2421 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002422 if (value.isFloat())
2423 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2424
2425 if (value.isVector()) {
2426 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2427 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2428 return false;
2429 return true;
2430 }
2431
2432 assert(value.isComplexFloat());
2433 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2434 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2435}
2436
John McCallb4eb64d2010-10-08 02:01:28 +00002437void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002438
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002439static bool IsZero(Sema &S, Expr *E) {
2440 // Suppress cases where we are comparing against an enum constant.
2441 if (const DeclRefExpr *DR =
2442 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2443 if (isa<EnumConstantDecl>(DR->getDecl()))
2444 return false;
2445
2446 // Suppress cases where the '0' value is expanded from a macro.
2447 if (E->getLocStart().isMacroID())
2448 return false;
2449
John McCall323ed742010-05-06 08:58:33 +00002450 llvm::APSInt Value;
2451 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2452}
2453
John McCall372e1032010-10-06 00:25:24 +00002454static bool HasEnumType(Expr *E) {
2455 // Strip off implicit integral promotions.
2456 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002457 if (ICE->getCastKind() != CK_IntegralCast &&
2458 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002459 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002460 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002461 }
2462
2463 return E->getType()->isEnumeralType();
2464}
2465
John McCall323ed742010-05-06 08:58:33 +00002466void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002467 BinaryOperatorKind op = E->getOpcode();
2468 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002469 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002470 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002471 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002472 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002473 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002474 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002475 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002476 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002477 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002478 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002479 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002480 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002481 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002482 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002483 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2484 }
2485}
2486
2487/// Analyze the operands of the given comparison. Implements the
2488/// fallback case from AnalyzeComparison.
2489void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002490 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2491 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002492}
John McCall51313c32010-01-04 23:31:57 +00002493
John McCallba26e582010-01-04 23:21:16 +00002494/// \brief Implements -Wsign-compare.
2495///
2496/// \param lex the left-hand expression
2497/// \param rex the right-hand expression
2498/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002499/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002500void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2501 // The type the comparison is being performed in.
2502 QualType T = E->getLHS()->getType();
2503 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2504 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002505
John McCall323ed742010-05-06 08:58:33 +00002506 // We don't do anything special if this isn't an unsigned integral
2507 // comparison: we're only interested in integral comparisons, and
2508 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregorf6094622010-07-23 15:58:24 +00002509 if (!T->hasUnsignedIntegerRepresentation())
John McCall323ed742010-05-06 08:58:33 +00002510 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002511
John McCall323ed742010-05-06 08:58:33 +00002512 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2513 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002514
John McCall323ed742010-05-06 08:58:33 +00002515 // Check to see if one of the (unmodified) operands is of different
2516 // signedness.
2517 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002518 if (lex->getType()->hasSignedIntegerRepresentation()) {
2519 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002520 "unsigned comparison between two signed integer expressions?");
2521 signedOperand = lex;
2522 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002523 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002524 signedOperand = rex;
2525 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002526 } else {
John McCall323ed742010-05-06 08:58:33 +00002527 CheckTrivialUnsignedComparison(S, E);
2528 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002529 }
2530
John McCall323ed742010-05-06 08:58:33 +00002531 // Otherwise, calculate the effective range of the signed operand.
2532 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002533
John McCall323ed742010-05-06 08:58:33 +00002534 // Go ahead and analyze implicit conversions in the operands. Note
2535 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002536 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2537 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002538
John McCall323ed742010-05-06 08:58:33 +00002539 // If the signed range is non-negative, -Wsign-compare won't fire,
2540 // but we should still check for comparisons which are always true
2541 // or false.
2542 if (signedRange.NonNegative)
2543 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002544
2545 // For (in)equality comparisons, if the unsigned operand is a
2546 // constant which cannot collide with a overflowed signed operand,
2547 // then reinterpreting the signed operand as unsigned will not
2548 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002549 if (E->isEqualityOp()) {
2550 unsigned comparisonWidth = S.Context.getIntWidth(T);
2551 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002552
John McCall323ed742010-05-06 08:58:33 +00002553 // We should never be unable to prove that the unsigned operand is
2554 // non-negative.
2555 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2556
2557 if (unsignedRange.Width < comparisonWidth)
2558 return;
2559 }
2560
2561 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2562 << lex->getType() << rex->getType()
2563 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002564}
2565
John McCall51313c32010-01-04 23:31:57 +00002566/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCallb4eb64d2010-10-08 02:01:28 +00002567void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2568 unsigned diag) {
2569 S.Diag(E->getExprLoc(), diag)
2570 << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
John McCall51313c32010-01-04 23:31:57 +00002571}
2572
John McCall323ed742010-05-06 08:58:33 +00002573void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002574 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002575 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002576
John McCall323ed742010-05-06 08:58:33 +00002577 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2578 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2579 if (Source == Target) return;
2580 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002581
John McCallb4eb64d2010-10-08 02:01:28 +00002582 // If the conversion context location is invalid or instantiated
2583 // from a system macro, don't complain.
2584 if (CC.isInvalid() ||
2585 (CC.isMacroID() && S.Context.getSourceManager().isInSystemHeader(
2586 S.Context.getSourceManager().getSpellingLoc(CC))))
2587 return;
2588
John McCall51313c32010-01-04 23:31:57 +00002589 // Never diagnose implicit casts to bool.
2590 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2591 return;
2592
2593 // Strip vector types.
2594 if (isa<VectorType>(Source)) {
2595 if (!isa<VectorType>(Target))
John McCallb4eb64d2010-10-08 02:01:28 +00002596 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
John McCall51313c32010-01-04 23:31:57 +00002597
2598 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2599 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2600 }
2601
2602 // Strip complex types.
2603 if (isa<ComplexType>(Source)) {
2604 if (!isa<ComplexType>(Target))
John McCallb4eb64d2010-10-08 02:01:28 +00002605 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
John McCall51313c32010-01-04 23:31:57 +00002606
2607 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2608 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2609 }
2610
2611 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2612 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2613
2614 // If the source is floating point...
2615 if (SourceBT && SourceBT->isFloatingPoint()) {
2616 // ...and the target is floating point...
2617 if (TargetBT && TargetBT->isFloatingPoint()) {
2618 // ...then warn if we're dropping FP rank.
2619
2620 // Builtin FP kinds are ordered by increasing FP rank.
2621 if (SourceBT->getKind() > TargetBT->getKind()) {
2622 // Don't warn about float constants that are precisely
2623 // representable in the target type.
2624 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002625 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002626 // Value might be a float, a float vector, or a float complex.
2627 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002628 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2629 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002630 return;
2631 }
2632
John McCallb4eb64d2010-10-08 02:01:28 +00002633 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002634 }
2635 return;
2636 }
2637
2638 // If the target is integral, always warn.
2639 if ((TargetBT && TargetBT->isInteger()))
2640 // TODO: don't warn for integer values?
John McCallb4eb64d2010-10-08 02:01:28 +00002641 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
John McCall51313c32010-01-04 23:31:57 +00002642
2643 return;
2644 }
2645
John McCallf2370c92010-01-06 05:24:50 +00002646 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002647 return;
2648
John McCall323ed742010-05-06 08:58:33 +00002649 IntRange SourceRange = GetExprRange(S.Context, E);
2650 IntRange TargetRange = IntRange::forCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002651
2652 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002653 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2654 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002655 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002656 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2657 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002658 }
2659
2660 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2661 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2662 SourceRange.Width == TargetRange.Width)) {
2663 unsigned DiagID = diag::warn_impcast_integer_sign;
2664
2665 // Traditionally, gcc has warned about this under -Wsign-compare.
2666 // We also want to warn about it in -Wconversion.
2667 // So if -Wconversion is off, use a completely identical diagnostic
2668 // in the sign-compare group.
2669 // The conditional-checking code will
2670 if (ICContext) {
2671 DiagID = diag::warn_impcast_integer_sign_conditional;
2672 *ICContext = true;
2673 }
2674
John McCallb4eb64d2010-10-08 02:01:28 +00002675 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002676 }
2677
2678 return;
2679}
2680
John McCall323ed742010-05-06 08:58:33 +00002681void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2682
2683void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002684 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00002685 E = E->IgnoreParenImpCasts();
2686
2687 if (isa<ConditionalOperator>(E))
2688 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2689
John McCallb4eb64d2010-10-08 02:01:28 +00002690 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002691 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002692 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00002693 return;
2694}
2695
2696void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00002697 SourceLocation CC = E->getQuestionLoc();
2698
2699 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00002700
2701 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00002702 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2703 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002704
2705 // If -Wconversion would have warned about either of the candidates
2706 // for a signedness conversion to the context type...
2707 if (!Suspicious) return;
2708
2709 // ...but it's currently ignored...
2710 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional))
2711 return;
2712
2713 // ...and -Wsign-compare isn't...
2714 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional))
2715 return;
2716
2717 // ...then check whether it would have warned about either of the
2718 // candidates for a signedness conversion to the condition type.
2719 if (E->getType() != T) {
2720 Suspicious = false;
2721 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002722 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002723 if (!Suspicious)
2724 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002725 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002726 if (!Suspicious)
2727 return;
2728 }
2729
2730 // If so, emit a diagnostic under -Wsign-compare.
2731 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2732 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2733 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2734 << lex->getType() << rex->getType()
2735 << lex->getSourceRange() << rex->getSourceRange();
2736}
2737
2738/// AnalyzeImplicitConversions - Find and report any interesting
2739/// implicit conversions in the given expression. There are a couple
2740/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00002741void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00002742 QualType T = OrigE->getType();
2743 Expr *E = OrigE->IgnoreParenImpCasts();
2744
2745 // For conditional operators, we analyze the arguments as if they
2746 // were being fed directly into the output.
2747 if (isa<ConditionalOperator>(E)) {
2748 ConditionalOperator *CO = cast<ConditionalOperator>(E);
2749 CheckConditionalOperator(S, CO, T);
2750 return;
2751 }
2752
2753 // Go ahead and check any implicit conversions we might have skipped.
2754 // The non-canonical typecheck is just an optimization;
2755 // CheckImplicitConversion will filter out dead implicit conversions.
2756 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002757 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00002758
2759 // Now continue drilling into this expression.
2760
2761 // Skip past explicit casts.
2762 if (isa<ExplicitCastExpr>(E)) {
2763 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00002764 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002765 }
2766
2767 // Do a somewhat different check with comparison operators.
2768 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isComparisonOp())
2769 return AnalyzeComparison(S, cast<BinaryOperator>(E));
2770
2771 // These break the otherwise-useful invariant below. Fortunately,
2772 // we don't really need to recurse into them, because any internal
2773 // expressions should have been analyzed already when they were
2774 // built into statements.
2775 if (isa<StmtExpr>(E)) return;
2776
2777 // Don't descend into unevaluated contexts.
2778 if (isa<SizeOfAlignOfExpr>(E)) return;
2779
2780 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00002781 CC = E->getExprLoc();
John McCall323ed742010-05-06 08:58:33 +00002782 for (Stmt::child_iterator I = E->child_begin(), IE = E->child_end();
2783 I != IE; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00002784 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00002785}
2786
2787} // end anonymous namespace
2788
2789/// Diagnoses "dangerous" implicit conversions within the given
2790/// expression (which is a full expression). Implements -Wconversion
2791/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00002792///
2793/// \param CC the "context" location of the implicit conversion, i.e.
2794/// the most location of the syntactic entity requiring the implicit
2795/// conversion
2796void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00002797 // Don't diagnose in unevaluated contexts.
2798 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2799 return;
2800
2801 // Don't diagnose for value- or type-dependent expressions.
2802 if (E->isTypeDependent() || E->isValueDependent())
2803 return;
2804
John McCallb4eb64d2010-10-08 02:01:28 +00002805 // This is not the right CC for (e.g.) a variable initialization.
2806 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002807}
2808
Mike Stumpf8c49212010-01-21 03:59:47 +00002809/// CheckParmsForFunctionDef - Check that the parameters of the given
2810/// function are appropriate for the definition of a function. This
2811/// takes care of any checks that cannot be performed on the
2812/// declaration itself, e.g., that the types of each of the function
2813/// parameters are complete.
2814bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2815 bool HasInvalidParm = false;
2816 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2817 ParmVarDecl *Param = FD->getParamDecl(p);
2818
2819 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2820 // function declarator that is part of a function definition of
2821 // that function shall not have incomplete type.
2822 //
2823 // This is also C++ [dcl.fct]p6.
2824 if (!Param->isInvalidDecl() &&
2825 RequireCompleteType(Param->getLocation(), Param->getType(),
2826 diag::err_typecheck_decl_incomplete_type)) {
2827 Param->setInvalidDecl();
2828 HasInvalidParm = true;
2829 }
2830
2831 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2832 // declaration of each parameter shall include an identifier.
2833 if (Param->getIdentifier() == 0 &&
2834 !Param->isImplicit() &&
2835 !getLangOptions().CPlusPlus)
2836 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002837
2838 // C99 6.7.5.3p12:
2839 // If the function declarator is not part of a definition of that
2840 // function, parameters may have incomplete type and may use the [*]
2841 // notation in their sequences of declarator specifiers to specify
2842 // variable length array types.
2843 QualType PType = Param->getOriginalType();
2844 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2845 if (AT->getSizeModifier() == ArrayType::Star) {
2846 // FIXME: This diagnosic should point the the '[*]' if source-location
2847 // information is added for it.
2848 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2849 }
2850 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002851 }
2852
2853 return HasInvalidParm;
2854}
John McCallb7f4ffe2010-08-12 21:44:57 +00002855
2856/// CheckCastAlign - Implements -Wcast-align, which warns when a
2857/// pointer cast increases the alignment requirements.
2858void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
2859 // This is actually a lot of work to potentially be doing on every
2860 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
2861 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align)
2862 == Diagnostic::Ignored)
2863 return;
2864
2865 // Ignore dependent types.
2866 if (T->isDependentType() || Op->getType()->isDependentType())
2867 return;
2868
2869 // Require that the destination be a pointer type.
2870 const PointerType *DestPtr = T->getAs<PointerType>();
2871 if (!DestPtr) return;
2872
2873 // If the destination has alignment 1, we're done.
2874 QualType DestPointee = DestPtr->getPointeeType();
2875 if (DestPointee->isIncompleteType()) return;
2876 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
2877 if (DestAlign.isOne()) return;
2878
2879 // Require that the source be a pointer type.
2880 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
2881 if (!SrcPtr) return;
2882 QualType SrcPointee = SrcPtr->getPointeeType();
2883
2884 // Whitelist casts from cv void*. We already implicitly
2885 // whitelisted casts to cv void*, since they have alignment 1.
2886 // Also whitelist casts involving incomplete types, which implicitly
2887 // includes 'void'.
2888 if (SrcPointee->isIncompleteType()) return;
2889
2890 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
2891 if (SrcAlign >= DestAlign) return;
2892
2893 Diag(TRange.getBegin(), diag::warn_cast_align)
2894 << Op->getType() << T
2895 << static_cast<unsigned>(SrcAlign.getQuantity())
2896 << static_cast<unsigned>(DestAlign.getQuantity())
2897 << TRange << Op->getSourceRange();
2898}
2899