blob: 4b1f423028d114731625a16bb12ab1260849f6f0 [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 Friedman6cfda232008-05-20 08:23:37 +0000185 case Builtin::BI__builtin_return_address:
Eric Christopher691ebc32010-04-17 02:26:23 +0000186 case Builtin::BI__builtin_frame_address: {
187 llvm::APSInt Result;
188 if (SemaBuiltinConstantArg(TheCall, 0, Result))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000189 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000190 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000191 }
192 case Builtin::BI__builtin_eh_return_data_regno: {
193 llvm::APSInt Result;
194 if (SemaBuiltinConstantArg(TheCall, 0, Result))
Chris Lattner21fb98e2009-09-23 06:06:36 +0000195 return ExprError();
196 break;
Eric Christopher691ebc32010-04-17 02:26:23 +0000197 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000198 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000199 return SemaBuiltinShuffleVector(TheCall);
200 // TheCall will be freed by the smart pointer here, but that's fine, since
201 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000202 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000203 if (SemaBuiltinPrefetch(TheCall))
204 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000205 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000206 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000207 if (SemaBuiltinObjectSize(TheCall))
208 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000209 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000210 case Builtin::BI__builtin_longjmp:
211 if (SemaBuiltinLongjmp(TheCall))
212 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000213 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000214 case Builtin::BI__sync_fetch_and_add:
215 case Builtin::BI__sync_fetch_and_sub:
216 case Builtin::BI__sync_fetch_and_or:
217 case Builtin::BI__sync_fetch_and_and:
218 case Builtin::BI__sync_fetch_and_xor:
219 case Builtin::BI__sync_add_and_fetch:
220 case Builtin::BI__sync_sub_and_fetch:
221 case Builtin::BI__sync_and_and_fetch:
222 case Builtin::BI__sync_or_and_fetch:
223 case Builtin::BI__sync_xor_and_fetch:
224 case Builtin::BI__sync_val_compare_and_swap:
225 case Builtin::BI__sync_bool_compare_and_swap:
226 case Builtin::BI__sync_lock_test_and_set:
227 case Builtin::BI__sync_lock_release:
Chandler Carruthd2014572010-07-09 18:59:35 +0000228 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000229 }
230
231 // Since the target specific builtins for each arch overlap, only check those
232 // of the arch we are compiling for.
233 if (BuiltinID >= Builtin::FirstTSBuiltin) {
234 switch (Context.Target.getTriple().getArch()) {
235 case llvm::Triple::arm:
236 case llvm::Triple::thumb:
237 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
238 return ExprError();
239 break;
240 case llvm::Triple::x86:
241 case llvm::Triple::x86_64:
242 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
243 return ExprError();
244 break;
245 default:
246 break;
247 }
248 }
249
250 return move(TheCallResult);
251}
252
253bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
254 switch (BuiltinID) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000255 case X86::BI__builtin_ia32_palignr128:
256 case X86::BI__builtin_ia32_palignr: {
257 llvm::APSInt Result;
258 if (SemaBuiltinConstantArg(TheCall, 2, Result))
Nate Begeman26a31422010-06-08 02:47:44 +0000259 return true;
Eric Christopher691ebc32010-04-17 02:26:23 +0000260 break;
261 }
Anders Carlsson71993dd2007-08-17 05:31:46 +0000262 }
Nate Begeman26a31422010-06-08 02:47:44 +0000263 return false;
264}
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Nate Begeman61eecf52010-06-14 05:21:25 +0000266// Get the valid immediate range for the specified NEON type code.
267static unsigned RFT(unsigned t, bool shift = false) {
268 bool quad = t & 0x10;
269
270 switch (t & 0x7) {
271 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000272 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000273 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000274 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000275 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000276 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000277 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000278 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000279 case 4: // f32
280 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000281 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000282 case 5: // poly8
283 assert(!shift && "cannot shift polynomial types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000284 return (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000285 case 6: // poly16
286 assert(!shift && "cannot shift polynomial types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000287 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000288 case 7: // float16
289 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000290 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000291 }
292 return 0;
293}
294
Nate Begeman26a31422010-06-08 02:47:44 +0000295bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000296 llvm::APSInt Result;
297
Nate Begeman0d15c532010-06-13 04:47:52 +0000298 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000299 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000300 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000301#define GET_NEON_OVERLOAD_CHECK
302#include "clang/Basic/arm_neon.inc"
303#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000304 }
305
Nate Begeman0d15c532010-06-13 04:47:52 +0000306 // For NEON intrinsics which are overloaded on vector element type, validate
307 // the immediate which specifies which variant to emit.
308 if (mask) {
309 unsigned ArgNo = TheCall->getNumArgs()-1;
310 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
311 return true;
312
Nate Begeman61eecf52010-06-14 05:21:25 +0000313 TV = Result.getLimitedValue(32);
314 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000315 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
316 << TheCall->getArg(ArgNo)->getSourceRange();
317 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000318
Nate Begeman0d15c532010-06-13 04:47:52 +0000319 // For NEON intrinsics which take an immediate value as part of the
320 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000321 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000322 switch (BuiltinID) {
323 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000324 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
325 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000326 case ARM::BI__builtin_arm_vcvtr_f:
327 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000328#define GET_NEON_IMMEDIATE_CHECK
329#include "clang/Basic/arm_neon.inc"
330#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000331 };
332
Nate Begeman61eecf52010-06-14 05:21:25 +0000333 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000334 if (SemaBuiltinConstantArg(TheCall, i, Result))
335 return true;
336
Nate Begeman61eecf52010-06-14 05:21:25 +0000337 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000338 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000339 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000340 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000341 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000342
Nate Begeman99c40bb2010-08-03 21:32:34 +0000343 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000344 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000345}
Daniel Dunbarde454282008-10-02 18:44:07 +0000346
Anders Carlssond406bf02009-08-16 01:56:34 +0000347/// CheckFunctionCall - Check a direct function call for various correctness
348/// and safety properties not strictly enforced by the C type system.
349bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
350 // Get the IdentifierInfo* for the called function.
351 IdentifierInfo *FnInfo = FDecl->getIdentifier();
352
353 // None of the checks below are needed for functions that don't have
354 // simple names (e.g., C++ conversion functions).
355 if (!FnInfo)
356 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Daniel Dunbarde454282008-10-02 18:44:07 +0000358 // FIXME: This mechanism should be abstracted to be less fragile and
359 // more efficient. For example, just map function ids to custom
360 // handlers.
361
Ted Kremenekc82faca2010-09-09 04:33:05 +0000362 // Printf and scanf checking.
363 for (specific_attr_iterator<FormatAttr>
364 i = FDecl->specific_attr_begin<FormatAttr>(),
365 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
366
367 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000368 const bool b = Format->getType() == "scanf";
369 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000370 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000371 CheckPrintfScanfArguments(TheCall, HasVAListArg,
372 Format->getFormatIdx() - 1,
373 HasVAListArg ? 0 : Format->getFirstArg() - 1,
374 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000375 }
Chris Lattner59907c42007-08-10 20:18:51 +0000376 }
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Ted Kremenekc82faca2010-09-09 04:33:05 +0000378 for (specific_attr_iterator<NonNullAttr>
379 i = FDecl->specific_attr_begin<NonNullAttr>(),
380 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Sean Huntcf807c42010-08-18 23:23:40 +0000381 CheckNonNullArguments(*i, TheCall);
Ted Kremenekc82faca2010-09-09 04:33:05 +0000382 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000383
Anders Carlssond406bf02009-08-16 01:56:34 +0000384 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000385}
386
Anders Carlssond406bf02009-08-16 01:56:34 +0000387bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000388 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000389 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000390 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000391 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000393 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
394 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000395 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000397 QualType Ty = V->getType();
398 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000399 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Ted Kremenek826a3452010-07-16 02:11:22 +0000401 const bool b = Format->getType() == "scanf";
402 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000403 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Anders Carlssond406bf02009-08-16 01:56:34 +0000405 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000406 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
407 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000408
409 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000410}
411
Chris Lattner5caa3702009-05-08 06:58:22 +0000412/// SemaBuiltinAtomicOverloaded - We have a call to a function like
413/// __sync_fetch_and_add, which is an overloaded function based on the pointer
414/// type of its first argument. The main ActOnCallExpr routines have already
415/// promoted the types of arguments because all of these calls are prototyped as
416/// void(...).
417///
418/// This function goes through and does final semantic checking for these
419/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000420ExprResult
421Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000422 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000423 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
424 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
425
426 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000427 if (TheCall->getNumArgs() < 1) {
428 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
429 << 0 << 1 << TheCall->getNumArgs()
430 << TheCall->getCallee()->getSourceRange();
431 return ExprError();
432 }
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Chris Lattner5caa3702009-05-08 06:58:22 +0000434 // Inspect the first argument of the atomic builtin. This should always be
435 // a pointer type, whose element is an integral scalar or pointer type.
436 // Because it is a pointer type, we don't have to worry about any implicit
437 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000438 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000439 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruthd2014572010-07-09 18:59:35 +0000440 if (!FirstArg->getType()->isPointerType()) {
441 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
442 << FirstArg->getType() << FirstArg->getSourceRange();
443 return ExprError();
444 }
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Chandler Carruthd2014572010-07-09 18:59:35 +0000446 QualType ValType =
447 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000448 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000449 !ValType->isBlockPointerType()) {
450 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
451 << FirstArg->getType() << FirstArg->getSourceRange();
452 return ExprError();
453 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000454
Chandler Carruth8d13d222010-07-18 20:54:12 +0000455 // The majority of builtins return a value, but a few have special return
456 // types, so allow them to override appropriately below.
457 QualType ResultType = ValType;
458
Chris Lattner5caa3702009-05-08 06:58:22 +0000459 // We need to figure out which concrete builtin this maps onto. For example,
460 // __sync_fetch_and_add with a 2 byte object turns into
461 // __sync_fetch_and_add_2.
462#define BUILTIN_ROW(x) \
463 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
464 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Chris Lattner5caa3702009-05-08 06:58:22 +0000466 static const unsigned BuiltinIndices[][5] = {
467 BUILTIN_ROW(__sync_fetch_and_add),
468 BUILTIN_ROW(__sync_fetch_and_sub),
469 BUILTIN_ROW(__sync_fetch_and_or),
470 BUILTIN_ROW(__sync_fetch_and_and),
471 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Chris Lattner5caa3702009-05-08 06:58:22 +0000473 BUILTIN_ROW(__sync_add_and_fetch),
474 BUILTIN_ROW(__sync_sub_and_fetch),
475 BUILTIN_ROW(__sync_and_and_fetch),
476 BUILTIN_ROW(__sync_or_and_fetch),
477 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Chris Lattner5caa3702009-05-08 06:58:22 +0000479 BUILTIN_ROW(__sync_val_compare_and_swap),
480 BUILTIN_ROW(__sync_bool_compare_and_swap),
481 BUILTIN_ROW(__sync_lock_test_and_set),
482 BUILTIN_ROW(__sync_lock_release)
483 };
Mike Stump1eb44332009-09-09 15:08:12 +0000484#undef BUILTIN_ROW
485
Chris Lattner5caa3702009-05-08 06:58:22 +0000486 // Determine the index of the size.
487 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000488 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000489 case 1: SizeIndex = 0; break;
490 case 2: SizeIndex = 1; break;
491 case 4: SizeIndex = 2; break;
492 case 8: SizeIndex = 3; break;
493 case 16: SizeIndex = 4; break;
494 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000495 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
496 << FirstArg->getType() << FirstArg->getSourceRange();
497 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Chris Lattner5caa3702009-05-08 06:58:22 +0000500 // Each of these builtins has one pointer argument, followed by some number of
501 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
502 // that we ignore. Find out which row of BuiltinIndices to read from as well
503 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000504 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000505 unsigned BuiltinIndex, NumFixed = 1;
506 switch (BuiltinID) {
507 default: assert(0 && "Unknown overloaded atomic builtin!");
508 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
509 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
510 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
511 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
512 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000514 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
515 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
516 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
517 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
518 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Chris Lattner5caa3702009-05-08 06:58:22 +0000520 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000521 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000522 NumFixed = 2;
523 break;
524 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000525 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000526 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000527 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000528 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000529 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000530 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000531 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000532 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000533 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000534 break;
535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner5caa3702009-05-08 06:58:22 +0000537 // Now that we know how many fixed arguments we expect, first check that we
538 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000539 if (TheCall->getNumArgs() < 1+NumFixed) {
540 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
541 << 0 << 1+NumFixed << TheCall->getNumArgs()
542 << TheCall->getCallee()->getSourceRange();
543 return ExprError();
544 }
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000546 // Get the decl for the concrete builtin from this, we can tell what the
547 // concrete integer type we should convert to is.
548 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
549 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
550 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000551 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000552 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
553 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000554
John McCallf871d0c2010-08-07 06:22:56 +0000555 // The first argument --- the pointer --- has a fixed type; we
556 // deduce the types of the rest of the arguments accordingly. Walk
557 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000558 for (unsigned i = 0; i != NumFixed; ++i) {
559 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Chris Lattner5caa3702009-05-08 06:58:22 +0000561 // If the argument is an implicit cast, then there was a promotion due to
562 // "...", just remove it now.
563 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
564 Arg = ICE->getSubExpr();
565 ICE->setSubExpr(0);
Chris Lattner5caa3702009-05-08 06:58:22 +0000566 TheCall->setArg(i+1, Arg);
567 }
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattner5caa3702009-05-08 06:58:22 +0000569 // GCC does an implicit conversion to the pointer or integer ValType. This
570 // can fail in some cases (1i -> int**), check for this error case now.
John McCall2de56d12010-08-25 11:45:40 +0000571 CastKind Kind = CK_Unknown;
John McCallf871d0c2010-08-07 06:22:56 +0000572 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000573 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, BasePath))
Chandler Carruthd2014572010-07-09 18:59:35 +0000574 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Chris Lattner5caa3702009-05-08 06:58:22 +0000576 // Okay, we have something that *can* be converted to the right type. Check
577 // to see if there is a potentially weird extension going on here. This can
578 // happen when you do an atomic operation on something like an char* and
579 // pass in 42. The 42 gets converted to char. This is even more strange
580 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000581 // FIXME: Do this check.
John McCall5baba9d2010-08-25 10:28:54 +0000582 ImpCastExprToType(Arg, ValType, Kind, VK_RValue, &BasePath);
Chris Lattner5caa3702009-05-08 06:58:22 +0000583 TheCall->setArg(i+1, Arg);
584 }
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner5caa3702009-05-08 06:58:22 +0000586 // Switch the DeclRefExpr to refer to the new decl.
587 DRE->setDecl(NewBuiltinDecl);
588 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattner5caa3702009-05-08 06:58:22 +0000590 // Set the callee in the CallExpr.
591 // FIXME: This leaks the original parens and implicit casts.
592 Expr *PromotedCall = DRE;
593 UsualUnaryConversions(PromotedCall);
594 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000596 // Change the result type of the call to match the original value type. This
597 // is arbitrary, but the codegen for these builtins ins design to handle it
598 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000599 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000600
601 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000602}
603
604
Chris Lattner69039812009-02-18 06:01:06 +0000605/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000606/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000607/// Note: It might also make sense to do the UTF-16 conversion here (would
608/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000609bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000610 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000611 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
612
613 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000614 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
615 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000616 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000617 }
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000619 size_t NulPos = Literal->getString().find('\0');
620 if (NulPos != llvm::StringRef::npos) {
621 Diag(getLocationOfStringLiteralByte(Literal, NulPos),
622 diag::warn_cfstring_literal_contains_nul_character)
623 << Arg->getSourceRange();
Daniel Dunbarf015b032009-09-22 10:03:52 +0000624 }
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000625 if (Literal->containsNonAsciiOrNull()) {
626 llvm::StringRef String = Literal->getString();
627 unsigned NumBytes = String.size();
628 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
629 const UTF8 *FromPtr = (UTF8 *)String.data();
630 UTF16 *ToPtr = &ToBuf[0];
631
632 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
633 &ToPtr, ToPtr + NumBytes,
634 strictConversion);
635 // Check for conversion failure.
636 if (Result != conversionOK)
637 Diag(Arg->getLocStart(),
638 diag::warn_cfstring_truncated) << Arg->getSourceRange();
639 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000640 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000641}
642
Chris Lattnerc27c6652007-12-20 00:05:45 +0000643/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
644/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000645bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
646 Expr *Fn = TheCall->getCallee();
647 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000648 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000649 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000650 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
651 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000652 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000653 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000654 return true;
655 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000656
657 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000658 return Diag(TheCall->getLocEnd(),
659 diag::err_typecheck_call_too_few_args_at_least)
660 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000661 }
662
Chris Lattnerc27c6652007-12-20 00:05:45 +0000663 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000664 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000665 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000666 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000667 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000668 else if (FunctionDecl *FD = getCurFunctionDecl())
669 isVariadic = FD->isVariadic();
670 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000671 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattnerc27c6652007-12-20 00:05:45 +0000673 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000674 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
675 return true;
676 }
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Chris Lattner30ce3442007-12-19 23:59:04 +0000678 // Verify that the second argument to the builtin is the last argument of the
679 // current function or method.
680 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000681 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Anders Carlsson88cf2262008-02-11 04:20:54 +0000683 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
684 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000685 // FIXME: This isn't correct for methods (results in bogus warning).
686 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000687 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000688 if (CurBlock)
689 LastArg = *(CurBlock->TheDecl->param_end()-1);
690 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000691 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000692 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000693 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000694 SecondArgIsLastNamedArgument = PV == LastArg;
695 }
696 }
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Chris Lattner30ce3442007-12-19 23:59:04 +0000698 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000699 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000700 diag::warn_second_parameter_of_va_start_not_last_named_argument);
701 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000702}
Chris Lattner30ce3442007-12-19 23:59:04 +0000703
Chris Lattner1b9a0792007-12-20 00:26:33 +0000704/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
705/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000706bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
707 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000708 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000709 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000710 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000711 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000712 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000713 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000714 << SourceRange(TheCall->getArg(2)->getLocStart(),
715 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattner925e60d2007-12-28 05:29:59 +0000717 Expr *OrigArg0 = TheCall->getArg(0);
718 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000719
Chris Lattner1b9a0792007-12-20 00:26:33 +0000720 // Do standard promotions between the two arguments, returning their common
721 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000722 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000723
724 // Make sure any conversions are pushed back into the call; this is
725 // type safe since unordered compare builtins are declared as "_Bool
726 // foo(...)".
727 TheCall->setArg(0, OrigArg0);
728 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Douglas Gregorcde01732009-05-19 22:10:17 +0000730 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
731 return false;
732
Chris Lattner1b9a0792007-12-20 00:26:33 +0000733 // If the common type isn't a real floating type, then the arguments were
734 // invalid for this operation.
735 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000736 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000737 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000738 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000739 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Chris Lattner1b9a0792007-12-20 00:26:33 +0000741 return false;
742}
743
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000744/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
745/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000746/// to check everything. We expect the last argument to be a floating point
747/// value.
748bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
749 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000750 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000751 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000752 if (TheCall->getNumArgs() > NumArgs)
753 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000754 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000755 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000756 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000757 (*(TheCall->arg_end()-1))->getLocEnd());
758
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000759 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Eli Friedman9ac6f622009-08-31 20:06:00 +0000761 if (OrigArg->isTypeDependent())
762 return false;
763
Chris Lattner81368fb2010-05-06 05:50:07 +0000764 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000765 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000766 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000767 diag::err_typecheck_call_invalid_unary_fp)
768 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattner81368fb2010-05-06 05:50:07 +0000770 // If this is an implicit conversion from float -> double, remove it.
771 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
772 Expr *CastArg = Cast->getSubExpr();
773 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
774 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
775 "promotion from float to double is the only expected cast here");
776 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000777 TheCall->setArg(NumArgs-1, CastArg);
778 OrigArg = CastArg;
779 }
780 }
781
Eli Friedman9ac6f622009-08-31 20:06:00 +0000782 return false;
783}
784
Eli Friedmand38617c2008-05-14 19:38:39 +0000785/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
786// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000787ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000788 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000789 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000790 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000791 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000792 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000793
Nate Begeman37b6a572010-06-08 00:16:34 +0000794 // Determine which of the following types of shufflevector we're checking:
795 // 1) unary, vector mask: (lhs, mask)
796 // 2) binary, vector mask: (lhs, rhs, mask)
797 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
798 QualType resType = TheCall->getArg(0)->getType();
799 unsigned numElements = 0;
800
Douglas Gregorcde01732009-05-19 22:10:17 +0000801 if (!TheCall->getArg(0)->isTypeDependent() &&
802 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000803 QualType LHSType = TheCall->getArg(0)->getType();
804 QualType RHSType = TheCall->getArg(1)->getType();
805
806 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000807 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000808 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000809 TheCall->getArg(1)->getLocEnd());
810 return ExprError();
811 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000812
813 numElements = LHSType->getAs<VectorType>()->getNumElements();
814 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Nate Begeman37b6a572010-06-08 00:16:34 +0000816 // Check to see if we have a call with 2 vector arguments, the unary shuffle
817 // with mask. If so, verify that RHS is an integer vector type with the
818 // same number of elts as lhs.
819 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000820 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000821 RHSType->getAs<VectorType>()->getNumElements() != numElements)
822 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
823 << SourceRange(TheCall->getArg(1)->getLocStart(),
824 TheCall->getArg(1)->getLocEnd());
825 numResElements = numElements;
826 }
827 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000828 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000829 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000830 TheCall->getArg(1)->getLocEnd());
831 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000832 } else if (numElements != numResElements) {
833 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000834 resType = Context.getVectorType(eltType, numResElements,
835 VectorType::NotAltiVec);
Douglas Gregorcde01732009-05-19 22:10:17 +0000836 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000837 }
838
839 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000840 if (TheCall->getArg(i)->isTypeDependent() ||
841 TheCall->getArg(i)->isValueDependent())
842 continue;
843
Nate Begeman37b6a572010-06-08 00:16:34 +0000844 llvm::APSInt Result(32);
845 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
846 return ExprError(Diag(TheCall->getLocStart(),
847 diag::err_shufflevector_nonconstant_argument)
848 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000849
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000850 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000851 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000852 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000853 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000854 }
855
856 llvm::SmallVector<Expr*, 32> exprs;
857
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000858 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000859 exprs.push_back(TheCall->getArg(i));
860 TheCall->setArg(i, 0);
861 }
862
Nate Begemana88dc302009-08-12 02:10:25 +0000863 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000864 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000865 TheCall->getCallee()->getLocStart(),
866 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000867}
Chris Lattner30ce3442007-12-19 23:59:04 +0000868
Daniel Dunbar4493f792008-07-21 22:59:13 +0000869/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
870// This is declared to take (const void*, ...) and can take two
871// optional constant int args.
872bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000873 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000874
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000875 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000876 return Diag(TheCall->getLocEnd(),
877 diag::err_typecheck_call_too_many_args_at_most)
878 << 0 /*function call*/ << 3 << NumArgs
879 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000880
881 // Argument 0 is checked for us and the remaining arguments must be
882 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000883 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000884 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000885
Eli Friedman9aef7262009-12-04 00:30:06 +0000886 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000887 if (SemaBuiltinConstantArg(TheCall, i, Result))
888 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Daniel Dunbar4493f792008-07-21 22:59:13 +0000890 // FIXME: gcc issues a warning and rewrites these to 0. These
891 // seems especially odd for the third argument since the default
892 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000893 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000894 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000895 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000896 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000897 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000898 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000899 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000900 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000901 }
902 }
903
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000904 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000905}
906
Eric Christopher691ebc32010-04-17 02:26:23 +0000907/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
908/// TheCall is a constant expression.
909bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
910 llvm::APSInt &Result) {
911 Expr *Arg = TheCall->getArg(ArgNum);
912 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
913 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
914
915 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
916
917 if (!Arg->isIntegerConstantExpr(Result, Context))
918 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000919 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000920
Chris Lattner21fb98e2009-09-23 06:06:36 +0000921 return false;
922}
923
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000924/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
925/// int type). This simply type checks that type is one of the defined
926/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000927// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000928bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000929 llvm::APSInt Result;
930
931 // Check constant-ness first.
932 if (SemaBuiltinConstantArg(TheCall, 1, Result))
933 return true;
934
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000935 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000936 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000937 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
938 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000939 }
940
941 return false;
942}
943
Eli Friedman586d6a82009-05-03 06:04:26 +0000944/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000945/// This checks that val is a constant 1.
946bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
947 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000948 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000949
Eric Christopher691ebc32010-04-17 02:26:23 +0000950 // TODO: This is less than ideal. Overload this to take a value.
951 if (SemaBuiltinConstantArg(TheCall, 1, Result))
952 return true;
953
954 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000955 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
956 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
957
958 return false;
959}
960
Ted Kremenekd30ef872009-01-12 23:09:09 +0000961// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000962bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
963 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000964 unsigned format_idx, unsigned firstDataArg,
965 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000966 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000967 if (E->isTypeDependent() || E->isValueDependent())
968 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000969
970 switch (E->getStmtClass()) {
971 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000972 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000973 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
974 format_idx, firstDataArg, isPrintf)
975 && SemaCheckStringLiteral(C->getRHS(), TheCall, HasVAListArg,
976 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000977 }
978
Ted Kremenek95355bb2010-09-09 03:51:42 +0000979 case Stmt::IntegerLiteralClass:
980 // Technically -Wformat-nonliteral does not warn about this case.
981 // The behavior of printf and friends in this case is implementation
982 // dependent. Ideally if the format string cannot be null then
983 // it should have a 'nonnull' attribute in the function prototype.
984 return true;
985
Ted Kremenekd30ef872009-01-12 23:09:09 +0000986 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000987 E = cast<ImplicitCastExpr>(E)->getSubExpr();
988 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000989 }
990
991 case Stmt::ParenExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000992 E = cast<ParenExpr>(E)->getSubExpr();
993 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000994 }
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Ted Kremenek082d9362009-03-20 21:35:28 +0000996 case Stmt::DeclRefExprClass: {
997 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Ted Kremenek082d9362009-03-20 21:35:28 +0000999 // As an exception, do not flag errors for variables binding to
1000 // const string literals.
1001 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1002 bool isConstant = false;
1003 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001004
Ted Kremenek082d9362009-03-20 21:35:28 +00001005 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1006 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001007 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001008 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001009 PT->getPointeeType().isConstant(Context);
1010 }
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Ted Kremenek082d9362009-03-20 21:35:28 +00001012 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001013 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001014 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001015 HasVAListArg, format_idx, firstDataArg,
1016 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +00001017 }
Mike Stump1eb44332009-09-09 15:08:12 +00001018
Anders Carlssond966a552009-06-28 19:55:58 +00001019 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1020 // special check to see if the format string is a function parameter
1021 // of the function calling the printf function. If the function
1022 // has an attribute indicating it is a printf-like function, then we
1023 // should suppress warnings concerning non-literals being used in a call
1024 // to a vprintf function. For example:
1025 //
1026 // void
1027 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1028 // va_list ap;
1029 // va_start(ap, fmt);
1030 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1031 // ...
1032 //
1033 //
1034 // FIXME: We don't have full attribute support yet, so just check to see
1035 // if the argument is a DeclRefExpr that references a parameter. We'll
1036 // add proper support for checking the attribute later.
1037 if (HasVAListArg)
1038 if (isa<ParmVarDecl>(VD))
1039 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001040 }
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Ted Kremenek082d9362009-03-20 21:35:28 +00001042 return false;
1043 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001044
Anders Carlsson8f031b32009-06-27 04:05:33 +00001045 case Stmt::CallExprClass: {
1046 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001047 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001048 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1049 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1050 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001051 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001052 unsigned ArgIndex = FA->getFormatIdx();
1053 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001054
1055 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001056 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001057 }
1058 }
1059 }
1060 }
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Anders Carlsson8f031b32009-06-27 04:05:33 +00001062 return false;
1063 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001064 case Stmt::ObjCStringLiteralClass:
1065 case Stmt::StringLiteralClass: {
1066 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001067
Ted Kremenek082d9362009-03-20 21:35:28 +00001068 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001069 StrE = ObjCFExpr->getString();
1070 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001071 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Ted Kremenekd30ef872009-01-12 23:09:09 +00001073 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001074 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1075 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001076 return true;
1077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Ted Kremenekd30ef872009-01-12 23:09:09 +00001079 return false;
1080 }
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Ted Kremenek082d9362009-03-20 21:35:28 +00001082 default:
1083 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001084 }
1085}
1086
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001087void
Mike Stump1eb44332009-09-09 15:08:12 +00001088Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1089 const CallExpr *TheCall) {
Sean Huntcf807c42010-08-18 23:23:40 +00001090 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1091 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001092 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +00001093 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001094 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001095 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +00001096 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1097 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001098 }
1099}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001100
Ted Kremenek826a3452010-07-16 02:11:22 +00001101/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1102/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001103void
Ted Kremenek826a3452010-07-16 02:11:22 +00001104Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1105 unsigned format_idx, unsigned firstDataArg,
1106 bool isPrintf) {
1107
Ted Kremenek082d9362009-03-20 21:35:28 +00001108 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001109
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001110 // The way the format attribute works in GCC, the implicit this argument
1111 // of member functions is counted. However, it doesn't appear in our own
1112 // lists, so decrement format_idx in that case.
1113 if (isa<CXXMemberCallExpr>(TheCall)) {
1114 // Catch a format attribute mistakenly referring to the object argument.
1115 if (format_idx == 0)
1116 return;
1117 --format_idx;
1118 if(firstDataArg != 0)
1119 --firstDataArg;
1120 }
1121
Ted Kremenek826a3452010-07-16 02:11:22 +00001122 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001123 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001124 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001125 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001126 return;
1127 }
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Ted Kremenek082d9362009-03-20 21:35:28 +00001129 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Chris Lattner59907c42007-08-10 20:18:51 +00001131 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001132 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001133 // Dynamically generated format strings are difficult to
1134 // automatically vet at compile time. Requiring that format strings
1135 // are string literals: (1) permits the checking of format strings by
1136 // the compiler and thereby (2) can practically remove the source of
1137 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001138
Mike Stump1eb44332009-09-09 15:08:12 +00001139 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001140 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001141 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001142 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001143 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001144 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001145 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001146
Chris Lattner655f1412009-04-29 04:59:47 +00001147 // If there are no arguments specified, warn with -Wformat-security, otherwise
1148 // warn only with -Wformat-nonliteral.
1149 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001150 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001151 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001152 << OrigFormatExpr->getSourceRange();
1153 else
Mike Stump1eb44332009-09-09 15:08:12 +00001154 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001155 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001156 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001157}
Ted Kremenek71895b92007-08-14 17:39:48 +00001158
Ted Kremeneke0e53132010-01-28 23:39:18 +00001159namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001160class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1161protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001162 Sema &S;
1163 const StringLiteral *FExpr;
1164 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001165 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001166 const unsigned NumDataArgs;
1167 const bool IsObjCLiteral;
1168 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001169 const bool HasVAListArg;
1170 const CallExpr *TheCall;
1171 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001172 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001173 bool usesPositionalArgs;
1174 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001175public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001176 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001177 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001178 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001179 const char *beg, bool hasVAListArg,
1180 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001181 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001182 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001183 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001184 IsObjCLiteral(isObjCLiteral), Beg(beg),
1185 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001186 TheCall(theCall), FormatIdx(formatIdx),
1187 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001188 CoveredArgs.resize(numDataArgs);
1189 CoveredArgs.reset();
1190 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001191
Ted Kremenek07d161f2010-01-29 01:50:07 +00001192 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001193
Ted Kremenek826a3452010-07-16 02:11:22 +00001194 void HandleIncompleteSpecifier(const char *startSpecifier,
1195 unsigned specifierLen);
1196
Ted Kremenekefaff192010-02-27 01:41:03 +00001197 virtual void HandleInvalidPosition(const char *startSpecifier,
1198 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001199 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001200
1201 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1202
Ted Kremeneke0e53132010-01-28 23:39:18 +00001203 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001204
Ted Kremenek826a3452010-07-16 02:11:22 +00001205protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001206 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1207 const char *startSpec,
1208 unsigned specifierLen,
1209 const char *csStart, unsigned csLen);
1210
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001211 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001212 CharSourceRange getSpecifierRange(const char *startSpecifier,
1213 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001214 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001215
Ted Kremenek0d277352010-01-29 01:06:55 +00001216 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001217
1218 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1219 const analyze_format_string::ConversionSpecifier &CS,
1220 const char *startSpecifier, unsigned specifierLen,
1221 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001222};
1223}
1224
Ted Kremenek826a3452010-07-16 02:11:22 +00001225SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001226 return OrigFormatExpr->getSourceRange();
1227}
1228
Ted Kremenek826a3452010-07-16 02:11:22 +00001229CharSourceRange CheckFormatHandler::
1230getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001231 SourceLocation Start = getLocationOfByte(startSpecifier);
1232 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1233
1234 // Advance the end SourceLocation by one due to half-open ranges.
1235 End = End.getFileLocWithOffset(1);
1236
1237 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001238}
1239
Ted Kremenek826a3452010-07-16 02:11:22 +00001240SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001241 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001242}
1243
Ted Kremenek826a3452010-07-16 02:11:22 +00001244void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1245 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001246 SourceLocation Loc = getLocationOfByte(startSpecifier);
1247 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001248 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001249}
1250
Ted Kremenekefaff192010-02-27 01:41:03 +00001251void
Ted Kremenek826a3452010-07-16 02:11:22 +00001252CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1253 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001254 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001255 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1256 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001257}
1258
Ted Kremenek826a3452010-07-16 02:11:22 +00001259void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001260 unsigned posLen) {
1261 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001262 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1263 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001264}
1265
Ted Kremenek826a3452010-07-16 02:11:22 +00001266void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1267 // The presence of a null character is likely an error.
1268 S.Diag(getLocationOfByte(nullCharacter),
1269 diag::warn_printf_format_string_contains_null_char)
1270 << getFormatStringRange();
1271}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001272
Ted Kremenek826a3452010-07-16 02:11:22 +00001273const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1274 return TheCall->getArg(FirstDataArg + i);
1275}
1276
1277void CheckFormatHandler::DoneProcessing() {
1278 // Does the number of data arguments exceed the number of
1279 // format conversions in the format string?
1280 if (!HasVAListArg) {
1281 // Find any arguments that weren't covered.
1282 CoveredArgs.flip();
1283 signed notCoveredArg = CoveredArgs.find_first();
1284 if (notCoveredArg >= 0) {
1285 assert((unsigned)notCoveredArg < NumDataArgs);
1286 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1287 diag::warn_printf_data_arg_not_used)
1288 << getFormatStringRange();
1289 }
1290 }
1291}
1292
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001293bool
1294CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1295 SourceLocation Loc,
1296 const char *startSpec,
1297 unsigned specifierLen,
1298 const char *csStart,
1299 unsigned csLen) {
1300
1301 bool keepGoing = true;
1302 if (argIndex < NumDataArgs) {
1303 // Consider the argument coverered, even though the specifier doesn't
1304 // make sense.
1305 CoveredArgs.set(argIndex);
1306 }
1307 else {
1308 // If argIndex exceeds the number of data arguments we
1309 // don't issue a warning because that is just a cascade of warnings (and
1310 // they may have intended '%%' anyway). We don't want to continue processing
1311 // the format string after this point, however, as we will like just get
1312 // gibberish when trying to match arguments.
1313 keepGoing = false;
1314 }
1315
1316 S.Diag(Loc, diag::warn_format_invalid_conversion)
1317 << llvm::StringRef(csStart, csLen)
1318 << getSpecifierRange(startSpec, specifierLen);
1319
1320 return keepGoing;
1321}
1322
Ted Kremenek666a1972010-07-26 19:45:42 +00001323bool
1324CheckFormatHandler::CheckNumArgs(
1325 const analyze_format_string::FormatSpecifier &FS,
1326 const analyze_format_string::ConversionSpecifier &CS,
1327 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1328
1329 if (argIndex >= NumDataArgs) {
1330 if (FS.usesPositionalArg()) {
1331 S.Diag(getLocationOfByte(CS.getStart()),
1332 diag::warn_printf_positional_arg_exceeds_data_args)
1333 << (argIndex+1) << NumDataArgs
1334 << getSpecifierRange(startSpecifier, specifierLen);
1335 }
1336 else {
1337 S.Diag(getLocationOfByte(CS.getStart()),
1338 diag::warn_printf_insufficient_data_args)
1339 << getSpecifierRange(startSpecifier, specifierLen);
1340 }
1341
1342 return false;
1343 }
1344 return true;
1345}
1346
Ted Kremenek826a3452010-07-16 02:11:22 +00001347//===--- CHECK: Printf format string checking ------------------------------===//
1348
1349namespace {
1350class CheckPrintfHandler : public CheckFormatHandler {
1351public:
1352 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1353 const Expr *origFormatExpr, unsigned firstDataArg,
1354 unsigned numDataArgs, bool isObjCLiteral,
1355 const char *beg, bool hasVAListArg,
1356 const CallExpr *theCall, unsigned formatIdx)
1357 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1358 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1359 theCall, formatIdx) {}
1360
1361
1362 bool HandleInvalidPrintfConversionSpecifier(
1363 const analyze_printf::PrintfSpecifier &FS,
1364 const char *startSpecifier,
1365 unsigned specifierLen);
1366
1367 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1368 const char *startSpecifier,
1369 unsigned specifierLen);
1370
1371 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1372 const char *startSpecifier, unsigned specifierLen);
1373 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1374 const analyze_printf::OptionalAmount &Amt,
1375 unsigned type,
1376 const char *startSpecifier, unsigned specifierLen);
1377 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1378 const analyze_printf::OptionalFlag &flag,
1379 const char *startSpecifier, unsigned specifierLen);
1380 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1381 const analyze_printf::OptionalFlag &ignoredFlag,
1382 const analyze_printf::OptionalFlag &flag,
1383 const char *startSpecifier, unsigned specifierLen);
1384};
1385}
1386
1387bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1388 const analyze_printf::PrintfSpecifier &FS,
1389 const char *startSpecifier,
1390 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001391 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001392 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001393
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001394 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1395 getLocationOfByte(CS.getStart()),
1396 startSpecifier, specifierLen,
1397 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001398}
1399
Ted Kremenek826a3452010-07-16 02:11:22 +00001400bool CheckPrintfHandler::HandleAmount(
1401 const analyze_format_string::OptionalAmount &Amt,
1402 unsigned k, const char *startSpecifier,
1403 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001404
1405 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001406 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001407 unsigned argIndex = Amt.getArgIndex();
1408 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001409 S.Diag(getLocationOfByte(Amt.getStart()),
1410 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001411 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001412 // Don't do any more checking. We will just emit
1413 // spurious errors.
1414 return false;
1415 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001416
Ted Kremenek0d277352010-01-29 01:06:55 +00001417 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001418 // Although not in conformance with C99, we also allow the argument to be
1419 // an 'unsigned int' as that is a reasonably safe case. GCC also
1420 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001421 CoveredArgs.set(argIndex);
1422 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001423 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001424
1425 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1426 assert(ATR.isValid());
1427
1428 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001429 S.Diag(getLocationOfByte(Amt.getStart()),
1430 diag::warn_printf_asterisk_wrong_type)
1431 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001432 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001433 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001434 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001435 // Don't do any more checking. We will just emit
1436 // spurious errors.
1437 return false;
1438 }
1439 }
1440 }
1441 return true;
1442}
Ted Kremenek0d277352010-01-29 01:06:55 +00001443
Tom Caree4ee9662010-06-17 19:00:27 +00001444void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001445 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001446 const analyze_printf::OptionalAmount &Amt,
1447 unsigned type,
1448 const char *startSpecifier,
1449 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001450 const analyze_printf::PrintfConversionSpecifier &CS =
1451 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001452 switch (Amt.getHowSpecified()) {
1453 case analyze_printf::OptionalAmount::Constant:
1454 S.Diag(getLocationOfByte(Amt.getStart()),
1455 diag::warn_printf_nonsensical_optional_amount)
1456 << type
1457 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001458 << getSpecifierRange(startSpecifier, specifierLen)
1459 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001460 Amt.getConstantLength()));
1461 break;
1462
1463 default:
1464 S.Diag(getLocationOfByte(Amt.getStart()),
1465 diag::warn_printf_nonsensical_optional_amount)
1466 << type
1467 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001468 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001469 break;
1470 }
1471}
1472
Ted Kremenek826a3452010-07-16 02:11:22 +00001473void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001474 const analyze_printf::OptionalFlag &flag,
1475 const char *startSpecifier,
1476 unsigned specifierLen) {
1477 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001478 const analyze_printf::PrintfConversionSpecifier &CS =
1479 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001480 S.Diag(getLocationOfByte(flag.getPosition()),
1481 diag::warn_printf_nonsensical_flag)
1482 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001483 << getSpecifierRange(startSpecifier, specifierLen)
1484 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001485}
1486
1487void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001488 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001489 const analyze_printf::OptionalFlag &ignoredFlag,
1490 const analyze_printf::OptionalFlag &flag,
1491 const char *startSpecifier,
1492 unsigned specifierLen) {
1493 // Warn about ignored flag with a fixit removal.
1494 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1495 diag::warn_printf_ignored_flag)
1496 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001497 << getSpecifierRange(startSpecifier, specifierLen)
1498 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001499 ignoredFlag.getPosition(), 1));
1500}
1501
Ted Kremeneke0e53132010-01-28 23:39:18 +00001502bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001503CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001504 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001505 const char *startSpecifier,
1506 unsigned specifierLen) {
1507
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001508 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001509 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001510 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001511
Ted Kremenekbaa40062010-07-19 22:01:06 +00001512 if (FS.consumesDataArgument()) {
1513 if (atFirstArg) {
1514 atFirstArg = false;
1515 usesPositionalArgs = FS.usesPositionalArg();
1516 }
1517 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1518 // Cannot mix-and-match positional and non-positional arguments.
1519 S.Diag(getLocationOfByte(CS.getStart()),
1520 diag::warn_format_mix_positional_nonpositional_args)
1521 << getSpecifierRange(startSpecifier, specifierLen);
1522 return false;
1523 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001524 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001525
Ted Kremenekefaff192010-02-27 01:41:03 +00001526 // First check if the field width, precision, and conversion specifier
1527 // have matching data arguments.
1528 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1529 startSpecifier, specifierLen)) {
1530 return false;
1531 }
1532
1533 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1534 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001535 return false;
1536 }
1537
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001538 if (!CS.consumesDataArgument()) {
1539 // FIXME: Technically specifying a precision or field width here
1540 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001541 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001542 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001543
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001544 // Consume the argument.
1545 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001546 if (argIndex < NumDataArgs) {
1547 // The check to see if the argIndex is valid will come later.
1548 // We set the bit here because we may exit early from this
1549 // function if we encounter some other error.
1550 CoveredArgs.set(argIndex);
1551 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001552
1553 // Check for using an Objective-C specific conversion specifier
1554 // in a non-ObjC literal.
1555 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001556 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1557 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001558 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001559
Tom Caree4ee9662010-06-17 19:00:27 +00001560 // Check for invalid use of field width
1561 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001562 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001563 startSpecifier, specifierLen);
1564 }
1565
1566 // Check for invalid use of precision
1567 if (!FS.hasValidPrecision()) {
1568 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1569 startSpecifier, specifierLen);
1570 }
1571
1572 // Check each flag does not conflict with any other component.
1573 if (!FS.hasValidLeadingZeros())
1574 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1575 if (!FS.hasValidPlusPrefix())
1576 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001577 if (!FS.hasValidSpacePrefix())
1578 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001579 if (!FS.hasValidAlternativeForm())
1580 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1581 if (!FS.hasValidLeftJustified())
1582 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1583
1584 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001585 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1586 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1587 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001588 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1589 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1590 startSpecifier, specifierLen);
1591
1592 // Check the length modifier is valid with the given conversion specifier.
1593 const LengthModifier &LM = FS.getLengthModifier();
1594 if (!FS.hasValidLengthModifier())
1595 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001596 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001597 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001598 << getSpecifierRange(startSpecifier, specifierLen)
1599 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001600 LM.getLength()));
1601
1602 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001603 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001604 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001605 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001606 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001607 // Continue checking the other format specifiers.
1608 return true;
1609 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001610
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001611 // The remaining checks depend on the data arguments.
1612 if (HasVAListArg)
1613 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001614
Ted Kremenek666a1972010-07-26 19:45:42 +00001615 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001616 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001617
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001618 // Now type check the data expression that matches the
1619 // format specifier.
1620 const Expr *Ex = getDataArg(argIndex);
1621 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1622 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1623 // Check if we didn't match because of an implicit cast from a 'char'
1624 // or 'short' to an 'int'. This is done because printf is a varargs
1625 // function.
1626 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1627 if (ICE->getType() == S.Context.IntTy)
1628 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1629 return true;
1630
1631 // We may be able to offer a FixItHint if it is a supported type.
1632 PrintfSpecifier fixedFS = FS;
1633 bool success = fixedFS.fixType(Ex->getType());
1634
1635 if (success) {
1636 // Get the fix string from the fixed format specifier
1637 llvm::SmallString<128> buf;
1638 llvm::raw_svector_ostream os(buf);
1639 fixedFS.toString(os);
1640
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001641 // FIXME: getRepresentativeType() perhaps should return a string
1642 // instead of a QualType to better handle when the representative
1643 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001644 S.Diag(getLocationOfByte(CS.getStart()),
1645 diag::warn_printf_conversion_argument_type_mismatch)
1646 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1647 << getSpecifierRange(startSpecifier, specifierLen)
1648 << Ex->getSourceRange()
1649 << FixItHint::CreateReplacement(
1650 getSpecifierRange(startSpecifier, specifierLen),
1651 os.str());
1652 }
1653 else {
1654 S.Diag(getLocationOfByte(CS.getStart()),
1655 diag::warn_printf_conversion_argument_type_mismatch)
1656 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1657 << getSpecifierRange(startSpecifier, specifierLen)
1658 << Ex->getSourceRange();
1659 }
1660 }
1661
Ted Kremeneke0e53132010-01-28 23:39:18 +00001662 return true;
1663}
1664
Ted Kremenek826a3452010-07-16 02:11:22 +00001665//===--- CHECK: Scanf format string checking ------------------------------===//
1666
1667namespace {
1668class CheckScanfHandler : public CheckFormatHandler {
1669public:
1670 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1671 const Expr *origFormatExpr, unsigned firstDataArg,
1672 unsigned numDataArgs, bool isObjCLiteral,
1673 const char *beg, bool hasVAListArg,
1674 const CallExpr *theCall, unsigned formatIdx)
1675 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1676 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1677 theCall, formatIdx) {}
1678
1679 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1680 const char *startSpecifier,
1681 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001682
1683 bool HandleInvalidScanfConversionSpecifier(
1684 const analyze_scanf::ScanfSpecifier &FS,
1685 const char *startSpecifier,
1686 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001687
1688 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001689};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001690}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001691
Ted Kremenekb7c21012010-07-16 18:28:03 +00001692void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1693 const char *end) {
1694 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1695 << getSpecifierRange(start, end - start);
1696}
1697
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001698bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1699 const analyze_scanf::ScanfSpecifier &FS,
1700 const char *startSpecifier,
1701 unsigned specifierLen) {
1702
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001703 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001704 FS.getConversionSpecifier();
1705
1706 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1707 getLocationOfByte(CS.getStart()),
1708 startSpecifier, specifierLen,
1709 CS.getStart(), CS.getLength());
1710}
1711
Ted Kremenek826a3452010-07-16 02:11:22 +00001712bool CheckScanfHandler::HandleScanfSpecifier(
1713 const analyze_scanf::ScanfSpecifier &FS,
1714 const char *startSpecifier,
1715 unsigned specifierLen) {
1716
1717 using namespace analyze_scanf;
1718 using namespace analyze_format_string;
1719
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001720 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001721
Ted Kremenekbaa40062010-07-19 22:01:06 +00001722 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1723 // be used to decide if we are using positional arguments consistently.
1724 if (FS.consumesDataArgument()) {
1725 if (atFirstArg) {
1726 atFirstArg = false;
1727 usesPositionalArgs = FS.usesPositionalArg();
1728 }
1729 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1730 // Cannot mix-and-match positional and non-positional arguments.
1731 S.Diag(getLocationOfByte(CS.getStart()),
1732 diag::warn_format_mix_positional_nonpositional_args)
1733 << getSpecifierRange(startSpecifier, specifierLen);
1734 return false;
1735 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001736 }
1737
1738 // Check if the field with is non-zero.
1739 const OptionalAmount &Amt = FS.getFieldWidth();
1740 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1741 if (Amt.getConstantAmount() == 0) {
1742 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1743 Amt.getConstantLength());
1744 S.Diag(getLocationOfByte(Amt.getStart()),
1745 diag::warn_scanf_nonzero_width)
1746 << R << FixItHint::CreateRemoval(R);
1747 }
1748 }
1749
1750 if (!FS.consumesDataArgument()) {
1751 // FIXME: Technically specifying a precision or field width here
1752 // makes no sense. Worth issuing a warning at some point.
1753 return true;
1754 }
1755
1756 // Consume the argument.
1757 unsigned argIndex = FS.getArgIndex();
1758 if (argIndex < NumDataArgs) {
1759 // The check to see if the argIndex is valid will come later.
1760 // We set the bit here because we may exit early from this
1761 // function if we encounter some other error.
1762 CoveredArgs.set(argIndex);
1763 }
1764
Ted Kremenek1e51c202010-07-20 20:04:47 +00001765 // Check the length modifier is valid with the given conversion specifier.
1766 const LengthModifier &LM = FS.getLengthModifier();
1767 if (!FS.hasValidLengthModifier()) {
1768 S.Diag(getLocationOfByte(LM.getStart()),
1769 diag::warn_format_nonsensical_length)
1770 << LM.toString() << CS.toString()
1771 << getSpecifierRange(startSpecifier, specifierLen)
1772 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1773 LM.getLength()));
1774 }
1775
Ted Kremenek826a3452010-07-16 02:11:22 +00001776 // The remaining checks depend on the data arguments.
1777 if (HasVAListArg)
1778 return true;
1779
Ted Kremenek666a1972010-07-26 19:45:42 +00001780 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001781 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001782
1783 // FIXME: Check that the argument type matches the format specifier.
1784
1785 return true;
1786}
1787
1788void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001789 const Expr *OrigFormatExpr,
1790 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001791 unsigned format_idx, unsigned firstDataArg,
1792 bool isPrintf) {
1793
Ted Kremeneke0e53132010-01-28 23:39:18 +00001794 // CHECK: is the format string a wide literal?
1795 if (FExpr->isWide()) {
1796 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001797 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001798 << OrigFormatExpr->getSourceRange();
1799 return;
1800 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001801
Ted Kremeneke0e53132010-01-28 23:39:18 +00001802 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001803 llvm::StringRef StrRef = FExpr->getString();
1804 const char *Str = StrRef.data();
1805 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001806
Ted Kremeneke0e53132010-01-28 23:39:18 +00001807 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001808 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001809 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001810 << OrigFormatExpr->getSourceRange();
1811 return;
1812 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001813
1814 if (isPrintf) {
1815 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1816 TheCall->getNumArgs() - firstDataArg,
1817 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1818 HasVAListArg, TheCall, format_idx);
1819
1820 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1821 H.DoneProcessing();
1822 }
1823 else {
1824 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1825 TheCall->getNumArgs() - firstDataArg,
1826 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1827 HasVAListArg, TheCall, format_idx);
1828
1829 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1830 H.DoneProcessing();
1831 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001832}
1833
Ted Kremenek06de2762007-08-17 16:46:58 +00001834//===--- CHECK: Return Address of Stack Variable --------------------------===//
1835
1836static DeclRefExpr* EvalVal(Expr *E);
1837static DeclRefExpr* EvalAddr(Expr* E);
1838
1839/// CheckReturnStackAddr - Check if a return statement returns the address
1840/// of a stack variable.
1841void
1842Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1843 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Ted Kremenek06de2762007-08-17 16:46:58 +00001845 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001846 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001847 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001848 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001849 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Steve Naroffc50a4a52008-09-16 22:25:10 +00001851 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001852 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001853
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001854 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001855 if (C->hasBlockDeclRefExprs())
1856 Diag(C->getLocStart(), diag::err_ret_local_block)
1857 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001858
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001859 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1860 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1861 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001862
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001863 } else if (lhsType->isReferenceType()) {
1864 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001865 // Check for a reference to the stack
1866 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001867 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001868 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001869 }
1870}
1871
1872/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1873/// check if the expression in a return statement evaluates to an address
1874/// to a location on the stack. The recursion is used to traverse the
1875/// AST of the return expression, with recursion backtracking when we
1876/// encounter a subexpression that (1) clearly does not lead to the address
1877/// of a stack variable or (2) is something we cannot determine leads to
1878/// the address of a stack variable based on such local checking.
1879///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001880/// EvalAddr processes expressions that are pointers that are used as
1881/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001882/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001883/// the refers to a stack variable.
1884///
1885/// This implementation handles:
1886///
1887/// * pointer-to-pointer casts
1888/// * implicit conversions from array references to pointers
1889/// * taking the address of fields
1890/// * arbitrary interplay between "&" and "*" operators
1891/// * pointer arithmetic from an address of a stack variable
1892/// * taking the address of an array element where the array is on the stack
1893static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001894 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001895 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001896 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001897 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001898 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001899
Ted Kremenek06de2762007-08-17 16:46:58 +00001900 // Our "symbolic interpreter" is just a dispatch off the currently
1901 // viewed AST node. We then recursively traverse the AST by calling
1902 // EvalAddr and EvalVal appropriately.
1903 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001904 case Stmt::ParenExprClass:
1905 // Ignore parentheses.
1906 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001907
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001908 case Stmt::UnaryOperatorClass: {
1909 // The only unary operator that make sense to handle here
1910 // is AddrOf. All others don't make sense as pointers.
1911 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001912
John McCall2de56d12010-08-25 11:45:40 +00001913 if (U->getOpcode() == UO_AddrOf)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001914 return EvalVal(U->getSubExpr());
1915 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001916 return NULL;
1917 }
Mike Stump1eb44332009-09-09 15:08:12 +00001918
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001919 case Stmt::BinaryOperatorClass: {
1920 // Handle pointer arithmetic. All other binary operators are not valid
1921 // in this context.
1922 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001923 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001924
John McCall2de56d12010-08-25 11:45:40 +00001925 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001926 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001927
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001928 Expr *Base = B->getLHS();
1929
1930 // Determine which argument is the real pointer base. It could be
1931 // the RHS argument instead of the LHS.
1932 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001934 assert (Base->getType()->isPointerType());
1935 return EvalAddr(Base);
1936 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001937
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001938 // For conditional operators we need to see if either the LHS or RHS are
1939 // valid DeclRefExpr*s. If one of them is valid, we return it.
1940 case Stmt::ConditionalOperatorClass: {
1941 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001943 // Handle the GNU extension for missing LHS.
1944 if (Expr *lhsExpr = C->getLHS())
1945 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1946 return LHS;
1947
1948 return EvalAddr(C->getRHS());
1949 }
Mike Stump1eb44332009-09-09 15:08:12 +00001950
Ted Kremenek54b52742008-08-07 00:49:01 +00001951 // For casts, we need to handle conversions from arrays to
1952 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001953 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001954 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001955 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001956 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001957 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Steve Naroffdd972f22008-09-05 22:11:13 +00001959 if (SubExpr->getType()->isPointerType() ||
1960 SubExpr->getType()->isBlockPointerType() ||
1961 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001962 return EvalAddr(SubExpr);
1963 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001964 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001965 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001966 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001967 }
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001969 // C++ casts. For dynamic casts, static casts, and const casts, we
1970 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001971 // through the cast. In the case the dynamic cast doesn't fail (and
1972 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001973 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001974 // FIXME: The comment about is wrong; we're not always converting
1975 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001976 // handle references to objects.
1977 case Stmt::CXXStaticCastExprClass:
1978 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001979 case Stmt::CXXConstCastExprClass:
1980 case Stmt::CXXReinterpretCastExprClass: {
1981 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001982 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001983 return EvalAddr(S);
1984 else
1985 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001986 }
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001988 // Everything else: we simply don't reason about them.
1989 default:
1990 return NULL;
1991 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001992}
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Ted Kremenek06de2762007-08-17 16:46:58 +00001994
1995/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1996/// See the comments for EvalAddr for more details.
1997static DeclRefExpr* EvalVal(Expr *E) {
Ted Kremenek68957a92010-08-04 20:01:07 +00001998do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001999 // We should only be called for evaluating non-pointer expressions, or
2000 // expressions with a pointer type that are not used as references but instead
2001 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Ted Kremenek06de2762007-08-17 16:46:58 +00002003 // Our "symbolic interpreter" is just a dispatch off the currently
2004 // viewed AST node. We then recursively traverse the AST by calling
2005 // EvalAddr and EvalVal appropriately.
2006 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002007 case Stmt::ImplicitCastExprClass: {
2008 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002009 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002010 E = IE->getSubExpr();
2011 continue;
2012 }
2013 return NULL;
2014 }
2015
Douglas Gregora2813ce2009-10-23 18:54:35 +00002016 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002017 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
2018 // at code that refers to a variable's name. We check if it has local
2019 // storage within the function, and if so, return the expression.
2020 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002021
Ted Kremenek06de2762007-08-17 16:46:58 +00002022 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00002023 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
2024
Ted Kremenek06de2762007-08-17 16:46:58 +00002025 return NULL;
2026 }
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Ted Kremenek68957a92010-08-04 20:01:07 +00002028 case Stmt::ParenExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002029 // Ignore parentheses.
Ted Kremenek68957a92010-08-04 20:01:07 +00002030 E = cast<ParenExpr>(E)->getSubExpr();
2031 continue;
2032 }
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Ted Kremenek06de2762007-08-17 16:46:58 +00002034 case Stmt::UnaryOperatorClass: {
2035 // The only unary operator that make sense to handle here
2036 // is Deref. All others don't resolve to a "name." This includes
2037 // handling all sorts of rvalues passed to a unary operator.
2038 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002039
John McCall2de56d12010-08-25 11:45:40 +00002040 if (U->getOpcode() == UO_Deref)
Ted Kremenek06de2762007-08-17 16:46:58 +00002041 return EvalAddr(U->getSubExpr());
2042
2043 return NULL;
2044 }
Mike Stump1eb44332009-09-09 15:08:12 +00002045
Ted Kremenek06de2762007-08-17 16:46:58 +00002046 case Stmt::ArraySubscriptExprClass: {
2047 // Array subscripts are potential references to data on the stack. We
2048 // retrieve the DeclRefExpr* for the array variable if it indeed
2049 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00002050 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00002051 }
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Ted Kremenek06de2762007-08-17 16:46:58 +00002053 case Stmt::ConditionalOperatorClass: {
2054 // For conditional operators we need to see if either the LHS or RHS are
2055 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
2056 ConditionalOperator *C = cast<ConditionalOperator>(E);
2057
Anders Carlsson39073232007-11-30 19:04:31 +00002058 // Handle the GNU extension for missing LHS.
2059 if (Expr *lhsExpr = C->getLHS())
2060 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
2061 return LHS;
2062
2063 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00002064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Ted Kremenek06de2762007-08-17 16:46:58 +00002066 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002067 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002068 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002069
Ted Kremenek06de2762007-08-17 16:46:58 +00002070 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002071 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002072 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002073
2074 // Check whether the member type is itself a reference, in which case
2075 // we're not going to refer to the member, but to what the member refers to.
2076 if (M->getMemberDecl()->getType()->isReferenceType())
2077 return NULL;
2078
2079 return EvalVal(M->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00002080 }
Mike Stump1eb44332009-09-09 15:08:12 +00002081
Ted Kremenek06de2762007-08-17 16:46:58 +00002082 // Everything else: we simply don't reason about them.
2083 default:
2084 return NULL;
2085 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002086} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002087}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002088
2089//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2090
2091/// Check for comparisons of floating point operands using != and ==.
2092/// Issue a warning if these are no self-comparisons, as they are not likely
2093/// to do what the programmer intended.
2094void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2095 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002097 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00002098 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002099
2100 // Special case: check for x == x (which is OK).
2101 // Do not emit warnings for such cases.
2102 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2103 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2104 if (DRL->getDecl() == DRR->getDecl())
2105 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002106
2107
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002108 // Special case: check for comparisons against literals that can be exactly
2109 // represented by APFloat. In such cases, do not emit a warning. This
2110 // is a heuristic: often comparison against such literals are used to
2111 // detect if a value in a variable has not changed. This clearly can
2112 // lead to false negatives.
2113 if (EmitWarning) {
2114 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2115 if (FLL->isExact())
2116 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002117 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002118 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2119 if (FLR->isExact())
2120 EmitWarning = false;
2121 }
2122 }
Mike Stump1eb44332009-09-09 15:08:12 +00002123
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002124 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002125 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002126 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002127 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002128 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Sebastian Redl0eb23302009-01-19 00:08:26 +00002130 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002131 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002132 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002133 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002135 // Emit the diagnostic.
2136 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002137 Diag(loc, diag::warn_floatingpoint_eq)
2138 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002139}
John McCallba26e582010-01-04 23:21:16 +00002140
John McCallf2370c92010-01-06 05:24:50 +00002141//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2142//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002143
John McCallf2370c92010-01-06 05:24:50 +00002144namespace {
John McCallba26e582010-01-04 23:21:16 +00002145
John McCallf2370c92010-01-06 05:24:50 +00002146/// Structure recording the 'active' range of an integer-valued
2147/// expression.
2148struct IntRange {
2149 /// The number of bits active in the int.
2150 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002151
John McCallf2370c92010-01-06 05:24:50 +00002152 /// True if the int is known not to have negative values.
2153 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002154
John McCallf2370c92010-01-06 05:24:50 +00002155 IntRange(unsigned Width, bool NonNegative)
2156 : Width(Width), NonNegative(NonNegative)
2157 {}
John McCallba26e582010-01-04 23:21:16 +00002158
John McCallf2370c92010-01-06 05:24:50 +00002159 // Returns the range of the bool type.
2160 static IntRange forBoolType() {
2161 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002162 }
2163
John McCallf2370c92010-01-06 05:24:50 +00002164 // Returns the range of an integral type.
2165 static IntRange forType(ASTContext &C, QualType T) {
2166 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002167 }
2168
John McCallf2370c92010-01-06 05:24:50 +00002169 // Returns the range of an integeral type based on its canonical
2170 // representation.
2171 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
2172 assert(T->isCanonicalUnqualified());
2173
2174 if (const VectorType *VT = dyn_cast<VectorType>(T))
2175 T = VT->getElementType().getTypePtr();
2176 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2177 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002178
2179 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2180 EnumDecl *Enum = ET->getDecl();
2181 unsigned NumPositive = Enum->getNumPositiveBits();
2182 unsigned NumNegative = Enum->getNumNegativeBits();
2183
2184 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2185 }
John McCallf2370c92010-01-06 05:24:50 +00002186
2187 const BuiltinType *BT = cast<BuiltinType>(T);
2188 assert(BT->isInteger());
2189
2190 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2191 }
2192
2193 // Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002194 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002195 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002196 L.NonNegative && R.NonNegative);
2197 }
2198
2199 // Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002200 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002201 return IntRange(std::min(L.Width, R.Width),
2202 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002203 }
2204};
2205
2206IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2207 if (value.isSigned() && value.isNegative())
2208 return IntRange(value.getMinSignedBits(), false);
2209
2210 if (value.getBitWidth() > MaxWidth)
2211 value.trunc(MaxWidth);
2212
2213 // isNonNegative() just checks the sign bit without considering
2214 // signedness.
2215 return IntRange(value.getActiveBits(), true);
2216}
2217
John McCall0acc3112010-01-06 22:57:21 +00002218IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002219 unsigned MaxWidth) {
2220 if (result.isInt())
2221 return GetValueRange(C, result.getInt(), MaxWidth);
2222
2223 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002224 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2225 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2226 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2227 R = IntRange::join(R, El);
2228 }
John McCallf2370c92010-01-06 05:24:50 +00002229 return R;
2230 }
2231
2232 if (result.isComplexInt()) {
2233 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2234 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2235 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002236 }
2237
2238 // This can happen with lossless casts to intptr_t of "based" lvalues.
2239 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002240 // FIXME: The only reason we need to pass the type in here is to get
2241 // the sign right on this one case. It would be nice if APValue
2242 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002243 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002244 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002245}
John McCallf2370c92010-01-06 05:24:50 +00002246
2247/// Pseudo-evaluate the given integer expression, estimating the
2248/// range of values it might take.
2249///
2250/// \param MaxWidth - the width to which the value will be truncated
2251IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2252 E = E->IgnoreParens();
2253
2254 // Try a full evaluation first.
2255 Expr::EvalResult result;
2256 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002257 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002258
2259 // I think we only want to look through implicit casts here; if the
2260 // user has an explicit widening cast, we should treat the value as
2261 // being of the new, wider type.
2262 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002263 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002264 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2265
2266 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
2267
John McCall2de56d12010-08-25 11:45:40 +00002268 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
2269 if (!isIntegerCast && CE->getCastKind() == CK_Unknown)
John McCall60fad452010-01-06 22:07:33 +00002270 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
2271
John McCallf2370c92010-01-06 05:24:50 +00002272 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002273 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002274 return OutputTypeRange;
2275
2276 IntRange SubRange
2277 = GetExprRange(C, CE->getSubExpr(),
2278 std::min(MaxWidth, OutputTypeRange.Width));
2279
2280 // Bail out if the subexpr's range is as wide as the cast type.
2281 if (SubRange.Width >= OutputTypeRange.Width)
2282 return OutputTypeRange;
2283
2284 // Otherwise, we take the smaller width, and we're non-negative if
2285 // either the output type or the subexpr is.
2286 return IntRange(SubRange.Width,
2287 SubRange.NonNegative || OutputTypeRange.NonNegative);
2288 }
2289
2290 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2291 // If we can fold the condition, just take that operand.
2292 bool CondResult;
2293 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2294 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2295 : CO->getFalseExpr(),
2296 MaxWidth);
2297
2298 // Otherwise, conservatively merge.
2299 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2300 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2301 return IntRange::join(L, R);
2302 }
2303
2304 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2305 switch (BO->getOpcode()) {
2306
2307 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002308 case BO_LAnd:
2309 case BO_LOr:
2310 case BO_LT:
2311 case BO_GT:
2312 case BO_LE:
2313 case BO_GE:
2314 case BO_EQ:
2315 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002316 return IntRange::forBoolType();
2317
John McCallc0cd21d2010-02-23 19:22:29 +00002318 // The type of these compound assignments is the type of the LHS,
2319 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002320 case BO_MulAssign:
2321 case BO_DivAssign:
2322 case BO_RemAssign:
2323 case BO_AddAssign:
2324 case BO_SubAssign:
John McCallc0cd21d2010-02-23 19:22:29 +00002325 return IntRange::forType(C, E->getType());
2326
John McCallf2370c92010-01-06 05:24:50 +00002327 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002328 case BO_PtrMemD:
2329 case BO_PtrMemI:
John McCallf2370c92010-01-06 05:24:50 +00002330 return IntRange::forType(C, E->getType());
2331
John McCall60fad452010-01-06 22:07:33 +00002332 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002333 case BO_And:
2334 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002335 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2336 GetExprRange(C, BO->getRHS(), MaxWidth));
2337
John McCallf2370c92010-01-06 05:24:50 +00002338 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002339 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002340 // ...except that we want to treat '1 << (blah)' as logically
2341 // positive. It's an important idiom.
2342 if (IntegerLiteral *I
2343 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2344 if (I->getValue() == 1) {
2345 IntRange R = IntRange::forType(C, E->getType());
2346 return IntRange(R.Width, /*NonNegative*/ true);
2347 }
2348 }
2349 // fallthrough
2350
John McCall2de56d12010-08-25 11:45:40 +00002351 case BO_ShlAssign:
John McCallf2370c92010-01-06 05:24:50 +00002352 return IntRange::forType(C, E->getType());
2353
John McCall60fad452010-01-06 22:07:33 +00002354 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002355 case BO_Shr:
2356 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002357 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2358
2359 // If the shift amount is a positive constant, drop the width by
2360 // that much.
2361 llvm::APSInt shift;
2362 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2363 shift.isNonNegative()) {
2364 unsigned zext = shift.getZExtValue();
2365 if (zext >= L.Width)
2366 L.Width = (L.NonNegative ? 0 : 1);
2367 else
2368 L.Width -= zext;
2369 }
2370
2371 return L;
2372 }
2373
2374 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002375 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002376 return GetExprRange(C, BO->getRHS(), MaxWidth);
2377
John McCall60fad452010-01-06 22:07:33 +00002378 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002379 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002380 if (BO->getLHS()->getType()->isPointerType())
2381 return IntRange::forType(C, E->getType());
2382 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002383
John McCallf2370c92010-01-06 05:24:50 +00002384 default:
2385 break;
2386 }
2387
2388 // Treat every other operator as if it were closed on the
2389 // narrowest type that encompasses both operands.
2390 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2391 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2392 return IntRange::join(L, R);
2393 }
2394
2395 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2396 switch (UO->getOpcode()) {
2397 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002398 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002399 return IntRange::forBoolType();
2400
2401 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002402 case UO_Deref:
2403 case UO_AddrOf: // should be impossible
John McCallf2370c92010-01-06 05:24:50 +00002404 return IntRange::forType(C, E->getType());
2405
2406 default:
2407 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2408 }
2409 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002410
2411 if (dyn_cast<OffsetOfExpr>(E)) {
2412 IntRange::forType(C, E->getType());
2413 }
John McCallf2370c92010-01-06 05:24:50 +00002414
2415 FieldDecl *BitField = E->getBitField();
2416 if (BitField) {
2417 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2418 unsigned BitWidth = BitWidthAP.getZExtValue();
2419
2420 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2421 }
2422
2423 return IntRange::forType(C, E->getType());
2424}
John McCall51313c32010-01-04 23:31:57 +00002425
John McCall323ed742010-05-06 08:58:33 +00002426IntRange GetExprRange(ASTContext &C, Expr *E) {
2427 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2428}
2429
John McCall51313c32010-01-04 23:31:57 +00002430/// Checks whether the given value, which currently has the given
2431/// source semantics, has the same value when coerced through the
2432/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002433bool IsSameFloatAfterCast(const llvm::APFloat &value,
2434 const llvm::fltSemantics &Src,
2435 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002436 llvm::APFloat truncated = value;
2437
2438 bool ignored;
2439 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2440 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2441
2442 return truncated.bitwiseIsEqual(value);
2443}
2444
2445/// Checks whether the given value, which currently has the given
2446/// source semantics, has the same value when coerced through the
2447/// target semantics.
2448///
2449/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002450bool IsSameFloatAfterCast(const APValue &value,
2451 const llvm::fltSemantics &Src,
2452 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002453 if (value.isFloat())
2454 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2455
2456 if (value.isVector()) {
2457 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2458 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2459 return false;
2460 return true;
2461 }
2462
2463 assert(value.isComplexFloat());
2464 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2465 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2466}
2467
John McCall323ed742010-05-06 08:58:33 +00002468void AnalyzeImplicitConversions(Sema &S, Expr *E);
2469
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002470static bool IsZero(Sema &S, Expr *E) {
2471 // Suppress cases where we are comparing against an enum constant.
2472 if (const DeclRefExpr *DR =
2473 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2474 if (isa<EnumConstantDecl>(DR->getDecl()))
2475 return false;
2476
2477 // Suppress cases where the '0' value is expanded from a macro.
2478 if (E->getLocStart().isMacroID())
2479 return false;
2480
John McCall323ed742010-05-06 08:58:33 +00002481 llvm::APSInt Value;
2482 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2483}
2484
2485void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002486 BinaryOperatorKind op = E->getOpcode();
2487 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002488 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2489 << "< 0" << "false"
2490 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002491 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002492 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2493 << ">= 0" << "true"
2494 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002495 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002496 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2497 << "0 >" << "false"
2498 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002499 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002500 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2501 << "0 <=" << "true"
2502 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2503 }
2504}
2505
2506/// Analyze the operands of the given comparison. Implements the
2507/// fallback case from AnalyzeComparison.
2508void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
2509 AnalyzeImplicitConversions(S, E->getLHS());
2510 AnalyzeImplicitConversions(S, E->getRHS());
2511}
John McCall51313c32010-01-04 23:31:57 +00002512
John McCallba26e582010-01-04 23:21:16 +00002513/// \brief Implements -Wsign-compare.
2514///
2515/// \param lex the left-hand expression
2516/// \param rex the right-hand expression
2517/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002518/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002519void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2520 // The type the comparison is being performed in.
2521 QualType T = E->getLHS()->getType();
2522 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2523 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002524
John McCall323ed742010-05-06 08:58:33 +00002525 // We don't do anything special if this isn't an unsigned integral
2526 // comparison: we're only interested in integral comparisons, and
2527 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregorf6094622010-07-23 15:58:24 +00002528 if (!T->hasUnsignedIntegerRepresentation())
John McCall323ed742010-05-06 08:58:33 +00002529 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002530
John McCall323ed742010-05-06 08:58:33 +00002531 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2532 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002533
John McCall323ed742010-05-06 08:58:33 +00002534 // Check to see if one of the (unmodified) operands is of different
2535 // signedness.
2536 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002537 if (lex->getType()->hasSignedIntegerRepresentation()) {
2538 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002539 "unsigned comparison between two signed integer expressions?");
2540 signedOperand = lex;
2541 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002542 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002543 signedOperand = rex;
2544 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002545 } else {
John McCall323ed742010-05-06 08:58:33 +00002546 CheckTrivialUnsignedComparison(S, E);
2547 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002548 }
2549
John McCall323ed742010-05-06 08:58:33 +00002550 // Otherwise, calculate the effective range of the signed operand.
2551 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002552
John McCall323ed742010-05-06 08:58:33 +00002553 // Go ahead and analyze implicit conversions in the operands. Note
2554 // that we skip the implicit conversions on both sides.
2555 AnalyzeImplicitConversions(S, lex);
2556 AnalyzeImplicitConversions(S, rex);
John McCallba26e582010-01-04 23:21:16 +00002557
John McCall323ed742010-05-06 08:58:33 +00002558 // If the signed range is non-negative, -Wsign-compare won't fire,
2559 // but we should still check for comparisons which are always true
2560 // or false.
2561 if (signedRange.NonNegative)
2562 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002563
2564 // For (in)equality comparisons, if the unsigned operand is a
2565 // constant which cannot collide with a overflowed signed operand,
2566 // then reinterpreting the signed operand as unsigned will not
2567 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002568 if (E->isEqualityOp()) {
2569 unsigned comparisonWidth = S.Context.getIntWidth(T);
2570 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002571
John McCall323ed742010-05-06 08:58:33 +00002572 // We should never be unable to prove that the unsigned operand is
2573 // non-negative.
2574 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2575
2576 if (unsignedRange.Width < comparisonWidth)
2577 return;
2578 }
2579
2580 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2581 << lex->getType() << rex->getType()
2582 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002583}
2584
John McCall51313c32010-01-04 23:31:57 +00002585/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCall323ed742010-05-06 08:58:33 +00002586void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
John McCall51313c32010-01-04 23:31:57 +00002587 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2588}
2589
John McCall323ed742010-05-06 08:58:33 +00002590void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
2591 bool *ICContext = 0) {
2592 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002593
John McCall323ed742010-05-06 08:58:33 +00002594 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2595 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2596 if (Source == Target) return;
2597 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002598
2599 // Never diagnose implicit casts to bool.
2600 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2601 return;
2602
2603 // Strip vector types.
2604 if (isa<VectorType>(Source)) {
2605 if (!isa<VectorType>(Target))
John McCall323ed742010-05-06 08:58:33 +00002606 return DiagnoseImpCast(S, E, T, diag::warn_impcast_vector_scalar);
John McCall51313c32010-01-04 23:31:57 +00002607
2608 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2609 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2610 }
2611
2612 // Strip complex types.
2613 if (isa<ComplexType>(Source)) {
2614 if (!isa<ComplexType>(Target))
John McCall323ed742010-05-06 08:58:33 +00002615 return DiagnoseImpCast(S, E, T, diag::warn_impcast_complex_scalar);
John McCall51313c32010-01-04 23:31:57 +00002616
2617 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2618 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2619 }
2620
2621 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2622 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2623
2624 // If the source is floating point...
2625 if (SourceBT && SourceBT->isFloatingPoint()) {
2626 // ...and the target is floating point...
2627 if (TargetBT && TargetBT->isFloatingPoint()) {
2628 // ...then warn if we're dropping FP rank.
2629
2630 // Builtin FP kinds are ordered by increasing FP rank.
2631 if (SourceBT->getKind() > TargetBT->getKind()) {
2632 // Don't warn about float constants that are precisely
2633 // representable in the target type.
2634 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002635 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002636 // Value might be a float, a float vector, or a float complex.
2637 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002638 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2639 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002640 return;
2641 }
2642
John McCall323ed742010-05-06 08:58:33 +00002643 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002644 }
2645 return;
2646 }
2647
2648 // If the target is integral, always warn.
2649 if ((TargetBT && TargetBT->isInteger()))
2650 // TODO: don't warn for integer values?
John McCall323ed742010-05-06 08:58:33 +00002651 DiagnoseImpCast(S, E, T, diag::warn_impcast_float_integer);
John McCall51313c32010-01-04 23:31:57 +00002652
2653 return;
2654 }
2655
John McCallf2370c92010-01-06 05:24:50 +00002656 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002657 return;
2658
John McCall323ed742010-05-06 08:58:33 +00002659 IntRange SourceRange = GetExprRange(S.Context, E);
2660 IntRange TargetRange = IntRange::forCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002661
2662 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002663 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2664 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002665 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall323ed742010-05-06 08:58:33 +00002666 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_64_32);
2667 return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_precision);
2668 }
2669
2670 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2671 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2672 SourceRange.Width == TargetRange.Width)) {
2673 unsigned DiagID = diag::warn_impcast_integer_sign;
2674
2675 // Traditionally, gcc has warned about this under -Wsign-compare.
2676 // We also want to warn about it in -Wconversion.
2677 // So if -Wconversion is off, use a completely identical diagnostic
2678 // in the sign-compare group.
2679 // The conditional-checking code will
2680 if (ICContext) {
2681 DiagID = diag::warn_impcast_integer_sign_conditional;
2682 *ICContext = true;
2683 }
2684
2685 return DiagnoseImpCast(S, E, T, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002686 }
2687
2688 return;
2689}
2690
John McCall323ed742010-05-06 08:58:33 +00002691void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2692
2693void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
2694 bool &ICContext) {
2695 E = E->IgnoreParenImpCasts();
2696
2697 if (isa<ConditionalOperator>(E))
2698 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2699
2700 AnalyzeImplicitConversions(S, E);
2701 if (E->getType() != T)
2702 return CheckImplicitConversion(S, E, T, &ICContext);
2703 return;
2704}
2705
2706void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
2707 AnalyzeImplicitConversions(S, E->getCond());
2708
2709 bool Suspicious = false;
2710 CheckConditionalOperand(S, E->getTrueExpr(), T, Suspicious);
2711 CheckConditionalOperand(S, E->getFalseExpr(), T, Suspicious);
2712
2713 // If -Wconversion would have warned about either of the candidates
2714 // for a signedness conversion to the context type...
2715 if (!Suspicious) return;
2716
2717 // ...but it's currently ignored...
2718 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional))
2719 return;
2720
2721 // ...and -Wsign-compare isn't...
2722 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional))
2723 return;
2724
2725 // ...then check whether it would have warned about either of the
2726 // candidates for a signedness conversion to the condition type.
2727 if (E->getType() != T) {
2728 Suspicious = false;
2729 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
2730 E->getType(), &Suspicious);
2731 if (!Suspicious)
2732 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
2733 E->getType(), &Suspicious);
2734 if (!Suspicious)
2735 return;
2736 }
2737
2738 // If so, emit a diagnostic under -Wsign-compare.
2739 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2740 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2741 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2742 << lex->getType() << rex->getType()
2743 << lex->getSourceRange() << rex->getSourceRange();
2744}
2745
2746/// AnalyzeImplicitConversions - Find and report any interesting
2747/// implicit conversions in the given expression. There are a couple
2748/// of competing diagnostics here, -Wconversion and -Wsign-compare.
2749void AnalyzeImplicitConversions(Sema &S, Expr *OrigE) {
2750 QualType T = OrigE->getType();
2751 Expr *E = OrigE->IgnoreParenImpCasts();
2752
2753 // For conditional operators, we analyze the arguments as if they
2754 // were being fed directly into the output.
2755 if (isa<ConditionalOperator>(E)) {
2756 ConditionalOperator *CO = cast<ConditionalOperator>(E);
2757 CheckConditionalOperator(S, CO, T);
2758 return;
2759 }
2760
2761 // Go ahead and check any implicit conversions we might have skipped.
2762 // The non-canonical typecheck is just an optimization;
2763 // CheckImplicitConversion will filter out dead implicit conversions.
2764 if (E->getType() != T)
2765 CheckImplicitConversion(S, E, T);
2766
2767 // Now continue drilling into this expression.
2768
2769 // Skip past explicit casts.
2770 if (isa<ExplicitCastExpr>(E)) {
2771 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
2772 return AnalyzeImplicitConversions(S, E);
2773 }
2774
2775 // Do a somewhat different check with comparison operators.
2776 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isComparisonOp())
2777 return AnalyzeComparison(S, cast<BinaryOperator>(E));
2778
2779 // These break the otherwise-useful invariant below. Fortunately,
2780 // we don't really need to recurse into them, because any internal
2781 // expressions should have been analyzed already when they were
2782 // built into statements.
2783 if (isa<StmtExpr>(E)) return;
2784
2785 // Don't descend into unevaluated contexts.
2786 if (isa<SizeOfAlignOfExpr>(E)) return;
2787
2788 // Now just recurse over the expression's children.
2789 for (Stmt::child_iterator I = E->child_begin(), IE = E->child_end();
2790 I != IE; ++I)
2791 AnalyzeImplicitConversions(S, cast<Expr>(*I));
2792}
2793
2794} // end anonymous namespace
2795
2796/// Diagnoses "dangerous" implicit conversions within the given
2797/// expression (which is a full expression). Implements -Wconversion
2798/// and -Wsign-compare.
2799void Sema::CheckImplicitConversions(Expr *E) {
2800 // Don't diagnose in unevaluated contexts.
2801 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2802 return;
2803
2804 // Don't diagnose for value- or type-dependent expressions.
2805 if (E->isTypeDependent() || E->isValueDependent())
2806 return;
2807
2808 AnalyzeImplicitConversions(*this, E);
2809}
2810
Mike Stumpf8c49212010-01-21 03:59:47 +00002811/// CheckParmsForFunctionDef - Check that the parameters of the given
2812/// function are appropriate for the definition of a function. This
2813/// takes care of any checks that cannot be performed on the
2814/// declaration itself, e.g., that the types of each of the function
2815/// parameters are complete.
2816bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2817 bool HasInvalidParm = false;
2818 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2819 ParmVarDecl *Param = FD->getParamDecl(p);
2820
2821 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2822 // function declarator that is part of a function definition of
2823 // that function shall not have incomplete type.
2824 //
2825 // This is also C++ [dcl.fct]p6.
2826 if (!Param->isInvalidDecl() &&
2827 RequireCompleteType(Param->getLocation(), Param->getType(),
2828 diag::err_typecheck_decl_incomplete_type)) {
2829 Param->setInvalidDecl();
2830 HasInvalidParm = true;
2831 }
2832
2833 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2834 // declaration of each parameter shall include an identifier.
2835 if (Param->getIdentifier() == 0 &&
2836 !Param->isImplicit() &&
2837 !getLangOptions().CPlusPlus)
2838 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002839
2840 // C99 6.7.5.3p12:
2841 // If the function declarator is not part of a definition of that
2842 // function, parameters may have incomplete type and may use the [*]
2843 // notation in their sequences of declarator specifiers to specify
2844 // variable length array types.
2845 QualType PType = Param->getOriginalType();
2846 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2847 if (AT->getSizeModifier() == ArrayType::Star) {
2848 // FIXME: This diagnosic should point the the '[*]' if source-location
2849 // information is added for it.
2850 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2851 }
2852 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002853 }
2854
2855 return HasInvalidParm;
2856}
John McCallb7f4ffe2010-08-12 21:44:57 +00002857
2858/// CheckCastAlign - Implements -Wcast-align, which warns when a
2859/// pointer cast increases the alignment requirements.
2860void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
2861 // This is actually a lot of work to potentially be doing on every
2862 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
2863 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align)
2864 == Diagnostic::Ignored)
2865 return;
2866
2867 // Ignore dependent types.
2868 if (T->isDependentType() || Op->getType()->isDependentType())
2869 return;
2870
2871 // Require that the destination be a pointer type.
2872 const PointerType *DestPtr = T->getAs<PointerType>();
2873 if (!DestPtr) return;
2874
2875 // If the destination has alignment 1, we're done.
2876 QualType DestPointee = DestPtr->getPointeeType();
2877 if (DestPointee->isIncompleteType()) return;
2878 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
2879 if (DestAlign.isOne()) return;
2880
2881 // Require that the source be a pointer type.
2882 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
2883 if (!SrcPtr) return;
2884 QualType SrcPointee = SrcPtr->getPointeeType();
2885
2886 // Whitelist casts from cv void*. We already implicitly
2887 // whitelisted casts to cv void*, since they have alignment 1.
2888 // Also whitelist casts involving incomplete types, which implicitly
2889 // includes 'void'.
2890 if (SrcPointee->isIncompleteType()) return;
2891
2892 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
2893 if (SrcAlign >= DestAlign) return;
2894
2895 Diag(TRange.getBegin(), diag::warn_cast_align)
2896 << Op->getType() << T
2897 << static_cast<unsigned>(SrcAlign.getQuantity())
2898 << static_cast<unsigned>(DestAlign.getQuantity())
2899 << TRange << Op->getSourceRange();
2900}
2901