blob: 74c69a3ce34f6db167bcfb8440dcef311cd6cd9b [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
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000035#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000036#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000037#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000038#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000041
Chris Lattner60800082009-02-18 17:49:48 +000042SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000044 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000046}
Chris Lattner08f92e32010-11-17 07:37:15 +000047
Chris Lattner60800082009-02-18 17:49:48 +000048
Ryan Flynn4403a5e2009-08-06 03:00:50 +000049/// CheckablePrintfAttr - does a function call have a "printf" attribute
50/// and arguments that merit checking?
51bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52 if (Format->getType() == "printf") return true;
53 if (Format->getType() == "printf0") {
54 // printf0 allows null "format" string; if so don't check format/args
55 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000056 // Does the index refer to the implicit object argument?
57 if (isa<CXXMemberCallExpr>(TheCall)) {
58 if (format_idx == 0)
59 return false;
60 --format_idx;
61 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000062 if (format_idx < TheCall->getNumArgs()) {
63 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000064 if (!Format->isNullPointerConstant(Context,
65 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000066 return true;
67 }
68 }
69 return false;
70}
Chris Lattner60800082009-02-18 17:49:48 +000071
John McCall8e10f3b2011-02-26 05:39:39 +000072/// Checks that a call expression's argument count is the desired number.
73/// This is useful when doing custom type-checking. Returns true on error.
74static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75 unsigned argCount = call->getNumArgs();
76 if (argCount == desiredArgCount) return false;
77
78 if (argCount < desiredArgCount)
79 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80 << 0 /*function call*/ << desiredArgCount << argCount
81 << call->getSourceRange();
82
83 // Highlight all the excess arguments.
84 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85 call->getArg(argCount - 1)->getLocEnd());
86
87 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88 << 0 /*function call*/ << desiredArgCount << argCount
89 << call->getArg(1)->getSourceRange();
90}
91
Julien Lerouge77f68bb2011-09-09 22:41:49 +000092/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93/// annotation is a non wide string literal.
94static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95 Arg = Arg->IgnoreParenCasts();
96 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97 if (!Literal || !Literal->isAscii()) {
98 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99 << Arg->getSourceRange();
100 return true;
101 }
102 return false;
103}
104
John McCall60d7b3a2010-08-24 06:29:42 +0000105ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000106Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000107 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000108
Chris Lattner946928f2010-10-01 23:23:24 +0000109 // Find out if any arguments are required to be integer constant expressions.
110 unsigned ICEArguments = 0;
111 ASTContext::GetBuiltinTypeError Error;
112 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113 if (Error != ASTContext::GE_None)
114 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
115
116 // If any arguments are required to be ICE's, check and diagnose.
117 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118 // Skip arguments not required to be ICE's.
119 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120
121 llvm::APSInt Result;
122 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123 return true;
124 ICEArguments &= ~(1 << ArgNo);
125 }
126
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000129 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000130 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000131 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000134 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000135 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinVAStart(TheCall))
137 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000138 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 case Builtin::BI__builtin_isgreater:
140 case Builtin::BI__builtin_isgreaterequal:
141 case Builtin::BI__builtin_isless:
142 case Builtin::BI__builtin_islessequal:
143 case Builtin::BI__builtin_islessgreater:
144 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinUnorderedCompare(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000148 case Builtin::BI__builtin_fpclassify:
149 if (SemaBuiltinFPClassification(TheCall, 6))
150 return ExprError();
151 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 case Builtin::BI__builtin_isfinite:
153 case Builtin::BI__builtin_isinf:
154 case Builtin::BI__builtin_isinf_sign:
155 case Builtin::BI__builtin_isnan:
156 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000157 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000158 return ExprError();
159 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000160 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161 return SemaBuiltinShuffleVector(TheCall);
162 // TheCall will be freed by the smart pointer here, but that's fine, since
163 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000164 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000165 if (SemaBuiltinPrefetch(TheCall))
166 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000167 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000168 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000169 if (SemaBuiltinObjectSize(TheCall))
170 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000171 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000172 case Builtin::BI__builtin_longjmp:
173 if (SemaBuiltinLongjmp(TheCall))
174 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000175 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000176
177 case Builtin::BI__builtin_classify_type:
178 if (checkArgCount(*this, TheCall, 1)) return true;
179 TheCall->setType(Context.IntTy);
180 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000181 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000182 if (checkArgCount(*this, TheCall, 1)) return true;
183 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000184 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_add:
186 case Builtin::BI__sync_fetch_and_sub:
187 case Builtin::BI__sync_fetch_and_or:
188 case Builtin::BI__sync_fetch_and_and:
189 case Builtin::BI__sync_fetch_and_xor:
190 case Builtin::BI__sync_add_and_fetch:
191 case Builtin::BI__sync_sub_and_fetch:
192 case Builtin::BI__sync_and_and_fetch:
193 case Builtin::BI__sync_or_and_fetch:
194 case Builtin::BI__sync_xor_and_fetch:
195 case Builtin::BI__sync_val_compare_and_swap:
196 case Builtin::BI__sync_bool_compare_and_swap:
197 case Builtin::BI__sync_lock_test_and_set:
198 case Builtin::BI__sync_lock_release:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000199 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000200 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000201 case Builtin::BI__atomic_load:
202 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
203 case Builtin::BI__atomic_store:
204 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
205 case Builtin::BI__atomic_exchange:
206 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
207 case Builtin::BI__atomic_compare_exchange_strong:
208 return SemaAtomicOpsOverloaded(move(TheCallResult),
209 AtomicExpr::CmpXchgStrong);
210 case Builtin::BI__atomic_compare_exchange_weak:
211 return SemaAtomicOpsOverloaded(move(TheCallResult),
212 AtomicExpr::CmpXchgWeak);
213 case Builtin::BI__atomic_fetch_add:
214 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
215 case Builtin::BI__atomic_fetch_sub:
216 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
217 case Builtin::BI__atomic_fetch_and:
218 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
219 case Builtin::BI__atomic_fetch_or:
220 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
221 case Builtin::BI__atomic_fetch_xor:
222 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000223 case Builtin::BI__builtin_annotation:
224 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
225 return ExprError();
226 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000227 }
228
229 // Since the target specific builtins for each arch overlap, only check those
230 // of the arch we are compiling for.
231 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000232 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000233 case llvm::Triple::arm:
234 case llvm::Triple::thumb:
235 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
236 return ExprError();
237 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000238 default:
239 break;
240 }
241 }
242
243 return move(TheCallResult);
244}
245
Nate Begeman61eecf52010-06-14 05:21:25 +0000246// Get the valid immediate range for the specified NEON type code.
247static unsigned RFT(unsigned t, bool shift = false) {
248 bool quad = t & 0x10;
249
250 switch (t & 0x7) {
251 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000252 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000253 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000254 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000255 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000256 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000257 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000258 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000259 case 4: // f32
260 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000261 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000262 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000263 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000264 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000265 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000266 case 7: // float16
267 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000268 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000269 }
270 return 0;
271}
272
Nate Begeman26a31422010-06-08 02:47:44 +0000273bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000274 llvm::APSInt Result;
275
Nate Begeman0d15c532010-06-13 04:47:52 +0000276 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000277 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000278 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000279#define GET_NEON_OVERLOAD_CHECK
280#include "clang/Basic/arm_neon.inc"
281#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000282 }
283
Nate Begeman0d15c532010-06-13 04:47:52 +0000284 // For NEON intrinsics which are overloaded on vector element type, validate
285 // the immediate which specifies which variant to emit.
286 if (mask) {
287 unsigned ArgNo = TheCall->getNumArgs()-1;
288 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
289 return true;
290
Nate Begeman61eecf52010-06-14 05:21:25 +0000291 TV = Result.getLimitedValue(32);
292 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000293 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
294 << TheCall->getArg(ArgNo)->getSourceRange();
295 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000296
Nate Begeman0d15c532010-06-13 04:47:52 +0000297 // For NEON intrinsics which take an immediate value as part of the
298 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000299 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000300 switch (BuiltinID) {
301 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000302 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
303 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000304 case ARM::BI__builtin_arm_vcvtr_f:
305 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000306#define GET_NEON_IMMEDIATE_CHECK
307#include "clang/Basic/arm_neon.inc"
308#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000309 };
310
Nate Begeman61eecf52010-06-14 05:21:25 +0000311 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000312 if (SemaBuiltinConstantArg(TheCall, i, Result))
313 return true;
314
Nate Begeman61eecf52010-06-14 05:21:25 +0000315 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000316 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000317 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000318 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000319 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000320
Nate Begeman99c40bb2010-08-03 21:32:34 +0000321 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000322 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000323}
Daniel Dunbarde454282008-10-02 18:44:07 +0000324
Anders Carlssond406bf02009-08-16 01:56:34 +0000325/// CheckFunctionCall - Check a direct function call for various correctness
326/// and safety properties not strictly enforced by the C type system.
327bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
328 // Get the IdentifierInfo* for the called function.
329 IdentifierInfo *FnInfo = FDecl->getIdentifier();
330
331 // None of the checks below are needed for functions that don't have
332 // simple names (e.g., C++ conversion functions).
333 if (!FnInfo)
334 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Daniel Dunbarde454282008-10-02 18:44:07 +0000336 // FIXME: This mechanism should be abstracted to be less fragile and
337 // more efficient. For example, just map function ids to custom
338 // handlers.
339
Ted Kremenekc82faca2010-09-09 04:33:05 +0000340 // Printf and scanf checking.
341 for (specific_attr_iterator<FormatAttr>
342 i = FDecl->specific_attr_begin<FormatAttr>(),
343 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
344
345 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000346 const bool b = Format->getType() == "scanf";
347 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000348 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000349 CheckPrintfScanfArguments(TheCall, HasVAListArg,
350 Format->getFormatIdx() - 1,
351 HasVAListArg ? 0 : Format->getFirstArg() - 1,
352 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000353 }
Chris Lattner59907c42007-08-10 20:18:51 +0000354 }
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Ted Kremenekc82faca2010-09-09 04:33:05 +0000356 for (specific_attr_iterator<NonNullAttr>
357 i = FDecl->specific_attr_begin<NonNullAttr>(),
358 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000359 CheckNonNullArguments(*i, TheCall->getArgs(),
360 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000361 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000362
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000363 // Builtin handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000364 int CMF = -1;
365 switch (FDecl->getBuiltinID()) {
366 case Builtin::BI__builtin_memset:
367 case Builtin::BI__builtin___memset_chk:
368 case Builtin::BImemset:
369 CMF = CMF_Memset;
370 break;
371
372 case Builtin::BI__builtin_memcpy:
373 case Builtin::BI__builtin___memcpy_chk:
374 case Builtin::BImemcpy:
375 CMF = CMF_Memcpy;
376 break;
377
378 case Builtin::BI__builtin_memmove:
379 case Builtin::BI__builtin___memmove_chk:
380 case Builtin::BImemmove:
381 CMF = CMF_Memmove;
382 break;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000383
384 case Builtin::BIstrlcpy:
385 case Builtin::BIstrlcat:
386 CheckStrlcpycatArguments(TheCall, FnInfo);
387 break;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000388
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000389 case Builtin::BI__builtin_memcmp:
390 CMF = CMF_Memcmp;
391 break;
392
Nico Webercda57822011-10-13 22:30:23 +0000393 case Builtin::BI__builtin_strncpy:
394 case Builtin::BI__builtin___strncpy_chk:
395 case Builtin::BIstrncpy:
396 CMF = CMF_Strncpy;
397 break;
398
399 case Builtin::BI__builtin_strncmp:
400 CMF = CMF_Strncmp;
401 break;
402
403 case Builtin::BI__builtin_strncasecmp:
404 CMF = CMF_Strncasecmp;
405 break;
406
407 case Builtin::BI__builtin_strncat:
408 case Builtin::BIstrncat:
409 CMF = CMF_Strncat;
410 break;
411
412 case Builtin::BI__builtin_strndup:
413 case Builtin::BIstrndup:
414 CMF = CMF_Strndup;
415 break;
416
Douglas Gregor707a23e2011-06-16 17:56:04 +0000417 default:
418 if (FDecl->getLinkage() == ExternalLinkage &&
419 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
420 if (FnInfo->isStr("memset"))
421 CMF = CMF_Memset;
422 else if (FnInfo->isStr("memcpy"))
423 CMF = CMF_Memcpy;
424 else if (FnInfo->isStr("memmove"))
425 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000426 else if (FnInfo->isStr("memcmp"))
427 CMF = CMF_Memcmp;
Nico Webercda57822011-10-13 22:30:23 +0000428 else if (FnInfo->isStr("strncpy"))
429 CMF = CMF_Strncpy;
430 else if (FnInfo->isStr("strncmp"))
431 CMF = CMF_Strncmp;
432 else if (FnInfo->isStr("strncasecmp"))
433 CMF = CMF_Strncasecmp;
434 else if (FnInfo->isStr("strncat"))
435 CMF = CMF_Strncat;
436 else if (FnInfo->isStr("strndup"))
437 CMF = CMF_Strndup;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000438 }
439 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000440 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000441
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000442 // Memset/memcpy/memmove handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000443 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000444 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000445
Anders Carlssond406bf02009-08-16 01:56:34 +0000446 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000447}
448
Anders Carlssond406bf02009-08-16 01:56:34 +0000449bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000450 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000451 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000452 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000453 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000455 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
456 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000457 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000459 QualType Ty = V->getType();
460 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000461 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Ted Kremenek826a3452010-07-16 02:11:22 +0000463 const bool b = Format->getType() == "scanf";
464 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000465 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Anders Carlssond406bf02009-08-16 01:56:34 +0000467 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000468 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
469 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000470
471 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000472}
473
Eli Friedman276b0612011-10-11 02:20:01 +0000474ExprResult
475Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
476 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
477 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
478 Expr *Ptr, *Order, *Val1, *Val2, *OrderFail;
479
480 // All these operations take one of the following four forms:
481 // T __atomic_load(_Atomic(T)*, int) (loads)
482 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
483 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
484 // (cmpxchg)
485 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
486 // where T is an appropriate type, and the int paremeterss are for orderings.
487 unsigned NumVals = 1;
488 unsigned NumOrders = 1;
489 if (Op == AtomicExpr::Load) {
490 NumVals = 0;
491 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
492 NumVals = 2;
493 NumOrders = 2;
494 }
495
496 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
497 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
498 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
499 << TheCall->getCallee()->getSourceRange();
500 return ExprError();
501 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
502 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
503 diag::err_typecheck_call_too_many_args)
504 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
505 << TheCall->getCallee()->getSourceRange();
506 return ExprError();
507 }
508
509 // Inspect the first argument of the atomic operation. This should always be
510 // a pointer to an _Atomic type.
511 Ptr = TheCall->getArg(0);
512 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
513 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
514 if (!pointerType) {
515 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
516 << Ptr->getType() << Ptr->getSourceRange();
517 return ExprError();
518 }
519
520 QualType AtomTy = pointerType->getPointeeType();
521 if (!AtomTy->isAtomicType()) {
522 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
523 << Ptr->getType() << Ptr->getSourceRange();
524 return ExprError();
525 }
526 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
527
528 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
529 !ValType->isIntegerType() && !ValType->isPointerType()) {
530 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
531 << Ptr->getType() << Ptr->getSourceRange();
532 return ExprError();
533 }
534
535 if (!ValType->isIntegerType() &&
536 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
537 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
538 << Ptr->getType() << Ptr->getSourceRange();
539 return ExprError();
540 }
541
542 switch (ValType.getObjCLifetime()) {
543 case Qualifiers::OCL_None:
544 case Qualifiers::OCL_ExplicitNone:
545 // okay
546 break;
547
548 case Qualifiers::OCL_Weak:
549 case Qualifiers::OCL_Strong:
550 case Qualifiers::OCL_Autoreleasing:
551 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
552 << ValType << Ptr->getSourceRange();
553 return ExprError();
554 }
555
556 QualType ResultType = ValType;
557 if (Op == AtomicExpr::Store)
558 ResultType = Context.VoidTy;
559 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
560 ResultType = Context.BoolTy;
561
562 // The first argument --- the pointer --- has a fixed type; we
563 // deduce the types of the rest of the arguments accordingly. Walk
564 // the remaining arguments, converting them to the deduced value type.
565 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
566 ExprResult Arg = TheCall->getArg(i);
567 QualType Ty;
568 if (i < NumVals+1) {
569 // The second argument to a cmpxchg is a pointer to the data which will
570 // be exchanged. The second argument to a pointer add/subtract is the
571 // amount to add/subtract, which must be a ptrdiff_t. The third
572 // argument to a cmpxchg and the second argument in all other cases
573 // is the type of the value.
574 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
575 Op == AtomicExpr::CmpXchgStrong))
576 Ty = Context.getPointerType(ValType.getUnqualifiedType());
577 else if (!ValType->isIntegerType() &&
578 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
579 Ty = Context.getPointerDiffType();
580 else
581 Ty = ValType;
582 } else {
583 // The order(s) are always converted to int.
584 Ty = Context.IntTy;
585 }
586 InitializedEntity Entity =
587 InitializedEntity::InitializeParameter(Context, Ty, false);
588 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
589 if (Arg.isInvalid())
590 return true;
591 TheCall->setArg(i, Arg.get());
592 }
593
594 if (Op == AtomicExpr::Load) {
595 Order = TheCall->getArg(1);
596 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
597 Ptr, Order, ResultType, Op,
598 TheCall->getRParenLoc(), false,
599 false));
600 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
601 Val1 = TheCall->getArg(1);
602 Order = TheCall->getArg(2);
603 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
604 Ptr, Val1, Order, ResultType, Op,
605 TheCall->getRParenLoc(), false,
606 false));
607 } else {
608 Val1 = TheCall->getArg(1);
609 Val2 = TheCall->getArg(2);
610 Order = TheCall->getArg(3);
611 OrderFail = TheCall->getArg(4);
612 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
613 Ptr, Val1, Val2, Order, OrderFail,
614 ResultType, Op,
615 TheCall->getRParenLoc(), false,
616 false));
617 }
618}
619
620
John McCall5f8d6042011-08-27 01:09:30 +0000621/// checkBuiltinArgument - Given a call to a builtin function, perform
622/// normal type-checking on the given argument, updating the call in
623/// place. This is useful when a builtin function requires custom
624/// type-checking for some of its arguments but not necessarily all of
625/// them.
626///
627/// Returns true on error.
628static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
629 FunctionDecl *Fn = E->getDirectCallee();
630 assert(Fn && "builtin call without direct callee!");
631
632 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
633 InitializedEntity Entity =
634 InitializedEntity::InitializeParameter(S.Context, Param);
635
636 ExprResult Arg = E->getArg(0);
637 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
638 if (Arg.isInvalid())
639 return true;
640
641 E->setArg(ArgIndex, Arg.take());
642 return false;
643}
644
Chris Lattner5caa3702009-05-08 06:58:22 +0000645/// SemaBuiltinAtomicOverloaded - We have a call to a function like
646/// __sync_fetch_and_add, which is an overloaded function based on the pointer
647/// type of its first argument. The main ActOnCallExpr routines have already
648/// promoted the types of arguments because all of these calls are prototyped as
649/// void(...).
650///
651/// This function goes through and does final semantic checking for these
652/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000653ExprResult
654Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000655 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000656 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
657 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
658
659 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000660 if (TheCall->getNumArgs() < 1) {
661 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
662 << 0 << 1 << TheCall->getNumArgs()
663 << TheCall->getCallee()->getSourceRange();
664 return ExprError();
665 }
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattner5caa3702009-05-08 06:58:22 +0000667 // Inspect the first argument of the atomic builtin. This should always be
668 // a pointer type, whose element is an integral scalar or pointer type.
669 // Because it is a pointer type, we don't have to worry about any implicit
670 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000671 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000672 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000673 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
674 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000675 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
676 << FirstArg->getType() << FirstArg->getSourceRange();
677 return ExprError();
678 }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
John McCallf85e1932011-06-15 23:02:42 +0000680 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000681 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000682 !ValType->isBlockPointerType()) {
683 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
684 << FirstArg->getType() << FirstArg->getSourceRange();
685 return ExprError();
686 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000687
John McCallf85e1932011-06-15 23:02:42 +0000688 switch (ValType.getObjCLifetime()) {
689 case Qualifiers::OCL_None:
690 case Qualifiers::OCL_ExplicitNone:
691 // okay
692 break;
693
694 case Qualifiers::OCL_Weak:
695 case Qualifiers::OCL_Strong:
696 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000697 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000698 << ValType << FirstArg->getSourceRange();
699 return ExprError();
700 }
701
John McCallb45ae252011-10-05 07:41:44 +0000702 // Strip any qualifiers off ValType.
703 ValType = ValType.getUnqualifiedType();
704
Chandler Carruth8d13d222010-07-18 20:54:12 +0000705 // The majority of builtins return a value, but a few have special return
706 // types, so allow them to override appropriately below.
707 QualType ResultType = ValType;
708
Chris Lattner5caa3702009-05-08 06:58:22 +0000709 // We need to figure out which concrete builtin this maps onto. For example,
710 // __sync_fetch_and_add with a 2 byte object turns into
711 // __sync_fetch_and_add_2.
712#define BUILTIN_ROW(x) \
713 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
714 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Chris Lattner5caa3702009-05-08 06:58:22 +0000716 static const unsigned BuiltinIndices[][5] = {
717 BUILTIN_ROW(__sync_fetch_and_add),
718 BUILTIN_ROW(__sync_fetch_and_sub),
719 BUILTIN_ROW(__sync_fetch_and_or),
720 BUILTIN_ROW(__sync_fetch_and_and),
721 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Chris Lattner5caa3702009-05-08 06:58:22 +0000723 BUILTIN_ROW(__sync_add_and_fetch),
724 BUILTIN_ROW(__sync_sub_and_fetch),
725 BUILTIN_ROW(__sync_and_and_fetch),
726 BUILTIN_ROW(__sync_or_and_fetch),
727 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Chris Lattner5caa3702009-05-08 06:58:22 +0000729 BUILTIN_ROW(__sync_val_compare_and_swap),
730 BUILTIN_ROW(__sync_bool_compare_and_swap),
731 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000732 BUILTIN_ROW(__sync_lock_release),
733 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000734 };
Mike Stump1eb44332009-09-09 15:08:12 +0000735#undef BUILTIN_ROW
736
Chris Lattner5caa3702009-05-08 06:58:22 +0000737 // Determine the index of the size.
738 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000739 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000740 case 1: SizeIndex = 0; break;
741 case 2: SizeIndex = 1; break;
742 case 4: SizeIndex = 2; break;
743 case 8: SizeIndex = 3; break;
744 case 16: SizeIndex = 4; break;
745 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000746 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
747 << FirstArg->getType() << FirstArg->getSourceRange();
748 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000749 }
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Chris Lattner5caa3702009-05-08 06:58:22 +0000751 // Each of these builtins has one pointer argument, followed by some number of
752 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
753 // that we ignore. Find out which row of BuiltinIndices to read from as well
754 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000755 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000756 unsigned BuiltinIndex, NumFixed = 1;
757 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000758 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Chris Lattner5caa3702009-05-08 06:58:22 +0000759 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
760 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
761 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
762 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
763 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000765 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
766 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
767 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
768 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
769 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000770
Chris Lattner5caa3702009-05-08 06:58:22 +0000771 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000772 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000773 NumFixed = 2;
774 break;
775 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000776 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000777 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000778 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000779 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000780 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000781 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000782 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000783 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000784 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000785 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000786 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000787 }
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Chris Lattner5caa3702009-05-08 06:58:22 +0000789 // Now that we know how many fixed arguments we expect, first check that we
790 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000791 if (TheCall->getNumArgs() < 1+NumFixed) {
792 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
793 << 0 << 1+NumFixed << TheCall->getNumArgs()
794 << TheCall->getCallee()->getSourceRange();
795 return ExprError();
796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000798 // Get the decl for the concrete builtin from this, we can tell what the
799 // concrete integer type we should convert to is.
800 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
801 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
802 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000803 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000804 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
805 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000806
John McCallf871d0c2010-08-07 06:22:56 +0000807 // The first argument --- the pointer --- has a fixed type; we
808 // deduce the types of the rest of the arguments accordingly. Walk
809 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000810 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000811 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Chris Lattner5caa3702009-05-08 06:58:22 +0000813 // If the argument is an implicit cast, then there was a promotion due to
814 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000815 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000816 Arg = ICE->getSubExpr();
817 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000818 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000819 }
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Chris Lattner5caa3702009-05-08 06:58:22 +0000821 // GCC does an implicit conversion to the pointer or integer ValType. This
822 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000823 // Initialize the argument.
824 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
825 ValType, /*consume*/ false);
826 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000827 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000828 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000829
Chris Lattner5caa3702009-05-08 06:58:22 +0000830 // Okay, we have something that *can* be converted to the right type. Check
831 // to see if there is a potentially weird extension going on here. This can
832 // happen when you do an atomic operation on something like an char* and
833 // pass in 42. The 42 gets converted to char. This is even more strange
834 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000835 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000836 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000839 ASTContext& Context = this->getASTContext();
840
841 // Create a new DeclRefExpr to refer to the new decl.
842 DeclRefExpr* NewDRE = DeclRefExpr::Create(
843 Context,
844 DRE->getQualifierLoc(),
845 NewBuiltinDecl,
846 DRE->getLocation(),
847 NewBuiltinDecl->getType(),
848 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Chris Lattner5caa3702009-05-08 06:58:22 +0000850 // Set the callee in the CallExpr.
851 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000852 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +0000853 if (PromotedCall.isInvalid())
854 return ExprError();
855 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000857 // Change the result type of the call to match the original value type. This
858 // is arbitrary, but the codegen for these builtins ins design to handle it
859 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000860 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000861
862 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000863}
864
Chris Lattner69039812009-02-18 06:01:06 +0000865/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000866/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000867/// Note: It might also make sense to do the UTF-16 conversion here (would
868/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000869bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000870 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000871 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
872
Douglas Gregor5cee1192011-07-27 05:40:30 +0000873 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000874 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
875 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000876 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000877 }
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000879 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000880 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000881 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000882 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000883 const UTF8 *FromPtr = (UTF8 *)String.data();
884 UTF16 *ToPtr = &ToBuf[0];
885
886 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
887 &ToPtr, ToPtr + NumBytes,
888 strictConversion);
889 // Check for conversion failure.
890 if (Result != conversionOK)
891 Diag(Arg->getLocStart(),
892 diag::warn_cfstring_truncated) << Arg->getSourceRange();
893 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000894 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000895}
896
Chris Lattnerc27c6652007-12-20 00:05:45 +0000897/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
898/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000899bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
900 Expr *Fn = TheCall->getCallee();
901 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000902 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000903 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000904 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
905 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000906 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000907 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000908 return true;
909 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000910
911 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000912 return Diag(TheCall->getLocEnd(),
913 diag::err_typecheck_call_too_few_args_at_least)
914 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000915 }
916
John McCall5f8d6042011-08-27 01:09:30 +0000917 // Type-check the first argument normally.
918 if (checkBuiltinArgument(*this, TheCall, 0))
919 return true;
920
Chris Lattnerc27c6652007-12-20 00:05:45 +0000921 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000922 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000923 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000924 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000925 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000926 else if (FunctionDecl *FD = getCurFunctionDecl())
927 isVariadic = FD->isVariadic();
928 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000929 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Chris Lattnerc27c6652007-12-20 00:05:45 +0000931 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000932 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
933 return true;
934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Chris Lattner30ce3442007-12-19 23:59:04 +0000936 // Verify that the second argument to the builtin is the last argument of the
937 // current function or method.
938 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000939 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000940
Anders Carlsson88cf2262008-02-11 04:20:54 +0000941 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
942 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000943 // FIXME: This isn't correct for methods (results in bogus warning).
944 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000945 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000946 if (CurBlock)
947 LastArg = *(CurBlock->TheDecl->param_end()-1);
948 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000949 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000950 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000951 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000952 SecondArgIsLastNamedArgument = PV == LastArg;
953 }
954 }
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Chris Lattner30ce3442007-12-19 23:59:04 +0000956 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000957 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000958 diag::warn_second_parameter_of_va_start_not_last_named_argument);
959 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000960}
Chris Lattner30ce3442007-12-19 23:59:04 +0000961
Chris Lattner1b9a0792007-12-20 00:26:33 +0000962/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
963/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000964bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
965 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000966 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000967 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000968 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000969 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000970 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000971 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000972 << SourceRange(TheCall->getArg(2)->getLocStart(),
973 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000974
John Wiegley429bb272011-04-08 18:41:53 +0000975 ExprResult OrigArg0 = TheCall->getArg(0);
976 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000977
Chris Lattner1b9a0792007-12-20 00:26:33 +0000978 // Do standard promotions between the two arguments, returning their common
979 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000980 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000981 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
982 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000983
984 // Make sure any conversions are pushed back into the call; this is
985 // type safe since unordered compare builtins are declared as "_Bool
986 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000987 TheCall->setArg(0, OrigArg0.get());
988 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000989
John Wiegley429bb272011-04-08 18:41:53 +0000990 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000991 return false;
992
Chris Lattner1b9a0792007-12-20 00:26:33 +0000993 // If the common type isn't a real floating type, then the arguments were
994 // invalid for this operation.
995 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000996 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000997 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000998 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
999 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattner1b9a0792007-12-20 00:26:33 +00001001 return false;
1002}
1003
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001004/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1005/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001006/// to check everything. We expect the last argument to be a floating point
1007/// value.
1008bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1009 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001010 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001011 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001012 if (TheCall->getNumArgs() > NumArgs)
1013 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001014 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001015 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001016 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001017 (*(TheCall->arg_end()-1))->getLocEnd());
1018
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001019 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Eli Friedman9ac6f622009-08-31 20:06:00 +00001021 if (OrigArg->isTypeDependent())
1022 return false;
1023
Chris Lattner81368fb2010-05-06 05:50:07 +00001024 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001025 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001026 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001027 diag::err_typecheck_call_invalid_unary_fp)
1028 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Chris Lattner81368fb2010-05-06 05:50:07 +00001030 // If this is an implicit conversion from float -> double, remove it.
1031 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1032 Expr *CastArg = Cast->getSubExpr();
1033 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1034 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1035 "promotion from float to double is the only expected cast here");
1036 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001037 TheCall->setArg(NumArgs-1, CastArg);
1038 OrigArg = CastArg;
1039 }
1040 }
1041
Eli Friedman9ac6f622009-08-31 20:06:00 +00001042 return false;
1043}
1044
Eli Friedmand38617c2008-05-14 19:38:39 +00001045/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1046// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001047ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001048 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001049 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001050 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001051 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001052 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001053
Nate Begeman37b6a572010-06-08 00:16:34 +00001054 // Determine which of the following types of shufflevector we're checking:
1055 // 1) unary, vector mask: (lhs, mask)
1056 // 2) binary, vector mask: (lhs, rhs, mask)
1057 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1058 QualType resType = TheCall->getArg(0)->getType();
1059 unsigned numElements = 0;
1060
Douglas Gregorcde01732009-05-19 22:10:17 +00001061 if (!TheCall->getArg(0)->isTypeDependent() &&
1062 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001063 QualType LHSType = TheCall->getArg(0)->getType();
1064 QualType RHSType = TheCall->getArg(1)->getType();
1065
1066 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001067 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001068 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001069 TheCall->getArg(1)->getLocEnd());
1070 return ExprError();
1071 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001072
1073 numElements = LHSType->getAs<VectorType>()->getNumElements();
1074 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Nate Begeman37b6a572010-06-08 00:16:34 +00001076 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1077 // with mask. If so, verify that RHS is an integer vector type with the
1078 // same number of elts as lhs.
1079 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001080 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001081 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1082 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1083 << SourceRange(TheCall->getArg(1)->getLocStart(),
1084 TheCall->getArg(1)->getLocEnd());
1085 numResElements = numElements;
1086 }
1087 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001088 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001089 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001090 TheCall->getArg(1)->getLocEnd());
1091 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001092 } else if (numElements != numResElements) {
1093 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001094 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001095 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001096 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001097 }
1098
1099 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001100 if (TheCall->getArg(i)->isTypeDependent() ||
1101 TheCall->getArg(i)->isValueDependent())
1102 continue;
1103
Nate Begeman37b6a572010-06-08 00:16:34 +00001104 llvm::APSInt Result(32);
1105 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1106 return ExprError(Diag(TheCall->getLocStart(),
1107 diag::err_shufflevector_nonconstant_argument)
1108 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001109
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001110 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001111 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001112 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001113 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001114 }
1115
Chris Lattner5f9e2722011-07-23 10:55:15 +00001116 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001117
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001118 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001119 exprs.push_back(TheCall->getArg(i));
1120 TheCall->setArg(i, 0);
1121 }
1122
Nate Begemana88dc302009-08-12 02:10:25 +00001123 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001124 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001125 TheCall->getCallee()->getLocStart(),
1126 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001127}
Chris Lattner30ce3442007-12-19 23:59:04 +00001128
Daniel Dunbar4493f792008-07-21 22:59:13 +00001129/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1130// This is declared to take (const void*, ...) and can take two
1131// optional constant int args.
1132bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001133 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001134
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001135 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001136 return Diag(TheCall->getLocEnd(),
1137 diag::err_typecheck_call_too_many_args_at_most)
1138 << 0 /*function call*/ << 3 << NumArgs
1139 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001140
1141 // Argument 0 is checked for us and the remaining arguments must be
1142 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001143 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001144 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001145
Eli Friedman9aef7262009-12-04 00:30:06 +00001146 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001147 if (SemaBuiltinConstantArg(TheCall, i, Result))
1148 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Daniel Dunbar4493f792008-07-21 22:59:13 +00001150 // FIXME: gcc issues a warning and rewrites these to 0. These
1151 // seems especially odd for the third argument since the default
1152 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001153 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001154 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001155 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001156 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001157 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001158 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001159 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001160 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001161 }
1162 }
1163
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001164 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001165}
1166
Eric Christopher691ebc32010-04-17 02:26:23 +00001167/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1168/// TheCall is a constant expression.
1169bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1170 llvm::APSInt &Result) {
1171 Expr *Arg = TheCall->getArg(ArgNum);
1172 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1173 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1174
1175 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1176
1177 if (!Arg->isIntegerConstantExpr(Result, Context))
1178 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001179 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001180
Chris Lattner21fb98e2009-09-23 06:06:36 +00001181 return false;
1182}
1183
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001184/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1185/// int type). This simply type checks that type is one of the defined
1186/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001187// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001188bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001189 llvm::APSInt Result;
1190
1191 // Check constant-ness first.
1192 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1193 return true;
1194
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001195 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001196 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001197 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1198 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001199 }
1200
1201 return false;
1202}
1203
Eli Friedman586d6a82009-05-03 06:04:26 +00001204/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001205/// This checks that val is a constant 1.
1206bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1207 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001208 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001209
Eric Christopher691ebc32010-04-17 02:26:23 +00001210 // TODO: This is less than ideal. Overload this to take a value.
1211 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1212 return true;
1213
1214 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001215 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1216 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1217
1218 return false;
1219}
1220
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001221// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +00001222bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1223 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001224 unsigned format_idx, unsigned firstDataArg,
1225 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001226 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001227 if (E->isTypeDependent() || E->isValueDependent())
1228 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001229
Peter Collingbournef111d932011-04-15 00:35:48 +00001230 E = E->IgnoreParens();
1231
Ted Kremenekd30ef872009-01-12 23:09:09 +00001232 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001233 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001234 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001235 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001236 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1237 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +00001238 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001239 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001240 }
1241
Ted Kremenek95355bb2010-09-09 03:51:42 +00001242 case Stmt::IntegerLiteralClass:
1243 // Technically -Wformat-nonliteral does not warn about this case.
1244 // The behavior of printf and friends in this case is implementation
1245 // dependent. Ideally if the format string cannot be null then
1246 // it should have a 'nonnull' attribute in the function prototype.
1247 return true;
1248
Ted Kremenekd30ef872009-01-12 23:09:09 +00001249 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001250 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1251 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001252 }
1253
John McCall56ca35d2011-02-17 10:25:35 +00001254 case Stmt::OpaqueValueExprClass:
1255 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1256 E = src;
1257 goto tryAgain;
1258 }
1259 return false;
1260
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001261 case Stmt::PredefinedExprClass:
1262 // While __func__, etc., are technically not string literals, they
1263 // cannot contain format specifiers and thus are not a security
1264 // liability.
1265 return true;
1266
Ted Kremenek082d9362009-03-20 21:35:28 +00001267 case Stmt::DeclRefExprClass: {
1268 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Ted Kremenek082d9362009-03-20 21:35:28 +00001270 // As an exception, do not flag errors for variables binding to
1271 // const string literals.
1272 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1273 bool isConstant = false;
1274 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001275
Ted Kremenek082d9362009-03-20 21:35:28 +00001276 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1277 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001278 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001279 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001280 PT->getPointeeType().isConstant(Context);
1281 }
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Ted Kremenek082d9362009-03-20 21:35:28 +00001283 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001284 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001285 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001286 HasVAListArg, format_idx, firstDataArg,
1287 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +00001288 }
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Anders Carlssond966a552009-06-28 19:55:58 +00001290 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1291 // special check to see if the format string is a function parameter
1292 // of the function calling the printf function. If the function
1293 // has an attribute indicating it is a printf-like function, then we
1294 // should suppress warnings concerning non-literals being used in a call
1295 // to a vprintf function. For example:
1296 //
1297 // void
1298 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1299 // va_list ap;
1300 // va_start(ap, fmt);
1301 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1302 // ...
1303 //
1304 //
1305 // FIXME: We don't have full attribute support yet, so just check to see
1306 // if the argument is a DeclRefExpr that references a parameter. We'll
1307 // add proper support for checking the attribute later.
1308 if (HasVAListArg)
1309 if (isa<ParmVarDecl>(VD))
1310 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001311 }
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Ted Kremenek082d9362009-03-20 21:35:28 +00001313 return false;
1314 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001315
Anders Carlsson8f031b32009-06-27 04:05:33 +00001316 case Stmt::CallExprClass: {
1317 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001318 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001319 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1320 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1321 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001322 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001323 unsigned ArgIndex = FA->getFormatIdx();
1324 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001325
1326 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001327 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001328 }
1329 }
1330 }
1331 }
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Anders Carlsson8f031b32009-06-27 04:05:33 +00001333 return false;
1334 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001335 case Stmt::ObjCStringLiteralClass:
1336 case Stmt::StringLiteralClass: {
1337 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Ted Kremenek082d9362009-03-20 21:35:28 +00001339 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001340 StrE = ObjCFExpr->getString();
1341 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001342 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Ted Kremenekd30ef872009-01-12 23:09:09 +00001344 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001345 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1346 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001347 return true;
1348 }
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Ted Kremenekd30ef872009-01-12 23:09:09 +00001350 return false;
1351 }
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Ted Kremenek082d9362009-03-20 21:35:28 +00001353 default:
1354 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001355 }
1356}
1357
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001358void
Mike Stump1eb44332009-09-09 15:08:12 +00001359Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001360 const Expr * const *ExprArgs,
1361 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001362 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1363 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001364 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001365 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001366 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001367 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001368 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001369 }
1370}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001371
Ted Kremenek826a3452010-07-16 02:11:22 +00001372/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1373/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001374void
Ted Kremenek826a3452010-07-16 02:11:22 +00001375Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1376 unsigned format_idx, unsigned firstDataArg,
1377 bool isPrintf) {
1378
Ted Kremenek082d9362009-03-20 21:35:28 +00001379 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001380
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001381 // The way the format attribute works in GCC, the implicit this argument
1382 // of member functions is counted. However, it doesn't appear in our own
1383 // lists, so decrement format_idx in that case.
1384 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001385 const CXXMethodDecl *method_decl =
1386 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1387 if (method_decl && method_decl->isInstance()) {
1388 // Catch a format attribute mistakenly referring to the object argument.
1389 if (format_idx == 0)
1390 return;
1391 --format_idx;
1392 if(firstDataArg != 0)
1393 --firstDataArg;
1394 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001395 }
1396
Ted Kremenek826a3452010-07-16 02:11:22 +00001397 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001398 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001399 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001400 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001401 return;
1402 }
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Ted Kremenek082d9362009-03-20 21:35:28 +00001404 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Chris Lattner59907c42007-08-10 20:18:51 +00001406 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001407 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001408 // Dynamically generated format strings are difficult to
1409 // automatically vet at compile time. Requiring that format strings
1410 // are string literals: (1) permits the checking of format strings by
1411 // the compiler and thereby (2) can practically remove the source of
1412 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001413
Mike Stump1eb44332009-09-09 15:08:12 +00001414 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001415 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001416 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001417 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001418 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001419 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001420 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001421
Chris Lattner655f1412009-04-29 04:59:47 +00001422 // If there are no arguments specified, warn with -Wformat-security, otherwise
1423 // warn only with -Wformat-nonliteral.
1424 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001425 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001426 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001427 << OrigFormatExpr->getSourceRange();
1428 else
Mike Stump1eb44332009-09-09 15:08:12 +00001429 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001430 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001431 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001432}
Ted Kremenek71895b92007-08-14 17:39:48 +00001433
Ted Kremeneke0e53132010-01-28 23:39:18 +00001434namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001435class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1436protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001437 Sema &S;
1438 const StringLiteral *FExpr;
1439 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001440 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001441 const unsigned NumDataArgs;
1442 const bool IsObjCLiteral;
1443 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001444 const bool HasVAListArg;
1445 const CallExpr *TheCall;
1446 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001447 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001448 bool usesPositionalArgs;
1449 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001450public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001451 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001452 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001453 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001454 const char *beg, bool hasVAListArg,
1455 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001456 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001457 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001458 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001459 IsObjCLiteral(isObjCLiteral), Beg(beg),
1460 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001461 TheCall(theCall), FormatIdx(formatIdx),
1462 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001463 CoveredArgs.resize(numDataArgs);
1464 CoveredArgs.reset();
1465 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001466
Ted Kremenek07d161f2010-01-29 01:50:07 +00001467 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001468
Ted Kremenek826a3452010-07-16 02:11:22 +00001469 void HandleIncompleteSpecifier(const char *startSpecifier,
1470 unsigned specifierLen);
1471
Ted Kremenekefaff192010-02-27 01:41:03 +00001472 virtual void HandleInvalidPosition(const char *startSpecifier,
1473 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001474 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001475
1476 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1477
Ted Kremeneke0e53132010-01-28 23:39:18 +00001478 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001479
Ted Kremenek826a3452010-07-16 02:11:22 +00001480protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001481 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1482 const char *startSpec,
1483 unsigned specifierLen,
1484 const char *csStart, unsigned csLen);
1485
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001486 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001487 CharSourceRange getSpecifierRange(const char *startSpecifier,
1488 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001489 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001490
Ted Kremenek0d277352010-01-29 01:06:55 +00001491 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001492
1493 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1494 const analyze_format_string::ConversionSpecifier &CS,
1495 const char *startSpecifier, unsigned specifierLen,
1496 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001497};
1498}
1499
Ted Kremenek826a3452010-07-16 02:11:22 +00001500SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001501 return OrigFormatExpr->getSourceRange();
1502}
1503
Ted Kremenek826a3452010-07-16 02:11:22 +00001504CharSourceRange CheckFormatHandler::
1505getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001506 SourceLocation Start = getLocationOfByte(startSpecifier);
1507 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1508
1509 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001510 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001511
1512 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001513}
1514
Ted Kremenek826a3452010-07-16 02:11:22 +00001515SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001516 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001517}
1518
Ted Kremenek826a3452010-07-16 02:11:22 +00001519void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1520 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001521 SourceLocation Loc = getLocationOfByte(startSpecifier);
1522 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001523 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001524}
1525
Ted Kremenekefaff192010-02-27 01:41:03 +00001526void
Ted Kremenek826a3452010-07-16 02:11:22 +00001527CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1528 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001529 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001530 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1531 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001532}
1533
Ted Kremenek826a3452010-07-16 02:11:22 +00001534void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001535 unsigned posLen) {
1536 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001537 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1538 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001539}
1540
Ted Kremenek826a3452010-07-16 02:11:22 +00001541void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001542 if (!IsObjCLiteral) {
1543 // The presence of a null character is likely an error.
1544 S.Diag(getLocationOfByte(nullCharacter),
1545 diag::warn_printf_format_string_contains_null_char)
1546 << getFormatStringRange();
1547 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001548}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001549
Ted Kremenek826a3452010-07-16 02:11:22 +00001550const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1551 return TheCall->getArg(FirstDataArg + i);
1552}
1553
1554void CheckFormatHandler::DoneProcessing() {
1555 // Does the number of data arguments exceed the number of
1556 // format conversions in the format string?
1557 if (!HasVAListArg) {
1558 // Find any arguments that weren't covered.
1559 CoveredArgs.flip();
1560 signed notCoveredArg = CoveredArgs.find_first();
1561 if (notCoveredArg >= 0) {
1562 assert((unsigned)notCoveredArg < NumDataArgs);
1563 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1564 diag::warn_printf_data_arg_not_used)
1565 << getFormatStringRange();
1566 }
1567 }
1568}
1569
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001570bool
1571CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1572 SourceLocation Loc,
1573 const char *startSpec,
1574 unsigned specifierLen,
1575 const char *csStart,
1576 unsigned csLen) {
1577
1578 bool keepGoing = true;
1579 if (argIndex < NumDataArgs) {
1580 // Consider the argument coverered, even though the specifier doesn't
1581 // make sense.
1582 CoveredArgs.set(argIndex);
1583 }
1584 else {
1585 // If argIndex exceeds the number of data arguments we
1586 // don't issue a warning because that is just a cascade of warnings (and
1587 // they may have intended '%%' anyway). We don't want to continue processing
1588 // the format string after this point, however, as we will like just get
1589 // gibberish when trying to match arguments.
1590 keepGoing = false;
1591 }
1592
1593 S.Diag(Loc, diag::warn_format_invalid_conversion)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001594 << StringRef(csStart, csLen)
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001595 << getSpecifierRange(startSpec, specifierLen);
1596
1597 return keepGoing;
1598}
1599
Ted Kremenek666a1972010-07-26 19:45:42 +00001600bool
1601CheckFormatHandler::CheckNumArgs(
1602 const analyze_format_string::FormatSpecifier &FS,
1603 const analyze_format_string::ConversionSpecifier &CS,
1604 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1605
1606 if (argIndex >= NumDataArgs) {
1607 if (FS.usesPositionalArg()) {
1608 S.Diag(getLocationOfByte(CS.getStart()),
1609 diag::warn_printf_positional_arg_exceeds_data_args)
1610 << (argIndex+1) << NumDataArgs
1611 << getSpecifierRange(startSpecifier, specifierLen);
1612 }
1613 else {
1614 S.Diag(getLocationOfByte(CS.getStart()),
1615 diag::warn_printf_insufficient_data_args)
1616 << getSpecifierRange(startSpecifier, specifierLen);
1617 }
1618
1619 return false;
1620 }
1621 return true;
1622}
1623
Ted Kremenek826a3452010-07-16 02:11:22 +00001624//===--- CHECK: Printf format string checking ------------------------------===//
1625
1626namespace {
1627class CheckPrintfHandler : public CheckFormatHandler {
1628public:
1629 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1630 const Expr *origFormatExpr, unsigned firstDataArg,
1631 unsigned numDataArgs, bool isObjCLiteral,
1632 const char *beg, bool hasVAListArg,
1633 const CallExpr *theCall, unsigned formatIdx)
1634 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1635 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1636 theCall, formatIdx) {}
1637
1638
1639 bool HandleInvalidPrintfConversionSpecifier(
1640 const analyze_printf::PrintfSpecifier &FS,
1641 const char *startSpecifier,
1642 unsigned specifierLen);
1643
1644 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1645 const char *startSpecifier,
1646 unsigned specifierLen);
1647
1648 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1649 const char *startSpecifier, unsigned specifierLen);
1650 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1651 const analyze_printf::OptionalAmount &Amt,
1652 unsigned type,
1653 const char *startSpecifier, unsigned specifierLen);
1654 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1655 const analyze_printf::OptionalFlag &flag,
1656 const char *startSpecifier, unsigned specifierLen);
1657 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1658 const analyze_printf::OptionalFlag &ignoredFlag,
1659 const analyze_printf::OptionalFlag &flag,
1660 const char *startSpecifier, unsigned specifierLen);
1661};
1662}
1663
1664bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1665 const analyze_printf::PrintfSpecifier &FS,
1666 const char *startSpecifier,
1667 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001668 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001669 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001670
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001671 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1672 getLocationOfByte(CS.getStart()),
1673 startSpecifier, specifierLen,
1674 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001675}
1676
Ted Kremenek826a3452010-07-16 02:11:22 +00001677bool CheckPrintfHandler::HandleAmount(
1678 const analyze_format_string::OptionalAmount &Amt,
1679 unsigned k, const char *startSpecifier,
1680 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001681
1682 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001683 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001684 unsigned argIndex = Amt.getArgIndex();
1685 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001686 S.Diag(getLocationOfByte(Amt.getStart()),
1687 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001688 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001689 // Don't do any more checking. We will just emit
1690 // spurious errors.
1691 return false;
1692 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001693
Ted Kremenek0d277352010-01-29 01:06:55 +00001694 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001695 // Although not in conformance with C99, we also allow the argument to be
1696 // an 'unsigned int' as that is a reasonably safe case. GCC also
1697 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001698 CoveredArgs.set(argIndex);
1699 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001700 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001701
1702 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1703 assert(ATR.isValid());
1704
1705 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001706 S.Diag(getLocationOfByte(Amt.getStart()),
1707 diag::warn_printf_asterisk_wrong_type)
1708 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001709 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001710 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001711 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001712 // Don't do any more checking. We will just emit
1713 // spurious errors.
1714 return false;
1715 }
1716 }
1717 }
1718 return true;
1719}
Ted Kremenek0d277352010-01-29 01:06:55 +00001720
Tom Caree4ee9662010-06-17 19:00:27 +00001721void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001722 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001723 const analyze_printf::OptionalAmount &Amt,
1724 unsigned type,
1725 const char *startSpecifier,
1726 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001727 const analyze_printf::PrintfConversionSpecifier &CS =
1728 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001729 switch (Amt.getHowSpecified()) {
1730 case analyze_printf::OptionalAmount::Constant:
1731 S.Diag(getLocationOfByte(Amt.getStart()),
1732 diag::warn_printf_nonsensical_optional_amount)
1733 << type
1734 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001735 << getSpecifierRange(startSpecifier, specifierLen)
1736 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001737 Amt.getConstantLength()));
1738 break;
1739
1740 default:
1741 S.Diag(getLocationOfByte(Amt.getStart()),
1742 diag::warn_printf_nonsensical_optional_amount)
1743 << type
1744 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001745 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001746 break;
1747 }
1748}
1749
Ted Kremenek826a3452010-07-16 02:11:22 +00001750void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001751 const analyze_printf::OptionalFlag &flag,
1752 const char *startSpecifier,
1753 unsigned specifierLen) {
1754 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001755 const analyze_printf::PrintfConversionSpecifier &CS =
1756 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001757 S.Diag(getLocationOfByte(flag.getPosition()),
1758 diag::warn_printf_nonsensical_flag)
1759 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001760 << getSpecifierRange(startSpecifier, specifierLen)
1761 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001762}
1763
1764void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001765 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001766 const analyze_printf::OptionalFlag &ignoredFlag,
1767 const analyze_printf::OptionalFlag &flag,
1768 const char *startSpecifier,
1769 unsigned specifierLen) {
1770 // Warn about ignored flag with a fixit removal.
1771 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1772 diag::warn_printf_ignored_flag)
1773 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001774 << getSpecifierRange(startSpecifier, specifierLen)
1775 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001776 ignoredFlag.getPosition(), 1));
1777}
1778
Ted Kremeneke0e53132010-01-28 23:39:18 +00001779bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001780CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001781 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001782 const char *startSpecifier,
1783 unsigned specifierLen) {
1784
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001785 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001786 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001787 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001788
Ted Kremenekbaa40062010-07-19 22:01:06 +00001789 if (FS.consumesDataArgument()) {
1790 if (atFirstArg) {
1791 atFirstArg = false;
1792 usesPositionalArgs = FS.usesPositionalArg();
1793 }
1794 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1795 // Cannot mix-and-match positional and non-positional arguments.
1796 S.Diag(getLocationOfByte(CS.getStart()),
1797 diag::warn_format_mix_positional_nonpositional_args)
1798 << getSpecifierRange(startSpecifier, specifierLen);
1799 return false;
1800 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001801 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001802
Ted Kremenekefaff192010-02-27 01:41:03 +00001803 // First check if the field width, precision, and conversion specifier
1804 // have matching data arguments.
1805 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1806 startSpecifier, specifierLen)) {
1807 return false;
1808 }
1809
1810 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1811 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001812 return false;
1813 }
1814
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001815 if (!CS.consumesDataArgument()) {
1816 // FIXME: Technically specifying a precision or field width here
1817 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001818 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001819 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001820
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001821 // Consume the argument.
1822 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001823 if (argIndex < NumDataArgs) {
1824 // The check to see if the argIndex is valid will come later.
1825 // We set the bit here because we may exit early from this
1826 // function if we encounter some other error.
1827 CoveredArgs.set(argIndex);
1828 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001829
1830 // Check for using an Objective-C specific conversion specifier
1831 // in a non-ObjC literal.
1832 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001833 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1834 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001835 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001836
Tom Caree4ee9662010-06-17 19:00:27 +00001837 // Check for invalid use of field width
1838 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001839 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001840 startSpecifier, specifierLen);
1841 }
1842
1843 // Check for invalid use of precision
1844 if (!FS.hasValidPrecision()) {
1845 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1846 startSpecifier, specifierLen);
1847 }
1848
1849 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001850 if (!FS.hasValidThousandsGroupingPrefix())
1851 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001852 if (!FS.hasValidLeadingZeros())
1853 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1854 if (!FS.hasValidPlusPrefix())
1855 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001856 if (!FS.hasValidSpacePrefix())
1857 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001858 if (!FS.hasValidAlternativeForm())
1859 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1860 if (!FS.hasValidLeftJustified())
1861 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1862
1863 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001864 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1865 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1866 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001867 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1868 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1869 startSpecifier, specifierLen);
1870
1871 // Check the length modifier is valid with the given conversion specifier.
1872 const LengthModifier &LM = FS.getLengthModifier();
1873 if (!FS.hasValidLengthModifier())
1874 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001875 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001876 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001877 << getSpecifierRange(startSpecifier, specifierLen)
1878 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001879 LM.getLength()));
1880
1881 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001882 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001883 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001884 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001885 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001886 // Continue checking the other format specifiers.
1887 return true;
1888 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001889
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001890 // The remaining checks depend on the data arguments.
1891 if (HasVAListArg)
1892 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001893
Ted Kremenek666a1972010-07-26 19:45:42 +00001894 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001895 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001896
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001897 // Now type check the data expression that matches the
1898 // format specifier.
1899 const Expr *Ex = getDataArg(argIndex);
1900 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1901 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1902 // Check if we didn't match because of an implicit cast from a 'char'
1903 // or 'short' to an 'int'. This is done because printf is a varargs
1904 // function.
1905 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001906 if (ICE->getType() == S.Context.IntTy) {
1907 // All further checking is done on the subexpression.
1908 Ex = ICE->getSubExpr();
1909 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001910 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001911 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001912
1913 // We may be able to offer a FixItHint if it is a supported type.
1914 PrintfSpecifier fixedFS = FS;
1915 bool success = fixedFS.fixType(Ex->getType());
1916
1917 if (success) {
1918 // Get the fix string from the fixed format specifier
1919 llvm::SmallString<128> buf;
1920 llvm::raw_svector_ostream os(buf);
1921 fixedFS.toString(os);
1922
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001923 // FIXME: getRepresentativeType() perhaps should return a string
1924 // instead of a QualType to better handle when the representative
1925 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001926 S.Diag(getLocationOfByte(CS.getStart()),
1927 diag::warn_printf_conversion_argument_type_mismatch)
1928 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1929 << getSpecifierRange(startSpecifier, specifierLen)
1930 << Ex->getSourceRange()
1931 << FixItHint::CreateReplacement(
1932 getSpecifierRange(startSpecifier, specifierLen),
1933 os.str());
1934 }
1935 else {
1936 S.Diag(getLocationOfByte(CS.getStart()),
1937 diag::warn_printf_conversion_argument_type_mismatch)
1938 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1939 << getSpecifierRange(startSpecifier, specifierLen)
1940 << Ex->getSourceRange();
1941 }
1942 }
1943
Ted Kremeneke0e53132010-01-28 23:39:18 +00001944 return true;
1945}
1946
Ted Kremenek826a3452010-07-16 02:11:22 +00001947//===--- CHECK: Scanf format string checking ------------------------------===//
1948
1949namespace {
1950class CheckScanfHandler : public CheckFormatHandler {
1951public:
1952 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1953 const Expr *origFormatExpr, unsigned firstDataArg,
1954 unsigned numDataArgs, bool isObjCLiteral,
1955 const char *beg, bool hasVAListArg,
1956 const CallExpr *theCall, unsigned formatIdx)
1957 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1958 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1959 theCall, formatIdx) {}
1960
1961 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1962 const char *startSpecifier,
1963 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001964
1965 bool HandleInvalidScanfConversionSpecifier(
1966 const analyze_scanf::ScanfSpecifier &FS,
1967 const char *startSpecifier,
1968 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001969
1970 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001971};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001972}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001973
Ted Kremenekb7c21012010-07-16 18:28:03 +00001974void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1975 const char *end) {
1976 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1977 << getSpecifierRange(start, end - start);
1978}
1979
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001980bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1981 const analyze_scanf::ScanfSpecifier &FS,
1982 const char *startSpecifier,
1983 unsigned specifierLen) {
1984
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001985 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001986 FS.getConversionSpecifier();
1987
1988 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1989 getLocationOfByte(CS.getStart()),
1990 startSpecifier, specifierLen,
1991 CS.getStart(), CS.getLength());
1992}
1993
Ted Kremenek826a3452010-07-16 02:11:22 +00001994bool CheckScanfHandler::HandleScanfSpecifier(
1995 const analyze_scanf::ScanfSpecifier &FS,
1996 const char *startSpecifier,
1997 unsigned specifierLen) {
1998
1999 using namespace analyze_scanf;
2000 using namespace analyze_format_string;
2001
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002002 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002003
Ted Kremenekbaa40062010-07-19 22:01:06 +00002004 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2005 // be used to decide if we are using positional arguments consistently.
2006 if (FS.consumesDataArgument()) {
2007 if (atFirstArg) {
2008 atFirstArg = false;
2009 usesPositionalArgs = FS.usesPositionalArg();
2010 }
2011 else if (usesPositionalArgs != FS.usesPositionalArg()) {
2012 // Cannot mix-and-match positional and non-positional arguments.
2013 S.Diag(getLocationOfByte(CS.getStart()),
2014 diag::warn_format_mix_positional_nonpositional_args)
2015 << getSpecifierRange(startSpecifier, specifierLen);
2016 return false;
2017 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002018 }
2019
2020 // Check if the field with is non-zero.
2021 const OptionalAmount &Amt = FS.getFieldWidth();
2022 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2023 if (Amt.getConstantAmount() == 0) {
2024 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2025 Amt.getConstantLength());
2026 S.Diag(getLocationOfByte(Amt.getStart()),
2027 diag::warn_scanf_nonzero_width)
2028 << R << FixItHint::CreateRemoval(R);
2029 }
2030 }
2031
2032 if (!FS.consumesDataArgument()) {
2033 // FIXME: Technically specifying a precision or field width here
2034 // makes no sense. Worth issuing a warning at some point.
2035 return true;
2036 }
2037
2038 // Consume the argument.
2039 unsigned argIndex = FS.getArgIndex();
2040 if (argIndex < NumDataArgs) {
2041 // The check to see if the argIndex is valid will come later.
2042 // We set the bit here because we may exit early from this
2043 // function if we encounter some other error.
2044 CoveredArgs.set(argIndex);
2045 }
2046
Ted Kremenek1e51c202010-07-20 20:04:47 +00002047 // Check the length modifier is valid with the given conversion specifier.
2048 const LengthModifier &LM = FS.getLengthModifier();
2049 if (!FS.hasValidLengthModifier()) {
2050 S.Diag(getLocationOfByte(LM.getStart()),
2051 diag::warn_format_nonsensical_length)
2052 << LM.toString() << CS.toString()
2053 << getSpecifierRange(startSpecifier, specifierLen)
2054 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2055 LM.getLength()));
2056 }
2057
Ted Kremenek826a3452010-07-16 02:11:22 +00002058 // The remaining checks depend on the data arguments.
2059 if (HasVAListArg)
2060 return true;
2061
Ted Kremenek666a1972010-07-26 19:45:42 +00002062 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002063 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002064
2065 // FIXME: Check that the argument type matches the format specifier.
2066
2067 return true;
2068}
2069
2070void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002071 const Expr *OrigFormatExpr,
2072 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00002073 unsigned format_idx, unsigned firstDataArg,
2074 bool isPrintf) {
2075
Ted Kremeneke0e53132010-01-28 23:39:18 +00002076 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002077 if (!FExpr->isAscii()) {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002078 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002079 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002080 << OrigFormatExpr->getSourceRange();
2081 return;
2082 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002083
Ted Kremeneke0e53132010-01-28 23:39:18 +00002084 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002085 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002086 const char *Str = StrRef.data();
2087 unsigned StrLen = StrRef.size();
Ted Kremenek4cd57912011-09-29 05:52:16 +00002088 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002089
Ted Kremeneke0e53132010-01-28 23:39:18 +00002090 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002091 if (StrLen == 0 && numDataArgs > 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002092 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002093 << OrigFormatExpr->getSourceRange();
2094 return;
2095 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002096
2097 if (isPrintf) {
2098 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002099 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2100 Str, HasVAListArg, TheCall, format_idx);
Ted Kremenek826a3452010-07-16 02:11:22 +00002101
2102 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2103 H.DoneProcessing();
2104 }
2105 else {
2106 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002107 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2108 Str, HasVAListArg, TheCall, format_idx);
Ted Kremenek826a3452010-07-16 02:11:22 +00002109
2110 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2111 H.DoneProcessing();
2112 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002113}
2114
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002115//===--- CHECK: Standard memory functions ---------------------------------===//
2116
Douglas Gregor2a053a32011-05-03 20:05:22 +00002117/// \brief Determine whether the given type is a dynamic class type (e.g.,
2118/// whether it has a vtable).
2119static bool isDynamicClassType(QualType T) {
2120 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2121 if (CXXRecordDecl *Definition = Record->getDefinition())
2122 if (Definition->isDynamicClass())
2123 return true;
2124
2125 return false;
2126}
2127
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002128/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002129/// otherwise returns NULL.
2130static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002131 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002132 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2133 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2134 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002135
Chandler Carruth000d4282011-06-16 09:09:40 +00002136 return 0;
2137}
2138
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002139/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002140static QualType getSizeOfArgType(const Expr* E) {
2141 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2142 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2143 if (SizeOf->getKind() == clang::UETT_SizeOf)
2144 return SizeOf->getTypeOfArgument();
2145
2146 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002147}
2148
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002149/// \brief Check for dangerous or invalid arguments to memset().
2150///
Chandler Carruth929f0132011-06-03 06:23:57 +00002151/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002152/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2153/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002154///
2155/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002156void Sema::CheckMemaccessArguments(const CallExpr *Call,
2157 CheckedMemoryFunction CMF,
2158 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002159 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002160 // we have enough arguments, and if not, abort further checking.
Nico Webercda57822011-10-13 22:30:23 +00002161 unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2162 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002163 return;
2164
Nico Webercda57822011-10-13 22:30:23 +00002165 unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2166 unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2167 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002168
2169 // We have special checking when the length is a sizeof expression.
2170 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2171 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2172 llvm::FoldingSetNodeID SizeOfArgID;
2173
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002174 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2175 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002176 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002177
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002178 QualType DestTy = Dest->getType();
2179 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2180 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002181
Chandler Carruth000d4282011-06-16 09:09:40 +00002182 // Never warn about void type pointers. This can be used to suppress
2183 // false positives.
2184 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002185 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002186
Chandler Carruth000d4282011-06-16 09:09:40 +00002187 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2188 // actually comparing the expressions for equality. Because computing the
2189 // expression IDs can be expensive, we only do this if the diagnostic is
2190 // enabled.
2191 if (SizeOfArg &&
2192 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2193 SizeOfArg->getExprLoc())) {
2194 // We only compute IDs for expressions if the warning is enabled, and
2195 // cache the sizeof arg's ID.
2196 if (SizeOfArgID == llvm::FoldingSetNodeID())
2197 SizeOfArg->Profile(SizeOfArgID, Context, true);
2198 llvm::FoldingSetNodeID DestID;
2199 Dest->Profile(DestID, Context, true);
2200 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002201 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2202 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002203 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2204 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2205 if (UnaryOp->getOpcode() == UO_AddrOf)
2206 ActionIdx = 1; // If its an address-of operator, just remove it.
2207 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2208 ActionIdx = 2; // If the pointee's size is sizeof(char),
2209 // suggest an explicit length.
Nico Webercda57822011-10-13 22:30:23 +00002210 unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002211 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2212 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002213 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002214 << Dest->getSourceRange()
2215 << SizeOfArg->getSourceRange());
2216 break;
2217 }
2218 }
2219
2220 // Also check for cases where the sizeof argument is the exact same
2221 // type as the memory argument, and where it points to a user-defined
2222 // record type.
2223 if (SizeOfArgTy != QualType()) {
2224 if (PointeeTy->isRecordType() &&
2225 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2226 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2227 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2228 << FnName << SizeOfArgTy << ArgIdx
2229 << PointeeTy << Dest->getSourceRange()
2230 << LenExpr->getSourceRange());
2231 break;
2232 }
Nico Webere4a1c642011-06-14 16:14:58 +00002233 }
2234
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002235 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00002236 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002237 DiagRuntimeBehavior(
2238 Dest->getExprLoc(), Dest,
2239 PDiag(diag::warn_dyn_class_memaccess)
2240 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2241 // "overwritten" if we're warning about the destination for any call
2242 // but memcmp; otherwise a verb appropriate to the call.
2243 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2244 << Call->getCallee()->getSourceRange());
Douglas Gregor707a23e2011-06-16 17:56:04 +00002245 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002246 DiagRuntimeBehavior(
2247 Dest->getExprLoc(), Dest,
2248 PDiag(diag::warn_arc_object_memaccess)
2249 << ArgIdx << FnName << PointeeTy
2250 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002251 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002252 continue;
John McCallf85e1932011-06-15 23:02:42 +00002253
2254 DiagRuntimeBehavior(
2255 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002256 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002257 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2258 break;
2259 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002260 }
2261}
2262
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002263// A little helper routine: ignore addition and subtraction of integer literals.
2264// This intentionally does not ignore all integer constant expressions because
2265// we don't want to remove sizeof().
2266static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2267 Ex = Ex->IgnoreParenCasts();
2268
2269 for (;;) {
2270 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2271 if (!BO || !BO->isAdditiveOp())
2272 break;
2273
2274 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2275 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2276
2277 if (isa<IntegerLiteral>(RHS))
2278 Ex = LHS;
2279 else if (isa<IntegerLiteral>(LHS))
2280 Ex = RHS;
2281 else
2282 break;
2283 }
2284
2285 return Ex;
2286}
2287
2288// Warn if the user has made the 'size' argument to strlcpy or strlcat
2289// be the size of the source, instead of the destination.
2290void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2291 IdentifierInfo *FnName) {
2292
2293 // Don't crash if the user has the wrong number of arguments
2294 if (Call->getNumArgs() != 3)
2295 return;
2296
2297 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2298 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2299 const Expr *CompareWithSrc = NULL;
2300
2301 // Look for 'strlcpy(dst, x, sizeof(x))'
2302 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2303 CompareWithSrc = Ex;
2304 else {
2305 // Look for 'strlcpy(dst, x, strlen(x))'
2306 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2307 if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2308 && SizeCall->getNumArgs() == 1)
2309 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2310 }
2311 }
2312
2313 if (!CompareWithSrc)
2314 return;
2315
2316 // Determine if the argument to sizeof/strlen is equal to the source
2317 // argument. In principle there's all kinds of things you could do
2318 // here, for instance creating an == expression and evaluating it with
2319 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2320 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2321 if (!SrcArgDRE)
2322 return;
2323
2324 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2325 if (!CompareWithSrcDRE ||
2326 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2327 return;
2328
2329 const Expr *OriginalSizeArg = Call->getArg(2);
2330 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2331 << OriginalSizeArg->getSourceRange() << FnName;
2332
2333 // Output a FIXIT hint if the destination is an array (rather than a
2334 // pointer to an array). This could be enhanced to handle some
2335 // pointers if we know the actual size, like if DstArg is 'array+2'
2336 // we could say 'sizeof(array)-2'.
2337 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002338 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002339
Ted Kremenek8f746222011-08-18 22:48:41 +00002340 // Only handle constant-sized or VLAs, but not flexible members.
2341 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2342 // Only issue the FIXIT for arrays of size > 1.
2343 if (CAT->getSize().getSExtValue() <= 1)
2344 return;
2345 } else if (!DstArgTy->isVariableArrayType()) {
2346 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002347 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002348
2349 llvm::SmallString<128> sizeString;
2350 llvm::raw_svector_ostream OS(sizeString);
2351 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002352 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002353 OS << ")";
2354
2355 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2356 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2357 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002358}
2359
Ted Kremenek06de2762007-08-17 16:46:58 +00002360//===--- CHECK: Return Address of Stack Variable --------------------------===//
2361
Chris Lattner5f9e2722011-07-23 10:55:15 +00002362static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2363static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002364
2365/// CheckReturnStackAddr - Check if a return statement returns the address
2366/// of a stack variable.
2367void
2368Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2369 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002370
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002371 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002372 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002373
2374 // Perform checking for returned stack addresses, local blocks,
2375 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002376 if (lhsType->isPointerType() ||
2377 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002378 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002379 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002380 stackE = EvalVal(RetValExp, refVars);
2381 }
2382
2383 if (stackE == 0)
2384 return; // Nothing suspicious was found.
2385
2386 SourceLocation diagLoc;
2387 SourceRange diagRange;
2388 if (refVars.empty()) {
2389 diagLoc = stackE->getLocStart();
2390 diagRange = stackE->getSourceRange();
2391 } else {
2392 // We followed through a reference variable. 'stackE' contains the
2393 // problematic expression but we will warn at the return statement pointing
2394 // at the reference variable. We will later display the "trail" of
2395 // reference variables using notes.
2396 diagLoc = refVars[0]->getLocStart();
2397 diagRange = refVars[0]->getSourceRange();
2398 }
2399
2400 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2401 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2402 : diag::warn_ret_stack_addr)
2403 << DR->getDecl()->getDeclName() << diagRange;
2404 } else if (isa<BlockExpr>(stackE)) { // local block.
2405 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2406 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2407 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2408 } else { // local temporary.
2409 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2410 : diag::warn_ret_local_temp_addr)
2411 << diagRange;
2412 }
2413
2414 // Display the "trail" of reference variables that we followed until we
2415 // found the problematic expression using notes.
2416 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2417 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2418 // If this var binds to another reference var, show the range of the next
2419 // var, otherwise the var binds to the problematic expression, in which case
2420 // show the range of the expression.
2421 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2422 : stackE->getSourceRange();
2423 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2424 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002425 }
2426}
2427
2428/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2429/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002430/// to a location on the stack, a local block, an address of a label, or a
2431/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002432/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002433/// encounter a subexpression that (1) clearly does not lead to one of the
2434/// above problematic expressions (2) is something we cannot determine leads to
2435/// a problematic expression based on such local checking.
2436///
2437/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2438/// the expression that they point to. Such variables are added to the
2439/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002440///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002441/// EvalAddr processes expressions that are pointers that are used as
2442/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002443/// At the base case of the recursion is a check for the above problematic
2444/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002445///
2446/// This implementation handles:
2447///
2448/// * pointer-to-pointer casts
2449/// * implicit conversions from array references to pointers
2450/// * taking the address of fields
2451/// * arbitrary interplay between "&" and "*" operators
2452/// * pointer arithmetic from an address of a stack variable
2453/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002454static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002455 if (E->isTypeDependent())
2456 return NULL;
2457
Ted Kremenek06de2762007-08-17 16:46:58 +00002458 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002459 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002460 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002461 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002462 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002463
Peter Collingbournef111d932011-04-15 00:35:48 +00002464 E = E->IgnoreParens();
2465
Ted Kremenek06de2762007-08-17 16:46:58 +00002466 // Our "symbolic interpreter" is just a dispatch off the currently
2467 // viewed AST node. We then recursively traverse the AST by calling
2468 // EvalAddr and EvalVal appropriately.
2469 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002470 case Stmt::DeclRefExprClass: {
2471 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2472
2473 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2474 // If this is a reference variable, follow through to the expression that
2475 // it points to.
2476 if (V->hasLocalStorage() &&
2477 V->getType()->isReferenceType() && V->hasInit()) {
2478 // Add the reference variable to the "trail".
2479 refVars.push_back(DR);
2480 return EvalAddr(V->getInit(), refVars);
2481 }
2482
2483 return NULL;
2484 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002485
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002486 case Stmt::UnaryOperatorClass: {
2487 // The only unary operator that make sense to handle here
2488 // is AddrOf. All others don't make sense as pointers.
2489 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002490
John McCall2de56d12010-08-25 11:45:40 +00002491 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002492 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002493 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002494 return NULL;
2495 }
Mike Stump1eb44332009-09-09 15:08:12 +00002496
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002497 case Stmt::BinaryOperatorClass: {
2498 // Handle pointer arithmetic. All other binary operators are not valid
2499 // in this context.
2500 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002501 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002502
John McCall2de56d12010-08-25 11:45:40 +00002503 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002504 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002505
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002506 Expr *Base = B->getLHS();
2507
2508 // Determine which argument is the real pointer base. It could be
2509 // the RHS argument instead of the LHS.
2510 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002511
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002512 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002513 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002514 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002515
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002516 // For conditional operators we need to see if either the LHS or RHS are
2517 // valid DeclRefExpr*s. If one of them is valid, we return it.
2518 case Stmt::ConditionalOperatorClass: {
2519 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002520
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002521 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002522 if (Expr *lhsExpr = C->getLHS()) {
2523 // In C++, we can have a throw-expression, which has 'void' type.
2524 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002525 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002526 return LHS;
2527 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002528
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002529 // In C++, we can have a throw-expression, which has 'void' type.
2530 if (C->getRHS()->getType()->isVoidType())
2531 return NULL;
2532
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002533 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002534 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002535
2536 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002537 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002538 return E; // local block.
2539 return NULL;
2540
2541 case Stmt::AddrLabelExprClass:
2542 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002543
Ted Kremenek54b52742008-08-07 00:49:01 +00002544 // For casts, we need to handle conversions from arrays to
2545 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002546 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002547 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002548 case Stmt::CXXFunctionalCastExprClass:
2549 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002550 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002551 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Steve Naroffdd972f22008-09-05 22:11:13 +00002553 if (SubExpr->getType()->isPointerType() ||
2554 SubExpr->getType()->isBlockPointerType() ||
2555 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002556 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002557 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002558 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002559 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002560 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002561 }
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002563 // C++ casts. For dynamic casts, static casts, and const casts, we
2564 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002565 // through the cast. In the case the dynamic cast doesn't fail (and
2566 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002567 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002568 // FIXME: The comment about is wrong; we're not always converting
2569 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002570 // handle references to objects.
2571 case Stmt::CXXStaticCastExprClass:
2572 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002573 case Stmt::CXXConstCastExprClass:
2574 case Stmt::CXXReinterpretCastExprClass: {
2575 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002576 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002577 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002578 else
2579 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002580 }
Mike Stump1eb44332009-09-09 15:08:12 +00002581
Douglas Gregor03e80032011-06-21 17:03:29 +00002582 case Stmt::MaterializeTemporaryExprClass:
2583 if (Expr *Result = EvalAddr(
2584 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2585 refVars))
2586 return Result;
2587
2588 return E;
2589
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002590 // Everything else: we simply don't reason about them.
2591 default:
2592 return NULL;
2593 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002594}
Mike Stump1eb44332009-09-09 15:08:12 +00002595
Ted Kremenek06de2762007-08-17 16:46:58 +00002596
2597/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2598/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002599static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002600do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002601 // We should only be called for evaluating non-pointer expressions, or
2602 // expressions with a pointer type that are not used as references but instead
2603 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002604
Ted Kremenek06de2762007-08-17 16:46:58 +00002605 // Our "symbolic interpreter" is just a dispatch off the currently
2606 // viewed AST node. We then recursively traverse the AST by calling
2607 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002608
2609 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002610 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002611 case Stmt::ImplicitCastExprClass: {
2612 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002613 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002614 E = IE->getSubExpr();
2615 continue;
2616 }
2617 return NULL;
2618 }
2619
Douglas Gregora2813ce2009-10-23 18:54:35 +00002620 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002621 // When we hit a DeclRefExpr we are looking at code that refers to a
2622 // variable's name. If it's not a reference variable we check if it has
2623 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002624 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002625
Ted Kremenek06de2762007-08-17 16:46:58 +00002626 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002627 if (V->hasLocalStorage()) {
2628 if (!V->getType()->isReferenceType())
2629 return DR;
2630
2631 // Reference variable, follow through to the expression that
2632 // it points to.
2633 if (V->hasInit()) {
2634 // Add the reference variable to the "trail".
2635 refVars.push_back(DR);
2636 return EvalVal(V->getInit(), refVars);
2637 }
2638 }
Mike Stump1eb44332009-09-09 15:08:12 +00002639
Ted Kremenek06de2762007-08-17 16:46:58 +00002640 return NULL;
2641 }
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Ted Kremenek06de2762007-08-17 16:46:58 +00002643 case Stmt::UnaryOperatorClass: {
2644 // The only unary operator that make sense to handle here
2645 // is Deref. All others don't resolve to a "name." This includes
2646 // handling all sorts of rvalues passed to a unary operator.
2647 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002648
John McCall2de56d12010-08-25 11:45:40 +00002649 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002650 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002651
2652 return NULL;
2653 }
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Ted Kremenek06de2762007-08-17 16:46:58 +00002655 case Stmt::ArraySubscriptExprClass: {
2656 // Array subscripts are potential references to data on the stack. We
2657 // retrieve the DeclRefExpr* for the array variable if it indeed
2658 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002659 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002660 }
Mike Stump1eb44332009-09-09 15:08:12 +00002661
Ted Kremenek06de2762007-08-17 16:46:58 +00002662 case Stmt::ConditionalOperatorClass: {
2663 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002664 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002665 ConditionalOperator *C = cast<ConditionalOperator>(E);
2666
Anders Carlsson39073232007-11-30 19:04:31 +00002667 // Handle the GNU extension for missing LHS.
2668 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002669 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002670 return LHS;
2671
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002672 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002673 }
Mike Stump1eb44332009-09-09 15:08:12 +00002674
Ted Kremenek06de2762007-08-17 16:46:58 +00002675 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002676 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002677 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Ted Kremenek06de2762007-08-17 16:46:58 +00002679 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002680 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002681 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002682
2683 // Check whether the member type is itself a reference, in which case
2684 // we're not going to refer to the member, but to what the member refers to.
2685 if (M->getMemberDecl()->getType()->isReferenceType())
2686 return NULL;
2687
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002688 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002689 }
Mike Stump1eb44332009-09-09 15:08:12 +00002690
Douglas Gregor03e80032011-06-21 17:03:29 +00002691 case Stmt::MaterializeTemporaryExprClass:
2692 if (Expr *Result = EvalVal(
2693 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2694 refVars))
2695 return Result;
2696
2697 return E;
2698
Ted Kremenek06de2762007-08-17 16:46:58 +00002699 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002700 // Check that we don't return or take the address of a reference to a
2701 // temporary. This is only useful in C++.
2702 if (!E->isTypeDependent() && E->isRValue())
2703 return E;
2704
2705 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002706 return NULL;
2707 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002708} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002709}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002710
2711//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2712
2713/// Check for comparisons of floating point operands using != and ==.
2714/// Issue a warning if these are no self-comparisons, as they are not likely
2715/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00002716void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002717 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002718
Richard Trieudd225092011-09-15 21:56:47 +00002719 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2720 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002721
2722 // Special case: check for x == x (which is OK).
2723 // Do not emit warnings for such cases.
2724 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2725 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2726 if (DRL->getDecl() == DRR->getDecl())
2727 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002728
2729
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002730 // Special case: check for comparisons against literals that can be exactly
2731 // represented by APFloat. In such cases, do not emit a warning. This
2732 // is a heuristic: often comparison against such literals are used to
2733 // detect if a value in a variable has not changed. This clearly can
2734 // lead to false negatives.
2735 if (EmitWarning) {
2736 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2737 if (FLL->isExact())
2738 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002739 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002740 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2741 if (FLR->isExact())
2742 EmitWarning = false;
2743 }
2744 }
Mike Stump1eb44332009-09-09 15:08:12 +00002745
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002746 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002747 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002748 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002749 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002750 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002751
Sebastian Redl0eb23302009-01-19 00:08:26 +00002752 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002753 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002754 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002755 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002757 // Emit the diagnostic.
2758 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00002759 Diag(Loc, diag::warn_floatingpoint_eq)
2760 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002761}
John McCallba26e582010-01-04 23:21:16 +00002762
John McCallf2370c92010-01-06 05:24:50 +00002763//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2764//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002765
John McCallf2370c92010-01-06 05:24:50 +00002766namespace {
John McCallba26e582010-01-04 23:21:16 +00002767
John McCallf2370c92010-01-06 05:24:50 +00002768/// Structure recording the 'active' range of an integer-valued
2769/// expression.
2770struct IntRange {
2771 /// The number of bits active in the int.
2772 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002773
John McCallf2370c92010-01-06 05:24:50 +00002774 /// True if the int is known not to have negative values.
2775 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002776
John McCallf2370c92010-01-06 05:24:50 +00002777 IntRange(unsigned Width, bool NonNegative)
2778 : Width(Width), NonNegative(NonNegative)
2779 {}
John McCallba26e582010-01-04 23:21:16 +00002780
John McCall1844a6e2010-11-10 23:38:19 +00002781 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002782 static IntRange forBoolType() {
2783 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002784 }
2785
John McCall1844a6e2010-11-10 23:38:19 +00002786 /// Returns the range of an opaque value of the given integral type.
2787 static IntRange forValueOfType(ASTContext &C, QualType T) {
2788 return forValueOfCanonicalType(C,
2789 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002790 }
2791
John McCall1844a6e2010-11-10 23:38:19 +00002792 /// Returns the range of an opaque value of a canonical integral type.
2793 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002794 assert(T->isCanonicalUnqualified());
2795
2796 if (const VectorType *VT = dyn_cast<VectorType>(T))
2797 T = VT->getElementType().getTypePtr();
2798 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2799 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002800
John McCall091f23f2010-11-09 22:22:12 +00002801 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002802 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2803 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00002804 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00002805 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2806
John McCall323ed742010-05-06 08:58:33 +00002807 unsigned NumPositive = Enum->getNumPositiveBits();
2808 unsigned NumNegative = Enum->getNumNegativeBits();
2809
2810 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2811 }
John McCallf2370c92010-01-06 05:24:50 +00002812
2813 const BuiltinType *BT = cast<BuiltinType>(T);
2814 assert(BT->isInteger());
2815
2816 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2817 }
2818
John McCall1844a6e2010-11-10 23:38:19 +00002819 /// Returns the "target" range of a canonical integral type, i.e.
2820 /// the range of values expressible in the type.
2821 ///
2822 /// This matches forValueOfCanonicalType except that enums have the
2823 /// full range of their type, not the range of their enumerators.
2824 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2825 assert(T->isCanonicalUnqualified());
2826
2827 if (const VectorType *VT = dyn_cast<VectorType>(T))
2828 T = VT->getElementType().getTypePtr();
2829 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2830 T = CT->getElementType().getTypePtr();
2831 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00002832 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00002833
2834 const BuiltinType *BT = cast<BuiltinType>(T);
2835 assert(BT->isInteger());
2836
2837 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2838 }
2839
2840 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002841 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002842 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002843 L.NonNegative && R.NonNegative);
2844 }
2845
John McCall1844a6e2010-11-10 23:38:19 +00002846 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002847 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002848 return IntRange(std::min(L.Width, R.Width),
2849 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002850 }
2851};
2852
2853IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2854 if (value.isSigned() && value.isNegative())
2855 return IntRange(value.getMinSignedBits(), false);
2856
2857 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002858 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002859
2860 // isNonNegative() just checks the sign bit without considering
2861 // signedness.
2862 return IntRange(value.getActiveBits(), true);
2863}
2864
John McCall0acc3112010-01-06 22:57:21 +00002865IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002866 unsigned MaxWidth) {
2867 if (result.isInt())
2868 return GetValueRange(C, result.getInt(), MaxWidth);
2869
2870 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002871 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2872 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2873 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2874 R = IntRange::join(R, El);
2875 }
John McCallf2370c92010-01-06 05:24:50 +00002876 return R;
2877 }
2878
2879 if (result.isComplexInt()) {
2880 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2881 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2882 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002883 }
2884
2885 // This can happen with lossless casts to intptr_t of "based" lvalues.
2886 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002887 // FIXME: The only reason we need to pass the type in here is to get
2888 // the sign right on this one case. It would be nice if APValue
2889 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002890 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002891 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00002892}
John McCallf2370c92010-01-06 05:24:50 +00002893
2894/// Pseudo-evaluate the given integer expression, estimating the
2895/// range of values it might take.
2896///
2897/// \param MaxWidth - the width to which the value will be truncated
2898IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2899 E = E->IgnoreParens();
2900
2901 // Try a full evaluation first.
2902 Expr::EvalResult result;
2903 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002904 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002905
2906 // I think we only want to look through implicit casts here; if the
2907 // user has an explicit widening cast, we should treat the value as
2908 // being of the new, wider type.
2909 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002910 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002911 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2912
John McCall1844a6e2010-11-10 23:38:19 +00002913 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002914
John McCall2de56d12010-08-25 11:45:40 +00002915 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002916
John McCallf2370c92010-01-06 05:24:50 +00002917 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002918 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002919 return OutputTypeRange;
2920
2921 IntRange SubRange
2922 = GetExprRange(C, CE->getSubExpr(),
2923 std::min(MaxWidth, OutputTypeRange.Width));
2924
2925 // Bail out if the subexpr's range is as wide as the cast type.
2926 if (SubRange.Width >= OutputTypeRange.Width)
2927 return OutputTypeRange;
2928
2929 // Otherwise, we take the smaller width, and we're non-negative if
2930 // either the output type or the subexpr is.
2931 return IntRange(SubRange.Width,
2932 SubRange.NonNegative || OutputTypeRange.NonNegative);
2933 }
2934
2935 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2936 // If we can fold the condition, just take that operand.
2937 bool CondResult;
2938 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2939 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2940 : CO->getFalseExpr(),
2941 MaxWidth);
2942
2943 // Otherwise, conservatively merge.
2944 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2945 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2946 return IntRange::join(L, R);
2947 }
2948
2949 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2950 switch (BO->getOpcode()) {
2951
2952 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002953 case BO_LAnd:
2954 case BO_LOr:
2955 case BO_LT:
2956 case BO_GT:
2957 case BO_LE:
2958 case BO_GE:
2959 case BO_EQ:
2960 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002961 return IntRange::forBoolType();
2962
John McCall862ff872011-07-13 06:35:24 +00002963 // The type of the assignments is the type of the LHS, so the RHS
2964 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00002965 case BO_MulAssign:
2966 case BO_DivAssign:
2967 case BO_RemAssign:
2968 case BO_AddAssign:
2969 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00002970 case BO_XorAssign:
2971 case BO_OrAssign:
2972 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00002973 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002974
John McCall862ff872011-07-13 06:35:24 +00002975 // Simple assignments just pass through the RHS, which will have
2976 // been coerced to the LHS type.
2977 case BO_Assign:
2978 // TODO: bitfields?
2979 return GetExprRange(C, BO->getRHS(), MaxWidth);
2980
John McCallf2370c92010-01-06 05:24:50 +00002981 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002982 case BO_PtrMemD:
2983 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002984 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002985
John McCall60fad452010-01-06 22:07:33 +00002986 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002987 case BO_And:
2988 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002989 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2990 GetExprRange(C, BO->getRHS(), MaxWidth));
2991
John McCallf2370c92010-01-06 05:24:50 +00002992 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002993 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002994 // ...except that we want to treat '1 << (blah)' as logically
2995 // positive. It's an important idiom.
2996 if (IntegerLiteral *I
2997 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2998 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002999 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003000 return IntRange(R.Width, /*NonNegative*/ true);
3001 }
3002 }
3003 // fallthrough
3004
John McCall2de56d12010-08-25 11:45:40 +00003005 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003006 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003007
John McCall60fad452010-01-06 22:07:33 +00003008 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003009 case BO_Shr:
3010 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003011 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3012
3013 // If the shift amount is a positive constant, drop the width by
3014 // that much.
3015 llvm::APSInt shift;
3016 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3017 shift.isNonNegative()) {
3018 unsigned zext = shift.getZExtValue();
3019 if (zext >= L.Width)
3020 L.Width = (L.NonNegative ? 0 : 1);
3021 else
3022 L.Width -= zext;
3023 }
3024
3025 return L;
3026 }
3027
3028 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003029 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003030 return GetExprRange(C, BO->getRHS(), MaxWidth);
3031
John McCall60fad452010-01-06 22:07:33 +00003032 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003033 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003034 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003035 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003036 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003037
John McCall00fe7612011-07-14 22:39:48 +00003038 // The width of a division result is mostly determined by the size
3039 // of the LHS.
3040 case BO_Div: {
3041 // Don't 'pre-truncate' the operands.
3042 unsigned opWidth = C.getIntWidth(E->getType());
3043 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3044
3045 // If the divisor is constant, use that.
3046 llvm::APSInt divisor;
3047 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3048 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3049 if (log2 >= L.Width)
3050 L.Width = (L.NonNegative ? 0 : 1);
3051 else
3052 L.Width = std::min(L.Width - log2, MaxWidth);
3053 return L;
3054 }
3055
3056 // Otherwise, just use the LHS's width.
3057 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3058 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3059 }
3060
3061 // The result of a remainder can't be larger than the result of
3062 // either side.
3063 case BO_Rem: {
3064 // Don't 'pre-truncate' the operands.
3065 unsigned opWidth = C.getIntWidth(E->getType());
3066 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3067 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3068
3069 IntRange meet = IntRange::meet(L, R);
3070 meet.Width = std::min(meet.Width, MaxWidth);
3071 return meet;
3072 }
3073
3074 // The default behavior is okay for these.
3075 case BO_Mul:
3076 case BO_Add:
3077 case BO_Xor:
3078 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003079 break;
3080 }
3081
John McCall00fe7612011-07-14 22:39:48 +00003082 // The default case is to treat the operation as if it were closed
3083 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003084 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3085 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3086 return IntRange::join(L, R);
3087 }
3088
3089 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3090 switch (UO->getOpcode()) {
3091 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003092 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003093 return IntRange::forBoolType();
3094
3095 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003096 case UO_Deref:
3097 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003098 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003099
3100 default:
3101 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3102 }
3103 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003104
3105 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003106 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003107 }
John McCallf2370c92010-01-06 05:24:50 +00003108
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003109 if (FieldDecl *BitField = E->getBitField())
3110 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003111 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003112
John McCall1844a6e2010-11-10 23:38:19 +00003113 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003114}
John McCall51313c32010-01-04 23:31:57 +00003115
John McCall323ed742010-05-06 08:58:33 +00003116IntRange GetExprRange(ASTContext &C, Expr *E) {
3117 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3118}
3119
John McCall51313c32010-01-04 23:31:57 +00003120/// Checks whether the given value, which currently has the given
3121/// source semantics, has the same value when coerced through the
3122/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003123bool IsSameFloatAfterCast(const llvm::APFloat &value,
3124 const llvm::fltSemantics &Src,
3125 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003126 llvm::APFloat truncated = value;
3127
3128 bool ignored;
3129 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3130 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3131
3132 return truncated.bitwiseIsEqual(value);
3133}
3134
3135/// Checks whether the given value, which currently has the given
3136/// source semantics, has the same value when coerced through the
3137/// target semantics.
3138///
3139/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003140bool IsSameFloatAfterCast(const APValue &value,
3141 const llvm::fltSemantics &Src,
3142 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003143 if (value.isFloat())
3144 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3145
3146 if (value.isVector()) {
3147 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3148 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3149 return false;
3150 return true;
3151 }
3152
3153 assert(value.isComplexFloat());
3154 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3155 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3156}
3157
John McCallb4eb64d2010-10-08 02:01:28 +00003158void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003159
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003160static bool IsZero(Sema &S, Expr *E) {
3161 // Suppress cases where we are comparing against an enum constant.
3162 if (const DeclRefExpr *DR =
3163 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3164 if (isa<EnumConstantDecl>(DR->getDecl()))
3165 return false;
3166
3167 // Suppress cases where the '0' value is expanded from a macro.
3168 if (E->getLocStart().isMacroID())
3169 return false;
3170
John McCall323ed742010-05-06 08:58:33 +00003171 llvm::APSInt Value;
3172 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3173}
3174
John McCall372e1032010-10-06 00:25:24 +00003175static bool HasEnumType(Expr *E) {
3176 // Strip off implicit integral promotions.
3177 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003178 if (ICE->getCastKind() != CK_IntegralCast &&
3179 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003180 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003181 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003182 }
3183
3184 return E->getType()->isEnumeralType();
3185}
3186
John McCall323ed742010-05-06 08:58:33 +00003187void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003188 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003189 if (E->isValueDependent())
3190 return;
3191
John McCall2de56d12010-08-25 11:45:40 +00003192 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003193 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003194 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003195 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003196 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003197 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003198 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003199 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003200 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003201 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003202 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003203 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003204 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003205 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003206 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003207 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3208 }
3209}
3210
3211/// Analyze the operands of the given comparison. Implements the
3212/// fallback case from AnalyzeComparison.
3213void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003214 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3215 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003216}
John McCall51313c32010-01-04 23:31:57 +00003217
John McCallba26e582010-01-04 23:21:16 +00003218/// \brief Implements -Wsign-compare.
3219///
Richard Trieudd225092011-09-15 21:56:47 +00003220/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003221void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3222 // The type the comparison is being performed in.
3223 QualType T = E->getLHS()->getType();
3224 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3225 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003226
John McCall323ed742010-05-06 08:58:33 +00003227 // We don't do anything special if this isn't an unsigned integral
3228 // comparison: we're only interested in integral comparisons, and
3229 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003230 //
3231 // We also don't care about value-dependent expressions or expressions
3232 // whose result is a constant.
3233 if (!T->hasUnsignedIntegerRepresentation()
3234 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003235 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003236
Richard Trieudd225092011-09-15 21:56:47 +00003237 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3238 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003239
John McCall323ed742010-05-06 08:58:33 +00003240 // Check to see if one of the (unmodified) operands is of different
3241 // signedness.
3242 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003243 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3244 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003245 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003246 signedOperand = LHS;
3247 unsignedOperand = RHS;
3248 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3249 signedOperand = RHS;
3250 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003251 } else {
John McCall323ed742010-05-06 08:58:33 +00003252 CheckTrivialUnsignedComparison(S, E);
3253 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003254 }
3255
John McCall323ed742010-05-06 08:58:33 +00003256 // Otherwise, calculate the effective range of the signed operand.
3257 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003258
John McCall323ed742010-05-06 08:58:33 +00003259 // Go ahead and analyze implicit conversions in the operands. Note
3260 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003261 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3262 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003263
John McCall323ed742010-05-06 08:58:33 +00003264 // If the signed range is non-negative, -Wsign-compare won't fire,
3265 // but we should still check for comparisons which are always true
3266 // or false.
3267 if (signedRange.NonNegative)
3268 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003269
3270 // For (in)equality comparisons, if the unsigned operand is a
3271 // constant which cannot collide with a overflowed signed operand,
3272 // then reinterpreting the signed operand as unsigned will not
3273 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003274 if (E->isEqualityOp()) {
3275 unsigned comparisonWidth = S.Context.getIntWidth(T);
3276 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003277
John McCall323ed742010-05-06 08:58:33 +00003278 // We should never be unable to prove that the unsigned operand is
3279 // non-negative.
3280 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3281
3282 if (unsignedRange.Width < comparisonWidth)
3283 return;
3284 }
3285
3286 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003287 << LHS->getType() << RHS->getType()
3288 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003289}
3290
John McCall15d7d122010-11-11 03:21:53 +00003291/// Analyzes an attempt to assign the given value to a bitfield.
3292///
3293/// Returns true if there was something fishy about the attempt.
3294bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3295 SourceLocation InitLoc) {
3296 assert(Bitfield->isBitField());
3297 if (Bitfield->isInvalidDecl())
3298 return false;
3299
John McCall91b60142010-11-11 05:33:51 +00003300 // White-list bool bitfields.
3301 if (Bitfield->getType()->isBooleanType())
3302 return false;
3303
Douglas Gregor46ff3032011-02-04 13:09:01 +00003304 // Ignore value- or type-dependent expressions.
3305 if (Bitfield->getBitWidth()->isValueDependent() ||
3306 Bitfield->getBitWidth()->isTypeDependent() ||
3307 Init->isValueDependent() ||
3308 Init->isTypeDependent())
3309 return false;
3310
John McCall15d7d122010-11-11 03:21:53 +00003311 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3312
John McCall15d7d122010-11-11 03:21:53 +00003313 Expr::EvalResult InitValue;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003314 if (!OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00003315 !InitValue.Val.isInt())
3316 return false;
3317
3318 const llvm::APSInt &Value = InitValue.Val.getInt();
3319 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003320 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003321
3322 if (OriginalWidth <= FieldWidth)
3323 return false;
3324
Jay Foad9f71a8f2010-12-07 08:25:34 +00003325 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003326
3327 // It's fairly common to write values into signed bitfields
3328 // that, if sign-extended, would end up becoming a different
3329 // value. We don't want to warn about that.
3330 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003331 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003332 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003333 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003334
3335 if (Value == TruncatedValue)
3336 return false;
3337
3338 std::string PrettyValue = Value.toString(10);
3339 std::string PrettyTrunc = TruncatedValue.toString(10);
3340
3341 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3342 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3343 << Init->getSourceRange();
3344
3345 return true;
3346}
3347
John McCallbeb22aa2010-11-09 23:24:47 +00003348/// Analyze the given simple or compound assignment for warning-worthy
3349/// operations.
3350void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3351 // Just recurse on the LHS.
3352 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3353
3354 // We want to recurse on the RHS as normal unless we're assigning to
3355 // a bitfield.
3356 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003357 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3358 E->getOperatorLoc())) {
3359 // Recurse, ignoring any implicit conversions on the RHS.
3360 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3361 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003362 }
3363 }
3364
3365 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3366}
3367
John McCall51313c32010-01-04 23:31:57 +00003368/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003369void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3370 SourceLocation CContext, unsigned diag) {
3371 S.Diag(E->getExprLoc(), diag)
3372 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3373}
3374
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003375/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3376void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3377 unsigned diag) {
3378 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3379}
3380
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003381/// Diagnose an implicit cast from a literal expression. Does not warn when the
3382/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003383void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3384 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003385 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003386 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003387 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003388 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3389 T->hasUnsignedIntegerRepresentation());
3390 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003391 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003392 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003393 return;
3394
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003395 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3396 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003397}
3398
John McCall091f23f2010-11-09 22:22:12 +00003399std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3400 if (!Range.Width) return "0";
3401
3402 llvm::APSInt ValueInRange = Value;
3403 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003404 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003405 return ValueInRange.toString(10);
3406}
3407
Ted Kremenekef9ff882011-03-10 20:03:42 +00003408static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3409 SourceManager &smgr = S.Context.getSourceManager();
3410 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3411}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003412
John McCall323ed742010-05-06 08:58:33 +00003413void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003414 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003415 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003416
John McCall323ed742010-05-06 08:58:33 +00003417 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3418 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3419 if (Source == Target) return;
3420 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003421
Chandler Carruth108f7562011-07-26 05:40:03 +00003422 // If the conversion context location is invalid don't complain. We also
3423 // don't want to emit a warning if the issue occurs from the expansion of
3424 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3425 // delay this check as long as possible. Once we detect we are in that
3426 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003427 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003428 return;
3429
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003430 // Diagnose implicit casts to bool.
3431 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3432 if (isa<StringLiteral>(E))
3433 // Warn on string literal to bool. Checks for string literals in logical
3434 // expressions, for instances, assert(0 && "error here"), is prevented
3435 // by a check in AnalyzeImplicitConversions().
3436 return DiagnoseImpCast(S, E, T, CC,
3437 diag::warn_impcast_string_literal_to_bool);
David Blaikiee37cdc42011-09-29 04:06:47 +00003438 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003439 }
John McCall51313c32010-01-04 23:31:57 +00003440
3441 // Strip vector types.
3442 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003443 if (!isa<VectorType>(Target)) {
3444 if (isFromSystemMacro(S, CC))
3445 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003446 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003447 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003448
3449 // If the vector cast is cast between two vectors of the same size, it is
3450 // a bitcast, not a conversion.
3451 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3452 return;
John McCall51313c32010-01-04 23:31:57 +00003453
3454 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3455 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3456 }
3457
3458 // Strip complex types.
3459 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003460 if (!isa<ComplexType>(Target)) {
3461 if (isFromSystemMacro(S, CC))
3462 return;
3463
John McCallb4eb64d2010-10-08 02:01:28 +00003464 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003465 }
John McCall51313c32010-01-04 23:31:57 +00003466
3467 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3468 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3469 }
3470
3471 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3472 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3473
3474 // If the source is floating point...
3475 if (SourceBT && SourceBT->isFloatingPoint()) {
3476 // ...and the target is floating point...
3477 if (TargetBT && TargetBT->isFloatingPoint()) {
3478 // ...then warn if we're dropping FP rank.
3479
3480 // Builtin FP kinds are ordered by increasing FP rank.
3481 if (SourceBT->getKind() > TargetBT->getKind()) {
3482 // Don't warn about float constants that are precisely
3483 // representable in the target type.
3484 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00003485 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003486 // Value might be a float, a float vector, or a float complex.
3487 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003488 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3489 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003490 return;
3491 }
3492
Ted Kremenekef9ff882011-03-10 20:03:42 +00003493 if (isFromSystemMacro(S, CC))
3494 return;
3495
John McCallb4eb64d2010-10-08 02:01:28 +00003496 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003497 }
3498 return;
3499 }
3500
Ted Kremenekef9ff882011-03-10 20:03:42 +00003501 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003502 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003503 if (isFromSystemMacro(S, CC))
3504 return;
3505
Chandler Carrutha5b93322011-02-17 11:05:49 +00003506 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003507 // We also want to warn on, e.g., "int i = -1.234"
3508 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3509 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3510 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3511
Chandler Carruthf65076e2011-04-10 08:36:24 +00003512 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3513 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003514 } else {
3515 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3516 }
3517 }
John McCall51313c32010-01-04 23:31:57 +00003518
3519 return;
3520 }
3521
John McCallf2370c92010-01-06 05:24:50 +00003522 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003523 return;
3524
Richard Trieu1838ca52011-05-29 19:59:02 +00003525 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3526 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3527 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3528 << E->getSourceRange() << clang::SourceRange(CC);
3529 return;
3530 }
3531
John McCall323ed742010-05-06 08:58:33 +00003532 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003533 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003534
3535 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003536 // If the source is a constant, use a default-on diagnostic.
3537 // TODO: this should happen for bitfield stores, too.
3538 llvm::APSInt Value(32);
3539 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003540 if (isFromSystemMacro(S, CC))
3541 return;
3542
John McCall091f23f2010-11-09 22:22:12 +00003543 std::string PrettySourceValue = Value.toString(10);
3544 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3545
3546 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3547 << PrettySourceValue << PrettyTargetValue
3548 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3549 return;
3550 }
3551
Chris Lattnerb792b302011-06-14 04:51:15 +00003552 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003553 if (isFromSystemMacro(S, CC))
3554 return;
3555
John McCallf2370c92010-01-06 05:24:50 +00003556 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003557 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3558 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003559 }
3560
3561 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3562 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3563 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003564
3565 if (isFromSystemMacro(S, CC))
3566 return;
3567
John McCall323ed742010-05-06 08:58:33 +00003568 unsigned DiagID = diag::warn_impcast_integer_sign;
3569
3570 // Traditionally, gcc has warned about this under -Wsign-compare.
3571 // We also want to warn about it in -Wconversion.
3572 // So if -Wconversion is off, use a completely identical diagnostic
3573 // in the sign-compare group.
3574 // The conditional-checking code will
3575 if (ICContext) {
3576 DiagID = diag::warn_impcast_integer_sign_conditional;
3577 *ICContext = true;
3578 }
3579
John McCallb4eb64d2010-10-08 02:01:28 +00003580 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003581 }
3582
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003583 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003584 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3585 // type, to give us better diagnostics.
3586 QualType SourceType = E->getType();
3587 if (!S.getLangOptions().CPlusPlus) {
3588 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3589 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3590 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3591 SourceType = S.Context.getTypeDeclType(Enum);
3592 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3593 }
3594 }
3595
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003596 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3597 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3598 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003599 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003600 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003601 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003602 SourceEnum != TargetEnum) {
3603 if (isFromSystemMacro(S, CC))
3604 return;
3605
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003606 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003607 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003608 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003609
John McCall51313c32010-01-04 23:31:57 +00003610 return;
3611}
3612
John McCall323ed742010-05-06 08:58:33 +00003613void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3614
3615void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003616 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003617 E = E->IgnoreParenImpCasts();
3618
3619 if (isa<ConditionalOperator>(E))
3620 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3621
John McCallb4eb64d2010-10-08 02:01:28 +00003622 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003623 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003624 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003625 return;
3626}
3627
3628void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003629 SourceLocation CC = E->getQuestionLoc();
3630
3631 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003632
3633 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003634 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3635 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003636
3637 // If -Wconversion would have warned about either of the candidates
3638 // for a signedness conversion to the context type...
3639 if (!Suspicious) return;
3640
3641 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003642 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3643 CC))
John McCall323ed742010-05-06 08:58:33 +00003644 return;
3645
John McCall323ed742010-05-06 08:58:33 +00003646 // ...then check whether it would have warned about either of the
3647 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003648 if (E->getType() == T) return;
3649
3650 Suspicious = false;
3651 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3652 E->getType(), CC, &Suspicious);
3653 if (!Suspicious)
3654 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003655 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003656}
3657
3658/// AnalyzeImplicitConversions - Find and report any interesting
3659/// implicit conversions in the given expression. There are a couple
3660/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003661void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003662 QualType T = OrigE->getType();
3663 Expr *E = OrigE->IgnoreParenImpCasts();
3664
Douglas Gregorf8b6e152011-10-10 17:38:18 +00003665 if (E->isTypeDependent() || E->isValueDependent())
3666 return;
3667
John McCall323ed742010-05-06 08:58:33 +00003668 // For conditional operators, we analyze the arguments as if they
3669 // were being fed directly into the output.
3670 if (isa<ConditionalOperator>(E)) {
3671 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3672 CheckConditionalOperator(S, CO, T);
3673 return;
3674 }
3675
3676 // Go ahead and check any implicit conversions we might have skipped.
3677 // The non-canonical typecheck is just an optimization;
3678 // CheckImplicitConversion will filter out dead implicit conversions.
3679 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003680 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003681
3682 // Now continue drilling into this expression.
3683
3684 // Skip past explicit casts.
3685 if (isa<ExplicitCastExpr>(E)) {
3686 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003687 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003688 }
3689
John McCallbeb22aa2010-11-09 23:24:47 +00003690 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3691 // Do a somewhat different check with comparison operators.
3692 if (BO->isComparisonOp())
3693 return AnalyzeComparison(S, BO);
3694
3695 // And with assignments and compound assignments.
3696 if (BO->isAssignmentOp())
3697 return AnalyzeAssignment(S, BO);
3698 }
John McCall323ed742010-05-06 08:58:33 +00003699
3700 // These break the otherwise-useful invariant below. Fortunately,
3701 // we don't really need to recurse into them, because any internal
3702 // expressions should have been analyzed already when they were
3703 // built into statements.
3704 if (isa<StmtExpr>(E)) return;
3705
3706 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003707 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003708
3709 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003710 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003711 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3712 bool IsLogicalOperator = BO && BO->isLogicalOp();
3713 for (Stmt::child_range I = E->children(); I; ++I) {
3714 Expr *ChildExpr = cast<Expr>(*I);
3715 if (IsLogicalOperator &&
3716 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3717 // Ignore checking string literals that are in logical operators.
3718 continue;
3719 AnalyzeImplicitConversions(S, ChildExpr, CC);
3720 }
John McCall323ed742010-05-06 08:58:33 +00003721}
3722
3723} // end anonymous namespace
3724
3725/// Diagnoses "dangerous" implicit conversions within the given
3726/// expression (which is a full expression). Implements -Wconversion
3727/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003728///
3729/// \param CC the "context" location of the implicit conversion, i.e.
3730/// the most location of the syntactic entity requiring the implicit
3731/// conversion
3732void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003733 // Don't diagnose in unevaluated contexts.
3734 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3735 return;
3736
3737 // Don't diagnose for value- or type-dependent expressions.
3738 if (E->isTypeDependent() || E->isValueDependent())
3739 return;
3740
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003741 // Check for array bounds violations in cases where the check isn't triggered
3742 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3743 // ArraySubscriptExpr is on the RHS of a variable initialization.
3744 CheckArrayAccess(E);
3745
John McCallb4eb64d2010-10-08 02:01:28 +00003746 // This is not the right CC for (e.g.) a variable initialization.
3747 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003748}
3749
John McCall15d7d122010-11-11 03:21:53 +00003750void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3751 FieldDecl *BitField,
3752 Expr *Init) {
3753 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3754}
3755
Mike Stumpf8c49212010-01-21 03:59:47 +00003756/// CheckParmsForFunctionDef - Check that the parameters of the given
3757/// function are appropriate for the definition of a function. This
3758/// takes care of any checks that cannot be performed on the
3759/// declaration itself, e.g., that the types of each of the function
3760/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003761bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3762 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003763 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003764 for (; P != PEnd; ++P) {
3765 ParmVarDecl *Param = *P;
3766
Mike Stumpf8c49212010-01-21 03:59:47 +00003767 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3768 // function declarator that is part of a function definition of
3769 // that function shall not have incomplete type.
3770 //
3771 // This is also C++ [dcl.fct]p6.
3772 if (!Param->isInvalidDecl() &&
3773 RequireCompleteType(Param->getLocation(), Param->getType(),
3774 diag::err_typecheck_decl_incomplete_type)) {
3775 Param->setInvalidDecl();
3776 HasInvalidParm = true;
3777 }
3778
3779 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3780 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003781 if (CheckParameterNames &&
3782 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003783 !Param->isImplicit() &&
3784 !getLangOptions().CPlusPlus)
3785 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003786
3787 // C99 6.7.5.3p12:
3788 // If the function declarator is not part of a definition of that
3789 // function, parameters may have incomplete type and may use the [*]
3790 // notation in their sequences of declarator specifiers to specify
3791 // variable length array types.
3792 QualType PType = Param->getOriginalType();
3793 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3794 if (AT->getSizeModifier() == ArrayType::Star) {
3795 // FIXME: This diagnosic should point the the '[*]' if source-location
3796 // information is added for it.
3797 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3798 }
3799 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003800 }
3801
3802 return HasInvalidParm;
3803}
John McCallb7f4ffe2010-08-12 21:44:57 +00003804
3805/// CheckCastAlign - Implements -Wcast-align, which warns when a
3806/// pointer cast increases the alignment requirements.
3807void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3808 // This is actually a lot of work to potentially be doing on every
3809 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003810 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3811 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00003812 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00003813 return;
3814
3815 // Ignore dependent types.
3816 if (T->isDependentType() || Op->getType()->isDependentType())
3817 return;
3818
3819 // Require that the destination be a pointer type.
3820 const PointerType *DestPtr = T->getAs<PointerType>();
3821 if (!DestPtr) return;
3822
3823 // If the destination has alignment 1, we're done.
3824 QualType DestPointee = DestPtr->getPointeeType();
3825 if (DestPointee->isIncompleteType()) return;
3826 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3827 if (DestAlign.isOne()) return;
3828
3829 // Require that the source be a pointer type.
3830 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3831 if (!SrcPtr) return;
3832 QualType SrcPointee = SrcPtr->getPointeeType();
3833
3834 // Whitelist casts from cv void*. We already implicitly
3835 // whitelisted casts to cv void*, since they have alignment 1.
3836 // Also whitelist casts involving incomplete types, which implicitly
3837 // includes 'void'.
3838 if (SrcPointee->isIncompleteType()) return;
3839
3840 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3841 if (SrcAlign >= DestAlign) return;
3842
3843 Diag(TRange.getBegin(), diag::warn_cast_align)
3844 << Op->getType() << T
3845 << static_cast<unsigned>(SrcAlign.getQuantity())
3846 << static_cast<unsigned>(DestAlign.getQuantity())
3847 << TRange << Op->getSourceRange();
3848}
3849
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003850static const Type* getElementType(const Expr *BaseExpr) {
3851 const Type* EltType = BaseExpr->getType().getTypePtr();
3852 if (EltType->isAnyPointerType())
3853 return EltType->getPointeeType().getTypePtr();
3854 else if (EltType->isArrayType())
3855 return EltType->getBaseElementTypeUnsafe();
3856 return EltType;
3857}
3858
Chandler Carruthc2684342011-08-05 09:10:50 +00003859/// \brief Check whether this array fits the idiom of a size-one tail padded
3860/// array member of a struct.
3861///
3862/// We avoid emitting out-of-bounds access warnings for such arrays as they are
3863/// commonly used to emulate flexible arrays in C89 code.
3864static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3865 const NamedDecl *ND) {
3866 if (Size != 1 || !ND) return false;
3867
3868 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3869 if (!FD) return false;
3870
3871 // Don't consider sizes resulting from macro expansions or template argument
3872 // substitution to form C89 tail-padded arrays.
3873 ConstantArrayTypeLoc TL =
3874 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3875 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3876 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3877 return false;
3878
3879 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3880 if (!RD || !RD->isStruct())
3881 return false;
3882
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00003883 // See if this is the last field decl in the record.
3884 const Decl *D = FD;
3885 while ((D = D->getNextDeclInContext()))
3886 if (isa<FieldDecl>(D))
3887 return false;
3888 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00003889}
3890
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003891void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3892 bool isSubscript, bool AllowOnePastEnd) {
3893 const Type* EffectiveType = getElementType(BaseExpr);
3894 BaseExpr = BaseExpr->IgnoreParenCasts();
3895 IndexExpr = IndexExpr->IgnoreParenCasts();
3896
Chandler Carruth34064582011-02-17 20:55:08 +00003897 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003898 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003899 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003900 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003901
Chandler Carruth34064582011-02-17 20:55:08 +00003902 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003903 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003904 llvm::APSInt index;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003905 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003906 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003907
Chandler Carruthba447122011-08-05 08:07:29 +00003908 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00003909 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3910 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00003911 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00003912 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00003913
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003914 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003915 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003916 if (!size.isStrictlyPositive())
3917 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003918
3919 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00003920 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003921 // Make sure we're comparing apples to apples when comparing index to size
3922 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3923 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00003924 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00003925 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003926 if (ptrarith_typesize != array_typesize) {
3927 // There's a cast to a different size type involved
3928 uint64_t ratio = array_typesize / ptrarith_typesize;
3929 // TODO: Be smarter about handling cases where array_typesize is not a
3930 // multiple of ptrarith_typesize
3931 if (ptrarith_typesize * ratio == array_typesize)
3932 size *= llvm::APInt(size.getBitWidth(), ratio);
3933 }
3934 }
3935
Chandler Carruth34064582011-02-17 20:55:08 +00003936 if (size.getBitWidth() > index.getBitWidth())
3937 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003938 else if (size.getBitWidth() < index.getBitWidth())
3939 size = size.sext(index.getBitWidth());
3940
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003941 // For array subscripting the index must be less than size, but for pointer
3942 // arithmetic also allow the index (offset) to be equal to size since
3943 // computing the next address after the end of the array is legal and
3944 // commonly done e.g. in C++ iterators and range-based for loops.
3945 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00003946 return;
3947
3948 // Also don't warn for arrays of size 1 which are members of some
3949 // structure. These are often used to approximate flexible arrays in C89
3950 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003951 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003952 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003953
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003954 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
3955 if (isSubscript)
3956 DiagID = diag::warn_array_index_exceeds_bounds;
3957
3958 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3959 PDiag(DiagID) << index.toString(10, true)
3960 << size.toString(10, true)
3961 << (unsigned)size.getLimitedValue(~0U)
3962 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003963 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003964 unsigned DiagID = diag::warn_array_index_precedes_bounds;
3965 if (!isSubscript) {
3966 DiagID = diag::warn_ptr_arith_precedes_bounds;
3967 if (index.isNegative()) index = -index;
3968 }
3969
3970 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3971 PDiag(DiagID) << index.toString(10, true)
3972 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003973 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003974
Chandler Carruth35001ca2011-02-17 21:10:52 +00003975 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003976 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3977 PDiag(diag::note_array_index_out_of_bounds)
3978 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003979}
3980
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003981void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003982 int AllowOnePastEnd = 0;
3983 while (expr) {
3984 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003985 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003986 case Stmt::ArraySubscriptExprClass: {
3987 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
3988 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
3989 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003990 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003991 }
3992 case Stmt::UnaryOperatorClass: {
3993 // Only unwrap the * and & unary operators
3994 const UnaryOperator *UO = cast<UnaryOperator>(expr);
3995 expr = UO->getSubExpr();
3996 switch (UO->getOpcode()) {
3997 case UO_AddrOf:
3998 AllowOnePastEnd++;
3999 break;
4000 case UO_Deref:
4001 AllowOnePastEnd--;
4002 break;
4003 default:
4004 return;
4005 }
4006 break;
4007 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004008 case Stmt::ConditionalOperatorClass: {
4009 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4010 if (const Expr *lhs = cond->getLHS())
4011 CheckArrayAccess(lhs);
4012 if (const Expr *rhs = cond->getRHS())
4013 CheckArrayAccess(rhs);
4014 return;
4015 }
4016 default:
4017 return;
4018 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004019 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004020}
John McCallf85e1932011-06-15 23:02:42 +00004021
4022//===--- CHECK: Objective-C retain cycles ----------------------------------//
4023
4024namespace {
4025 struct RetainCycleOwner {
4026 RetainCycleOwner() : Variable(0), Indirect(false) {}
4027 VarDecl *Variable;
4028 SourceRange Range;
4029 SourceLocation Loc;
4030 bool Indirect;
4031
4032 void setLocsFrom(Expr *e) {
4033 Loc = e->getExprLoc();
4034 Range = e->getSourceRange();
4035 }
4036 };
4037}
4038
4039/// Consider whether capturing the given variable can possibly lead to
4040/// a retain cycle.
4041static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4042 // In ARC, it's captured strongly iff the variable has __strong
4043 // lifetime. In MRR, it's captured strongly if the variable is
4044 // __block and has an appropriate type.
4045 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4046 return false;
4047
4048 owner.Variable = var;
4049 owner.setLocsFrom(ref);
4050 return true;
4051}
4052
4053static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4054 while (true) {
4055 e = e->IgnoreParens();
4056 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4057 switch (cast->getCastKind()) {
4058 case CK_BitCast:
4059 case CK_LValueBitCast:
4060 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004061 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004062 e = cast->getSubExpr();
4063 continue;
4064
4065 case CK_GetObjCProperty: {
4066 // Bail out if this isn't a strong explicit property.
4067 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
4068 if (pre->isImplicitProperty()) return false;
4069 ObjCPropertyDecl *property = pre->getExplicitProperty();
John McCall265941b2011-09-13 18:31:23 +00004070 if (!property->isRetaining() &&
John McCallf85e1932011-06-15 23:02:42 +00004071 !(property->getPropertyIvarDecl() &&
4072 property->getPropertyIvarDecl()->getType()
4073 .getObjCLifetime() == Qualifiers::OCL_Strong))
4074 return false;
4075
4076 owner.Indirect = true;
4077 e = const_cast<Expr*>(pre->getBase());
4078 continue;
4079 }
4080
4081 default:
4082 return false;
4083 }
4084 }
4085
4086 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4087 ObjCIvarDecl *ivar = ref->getDecl();
4088 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4089 return false;
4090
4091 // Try to find a retain cycle in the base.
4092 if (!findRetainCycleOwner(ref->getBase(), owner))
4093 return false;
4094
4095 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4096 owner.Indirect = true;
4097 return true;
4098 }
4099
4100 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4101 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4102 if (!var) return false;
4103 return considerVariable(var, ref, owner);
4104 }
4105
4106 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4107 owner.Variable = ref->getDecl();
4108 owner.setLocsFrom(ref);
4109 return true;
4110 }
4111
4112 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4113 if (member->isArrow()) return false;
4114
4115 // Don't count this as an indirect ownership.
4116 e = member->getBase();
4117 continue;
4118 }
4119
4120 // Array ivars?
4121
4122 return false;
4123 }
4124}
4125
4126namespace {
4127 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4128 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4129 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4130 Variable(variable), Capturer(0) {}
4131
4132 VarDecl *Variable;
4133 Expr *Capturer;
4134
4135 void VisitDeclRefExpr(DeclRefExpr *ref) {
4136 if (ref->getDecl() == Variable && !Capturer)
4137 Capturer = ref;
4138 }
4139
4140 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4141 if (ref->getDecl() == Variable && !Capturer)
4142 Capturer = ref;
4143 }
4144
4145 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4146 if (Capturer) return;
4147 Visit(ref->getBase());
4148 if (Capturer && ref->isFreeIvar())
4149 Capturer = ref;
4150 }
4151
4152 void VisitBlockExpr(BlockExpr *block) {
4153 // Look inside nested blocks
4154 if (block->getBlockDecl()->capturesVariable(Variable))
4155 Visit(block->getBlockDecl()->getBody());
4156 }
4157 };
4158}
4159
4160/// Check whether the given argument is a block which captures a
4161/// variable.
4162static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4163 assert(owner.Variable && owner.Loc.isValid());
4164
4165 e = e->IgnoreParenCasts();
4166 BlockExpr *block = dyn_cast<BlockExpr>(e);
4167 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4168 return 0;
4169
4170 FindCaptureVisitor visitor(S.Context, owner.Variable);
4171 visitor.Visit(block->getBlockDecl()->getBody());
4172 return visitor.Capturer;
4173}
4174
4175static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4176 RetainCycleOwner &owner) {
4177 assert(capturer);
4178 assert(owner.Variable && owner.Loc.isValid());
4179
4180 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4181 << owner.Variable << capturer->getSourceRange();
4182 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4183 << owner.Indirect << owner.Range;
4184}
4185
4186/// Check for a keyword selector that starts with the word 'add' or
4187/// 'set'.
4188static bool isSetterLikeSelector(Selector sel) {
4189 if (sel.isUnarySelector()) return false;
4190
Chris Lattner5f9e2722011-07-23 10:55:15 +00004191 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004192 while (!str.empty() && str.front() == '_') str = str.substr(1);
4193 if (str.startswith("set") || str.startswith("add"))
4194 str = str.substr(3);
4195 else
4196 return false;
4197
4198 if (str.empty()) return true;
4199 return !islower(str.front());
4200}
4201
4202/// Check a message send to see if it's likely to cause a retain cycle.
4203void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4204 // Only check instance methods whose selector looks like a setter.
4205 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4206 return;
4207
4208 // Try to find a variable that the receiver is strongly owned by.
4209 RetainCycleOwner owner;
4210 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4211 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4212 return;
4213 } else {
4214 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4215 owner.Variable = getCurMethodDecl()->getSelfDecl();
4216 owner.Loc = msg->getSuperLoc();
4217 owner.Range = msg->getSuperLoc();
4218 }
4219
4220 // Check whether the receiver is captured by any of the arguments.
4221 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4222 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4223 return diagnoseRetainCycle(*this, capturer, owner);
4224}
4225
4226/// Check a property assign to see if it's likely to cause a retain cycle.
4227void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4228 RetainCycleOwner owner;
4229 if (!findRetainCycleOwner(receiver, owner))
4230 return;
4231
4232 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4233 diagnoseRetainCycle(*this, capturer, owner);
4234}
4235
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004236bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004237 QualType LHS, Expr *RHS) {
4238 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4239 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004240 return false;
4241 // strip off any implicit cast added to get to the one arc-specific
4242 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004243 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004244 Diag(Loc, diag::warn_arc_retained_assign)
4245 << (LT == Qualifiers::OCL_ExplicitNone)
4246 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004247 return true;
4248 }
4249 RHS = cast->getSubExpr();
4250 }
4251 return false;
John McCallf85e1932011-06-15 23:02:42 +00004252}
4253
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004254void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4255 Expr *LHS, Expr *RHS) {
4256 QualType LHSType = LHS->getType();
4257 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4258 return;
4259 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4260 // FIXME. Check for other life times.
4261 if (LT != Qualifiers::OCL_None)
4262 return;
4263
4264 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
4265 if (PRE->isImplicitProperty())
4266 return;
4267 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4268 if (!PD)
4269 return;
4270
4271 unsigned Attributes = PD->getPropertyAttributes();
4272 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4273 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004274 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004275 Diag(Loc, diag::warn_arc_retained_property_assign)
4276 << RHS->getSourceRange();
4277 return;
4278 }
4279 RHS = cast->getSubExpr();
4280 }
4281 }
4282}