blob: 760b5f33b221b38bbf284752cddc42dc1bf38c0d [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) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000248 NeonTypeFlags Type(t);
249 int IsQuad = Type.isQuad();
250 switch (Type.getEltType()) {
251 case NeonTypeFlags::Int8:
252 case NeonTypeFlags::Poly8:
253 return shift ? 7 : (8 << IsQuad) - 1;
254 case NeonTypeFlags::Int16:
255 case NeonTypeFlags::Poly16:
256 return shift ? 15 : (4 << IsQuad) - 1;
257 case NeonTypeFlags::Int32:
258 return shift ? 31 : (2 << IsQuad) - 1;
259 case NeonTypeFlags::Int64:
260 return shift ? 63 : (1 << IsQuad) - 1;
261 case NeonTypeFlags::Float16:
262 assert(!shift && "cannot shift float types!");
263 return (4 << IsQuad) - 1;
264 case NeonTypeFlags::Float32:
265 assert(!shift && "cannot shift float types!");
266 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000267 }
268 return 0;
269}
270
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000271/// getNeonEltType - Return the QualType corresponding to the elements of
272/// the vector type specified by the NeonTypeFlags. This is used to check
273/// the pointer arguments for Neon load/store intrinsics.
274static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
275 switch (Flags.getEltType()) {
276 case NeonTypeFlags::Int8:
277 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
278 case NeonTypeFlags::Int16:
279 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
280 case NeonTypeFlags::Int32:
281 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
282 case NeonTypeFlags::Int64:
283 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
284 case NeonTypeFlags::Poly8:
285 return Context.SignedCharTy;
286 case NeonTypeFlags::Poly16:
287 return Context.ShortTy;
288 case NeonTypeFlags::Float16:
289 return Context.UnsignedShortTy;
290 case NeonTypeFlags::Float32:
291 return Context.FloatTy;
292 }
293 return QualType();
294}
295
Nate Begeman26a31422010-06-08 02:47:44 +0000296bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000297 llvm::APSInt Result;
298
Nate Begeman0d15c532010-06-13 04:47:52 +0000299 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000300 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000301 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000302 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000303 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000304#define GET_NEON_OVERLOAD_CHECK
305#include "clang/Basic/arm_neon.inc"
306#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000307 }
308
Nate Begeman0d15c532010-06-13 04:47:52 +0000309 // For NEON intrinsics which are overloaded on vector element type, validate
310 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000311 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000312 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000313 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000314 return true;
315
Bob Wilsonda95f732011-11-08 01:16:11 +0000316 TV = Result.getLimitedValue(64);
317 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000318 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000319 << TheCall->getArg(ImmArg)->getSourceRange();
320 }
321
Bob Wilson46482552011-11-16 21:32:23 +0000322 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000323 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000324 Expr *Arg = TheCall->getArg(PtrArgNum);
325 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
326 Arg = ICE->getSubExpr();
327 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
328 QualType RHSTy = RHS.get()->getType();
329 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
330 if (HasConstPtr)
331 EltTy = EltTy.withConst();
332 QualType LHSTy = Context.getPointerType(EltTy);
333 AssignConvertType ConvTy;
334 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
335 if (RHS.isInvalid())
336 return true;
337 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
338 RHS.get(), AA_Assigning))
339 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000340 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000341
Nate Begeman0d15c532010-06-13 04:47:52 +0000342 // For NEON intrinsics which take an immediate value as part of the
343 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000344 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000345 switch (BuiltinID) {
346 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000347 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
348 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000349 case ARM::BI__builtin_arm_vcvtr_f:
350 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000351#define GET_NEON_IMMEDIATE_CHECK
352#include "clang/Basic/arm_neon.inc"
353#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000354 };
355
Nate Begeman61eecf52010-06-14 05:21:25 +0000356 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000357 if (SemaBuiltinConstantArg(TheCall, i, Result))
358 return true;
359
Nate Begeman61eecf52010-06-14 05:21:25 +0000360 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000361 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000362 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000363 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000364 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000365
Nate Begeman99c40bb2010-08-03 21:32:34 +0000366 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000367 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000368}
Daniel Dunbarde454282008-10-02 18:44:07 +0000369
Anders Carlssond406bf02009-08-16 01:56:34 +0000370/// CheckFunctionCall - Check a direct function call for various correctness
371/// and safety properties not strictly enforced by the C type system.
372bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
373 // Get the IdentifierInfo* for the called function.
374 IdentifierInfo *FnInfo = FDecl->getIdentifier();
375
376 // None of the checks below are needed for functions that don't have
377 // simple names (e.g., C++ conversion functions).
378 if (!FnInfo)
379 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Daniel Dunbarde454282008-10-02 18:44:07 +0000381 // FIXME: This mechanism should be abstracted to be less fragile and
382 // more efficient. For example, just map function ids to custom
383 // handlers.
384
Ted Kremenekc82faca2010-09-09 04:33:05 +0000385 // Printf and scanf checking.
386 for (specific_attr_iterator<FormatAttr>
387 i = FDecl->specific_attr_begin<FormatAttr>(),
388 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
389
390 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000391 const bool b = Format->getType() == "scanf";
392 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000393 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000394 CheckPrintfScanfArguments(TheCall, HasVAListArg,
395 Format->getFormatIdx() - 1,
396 HasVAListArg ? 0 : Format->getFirstArg() - 1,
397 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000398 }
Chris Lattner59907c42007-08-10 20:18:51 +0000399 }
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Ted Kremenekc82faca2010-09-09 04:33:05 +0000401 for (specific_attr_iterator<NonNullAttr>
402 i = FDecl->specific_attr_begin<NonNullAttr>(),
403 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000404 CheckNonNullArguments(*i, TheCall->getArgs(),
405 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000406 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000407
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000408 // Builtin handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000409 int CMF = -1;
410 switch (FDecl->getBuiltinID()) {
411 case Builtin::BI__builtin_memset:
412 case Builtin::BI__builtin___memset_chk:
413 case Builtin::BImemset:
414 CMF = CMF_Memset;
415 break;
416
417 case Builtin::BI__builtin_memcpy:
418 case Builtin::BI__builtin___memcpy_chk:
419 case Builtin::BImemcpy:
420 CMF = CMF_Memcpy;
421 break;
422
423 case Builtin::BI__builtin_memmove:
424 case Builtin::BI__builtin___memmove_chk:
425 case Builtin::BImemmove:
426 CMF = CMF_Memmove;
427 break;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000428
429 case Builtin::BIstrlcpy:
430 case Builtin::BIstrlcat:
431 CheckStrlcpycatArguments(TheCall, FnInfo);
432 break;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000433
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000434 case Builtin::BI__builtin_memcmp:
435 CMF = CMF_Memcmp;
436 break;
437
Nico Webercda57822011-10-13 22:30:23 +0000438 case Builtin::BI__builtin_strncpy:
439 case Builtin::BI__builtin___strncpy_chk:
440 case Builtin::BIstrncpy:
441 CMF = CMF_Strncpy;
442 break;
443
444 case Builtin::BI__builtin_strncmp:
445 CMF = CMF_Strncmp;
446 break;
447
448 case Builtin::BI__builtin_strncasecmp:
449 CMF = CMF_Strncasecmp;
450 break;
451
452 case Builtin::BI__builtin_strncat:
453 case Builtin::BIstrncat:
454 CMF = CMF_Strncat;
455 break;
456
457 case Builtin::BI__builtin_strndup:
458 case Builtin::BIstrndup:
459 CMF = CMF_Strndup;
460 break;
461
Douglas Gregor707a23e2011-06-16 17:56:04 +0000462 default:
463 if (FDecl->getLinkage() == ExternalLinkage &&
464 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
465 if (FnInfo->isStr("memset"))
466 CMF = CMF_Memset;
467 else if (FnInfo->isStr("memcpy"))
468 CMF = CMF_Memcpy;
469 else if (FnInfo->isStr("memmove"))
470 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000471 else if (FnInfo->isStr("memcmp"))
472 CMF = CMF_Memcmp;
Nico Webercda57822011-10-13 22:30:23 +0000473 else if (FnInfo->isStr("strncpy"))
474 CMF = CMF_Strncpy;
475 else if (FnInfo->isStr("strncmp"))
476 CMF = CMF_Strncmp;
477 else if (FnInfo->isStr("strncasecmp"))
478 CMF = CMF_Strncasecmp;
479 else if (FnInfo->isStr("strncat"))
480 CMF = CMF_Strncat;
481 else if (FnInfo->isStr("strndup"))
482 CMF = CMF_Strndup;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000483 }
484 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000485 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000486
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000487 // Memset/memcpy/memmove handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000488 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000489 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000490
Anders Carlssond406bf02009-08-16 01:56:34 +0000491 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000492}
493
Anders Carlssond406bf02009-08-16 01:56:34 +0000494bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000495 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000496 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000497 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000498 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000500 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
501 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000502 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000504 QualType Ty = V->getType();
505 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000506 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Ted Kremenek826a3452010-07-16 02:11:22 +0000508 const bool b = Format->getType() == "scanf";
509 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000510 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Anders Carlssond406bf02009-08-16 01:56:34 +0000512 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000513 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
514 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000515
516 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000517}
518
Eli Friedman276b0612011-10-11 02:20:01 +0000519ExprResult
520Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
521 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
522 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000523
524 // All these operations take one of the following four forms:
525 // T __atomic_load(_Atomic(T)*, int) (loads)
526 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
527 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
528 // (cmpxchg)
529 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
530 // where T is an appropriate type, and the int paremeterss are for orderings.
531 unsigned NumVals = 1;
532 unsigned NumOrders = 1;
533 if (Op == AtomicExpr::Load) {
534 NumVals = 0;
535 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
536 NumVals = 2;
537 NumOrders = 2;
538 }
539
540 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
541 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
542 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
543 << TheCall->getCallee()->getSourceRange();
544 return ExprError();
545 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
546 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
547 diag::err_typecheck_call_too_many_args)
548 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
549 << TheCall->getCallee()->getSourceRange();
550 return ExprError();
551 }
552
553 // Inspect the first argument of the atomic operation. This should always be
554 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000555 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000556 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
557 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
558 if (!pointerType) {
559 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
560 << Ptr->getType() << Ptr->getSourceRange();
561 return ExprError();
562 }
563
564 QualType AtomTy = pointerType->getPointeeType();
565 if (!AtomTy->isAtomicType()) {
566 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
567 << Ptr->getType() << Ptr->getSourceRange();
568 return ExprError();
569 }
570 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
571
572 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
573 !ValType->isIntegerType() && !ValType->isPointerType()) {
574 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
575 << Ptr->getType() << Ptr->getSourceRange();
576 return ExprError();
577 }
578
579 if (!ValType->isIntegerType() &&
580 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
581 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
582 << Ptr->getType() << Ptr->getSourceRange();
583 return ExprError();
584 }
585
586 switch (ValType.getObjCLifetime()) {
587 case Qualifiers::OCL_None:
588 case Qualifiers::OCL_ExplicitNone:
589 // okay
590 break;
591
592 case Qualifiers::OCL_Weak:
593 case Qualifiers::OCL_Strong:
594 case Qualifiers::OCL_Autoreleasing:
595 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
596 << ValType << Ptr->getSourceRange();
597 return ExprError();
598 }
599
600 QualType ResultType = ValType;
601 if (Op == AtomicExpr::Store)
602 ResultType = Context.VoidTy;
603 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
604 ResultType = Context.BoolTy;
605
606 // The first argument --- the pointer --- has a fixed type; we
607 // deduce the types of the rest of the arguments accordingly. Walk
608 // the remaining arguments, converting them to the deduced value type.
609 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
610 ExprResult Arg = TheCall->getArg(i);
611 QualType Ty;
612 if (i < NumVals+1) {
613 // The second argument to a cmpxchg is a pointer to the data which will
614 // be exchanged. The second argument to a pointer add/subtract is the
615 // amount to add/subtract, which must be a ptrdiff_t. The third
616 // argument to a cmpxchg and the second argument in all other cases
617 // is the type of the value.
618 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
619 Op == AtomicExpr::CmpXchgStrong))
620 Ty = Context.getPointerType(ValType.getUnqualifiedType());
621 else if (!ValType->isIntegerType() &&
622 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
623 Ty = Context.getPointerDiffType();
624 else
625 Ty = ValType;
626 } else {
627 // The order(s) are always converted to int.
628 Ty = Context.IntTy;
629 }
630 InitializedEntity Entity =
631 InitializedEntity::InitializeParameter(Context, Ty, false);
632 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
633 if (Arg.isInvalid())
634 return true;
635 TheCall->setArg(i, Arg.get());
636 }
637
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000638 SmallVector<Expr*, 5> SubExprs;
639 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000640 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000641 SubExprs.push_back(TheCall->getArg(1)); // Order
Eli Friedman276b0612011-10-11 02:20:01 +0000642 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000643 SubExprs.push_back(TheCall->getArg(2)); // Order
644 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000645 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000646 SubExprs.push_back(TheCall->getArg(3)); // Order
647 SubExprs.push_back(TheCall->getArg(1)); // Val1
648 SubExprs.push_back(TheCall->getArg(2)); // Val2
649 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000650 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000651
652 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
653 SubExprs.data(), SubExprs.size(),
654 ResultType, Op,
655 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000656}
657
658
John McCall5f8d6042011-08-27 01:09:30 +0000659/// checkBuiltinArgument - Given a call to a builtin function, perform
660/// normal type-checking on the given argument, updating the call in
661/// place. This is useful when a builtin function requires custom
662/// type-checking for some of its arguments but not necessarily all of
663/// them.
664///
665/// Returns true on error.
666static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
667 FunctionDecl *Fn = E->getDirectCallee();
668 assert(Fn && "builtin call without direct callee!");
669
670 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
671 InitializedEntity Entity =
672 InitializedEntity::InitializeParameter(S.Context, Param);
673
674 ExprResult Arg = E->getArg(0);
675 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
676 if (Arg.isInvalid())
677 return true;
678
679 E->setArg(ArgIndex, Arg.take());
680 return false;
681}
682
Chris Lattner5caa3702009-05-08 06:58:22 +0000683/// SemaBuiltinAtomicOverloaded - We have a call to a function like
684/// __sync_fetch_and_add, which is an overloaded function based on the pointer
685/// type of its first argument. The main ActOnCallExpr routines have already
686/// promoted the types of arguments because all of these calls are prototyped as
687/// void(...).
688///
689/// This function goes through and does final semantic checking for these
690/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000691ExprResult
692Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000693 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000694 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
695 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
696
697 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000698 if (TheCall->getNumArgs() < 1) {
699 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
700 << 0 << 1 << TheCall->getNumArgs()
701 << TheCall->getCallee()->getSourceRange();
702 return ExprError();
703 }
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Chris Lattner5caa3702009-05-08 06:58:22 +0000705 // Inspect the first argument of the atomic builtin. This should always be
706 // a pointer type, whose element is an integral scalar or pointer type.
707 // Because it is a pointer type, we don't have to worry about any implicit
708 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000709 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000710 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000711 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
712 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000713 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
714 << FirstArg->getType() << FirstArg->getSourceRange();
715 return ExprError();
716 }
Mike Stump1eb44332009-09-09 15:08:12 +0000717
John McCallf85e1932011-06-15 23:02:42 +0000718 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000719 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000720 !ValType->isBlockPointerType()) {
721 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
722 << FirstArg->getType() << FirstArg->getSourceRange();
723 return ExprError();
724 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000725
John McCallf85e1932011-06-15 23:02:42 +0000726 switch (ValType.getObjCLifetime()) {
727 case Qualifiers::OCL_None:
728 case Qualifiers::OCL_ExplicitNone:
729 // okay
730 break;
731
732 case Qualifiers::OCL_Weak:
733 case Qualifiers::OCL_Strong:
734 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000735 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000736 << ValType << FirstArg->getSourceRange();
737 return ExprError();
738 }
739
John McCallb45ae252011-10-05 07:41:44 +0000740 // Strip any qualifiers off ValType.
741 ValType = ValType.getUnqualifiedType();
742
Chandler Carruth8d13d222010-07-18 20:54:12 +0000743 // The majority of builtins return a value, but a few have special return
744 // types, so allow them to override appropriately below.
745 QualType ResultType = ValType;
746
Chris Lattner5caa3702009-05-08 06:58:22 +0000747 // We need to figure out which concrete builtin this maps onto. For example,
748 // __sync_fetch_and_add with a 2 byte object turns into
749 // __sync_fetch_and_add_2.
750#define BUILTIN_ROW(x) \
751 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
752 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000753
Chris Lattner5caa3702009-05-08 06:58:22 +0000754 static const unsigned BuiltinIndices[][5] = {
755 BUILTIN_ROW(__sync_fetch_and_add),
756 BUILTIN_ROW(__sync_fetch_and_sub),
757 BUILTIN_ROW(__sync_fetch_and_or),
758 BUILTIN_ROW(__sync_fetch_and_and),
759 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Chris Lattner5caa3702009-05-08 06:58:22 +0000761 BUILTIN_ROW(__sync_add_and_fetch),
762 BUILTIN_ROW(__sync_sub_and_fetch),
763 BUILTIN_ROW(__sync_and_and_fetch),
764 BUILTIN_ROW(__sync_or_and_fetch),
765 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Chris Lattner5caa3702009-05-08 06:58:22 +0000767 BUILTIN_ROW(__sync_val_compare_and_swap),
768 BUILTIN_ROW(__sync_bool_compare_and_swap),
769 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000770 BUILTIN_ROW(__sync_lock_release),
771 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000772 };
Mike Stump1eb44332009-09-09 15:08:12 +0000773#undef BUILTIN_ROW
774
Chris Lattner5caa3702009-05-08 06:58:22 +0000775 // Determine the index of the size.
776 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000777 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000778 case 1: SizeIndex = 0; break;
779 case 2: SizeIndex = 1; break;
780 case 4: SizeIndex = 2; break;
781 case 8: SizeIndex = 3; break;
782 case 16: SizeIndex = 4; break;
783 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000784 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
785 << FirstArg->getType() << FirstArg->getSourceRange();
786 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000787 }
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Chris Lattner5caa3702009-05-08 06:58:22 +0000789 // Each of these builtins has one pointer argument, followed by some number of
790 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
791 // that we ignore. Find out which row of BuiltinIndices to read from as well
792 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000793 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000794 unsigned BuiltinIndex, NumFixed = 1;
795 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000796 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Chris Lattner5caa3702009-05-08 06:58:22 +0000797 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
798 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
799 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
800 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
801 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000803 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
804 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
805 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
806 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
807 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Chris Lattner5caa3702009-05-08 06:58:22 +0000809 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000810 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000811 NumFixed = 2;
812 break;
813 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000814 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000815 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000816 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000817 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000818 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000819 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000820 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000821 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000822 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000823 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000824 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000825 }
Mike Stump1eb44332009-09-09 15:08:12 +0000826
Chris Lattner5caa3702009-05-08 06:58:22 +0000827 // Now that we know how many fixed arguments we expect, first check that we
828 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000829 if (TheCall->getNumArgs() < 1+NumFixed) {
830 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
831 << 0 << 1+NumFixed << TheCall->getNumArgs()
832 << TheCall->getCallee()->getSourceRange();
833 return ExprError();
834 }
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000836 // Get the decl for the concrete builtin from this, we can tell what the
837 // concrete integer type we should convert to is.
838 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
839 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
840 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000841 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000842 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
843 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000844
John McCallf871d0c2010-08-07 06:22:56 +0000845 // The first argument --- the pointer --- has a fixed type; we
846 // deduce the types of the rest of the arguments accordingly. Walk
847 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000848 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000849 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000850
Chris Lattner5caa3702009-05-08 06:58:22 +0000851 // GCC does an implicit conversion to the pointer or integer ValType. This
852 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000853 // Initialize the argument.
854 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
855 ValType, /*consume*/ false);
856 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000857 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000858 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Chris Lattner5caa3702009-05-08 06:58:22 +0000860 // Okay, we have something that *can* be converted to the right type. Check
861 // to see if there is a potentially weird extension going on here. This can
862 // happen when you do an atomic operation on something like an char* and
863 // pass in 42. The 42 gets converted to char. This is even more strange
864 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000865 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000866 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000867 }
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000869 ASTContext& Context = this->getASTContext();
870
871 // Create a new DeclRefExpr to refer to the new decl.
872 DeclRefExpr* NewDRE = DeclRefExpr::Create(
873 Context,
874 DRE->getQualifierLoc(),
875 NewBuiltinDecl,
876 DRE->getLocation(),
877 NewBuiltinDecl->getType(),
878 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Chris Lattner5caa3702009-05-08 06:58:22 +0000880 // Set the callee in the CallExpr.
881 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000882 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +0000883 if (PromotedCall.isInvalid())
884 return ExprError();
885 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000887 // Change the result type of the call to match the original value type. This
888 // is arbitrary, but the codegen for these builtins ins design to handle it
889 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000890 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000891
892 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000893}
894
Chris Lattner69039812009-02-18 06:01:06 +0000895/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000896/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000897/// Note: It might also make sense to do the UTF-16 conversion here (would
898/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000899bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000900 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000901 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
902
Douglas Gregor5cee1192011-07-27 05:40:30 +0000903 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000904 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
905 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000906 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000907 }
Mike Stump1eb44332009-09-09 15:08:12 +0000908
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000909 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000910 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000911 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000912 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000913 const UTF8 *FromPtr = (UTF8 *)String.data();
914 UTF16 *ToPtr = &ToBuf[0];
915
916 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
917 &ToPtr, ToPtr + NumBytes,
918 strictConversion);
919 // Check for conversion failure.
920 if (Result != conversionOK)
921 Diag(Arg->getLocStart(),
922 diag::warn_cfstring_truncated) << Arg->getSourceRange();
923 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000924 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000925}
926
Chris Lattnerc27c6652007-12-20 00:05:45 +0000927/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
928/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000929bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
930 Expr *Fn = TheCall->getCallee();
931 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000932 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000933 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000934 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
935 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000936 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000937 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000938 return true;
939 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000940
941 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000942 return Diag(TheCall->getLocEnd(),
943 diag::err_typecheck_call_too_few_args_at_least)
944 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000945 }
946
John McCall5f8d6042011-08-27 01:09:30 +0000947 // Type-check the first argument normally.
948 if (checkBuiltinArgument(*this, TheCall, 0))
949 return true;
950
Chris Lattnerc27c6652007-12-20 00:05:45 +0000951 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000952 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000953 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000954 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000955 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000956 else if (FunctionDecl *FD = getCurFunctionDecl())
957 isVariadic = FD->isVariadic();
958 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000959 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattnerc27c6652007-12-20 00:05:45 +0000961 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000962 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
963 return true;
964 }
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Chris Lattner30ce3442007-12-19 23:59:04 +0000966 // Verify that the second argument to the builtin is the last argument of the
967 // current function or method.
968 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000969 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Anders Carlsson88cf2262008-02-11 04:20:54 +0000971 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
972 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000973 // FIXME: This isn't correct for methods (results in bogus warning).
974 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000975 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000976 if (CurBlock)
977 LastArg = *(CurBlock->TheDecl->param_end()-1);
978 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000979 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000980 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000981 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000982 SecondArgIsLastNamedArgument = PV == LastArg;
983 }
984 }
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Chris Lattner30ce3442007-12-19 23:59:04 +0000986 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000987 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000988 diag::warn_second_parameter_of_va_start_not_last_named_argument);
989 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000990}
Chris Lattner30ce3442007-12-19 23:59:04 +0000991
Chris Lattner1b9a0792007-12-20 00:26:33 +0000992/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
993/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000994bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
995 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000996 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000997 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000998 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000999 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001000 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001001 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001002 << SourceRange(TheCall->getArg(2)->getLocStart(),
1003 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001004
John Wiegley429bb272011-04-08 18:41:53 +00001005 ExprResult OrigArg0 = TheCall->getArg(0);
1006 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001007
Chris Lattner1b9a0792007-12-20 00:26:33 +00001008 // Do standard promotions between the two arguments, returning their common
1009 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001010 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001011 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1012 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001013
1014 // Make sure any conversions are pushed back into the call; this is
1015 // type safe since unordered compare builtins are declared as "_Bool
1016 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001017 TheCall->setArg(0, OrigArg0.get());
1018 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001019
John Wiegley429bb272011-04-08 18:41:53 +00001020 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001021 return false;
1022
Chris Lattner1b9a0792007-12-20 00:26:33 +00001023 // If the common type isn't a real floating type, then the arguments were
1024 // invalid for this operation.
1025 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001026 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001027 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001028 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1029 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Chris Lattner1b9a0792007-12-20 00:26:33 +00001031 return false;
1032}
1033
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001034/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1035/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001036/// to check everything. We expect the last argument to be a floating point
1037/// value.
1038bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1039 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001040 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001041 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001042 if (TheCall->getNumArgs() > NumArgs)
1043 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001044 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001045 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001046 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001047 (*(TheCall->arg_end()-1))->getLocEnd());
1048
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001049 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Eli Friedman9ac6f622009-08-31 20:06:00 +00001051 if (OrigArg->isTypeDependent())
1052 return false;
1053
Chris Lattner81368fb2010-05-06 05:50:07 +00001054 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001055 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001056 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001057 diag::err_typecheck_call_invalid_unary_fp)
1058 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Chris Lattner81368fb2010-05-06 05:50:07 +00001060 // If this is an implicit conversion from float -> double, remove it.
1061 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1062 Expr *CastArg = Cast->getSubExpr();
1063 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1064 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1065 "promotion from float to double is the only expected cast here");
1066 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001067 TheCall->setArg(NumArgs-1, CastArg);
1068 OrigArg = CastArg;
1069 }
1070 }
1071
Eli Friedman9ac6f622009-08-31 20:06:00 +00001072 return false;
1073}
1074
Eli Friedmand38617c2008-05-14 19:38:39 +00001075/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1076// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001077ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001078 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001079 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001080 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001081 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001082 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001083
Nate Begeman37b6a572010-06-08 00:16:34 +00001084 // Determine which of the following types of shufflevector we're checking:
1085 // 1) unary, vector mask: (lhs, mask)
1086 // 2) binary, vector mask: (lhs, rhs, mask)
1087 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1088 QualType resType = TheCall->getArg(0)->getType();
1089 unsigned numElements = 0;
1090
Douglas Gregorcde01732009-05-19 22:10:17 +00001091 if (!TheCall->getArg(0)->isTypeDependent() &&
1092 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001093 QualType LHSType = TheCall->getArg(0)->getType();
1094 QualType RHSType = TheCall->getArg(1)->getType();
1095
1096 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001097 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001098 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001099 TheCall->getArg(1)->getLocEnd());
1100 return ExprError();
1101 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001102
1103 numElements = LHSType->getAs<VectorType>()->getNumElements();
1104 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Nate Begeman37b6a572010-06-08 00:16:34 +00001106 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1107 // with mask. If so, verify that RHS is an integer vector type with the
1108 // same number of elts as lhs.
1109 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001110 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001111 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1112 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1113 << SourceRange(TheCall->getArg(1)->getLocStart(),
1114 TheCall->getArg(1)->getLocEnd());
1115 numResElements = numElements;
1116 }
1117 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001118 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001119 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001120 TheCall->getArg(1)->getLocEnd());
1121 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001122 } else if (numElements != numResElements) {
1123 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001124 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001125 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001126 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001127 }
1128
1129 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001130 if (TheCall->getArg(i)->isTypeDependent() ||
1131 TheCall->getArg(i)->isValueDependent())
1132 continue;
1133
Nate Begeman37b6a572010-06-08 00:16:34 +00001134 llvm::APSInt Result(32);
1135 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1136 return ExprError(Diag(TheCall->getLocStart(),
1137 diag::err_shufflevector_nonconstant_argument)
1138 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001139
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001140 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001141 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001142 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001143 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001144 }
1145
Chris Lattner5f9e2722011-07-23 10:55:15 +00001146 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001147
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001148 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001149 exprs.push_back(TheCall->getArg(i));
1150 TheCall->setArg(i, 0);
1151 }
1152
Nate Begemana88dc302009-08-12 02:10:25 +00001153 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001154 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001155 TheCall->getCallee()->getLocStart(),
1156 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001157}
Chris Lattner30ce3442007-12-19 23:59:04 +00001158
Daniel Dunbar4493f792008-07-21 22:59:13 +00001159/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1160// This is declared to take (const void*, ...) and can take two
1161// optional constant int args.
1162bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001163 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001164
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001165 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001166 return Diag(TheCall->getLocEnd(),
1167 diag::err_typecheck_call_too_many_args_at_most)
1168 << 0 /*function call*/ << 3 << NumArgs
1169 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001170
1171 // Argument 0 is checked for us and the remaining arguments must be
1172 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001173 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001174 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001175
Eli Friedman9aef7262009-12-04 00:30:06 +00001176 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001177 if (SemaBuiltinConstantArg(TheCall, i, Result))
1178 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Daniel Dunbar4493f792008-07-21 22:59:13 +00001180 // FIXME: gcc issues a warning and rewrites these to 0. These
1181 // seems especially odd for the third argument since the default
1182 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001183 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001184 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001185 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001186 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001187 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001188 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001189 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001190 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001191 }
1192 }
1193
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001194 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001195}
1196
Eric Christopher691ebc32010-04-17 02:26:23 +00001197/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1198/// TheCall is a constant expression.
1199bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1200 llvm::APSInt &Result) {
1201 Expr *Arg = TheCall->getArg(ArgNum);
1202 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1203 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1204
1205 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1206
1207 if (!Arg->isIntegerConstantExpr(Result, Context))
1208 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001209 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001210
Chris Lattner21fb98e2009-09-23 06:06:36 +00001211 return false;
1212}
1213
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001214/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1215/// int type). This simply type checks that type is one of the defined
1216/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001217// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001218bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001219 llvm::APSInt Result;
1220
1221 // Check constant-ness first.
1222 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1223 return true;
1224
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001225 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001226 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001227 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1228 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001229 }
1230
1231 return false;
1232}
1233
Eli Friedman586d6a82009-05-03 06:04:26 +00001234/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001235/// This checks that val is a constant 1.
1236bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1237 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001238 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001239
Eric Christopher691ebc32010-04-17 02:26:23 +00001240 // TODO: This is less than ideal. Overload this to take a value.
1241 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1242 return true;
1243
1244 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001245 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1246 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1247
1248 return false;
1249}
1250
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001251// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +00001252bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1253 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001254 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001255 bool isPrintf, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001256 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001257 if (E->isTypeDependent() || E->isValueDependent())
1258 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001259
Peter Collingbournef111d932011-04-15 00:35:48 +00001260 E = E->IgnoreParens();
1261
Ted Kremenekd30ef872009-01-12 23:09:09 +00001262 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001263 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001264 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001265 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001266 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001267 format_idx, firstDataArg, isPrintf,
1268 inFunctionCall)
John McCall56ca35d2011-02-17 10:25:35 +00001269 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001270 format_idx, firstDataArg, isPrintf,
1271 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001272 }
1273
Ted Kremenek95355bb2010-09-09 03:51:42 +00001274 case Stmt::IntegerLiteralClass:
1275 // Technically -Wformat-nonliteral does not warn about this case.
1276 // The behavior of printf and friends in this case is implementation
1277 // dependent. Ideally if the format string cannot be null then
1278 // it should have a 'nonnull' attribute in the function prototype.
1279 return true;
1280
Ted Kremenekd30ef872009-01-12 23:09:09 +00001281 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001282 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1283 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001284 }
1285
John McCall56ca35d2011-02-17 10:25:35 +00001286 case Stmt::OpaqueValueExprClass:
1287 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1288 E = src;
1289 goto tryAgain;
1290 }
1291 return false;
1292
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001293 case Stmt::PredefinedExprClass:
1294 // While __func__, etc., are technically not string literals, they
1295 // cannot contain format specifiers and thus are not a security
1296 // liability.
1297 return true;
1298
Ted Kremenek082d9362009-03-20 21:35:28 +00001299 case Stmt::DeclRefExprClass: {
1300 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Ted Kremenek082d9362009-03-20 21:35:28 +00001302 // As an exception, do not flag errors for variables binding to
1303 // const string literals.
1304 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1305 bool isConstant = false;
1306 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001307
Ted Kremenek082d9362009-03-20 21:35:28 +00001308 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1309 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001310 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001311 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001312 PT->getPointeeType().isConstant(Context);
1313 }
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Ted Kremenek082d9362009-03-20 21:35:28 +00001315 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001316 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001317 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001318 HasVAListArg, format_idx, firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001319 isPrintf, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001320 }
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Anders Carlssond966a552009-06-28 19:55:58 +00001322 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1323 // special check to see if the format string is a function parameter
1324 // of the function calling the printf function. If the function
1325 // has an attribute indicating it is a printf-like function, then we
1326 // should suppress warnings concerning non-literals being used in a call
1327 // to a vprintf function. For example:
1328 //
1329 // void
1330 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1331 // va_list ap;
1332 // va_start(ap, fmt);
1333 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1334 // ...
1335 //
1336 //
1337 // FIXME: We don't have full attribute support yet, so just check to see
1338 // if the argument is a DeclRefExpr that references a parameter. We'll
1339 // add proper support for checking the attribute later.
1340 if (HasVAListArg)
1341 if (isa<ParmVarDecl>(VD))
1342 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001343 }
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Ted Kremenek082d9362009-03-20 21:35:28 +00001345 return false;
1346 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001347
Anders Carlsson8f031b32009-06-27 04:05:33 +00001348 case Stmt::CallExprClass: {
1349 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001350 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001351 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1352 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1353 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001354 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001355 unsigned ArgIndex = FA->getFormatIdx();
1356 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001357
1358 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001359 format_idx, firstDataArg, isPrintf,
1360 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001361 }
1362 }
1363 }
1364 }
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Anders Carlsson8f031b32009-06-27 04:05:33 +00001366 return false;
1367 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001368 case Stmt::ObjCStringLiteralClass:
1369 case Stmt::StringLiteralClass: {
1370 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Ted Kremenek082d9362009-03-20 21:35:28 +00001372 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001373 StrE = ObjCFExpr->getString();
1374 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001375 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Ted Kremenekd30ef872009-01-12 23:09:09 +00001377 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001378 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00001379 firstDataArg, isPrintf, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001380 return true;
1381 }
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Ted Kremenekd30ef872009-01-12 23:09:09 +00001383 return false;
1384 }
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Ted Kremenek082d9362009-03-20 21:35:28 +00001386 default:
1387 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001388 }
1389}
1390
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001391void
Mike Stump1eb44332009-09-09 15:08:12 +00001392Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001393 const Expr * const *ExprArgs,
1394 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001395 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1396 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001397 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001398 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001399 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001400 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001401 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001402 }
1403}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001404
Ted Kremenek826a3452010-07-16 02:11:22 +00001405/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1406/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001407void
Ted Kremenek826a3452010-07-16 02:11:22 +00001408Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1409 unsigned format_idx, unsigned firstDataArg,
1410 bool isPrintf) {
1411
Ted Kremenek082d9362009-03-20 21:35:28 +00001412 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001413
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001414 // The way the format attribute works in GCC, the implicit this argument
1415 // of member functions is counted. However, it doesn't appear in our own
1416 // lists, so decrement format_idx in that case.
1417 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001418 const CXXMethodDecl *method_decl =
1419 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1420 if (method_decl && method_decl->isInstance()) {
1421 // Catch a format attribute mistakenly referring to the object argument.
1422 if (format_idx == 0)
1423 return;
1424 --format_idx;
1425 if(firstDataArg != 0)
1426 --firstDataArg;
1427 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001428 }
1429
Ted Kremenek826a3452010-07-16 02:11:22 +00001430 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001431 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001432 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001433 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001434 return;
1435 }
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Ted Kremenek082d9362009-03-20 21:35:28 +00001437 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001438
Chris Lattner59907c42007-08-10 20:18:51 +00001439 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001440 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001441 // Dynamically generated format strings are difficult to
1442 // automatically vet at compile time. Requiring that format strings
1443 // are string literals: (1) permits the checking of format strings by
1444 // the compiler and thereby (2) can practically remove the source of
1445 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001446
Mike Stump1eb44332009-09-09 15:08:12 +00001447 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001448 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001449 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001450 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001451 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001452 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001453 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001454
Chris Lattner655f1412009-04-29 04:59:47 +00001455 // If there are no arguments specified, warn with -Wformat-security, otherwise
1456 // warn only with -Wformat-nonliteral.
1457 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001458 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001459 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001460 << OrigFormatExpr->getSourceRange();
1461 else
Mike Stump1eb44332009-09-09 15:08:12 +00001462 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001463 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001464 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001465}
Ted Kremenek71895b92007-08-14 17:39:48 +00001466
Ted Kremeneke0e53132010-01-28 23:39:18 +00001467namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001468class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1469protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001470 Sema &S;
1471 const StringLiteral *FExpr;
1472 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001473 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001474 const unsigned NumDataArgs;
1475 const bool IsObjCLiteral;
1476 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001477 const bool HasVAListArg;
1478 const CallExpr *TheCall;
1479 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001480 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001481 bool usesPositionalArgs;
1482 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001483 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001484public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001485 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001486 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001487 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001488 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001489 const CallExpr *theCall, unsigned formatIdx,
1490 bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001491 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001492 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001493 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001494 IsObjCLiteral(isObjCLiteral), Beg(beg),
1495 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001496 TheCall(theCall), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001497 usesPositionalArgs(false), atFirstArg(true),
1498 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001499 CoveredArgs.resize(numDataArgs);
1500 CoveredArgs.reset();
1501 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001502
Ted Kremenek07d161f2010-01-29 01:50:07 +00001503 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001504
Ted Kremenek826a3452010-07-16 02:11:22 +00001505 void HandleIncompleteSpecifier(const char *startSpecifier,
1506 unsigned specifierLen);
1507
Ted Kremenekefaff192010-02-27 01:41:03 +00001508 virtual void HandleInvalidPosition(const char *startSpecifier,
1509 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001510 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001511
1512 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1513
Ted Kremeneke0e53132010-01-28 23:39:18 +00001514 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001515
Richard Trieu55733de2011-10-28 00:41:25 +00001516 template <typename Range>
1517 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1518 const Expr *ArgumentExpr,
1519 PartialDiagnostic PDiag,
1520 SourceLocation StringLoc,
1521 bool IsStringLocation, Range StringRange,
1522 FixItHint Fixit = FixItHint());
1523
Ted Kremenek826a3452010-07-16 02:11:22 +00001524protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001525 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1526 const char *startSpec,
1527 unsigned specifierLen,
1528 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001529
1530 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1531 const char *startSpec,
1532 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001533
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001534 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001535 CharSourceRange getSpecifierRange(const char *startSpecifier,
1536 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001537 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001538
Ted Kremenek0d277352010-01-29 01:06:55 +00001539 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001540
1541 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1542 const analyze_format_string::ConversionSpecifier &CS,
1543 const char *startSpecifier, unsigned specifierLen,
1544 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001545
1546 template <typename Range>
1547 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1548 bool IsStringLocation, Range StringRange,
1549 FixItHint Fixit = FixItHint());
1550
1551 void CheckPositionalAndNonpositionalArgs(
1552 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001553};
1554}
1555
Ted Kremenek826a3452010-07-16 02:11:22 +00001556SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001557 return OrigFormatExpr->getSourceRange();
1558}
1559
Ted Kremenek826a3452010-07-16 02:11:22 +00001560CharSourceRange CheckFormatHandler::
1561getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001562 SourceLocation Start = getLocationOfByte(startSpecifier);
1563 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1564
1565 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001566 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001567
1568 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001569}
1570
Ted Kremenek826a3452010-07-16 02:11:22 +00001571SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001572 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001573}
1574
Ted Kremenek826a3452010-07-16 02:11:22 +00001575void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1576 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001577 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1578 getLocationOfByte(startSpecifier),
1579 /*IsStringLocation*/true,
1580 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001581}
1582
Ted Kremenekefaff192010-02-27 01:41:03 +00001583void
Ted Kremenek826a3452010-07-16 02:11:22 +00001584CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1585 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001586 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1587 << (unsigned) p,
1588 getLocationOfByte(startPos), /*IsStringLocation*/true,
1589 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001590}
1591
Ted Kremenek826a3452010-07-16 02:11:22 +00001592void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001593 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001594 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1595 getLocationOfByte(startPos),
1596 /*IsStringLocation*/true,
1597 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001598}
1599
Ted Kremenek826a3452010-07-16 02:11:22 +00001600void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001601 if (!IsObjCLiteral) {
1602 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001603 EmitFormatDiagnostic(
1604 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1605 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1606 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001607 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001608}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001609
Ted Kremenek826a3452010-07-16 02:11:22 +00001610const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1611 return TheCall->getArg(FirstDataArg + i);
1612}
1613
1614void CheckFormatHandler::DoneProcessing() {
1615 // Does the number of data arguments exceed the number of
1616 // format conversions in the format string?
1617 if (!HasVAListArg) {
1618 // Find any arguments that weren't covered.
1619 CoveredArgs.flip();
1620 signed notCoveredArg = CoveredArgs.find_first();
1621 if (notCoveredArg >= 0) {
1622 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001623 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1624 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1625 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001626 }
1627 }
1628}
1629
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001630bool
1631CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1632 SourceLocation Loc,
1633 const char *startSpec,
1634 unsigned specifierLen,
1635 const char *csStart,
1636 unsigned csLen) {
1637
1638 bool keepGoing = true;
1639 if (argIndex < NumDataArgs) {
1640 // Consider the argument coverered, even though the specifier doesn't
1641 // make sense.
1642 CoveredArgs.set(argIndex);
1643 }
1644 else {
1645 // If argIndex exceeds the number of data arguments we
1646 // don't issue a warning because that is just a cascade of warnings (and
1647 // they may have intended '%%' anyway). We don't want to continue processing
1648 // the format string after this point, however, as we will like just get
1649 // gibberish when trying to match arguments.
1650 keepGoing = false;
1651 }
1652
Richard Trieu55733de2011-10-28 00:41:25 +00001653 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1654 << StringRef(csStart, csLen),
1655 Loc, /*IsStringLocation*/true,
1656 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001657
1658 return keepGoing;
1659}
1660
Richard Trieu55733de2011-10-28 00:41:25 +00001661void
1662CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1663 const char *startSpec,
1664 unsigned specifierLen) {
1665 EmitFormatDiagnostic(
1666 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1667 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1668}
1669
Ted Kremenek666a1972010-07-26 19:45:42 +00001670bool
1671CheckFormatHandler::CheckNumArgs(
1672 const analyze_format_string::FormatSpecifier &FS,
1673 const analyze_format_string::ConversionSpecifier &CS,
1674 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1675
1676 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001677 PartialDiagnostic PDiag = FS.usesPositionalArg()
1678 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1679 << (argIndex+1) << NumDataArgs)
1680 : S.PDiag(diag::warn_printf_insufficient_data_args);
1681 EmitFormatDiagnostic(
1682 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1683 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001684 return false;
1685 }
1686 return true;
1687}
1688
Richard Trieu55733de2011-10-28 00:41:25 +00001689template<typename Range>
1690void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1691 SourceLocation Loc,
1692 bool IsStringLocation,
1693 Range StringRange,
1694 FixItHint FixIt) {
1695 EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
1696 Loc, IsStringLocation, StringRange, FixIt);
1697}
1698
1699/// \brief If the format string is not within the funcion call, emit a note
1700/// so that the function call and string are in diagnostic messages.
1701///
1702/// \param inFunctionCall if true, the format string is within the function
1703/// call and only one diagnostic message will be produced. Otherwise, an
1704/// extra note will be emitted pointing to location of the format string.
1705///
1706/// \param ArgumentExpr the expression that is passed as the format string
1707/// argument in the function call. Used for getting locations when two
1708/// diagnostics are emitted.
1709///
1710/// \param PDiag the callee should already have provided any strings for the
1711/// diagnostic message. This function only adds locations and fixits
1712/// to diagnostics.
1713///
1714/// \param Loc primary location for diagnostic. If two diagnostics are
1715/// required, one will be at Loc and a new SourceLocation will be created for
1716/// the other one.
1717///
1718/// \param IsStringLocation if true, Loc points to the format string should be
1719/// used for the note. Otherwise, Loc points to the argument list and will
1720/// be used with PDiag.
1721///
1722/// \param StringRange some or all of the string to highlight. This is
1723/// templated so it can accept either a CharSourceRange or a SourceRange.
1724///
1725/// \param Fixit optional fix it hint for the format string.
1726template<typename Range>
1727void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1728 const Expr *ArgumentExpr,
1729 PartialDiagnostic PDiag,
1730 SourceLocation Loc,
1731 bool IsStringLocation,
1732 Range StringRange,
1733 FixItHint FixIt) {
1734 if (InFunctionCall)
1735 S.Diag(Loc, PDiag) << StringRange << FixIt;
1736 else {
1737 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1738 << ArgumentExpr->getSourceRange();
1739 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1740 diag::note_format_string_defined)
1741 << StringRange << FixIt;
1742 }
1743}
1744
Ted Kremenek826a3452010-07-16 02:11:22 +00001745//===--- CHECK: Printf format string checking ------------------------------===//
1746
1747namespace {
1748class CheckPrintfHandler : public CheckFormatHandler {
1749public:
1750 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1751 const Expr *origFormatExpr, unsigned firstDataArg,
1752 unsigned numDataArgs, bool isObjCLiteral,
1753 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001754 const CallExpr *theCall, unsigned formatIdx,
1755 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001756 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1757 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00001758 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001759
1760
1761 bool HandleInvalidPrintfConversionSpecifier(
1762 const analyze_printf::PrintfSpecifier &FS,
1763 const char *startSpecifier,
1764 unsigned specifierLen);
1765
1766 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1767 const char *startSpecifier,
1768 unsigned specifierLen);
1769
1770 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1771 const char *startSpecifier, unsigned specifierLen);
1772 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1773 const analyze_printf::OptionalAmount &Amt,
1774 unsigned type,
1775 const char *startSpecifier, unsigned specifierLen);
1776 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1777 const analyze_printf::OptionalFlag &flag,
1778 const char *startSpecifier, unsigned specifierLen);
1779 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1780 const analyze_printf::OptionalFlag &ignoredFlag,
1781 const analyze_printf::OptionalFlag &flag,
1782 const char *startSpecifier, unsigned specifierLen);
1783};
1784}
1785
1786bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1787 const analyze_printf::PrintfSpecifier &FS,
1788 const char *startSpecifier,
1789 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001790 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001791 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001792
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001793 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1794 getLocationOfByte(CS.getStart()),
1795 startSpecifier, specifierLen,
1796 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001797}
1798
Ted Kremenek826a3452010-07-16 02:11:22 +00001799bool CheckPrintfHandler::HandleAmount(
1800 const analyze_format_string::OptionalAmount &Amt,
1801 unsigned k, const char *startSpecifier,
1802 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001803
1804 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001805 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001806 unsigned argIndex = Amt.getArgIndex();
1807 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001808 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1809 << k,
1810 getLocationOfByte(Amt.getStart()),
1811 /*IsStringLocation*/true,
1812 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001813 // Don't do any more checking. We will just emit
1814 // spurious errors.
1815 return false;
1816 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001817
Ted Kremenek0d277352010-01-29 01:06:55 +00001818 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001819 // Although not in conformance with C99, we also allow the argument to be
1820 // an 'unsigned int' as that is a reasonably safe case. GCC also
1821 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001822 CoveredArgs.set(argIndex);
1823 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001824 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001825
1826 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1827 assert(ATR.isValid());
1828
1829 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00001830 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
1831 << k << ATR.getRepresentativeType(S.Context)
1832 << T << Arg->getSourceRange(),
1833 getLocationOfByte(Amt.getStart()),
1834 /*IsStringLocation*/true,
1835 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00001836 // Don't do any more checking. We will just emit
1837 // spurious errors.
1838 return false;
1839 }
1840 }
1841 }
1842 return true;
1843}
Ted Kremenek0d277352010-01-29 01:06:55 +00001844
Tom Caree4ee9662010-06-17 19:00:27 +00001845void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001846 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001847 const analyze_printf::OptionalAmount &Amt,
1848 unsigned type,
1849 const char *startSpecifier,
1850 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001851 const analyze_printf::PrintfConversionSpecifier &CS =
1852 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001853
Richard Trieu55733de2011-10-28 00:41:25 +00001854 FixItHint fixit =
1855 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
1856 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1857 Amt.getConstantLength()))
1858 : FixItHint();
1859
1860 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
1861 << type << CS.toString(),
1862 getLocationOfByte(Amt.getStart()),
1863 /*IsStringLocation*/true,
1864 getSpecifierRange(startSpecifier, specifierLen),
1865 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00001866}
1867
Ted Kremenek826a3452010-07-16 02:11:22 +00001868void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001869 const analyze_printf::OptionalFlag &flag,
1870 const char *startSpecifier,
1871 unsigned specifierLen) {
1872 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001873 const analyze_printf::PrintfConversionSpecifier &CS =
1874 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00001875 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
1876 << flag.toString() << CS.toString(),
1877 getLocationOfByte(flag.getPosition()),
1878 /*IsStringLocation*/true,
1879 getSpecifierRange(startSpecifier, specifierLen),
1880 FixItHint::CreateRemoval(
1881 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00001882}
1883
1884void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001885 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001886 const analyze_printf::OptionalFlag &ignoredFlag,
1887 const analyze_printf::OptionalFlag &flag,
1888 const char *startSpecifier,
1889 unsigned specifierLen) {
1890 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00001891 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
1892 << ignoredFlag.toString() << flag.toString(),
1893 getLocationOfByte(ignoredFlag.getPosition()),
1894 /*IsStringLocation*/true,
1895 getSpecifierRange(startSpecifier, specifierLen),
1896 FixItHint::CreateRemoval(
1897 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00001898}
1899
Ted Kremeneke0e53132010-01-28 23:39:18 +00001900bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001901CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001902 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001903 const char *startSpecifier,
1904 unsigned specifierLen) {
1905
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001906 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001907 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001908 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001909
Ted Kremenekbaa40062010-07-19 22:01:06 +00001910 if (FS.consumesDataArgument()) {
1911 if (atFirstArg) {
1912 atFirstArg = false;
1913 usesPositionalArgs = FS.usesPositionalArg();
1914 }
1915 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00001916 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
1917 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00001918 return false;
1919 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001920 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001921
Ted Kremenekefaff192010-02-27 01:41:03 +00001922 // First check if the field width, precision, and conversion specifier
1923 // have matching data arguments.
1924 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1925 startSpecifier, specifierLen)) {
1926 return false;
1927 }
1928
1929 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1930 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001931 return false;
1932 }
1933
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001934 if (!CS.consumesDataArgument()) {
1935 // FIXME: Technically specifying a precision or field width here
1936 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001937 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001938 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001939
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001940 // Consume the argument.
1941 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001942 if (argIndex < NumDataArgs) {
1943 // The check to see if the argIndex is valid will come later.
1944 // We set the bit here because we may exit early from this
1945 // function if we encounter some other error.
1946 CoveredArgs.set(argIndex);
1947 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001948
1949 // Check for using an Objective-C specific conversion specifier
1950 // in a non-ObjC literal.
1951 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001952 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1953 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001954 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001955
Tom Caree4ee9662010-06-17 19:00:27 +00001956 // Check for invalid use of field width
1957 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001958 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001959 startSpecifier, specifierLen);
1960 }
1961
1962 // Check for invalid use of precision
1963 if (!FS.hasValidPrecision()) {
1964 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1965 startSpecifier, specifierLen);
1966 }
1967
1968 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001969 if (!FS.hasValidThousandsGroupingPrefix())
1970 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001971 if (!FS.hasValidLeadingZeros())
1972 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1973 if (!FS.hasValidPlusPrefix())
1974 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001975 if (!FS.hasValidSpacePrefix())
1976 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001977 if (!FS.hasValidAlternativeForm())
1978 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1979 if (!FS.hasValidLeftJustified())
1980 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1981
1982 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001983 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1984 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1985 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001986 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1987 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1988 startSpecifier, specifierLen);
1989
1990 // Check the length modifier is valid with the given conversion specifier.
1991 const LengthModifier &LM = FS.getLengthModifier();
1992 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00001993 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
1994 << LM.toString() << CS.toString(),
1995 getLocationOfByte(LM.getStart()),
1996 /*IsStringLocation*/true,
1997 getSpecifierRange(startSpecifier, specifierLen),
1998 FixItHint::CreateRemoval(
1999 getSpecifierRange(LM.getStart(),
2000 LM.getLength())));
Tom Caree4ee9662010-06-17 19:00:27 +00002001
2002 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002003 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002004 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002005 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2006 getLocationOfByte(CS.getStart()),
2007 /*IsStringLocation*/true,
2008 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002009 // Continue checking the other format specifiers.
2010 return true;
2011 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002012
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002013 // The remaining checks depend on the data arguments.
2014 if (HasVAListArg)
2015 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002016
Ted Kremenek666a1972010-07-26 19:45:42 +00002017 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002018 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002019
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002020 // Now type check the data expression that matches the
2021 // format specifier.
2022 const Expr *Ex = getDataArg(argIndex);
2023 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
2024 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2025 // Check if we didn't match because of an implicit cast from a 'char'
2026 // or 'short' to an 'int'. This is done because printf is a varargs
2027 // function.
2028 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002029 if (ICE->getType() == S.Context.IntTy) {
2030 // All further checking is done on the subexpression.
2031 Ex = ICE->getSubExpr();
2032 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002033 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002034 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002035
2036 // We may be able to offer a FixItHint if it is a supported type.
2037 PrintfSpecifier fixedFS = FS;
Hans Wennborga7da2152011-10-18 08:10:06 +00002038 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002039
2040 if (success) {
2041 // Get the fix string from the fixed format specifier
2042 llvm::SmallString<128> buf;
2043 llvm::raw_svector_ostream os(buf);
2044 fixedFS.toString(os);
2045
Ted Kremenek9325eaf2010-08-24 22:24:51 +00002046 // FIXME: getRepresentativeType() perhaps should return a string
2047 // instead of a QualType to better handle when the representative
2048 // type is 'wint_t' (which is defined in the system headers).
Richard Trieu55733de2011-10-28 00:41:25 +00002049 EmitFormatDiagnostic(
2050 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2051 << ATR.getRepresentativeType(S.Context) << Ex->getType()
2052 << Ex->getSourceRange(),
2053 getLocationOfByte(CS.getStart()),
2054 /*IsStringLocation*/true,
2055 getSpecifierRange(startSpecifier, specifierLen),
2056 FixItHint::CreateReplacement(
2057 getSpecifierRange(startSpecifier, specifierLen),
2058 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002059 }
2060 else {
2061 S.Diag(getLocationOfByte(CS.getStart()),
2062 diag::warn_printf_conversion_argument_type_mismatch)
2063 << ATR.getRepresentativeType(S.Context) << Ex->getType()
2064 << getSpecifierRange(startSpecifier, specifierLen)
2065 << Ex->getSourceRange();
2066 }
2067 }
2068
Ted Kremeneke0e53132010-01-28 23:39:18 +00002069 return true;
2070}
2071
Ted Kremenek826a3452010-07-16 02:11:22 +00002072//===--- CHECK: Scanf format string checking ------------------------------===//
2073
2074namespace {
2075class CheckScanfHandler : public CheckFormatHandler {
2076public:
2077 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2078 const Expr *origFormatExpr, unsigned firstDataArg,
2079 unsigned numDataArgs, bool isObjCLiteral,
2080 const char *beg, bool hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002081 const CallExpr *theCall, unsigned formatIdx,
2082 bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002083 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2084 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002085 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002086
2087 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2088 const char *startSpecifier,
2089 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002090
2091 bool HandleInvalidScanfConversionSpecifier(
2092 const analyze_scanf::ScanfSpecifier &FS,
2093 const char *startSpecifier,
2094 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002095
2096 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002097};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002098}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002099
Ted Kremenekb7c21012010-07-16 18:28:03 +00002100void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2101 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002102 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2103 getLocationOfByte(end), /*IsStringLocation*/true,
2104 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002105}
2106
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002107bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2108 const analyze_scanf::ScanfSpecifier &FS,
2109 const char *startSpecifier,
2110 unsigned specifierLen) {
2111
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002112 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002113 FS.getConversionSpecifier();
2114
2115 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2116 getLocationOfByte(CS.getStart()),
2117 startSpecifier, specifierLen,
2118 CS.getStart(), CS.getLength());
2119}
2120
Ted Kremenek826a3452010-07-16 02:11:22 +00002121bool CheckScanfHandler::HandleScanfSpecifier(
2122 const analyze_scanf::ScanfSpecifier &FS,
2123 const char *startSpecifier,
2124 unsigned specifierLen) {
2125
2126 using namespace analyze_scanf;
2127 using namespace analyze_format_string;
2128
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002129 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002130
Ted Kremenekbaa40062010-07-19 22:01:06 +00002131 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2132 // be used to decide if we are using positional arguments consistently.
2133 if (FS.consumesDataArgument()) {
2134 if (atFirstArg) {
2135 atFirstArg = false;
2136 usesPositionalArgs = FS.usesPositionalArg();
2137 }
2138 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002139 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2140 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002141 return false;
2142 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002143 }
2144
2145 // Check if the field with is non-zero.
2146 const OptionalAmount &Amt = FS.getFieldWidth();
2147 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2148 if (Amt.getConstantAmount() == 0) {
2149 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2150 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002151 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2152 getLocationOfByte(Amt.getStart()),
2153 /*IsStringLocation*/true, R,
2154 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002155 }
2156 }
2157
2158 if (!FS.consumesDataArgument()) {
2159 // FIXME: Technically specifying a precision or field width here
2160 // makes no sense. Worth issuing a warning at some point.
2161 return true;
2162 }
2163
2164 // Consume the argument.
2165 unsigned argIndex = FS.getArgIndex();
2166 if (argIndex < NumDataArgs) {
2167 // The check to see if the argIndex is valid will come later.
2168 // We set the bit here because we may exit early from this
2169 // function if we encounter some other error.
2170 CoveredArgs.set(argIndex);
2171 }
2172
Ted Kremenek1e51c202010-07-20 20:04:47 +00002173 // Check the length modifier is valid with the given conversion specifier.
2174 const LengthModifier &LM = FS.getLengthModifier();
2175 if (!FS.hasValidLengthModifier()) {
2176 S.Diag(getLocationOfByte(LM.getStart()),
2177 diag::warn_format_nonsensical_length)
2178 << LM.toString() << CS.toString()
2179 << getSpecifierRange(startSpecifier, specifierLen)
2180 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2181 LM.getLength()));
2182 }
2183
Ted Kremenek826a3452010-07-16 02:11:22 +00002184 // The remaining checks depend on the data arguments.
2185 if (HasVAListArg)
2186 return true;
2187
Ted Kremenek666a1972010-07-26 19:45:42 +00002188 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002189 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002190
2191 // FIXME: Check that the argument type matches the format specifier.
2192
2193 return true;
2194}
2195
2196void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002197 const Expr *OrigFormatExpr,
2198 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00002199 unsigned format_idx, unsigned firstDataArg,
Richard Trieu55733de2011-10-28 00:41:25 +00002200 bool isPrintf, bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002201
Ted Kremeneke0e53132010-01-28 23:39:18 +00002202 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002203 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002204 CheckFormatHandler::EmitFormatDiagnostic(
2205 *this, inFunctionCall, TheCall->getArg(format_idx),
2206 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2207 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002208 return;
2209 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002210
Ted Kremeneke0e53132010-01-28 23:39:18 +00002211 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002212 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002213 const char *Str = StrRef.data();
2214 unsigned StrLen = StrRef.size();
Ted Kremenek4cd57912011-09-29 05:52:16 +00002215 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002216
Ted Kremeneke0e53132010-01-28 23:39:18 +00002217 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002218 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002219 CheckFormatHandler::EmitFormatDiagnostic(
2220 *this, inFunctionCall, TheCall->getArg(format_idx),
2221 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2222 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002223 return;
2224 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002225
2226 if (isPrintf) {
2227 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002228 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002229 Str, HasVAListArg, TheCall, format_idx,
2230 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002231
2232 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2233 H.DoneProcessing();
2234 }
2235 else {
2236 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002237 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu55733de2011-10-28 00:41:25 +00002238 Str, HasVAListArg, TheCall, format_idx,
2239 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002240
2241 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2242 H.DoneProcessing();
2243 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002244}
2245
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002246//===--- CHECK: Standard memory functions ---------------------------------===//
2247
Douglas Gregor2a053a32011-05-03 20:05:22 +00002248/// \brief Determine whether the given type is a dynamic class type (e.g.,
2249/// whether it has a vtable).
2250static bool isDynamicClassType(QualType T) {
2251 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2252 if (CXXRecordDecl *Definition = Record->getDefinition())
2253 if (Definition->isDynamicClass())
2254 return true;
2255
2256 return false;
2257}
2258
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002259/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002260/// otherwise returns NULL.
2261static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002262 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002263 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2264 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2265 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002266
Chandler Carruth000d4282011-06-16 09:09:40 +00002267 return 0;
2268}
2269
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002270/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002271static QualType getSizeOfArgType(const Expr* E) {
2272 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2273 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2274 if (SizeOf->getKind() == clang::UETT_SizeOf)
2275 return SizeOf->getTypeOfArgument();
2276
2277 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002278}
2279
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002280/// \brief Check for dangerous or invalid arguments to memset().
2281///
Chandler Carruth929f0132011-06-03 06:23:57 +00002282/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002283/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2284/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002285///
2286/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002287void Sema::CheckMemaccessArguments(const CallExpr *Call,
2288 CheckedMemoryFunction CMF,
2289 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002290 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002291 // we have enough arguments, and if not, abort further checking.
Nico Webercda57822011-10-13 22:30:23 +00002292 unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2293 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002294 return;
2295
Nico Webercda57822011-10-13 22:30:23 +00002296 unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2297 unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2298 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002299
2300 // We have special checking when the length is a sizeof expression.
2301 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2302 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2303 llvm::FoldingSetNodeID SizeOfArgID;
2304
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002305 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2306 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002307 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002308
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002309 QualType DestTy = Dest->getType();
2310 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2311 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002312
Chandler Carruth000d4282011-06-16 09:09:40 +00002313 // Never warn about void type pointers. This can be used to suppress
2314 // false positives.
2315 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002316 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002317
Chandler Carruth000d4282011-06-16 09:09:40 +00002318 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2319 // actually comparing the expressions for equality. Because computing the
2320 // expression IDs can be expensive, we only do this if the diagnostic is
2321 // enabled.
2322 if (SizeOfArg &&
2323 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2324 SizeOfArg->getExprLoc())) {
2325 // We only compute IDs for expressions if the warning is enabled, and
2326 // cache the sizeof arg's ID.
2327 if (SizeOfArgID == llvm::FoldingSetNodeID())
2328 SizeOfArg->Profile(SizeOfArgID, Context, true);
2329 llvm::FoldingSetNodeID DestID;
2330 Dest->Profile(DestID, Context, true);
2331 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002332 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2333 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002334 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2335 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2336 if (UnaryOp->getOpcode() == UO_AddrOf)
2337 ActionIdx = 1; // If its an address-of operator, just remove it.
2338 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2339 ActionIdx = 2; // If the pointee's size is sizeof(char),
2340 // suggest an explicit length.
Nico Webercda57822011-10-13 22:30:23 +00002341 unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002342 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2343 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002344 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002345 << Dest->getSourceRange()
2346 << SizeOfArg->getSourceRange());
2347 break;
2348 }
2349 }
2350
2351 // Also check for cases where the sizeof argument is the exact same
2352 // type as the memory argument, and where it points to a user-defined
2353 // record type.
2354 if (SizeOfArgTy != QualType()) {
2355 if (PointeeTy->isRecordType() &&
2356 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2357 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2358 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2359 << FnName << SizeOfArgTy << ArgIdx
2360 << PointeeTy << Dest->getSourceRange()
2361 << LenExpr->getSourceRange());
2362 break;
2363 }
Nico Webere4a1c642011-06-14 16:14:58 +00002364 }
2365
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002366 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00002367 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002368 DiagRuntimeBehavior(
2369 Dest->getExprLoc(), Dest,
2370 PDiag(diag::warn_dyn_class_memaccess)
2371 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2372 // "overwritten" if we're warning about the destination for any call
2373 // but memcmp; otherwise a verb appropriate to the call.
2374 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2375 << Call->getCallee()->getSourceRange());
Douglas Gregor707a23e2011-06-16 17:56:04 +00002376 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002377 DiagRuntimeBehavior(
2378 Dest->getExprLoc(), Dest,
2379 PDiag(diag::warn_arc_object_memaccess)
2380 << ArgIdx << FnName << PointeeTy
2381 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002382 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002383 continue;
John McCallf85e1932011-06-15 23:02:42 +00002384
2385 DiagRuntimeBehavior(
2386 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002387 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002388 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2389 break;
2390 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002391 }
2392}
2393
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002394// A little helper routine: ignore addition and subtraction of integer literals.
2395// This intentionally does not ignore all integer constant expressions because
2396// we don't want to remove sizeof().
2397static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2398 Ex = Ex->IgnoreParenCasts();
2399
2400 for (;;) {
2401 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2402 if (!BO || !BO->isAdditiveOp())
2403 break;
2404
2405 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2406 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2407
2408 if (isa<IntegerLiteral>(RHS))
2409 Ex = LHS;
2410 else if (isa<IntegerLiteral>(LHS))
2411 Ex = RHS;
2412 else
2413 break;
2414 }
2415
2416 return Ex;
2417}
2418
2419// Warn if the user has made the 'size' argument to strlcpy or strlcat
2420// be the size of the source, instead of the destination.
2421void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2422 IdentifierInfo *FnName) {
2423
2424 // Don't crash if the user has the wrong number of arguments
2425 if (Call->getNumArgs() != 3)
2426 return;
2427
2428 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2429 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2430 const Expr *CompareWithSrc = NULL;
2431
2432 // Look for 'strlcpy(dst, x, sizeof(x))'
2433 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2434 CompareWithSrc = Ex;
2435 else {
2436 // Look for 'strlcpy(dst, x, strlen(x))'
2437 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002438 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002439 && SizeCall->getNumArgs() == 1)
2440 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2441 }
2442 }
2443
2444 if (!CompareWithSrc)
2445 return;
2446
2447 // Determine if the argument to sizeof/strlen is equal to the source
2448 // argument. In principle there's all kinds of things you could do
2449 // here, for instance creating an == expression and evaluating it with
2450 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2451 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2452 if (!SrcArgDRE)
2453 return;
2454
2455 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2456 if (!CompareWithSrcDRE ||
2457 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2458 return;
2459
2460 const Expr *OriginalSizeArg = Call->getArg(2);
2461 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2462 << OriginalSizeArg->getSourceRange() << FnName;
2463
2464 // Output a FIXIT hint if the destination is an array (rather than a
2465 // pointer to an array). This could be enhanced to handle some
2466 // pointers if we know the actual size, like if DstArg is 'array+2'
2467 // we could say 'sizeof(array)-2'.
2468 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002469 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002470
Ted Kremenek8f746222011-08-18 22:48:41 +00002471 // Only handle constant-sized or VLAs, but not flexible members.
2472 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2473 // Only issue the FIXIT for arrays of size > 1.
2474 if (CAT->getSize().getSExtValue() <= 1)
2475 return;
2476 } else if (!DstArgTy->isVariableArrayType()) {
2477 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002478 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002479
2480 llvm::SmallString<128> sizeString;
2481 llvm::raw_svector_ostream OS(sizeString);
2482 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002483 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002484 OS << ")";
2485
2486 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2487 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2488 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002489}
2490
Ted Kremenek06de2762007-08-17 16:46:58 +00002491//===--- CHECK: Return Address of Stack Variable --------------------------===//
2492
Chris Lattner5f9e2722011-07-23 10:55:15 +00002493static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2494static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002495
2496/// CheckReturnStackAddr - Check if a return statement returns the address
2497/// of a stack variable.
2498void
2499Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2500 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002502 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002503 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002504
2505 // Perform checking for returned stack addresses, local blocks,
2506 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002507 if (lhsType->isPointerType() ||
2508 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002509 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002510 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002511 stackE = EvalVal(RetValExp, refVars);
2512 }
2513
2514 if (stackE == 0)
2515 return; // Nothing suspicious was found.
2516
2517 SourceLocation diagLoc;
2518 SourceRange diagRange;
2519 if (refVars.empty()) {
2520 diagLoc = stackE->getLocStart();
2521 diagRange = stackE->getSourceRange();
2522 } else {
2523 // We followed through a reference variable. 'stackE' contains the
2524 // problematic expression but we will warn at the return statement pointing
2525 // at the reference variable. We will later display the "trail" of
2526 // reference variables using notes.
2527 diagLoc = refVars[0]->getLocStart();
2528 diagRange = refVars[0]->getSourceRange();
2529 }
2530
2531 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2532 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2533 : diag::warn_ret_stack_addr)
2534 << DR->getDecl()->getDeclName() << diagRange;
2535 } else if (isa<BlockExpr>(stackE)) { // local block.
2536 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2537 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2538 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2539 } else { // local temporary.
2540 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2541 : diag::warn_ret_local_temp_addr)
2542 << diagRange;
2543 }
2544
2545 // Display the "trail" of reference variables that we followed until we
2546 // found the problematic expression using notes.
2547 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2548 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2549 // If this var binds to another reference var, show the range of the next
2550 // var, otherwise the var binds to the problematic expression, in which case
2551 // show the range of the expression.
2552 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2553 : stackE->getSourceRange();
2554 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2555 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002556 }
2557}
2558
2559/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2560/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002561/// to a location on the stack, a local block, an address of a label, or a
2562/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002563/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002564/// encounter a subexpression that (1) clearly does not lead to one of the
2565/// above problematic expressions (2) is something we cannot determine leads to
2566/// a problematic expression based on such local checking.
2567///
2568/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2569/// the expression that they point to. Such variables are added to the
2570/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002571///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002572/// EvalAddr processes expressions that are pointers that are used as
2573/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002574/// At the base case of the recursion is a check for the above problematic
2575/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002576///
2577/// This implementation handles:
2578///
2579/// * pointer-to-pointer casts
2580/// * implicit conversions from array references to pointers
2581/// * taking the address of fields
2582/// * arbitrary interplay between "&" and "*" operators
2583/// * pointer arithmetic from an address of a stack variable
2584/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002585static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002586 if (E->isTypeDependent())
2587 return NULL;
2588
Ted Kremenek06de2762007-08-17 16:46:58 +00002589 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002590 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002591 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002592 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002593 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002594
Peter Collingbournef111d932011-04-15 00:35:48 +00002595 E = E->IgnoreParens();
2596
Ted Kremenek06de2762007-08-17 16:46:58 +00002597 // Our "symbolic interpreter" is just a dispatch off the currently
2598 // viewed AST node. We then recursively traverse the AST by calling
2599 // EvalAddr and EvalVal appropriately.
2600 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002601 case Stmt::DeclRefExprClass: {
2602 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2603
2604 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2605 // If this is a reference variable, follow through to the expression that
2606 // it points to.
2607 if (V->hasLocalStorage() &&
2608 V->getType()->isReferenceType() && V->hasInit()) {
2609 // Add the reference variable to the "trail".
2610 refVars.push_back(DR);
2611 return EvalAddr(V->getInit(), refVars);
2612 }
2613
2614 return NULL;
2615 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002616
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002617 case Stmt::UnaryOperatorClass: {
2618 // The only unary operator that make sense to handle here
2619 // is AddrOf. All others don't make sense as pointers.
2620 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002621
John McCall2de56d12010-08-25 11:45:40 +00002622 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002623 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002624 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002625 return NULL;
2626 }
Mike Stump1eb44332009-09-09 15:08:12 +00002627
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002628 case Stmt::BinaryOperatorClass: {
2629 // Handle pointer arithmetic. All other binary operators are not valid
2630 // in this context.
2631 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002632 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002633
John McCall2de56d12010-08-25 11:45:40 +00002634 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002635 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002636
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002637 Expr *Base = B->getLHS();
2638
2639 // Determine which argument is the real pointer base. It could be
2640 // the RHS argument instead of the LHS.
2641 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002642
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002643 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002644 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002645 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002646
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002647 // For conditional operators we need to see if either the LHS or RHS are
2648 // valid DeclRefExpr*s. If one of them is valid, we return it.
2649 case Stmt::ConditionalOperatorClass: {
2650 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002652 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002653 if (Expr *lhsExpr = C->getLHS()) {
2654 // In C++, we can have a throw-expression, which has 'void' type.
2655 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002656 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002657 return LHS;
2658 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002659
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002660 // In C++, we can have a throw-expression, which has 'void' type.
2661 if (C->getRHS()->getType()->isVoidType())
2662 return NULL;
2663
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002664 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002665 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002666
2667 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002668 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002669 return E; // local block.
2670 return NULL;
2671
2672 case Stmt::AddrLabelExprClass:
2673 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002674
John McCall80ee6e82011-11-10 05:35:25 +00002675 case Stmt::ExprWithCleanupsClass:
2676 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2677
Ted Kremenek54b52742008-08-07 00:49:01 +00002678 // For casts, we need to handle conversions from arrays to
2679 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002680 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002681 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002682 case Stmt::CXXFunctionalCastExprClass:
2683 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002684 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002685 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002686
Steve Naroffdd972f22008-09-05 22:11:13 +00002687 if (SubExpr->getType()->isPointerType() ||
2688 SubExpr->getType()->isBlockPointerType() ||
2689 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002690 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002691 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002692 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002693 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002694 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002695 }
Mike Stump1eb44332009-09-09 15:08:12 +00002696
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002697 // C++ casts. For dynamic casts, static casts, and const casts, we
2698 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002699 // through the cast. In the case the dynamic cast doesn't fail (and
2700 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002701 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002702 // FIXME: The comment about is wrong; we're not always converting
2703 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002704 // handle references to objects.
2705 case Stmt::CXXStaticCastExprClass:
2706 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002707 case Stmt::CXXConstCastExprClass:
2708 case Stmt::CXXReinterpretCastExprClass: {
2709 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002710 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002711 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002712 else
2713 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002714 }
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Douglas Gregor03e80032011-06-21 17:03:29 +00002716 case Stmt::MaterializeTemporaryExprClass:
2717 if (Expr *Result = EvalAddr(
2718 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2719 refVars))
2720 return Result;
2721
2722 return E;
2723
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002724 // Everything else: we simply don't reason about them.
2725 default:
2726 return NULL;
2727 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002728}
Mike Stump1eb44332009-09-09 15:08:12 +00002729
Ted Kremenek06de2762007-08-17 16:46:58 +00002730
2731/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2732/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002733static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002734do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002735 // We should only be called for evaluating non-pointer expressions, or
2736 // expressions with a pointer type that are not used as references but instead
2737 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Ted Kremenek06de2762007-08-17 16:46:58 +00002739 // Our "symbolic interpreter" is just a dispatch off the currently
2740 // viewed AST node. We then recursively traverse the AST by calling
2741 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002742
2743 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002744 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002745 case Stmt::ImplicitCastExprClass: {
2746 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002747 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002748 E = IE->getSubExpr();
2749 continue;
2750 }
2751 return NULL;
2752 }
2753
John McCall80ee6e82011-11-10 05:35:25 +00002754 case Stmt::ExprWithCleanupsClass:
2755 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2756
Douglas Gregora2813ce2009-10-23 18:54:35 +00002757 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002758 // When we hit a DeclRefExpr we are looking at code that refers to a
2759 // variable's name. If it's not a reference variable we check if it has
2760 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002761 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002762
Ted Kremenek06de2762007-08-17 16:46:58 +00002763 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002764 if (V->hasLocalStorage()) {
2765 if (!V->getType()->isReferenceType())
2766 return DR;
2767
2768 // Reference variable, follow through to the expression that
2769 // it points to.
2770 if (V->hasInit()) {
2771 // Add the reference variable to the "trail".
2772 refVars.push_back(DR);
2773 return EvalVal(V->getInit(), refVars);
2774 }
2775 }
Mike Stump1eb44332009-09-09 15:08:12 +00002776
Ted Kremenek06de2762007-08-17 16:46:58 +00002777 return NULL;
2778 }
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Ted Kremenek06de2762007-08-17 16:46:58 +00002780 case Stmt::UnaryOperatorClass: {
2781 // The only unary operator that make sense to handle here
2782 // is Deref. All others don't resolve to a "name." This includes
2783 // handling all sorts of rvalues passed to a unary operator.
2784 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002785
John McCall2de56d12010-08-25 11:45:40 +00002786 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002787 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002788
2789 return NULL;
2790 }
Mike Stump1eb44332009-09-09 15:08:12 +00002791
Ted Kremenek06de2762007-08-17 16:46:58 +00002792 case Stmt::ArraySubscriptExprClass: {
2793 // Array subscripts are potential references to data on the stack. We
2794 // retrieve the DeclRefExpr* for the array variable if it indeed
2795 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002796 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002797 }
Mike Stump1eb44332009-09-09 15:08:12 +00002798
Ted Kremenek06de2762007-08-17 16:46:58 +00002799 case Stmt::ConditionalOperatorClass: {
2800 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002801 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002802 ConditionalOperator *C = cast<ConditionalOperator>(E);
2803
Anders Carlsson39073232007-11-30 19:04:31 +00002804 // Handle the GNU extension for missing LHS.
2805 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002806 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002807 return LHS;
2808
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002809 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002810 }
Mike Stump1eb44332009-09-09 15:08:12 +00002811
Ted Kremenek06de2762007-08-17 16:46:58 +00002812 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002813 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002814 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Ted Kremenek06de2762007-08-17 16:46:58 +00002816 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002817 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002818 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002819
2820 // Check whether the member type is itself a reference, in which case
2821 // we're not going to refer to the member, but to what the member refers to.
2822 if (M->getMemberDecl()->getType()->isReferenceType())
2823 return NULL;
2824
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002825 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002826 }
Mike Stump1eb44332009-09-09 15:08:12 +00002827
Douglas Gregor03e80032011-06-21 17:03:29 +00002828 case Stmt::MaterializeTemporaryExprClass:
2829 if (Expr *Result = EvalVal(
2830 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2831 refVars))
2832 return Result;
2833
2834 return E;
2835
Ted Kremenek06de2762007-08-17 16:46:58 +00002836 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002837 // Check that we don't return or take the address of a reference to a
2838 // temporary. This is only useful in C++.
2839 if (!E->isTypeDependent() && E->isRValue())
2840 return E;
2841
2842 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002843 return NULL;
2844 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002845} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002846}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002847
2848//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2849
2850/// Check for comparisons of floating point operands using != and ==.
2851/// Issue a warning if these are no self-comparisons, as they are not likely
2852/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00002853void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002854 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Richard Trieudd225092011-09-15 21:56:47 +00002856 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2857 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002858
2859 // Special case: check for x == x (which is OK).
2860 // Do not emit warnings for such cases.
2861 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2862 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2863 if (DRL->getDecl() == DRR->getDecl())
2864 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002865
2866
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002867 // Special case: check for comparisons against literals that can be exactly
2868 // represented by APFloat. In such cases, do not emit a warning. This
2869 // is a heuristic: often comparison against such literals are used to
2870 // detect if a value in a variable has not changed. This clearly can
2871 // lead to false negatives.
2872 if (EmitWarning) {
2873 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2874 if (FLL->isExact())
2875 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002876 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002877 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2878 if (FLR->isExact())
2879 EmitWarning = false;
2880 }
2881 }
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002883 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002884 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002885 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00002886 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002887 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002888
Sebastian Redl0eb23302009-01-19 00:08:26 +00002889 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002890 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00002891 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002892 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002893
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002894 // Emit the diagnostic.
2895 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00002896 Diag(Loc, diag::warn_floatingpoint_eq)
2897 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002898}
John McCallba26e582010-01-04 23:21:16 +00002899
John McCallf2370c92010-01-06 05:24:50 +00002900//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2901//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002902
John McCallf2370c92010-01-06 05:24:50 +00002903namespace {
John McCallba26e582010-01-04 23:21:16 +00002904
John McCallf2370c92010-01-06 05:24:50 +00002905/// Structure recording the 'active' range of an integer-valued
2906/// expression.
2907struct IntRange {
2908 /// The number of bits active in the int.
2909 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002910
John McCallf2370c92010-01-06 05:24:50 +00002911 /// True if the int is known not to have negative values.
2912 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002913
John McCallf2370c92010-01-06 05:24:50 +00002914 IntRange(unsigned Width, bool NonNegative)
2915 : Width(Width), NonNegative(NonNegative)
2916 {}
John McCallba26e582010-01-04 23:21:16 +00002917
John McCall1844a6e2010-11-10 23:38:19 +00002918 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002919 static IntRange forBoolType() {
2920 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002921 }
2922
John McCall1844a6e2010-11-10 23:38:19 +00002923 /// Returns the range of an opaque value of the given integral type.
2924 static IntRange forValueOfType(ASTContext &C, QualType T) {
2925 return forValueOfCanonicalType(C,
2926 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002927 }
2928
John McCall1844a6e2010-11-10 23:38:19 +00002929 /// Returns the range of an opaque value of a canonical integral type.
2930 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002931 assert(T->isCanonicalUnqualified());
2932
2933 if (const VectorType *VT = dyn_cast<VectorType>(T))
2934 T = VT->getElementType().getTypePtr();
2935 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2936 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002937
John McCall091f23f2010-11-09 22:22:12 +00002938 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002939 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2940 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00002941 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00002942 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2943
John McCall323ed742010-05-06 08:58:33 +00002944 unsigned NumPositive = Enum->getNumPositiveBits();
2945 unsigned NumNegative = Enum->getNumNegativeBits();
2946
2947 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2948 }
John McCallf2370c92010-01-06 05:24:50 +00002949
2950 const BuiltinType *BT = cast<BuiltinType>(T);
2951 assert(BT->isInteger());
2952
2953 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2954 }
2955
John McCall1844a6e2010-11-10 23:38:19 +00002956 /// Returns the "target" range of a canonical integral type, i.e.
2957 /// the range of values expressible in the type.
2958 ///
2959 /// This matches forValueOfCanonicalType except that enums have the
2960 /// full range of their type, not the range of their enumerators.
2961 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2962 assert(T->isCanonicalUnqualified());
2963
2964 if (const VectorType *VT = dyn_cast<VectorType>(T))
2965 T = VT->getElementType().getTypePtr();
2966 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2967 T = CT->getElementType().getTypePtr();
2968 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00002969 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00002970
2971 const BuiltinType *BT = cast<BuiltinType>(T);
2972 assert(BT->isInteger());
2973
2974 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2975 }
2976
2977 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002978 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002979 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002980 L.NonNegative && R.NonNegative);
2981 }
2982
John McCall1844a6e2010-11-10 23:38:19 +00002983 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002984 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002985 return IntRange(std::min(L.Width, R.Width),
2986 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002987 }
2988};
2989
2990IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2991 if (value.isSigned() && value.isNegative())
2992 return IntRange(value.getMinSignedBits(), false);
2993
2994 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002995 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002996
2997 // isNonNegative() just checks the sign bit without considering
2998 // signedness.
2999 return IntRange(value.getActiveBits(), true);
3000}
3001
John McCall0acc3112010-01-06 22:57:21 +00003002IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00003003 unsigned MaxWidth) {
3004 if (result.isInt())
3005 return GetValueRange(C, result.getInt(), MaxWidth);
3006
3007 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003008 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3009 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3010 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3011 R = IntRange::join(R, El);
3012 }
John McCallf2370c92010-01-06 05:24:50 +00003013 return R;
3014 }
3015
3016 if (result.isComplexInt()) {
3017 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3018 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3019 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003020 }
3021
3022 // This can happen with lossless casts to intptr_t of "based" lvalues.
3023 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003024 // FIXME: The only reason we need to pass the type in here is to get
3025 // the sign right on this one case. It would be nice if APValue
3026 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00003027 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003028 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003029}
John McCallf2370c92010-01-06 05:24:50 +00003030
3031/// Pseudo-evaluate the given integer expression, estimating the
3032/// range of values it might take.
3033///
3034/// \param MaxWidth - the width to which the value will be truncated
3035IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3036 E = E->IgnoreParens();
3037
3038 // Try a full evaluation first.
3039 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003040 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003041 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003042
3043 // I think we only want to look through implicit casts here; if the
3044 // user has an explicit widening cast, we should treat the value as
3045 // being of the new, wider type.
3046 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00003047 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00003048 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3049
John McCall1844a6e2010-11-10 23:38:19 +00003050 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003051
John McCall2de56d12010-08-25 11:45:40 +00003052 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003053
John McCallf2370c92010-01-06 05:24:50 +00003054 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003055 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003056 return OutputTypeRange;
3057
3058 IntRange SubRange
3059 = GetExprRange(C, CE->getSubExpr(),
3060 std::min(MaxWidth, OutputTypeRange.Width));
3061
3062 // Bail out if the subexpr's range is as wide as the cast type.
3063 if (SubRange.Width >= OutputTypeRange.Width)
3064 return OutputTypeRange;
3065
3066 // Otherwise, we take the smaller width, and we're non-negative if
3067 // either the output type or the subexpr is.
3068 return IntRange(SubRange.Width,
3069 SubRange.NonNegative || OutputTypeRange.NonNegative);
3070 }
3071
3072 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3073 // If we can fold the condition, just take that operand.
3074 bool CondResult;
3075 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3076 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3077 : CO->getFalseExpr(),
3078 MaxWidth);
3079
3080 // Otherwise, conservatively merge.
3081 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3082 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3083 return IntRange::join(L, R);
3084 }
3085
3086 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3087 switch (BO->getOpcode()) {
3088
3089 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003090 case BO_LAnd:
3091 case BO_LOr:
3092 case BO_LT:
3093 case BO_GT:
3094 case BO_LE:
3095 case BO_GE:
3096 case BO_EQ:
3097 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003098 return IntRange::forBoolType();
3099
John McCall862ff872011-07-13 06:35:24 +00003100 // The type of the assignments is the type of the LHS, so the RHS
3101 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003102 case BO_MulAssign:
3103 case BO_DivAssign:
3104 case BO_RemAssign:
3105 case BO_AddAssign:
3106 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003107 case BO_XorAssign:
3108 case BO_OrAssign:
3109 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003110 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003111
John McCall862ff872011-07-13 06:35:24 +00003112 // Simple assignments just pass through the RHS, which will have
3113 // been coerced to the LHS type.
3114 case BO_Assign:
3115 // TODO: bitfields?
3116 return GetExprRange(C, BO->getRHS(), MaxWidth);
3117
John McCallf2370c92010-01-06 05:24:50 +00003118 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003119 case BO_PtrMemD:
3120 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003121 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003122
John McCall60fad452010-01-06 22:07:33 +00003123 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003124 case BO_And:
3125 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003126 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3127 GetExprRange(C, BO->getRHS(), MaxWidth));
3128
John McCallf2370c92010-01-06 05:24:50 +00003129 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003130 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003131 // ...except that we want to treat '1 << (blah)' as logically
3132 // positive. It's an important idiom.
3133 if (IntegerLiteral *I
3134 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3135 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003136 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003137 return IntRange(R.Width, /*NonNegative*/ true);
3138 }
3139 }
3140 // fallthrough
3141
John McCall2de56d12010-08-25 11:45:40 +00003142 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003143 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003144
John McCall60fad452010-01-06 22:07:33 +00003145 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003146 case BO_Shr:
3147 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003148 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3149
3150 // If the shift amount is a positive constant, drop the width by
3151 // that much.
3152 llvm::APSInt shift;
3153 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3154 shift.isNonNegative()) {
3155 unsigned zext = shift.getZExtValue();
3156 if (zext >= L.Width)
3157 L.Width = (L.NonNegative ? 0 : 1);
3158 else
3159 L.Width -= zext;
3160 }
3161
3162 return L;
3163 }
3164
3165 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003166 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003167 return GetExprRange(C, BO->getRHS(), MaxWidth);
3168
John McCall60fad452010-01-06 22:07:33 +00003169 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003170 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003171 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003172 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003173 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003174
John McCall00fe7612011-07-14 22:39:48 +00003175 // The width of a division result is mostly determined by the size
3176 // of the LHS.
3177 case BO_Div: {
3178 // Don't 'pre-truncate' the operands.
3179 unsigned opWidth = C.getIntWidth(E->getType());
3180 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3181
3182 // If the divisor is constant, use that.
3183 llvm::APSInt divisor;
3184 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3185 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3186 if (log2 >= L.Width)
3187 L.Width = (L.NonNegative ? 0 : 1);
3188 else
3189 L.Width = std::min(L.Width - log2, MaxWidth);
3190 return L;
3191 }
3192
3193 // Otherwise, just use the LHS's width.
3194 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3195 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3196 }
3197
3198 // The result of a remainder can't be larger than the result of
3199 // either side.
3200 case BO_Rem: {
3201 // Don't 'pre-truncate' the operands.
3202 unsigned opWidth = C.getIntWidth(E->getType());
3203 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3204 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3205
3206 IntRange meet = IntRange::meet(L, R);
3207 meet.Width = std::min(meet.Width, MaxWidth);
3208 return meet;
3209 }
3210
3211 // The default behavior is okay for these.
3212 case BO_Mul:
3213 case BO_Add:
3214 case BO_Xor:
3215 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003216 break;
3217 }
3218
John McCall00fe7612011-07-14 22:39:48 +00003219 // The default case is to treat the operation as if it were closed
3220 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003221 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3222 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3223 return IntRange::join(L, R);
3224 }
3225
3226 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3227 switch (UO->getOpcode()) {
3228 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003229 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003230 return IntRange::forBoolType();
3231
3232 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003233 case UO_Deref:
3234 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003235 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003236
3237 default:
3238 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3239 }
3240 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003241
3242 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003243 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003244 }
John McCallf2370c92010-01-06 05:24:50 +00003245
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003246 if (FieldDecl *BitField = E->getBitField())
3247 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003248 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003249
John McCall1844a6e2010-11-10 23:38:19 +00003250 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003251}
John McCall51313c32010-01-04 23:31:57 +00003252
John McCall323ed742010-05-06 08:58:33 +00003253IntRange GetExprRange(ASTContext &C, Expr *E) {
3254 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3255}
3256
John McCall51313c32010-01-04 23:31:57 +00003257/// Checks whether the given value, which currently has the given
3258/// source semantics, has the same value when coerced through the
3259/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003260bool IsSameFloatAfterCast(const llvm::APFloat &value,
3261 const llvm::fltSemantics &Src,
3262 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003263 llvm::APFloat truncated = value;
3264
3265 bool ignored;
3266 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3267 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3268
3269 return truncated.bitwiseIsEqual(value);
3270}
3271
3272/// Checks whether the given value, which currently has the given
3273/// source semantics, has the same value when coerced through the
3274/// target semantics.
3275///
3276/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003277bool IsSameFloatAfterCast(const APValue &value,
3278 const llvm::fltSemantics &Src,
3279 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003280 if (value.isFloat())
3281 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3282
3283 if (value.isVector()) {
3284 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3285 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3286 return false;
3287 return true;
3288 }
3289
3290 assert(value.isComplexFloat());
3291 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3292 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3293}
3294
John McCallb4eb64d2010-10-08 02:01:28 +00003295void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003296
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003297static bool IsZero(Sema &S, Expr *E) {
3298 // Suppress cases where we are comparing against an enum constant.
3299 if (const DeclRefExpr *DR =
3300 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3301 if (isa<EnumConstantDecl>(DR->getDecl()))
3302 return false;
3303
3304 // Suppress cases where the '0' value is expanded from a macro.
3305 if (E->getLocStart().isMacroID())
3306 return false;
3307
John McCall323ed742010-05-06 08:58:33 +00003308 llvm::APSInt Value;
3309 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3310}
3311
John McCall372e1032010-10-06 00:25:24 +00003312static bool HasEnumType(Expr *E) {
3313 // Strip off implicit integral promotions.
3314 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003315 if (ICE->getCastKind() != CK_IntegralCast &&
3316 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003317 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003318 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003319 }
3320
3321 return E->getType()->isEnumeralType();
3322}
3323
John McCall323ed742010-05-06 08:58:33 +00003324void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003325 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003326 if (E->isValueDependent())
3327 return;
3328
John McCall2de56d12010-08-25 11:45:40 +00003329 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003330 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003331 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003332 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003333 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003334 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003335 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003336 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003337 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003338 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003339 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003340 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003341 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003342 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003343 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003344 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3345 }
3346}
3347
3348/// Analyze the operands of the given comparison. Implements the
3349/// fallback case from AnalyzeComparison.
3350void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003351 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3352 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003353}
John McCall51313c32010-01-04 23:31:57 +00003354
John McCallba26e582010-01-04 23:21:16 +00003355/// \brief Implements -Wsign-compare.
3356///
Richard Trieudd225092011-09-15 21:56:47 +00003357/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003358void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3359 // The type the comparison is being performed in.
3360 QualType T = E->getLHS()->getType();
3361 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3362 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003363
John McCall323ed742010-05-06 08:58:33 +00003364 // We don't do anything special if this isn't an unsigned integral
3365 // comparison: we're only interested in integral comparisons, and
3366 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003367 //
3368 // We also don't care about value-dependent expressions or expressions
3369 // whose result is a constant.
3370 if (!T->hasUnsignedIntegerRepresentation()
3371 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003372 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003373
Richard Trieudd225092011-09-15 21:56:47 +00003374 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3375 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003376
John McCall323ed742010-05-06 08:58:33 +00003377 // Check to see if one of the (unmodified) operands is of different
3378 // signedness.
3379 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003380 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3381 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003382 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003383 signedOperand = LHS;
3384 unsignedOperand = RHS;
3385 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3386 signedOperand = RHS;
3387 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003388 } else {
John McCall323ed742010-05-06 08:58:33 +00003389 CheckTrivialUnsignedComparison(S, E);
3390 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003391 }
3392
John McCall323ed742010-05-06 08:58:33 +00003393 // Otherwise, calculate the effective range of the signed operand.
3394 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003395
John McCall323ed742010-05-06 08:58:33 +00003396 // Go ahead and analyze implicit conversions in the operands. Note
3397 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003398 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3399 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003400
John McCall323ed742010-05-06 08:58:33 +00003401 // If the signed range is non-negative, -Wsign-compare won't fire,
3402 // but we should still check for comparisons which are always true
3403 // or false.
3404 if (signedRange.NonNegative)
3405 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003406
3407 // For (in)equality comparisons, if the unsigned operand is a
3408 // constant which cannot collide with a overflowed signed operand,
3409 // then reinterpreting the signed operand as unsigned will not
3410 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003411 if (E->isEqualityOp()) {
3412 unsigned comparisonWidth = S.Context.getIntWidth(T);
3413 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003414
John McCall323ed742010-05-06 08:58:33 +00003415 // We should never be unable to prove that the unsigned operand is
3416 // non-negative.
3417 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3418
3419 if (unsignedRange.Width < comparisonWidth)
3420 return;
3421 }
3422
3423 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003424 << LHS->getType() << RHS->getType()
3425 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003426}
3427
John McCall15d7d122010-11-11 03:21:53 +00003428/// Analyzes an attempt to assign the given value to a bitfield.
3429///
3430/// Returns true if there was something fishy about the attempt.
3431bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3432 SourceLocation InitLoc) {
3433 assert(Bitfield->isBitField());
3434 if (Bitfield->isInvalidDecl())
3435 return false;
3436
John McCall91b60142010-11-11 05:33:51 +00003437 // White-list bool bitfields.
3438 if (Bitfield->getType()->isBooleanType())
3439 return false;
3440
Douglas Gregor46ff3032011-02-04 13:09:01 +00003441 // Ignore value- or type-dependent expressions.
3442 if (Bitfield->getBitWidth()->isValueDependent() ||
3443 Bitfield->getBitWidth()->isTypeDependent() ||
3444 Init->isValueDependent() ||
3445 Init->isTypeDependent())
3446 return false;
3447
John McCall15d7d122010-11-11 03:21:53 +00003448 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3449
John McCall15d7d122010-11-11 03:21:53 +00003450 Expr::EvalResult InitValue;
Richard Smith51f47082011-10-29 00:50:52 +00003451 if (!OriginalInit->EvaluateAsRValue(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00003452 !InitValue.Val.isInt())
3453 return false;
3454
3455 const llvm::APSInt &Value = InitValue.Val.getInt();
3456 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003457 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003458
3459 if (OriginalWidth <= FieldWidth)
3460 return false;
3461
Jay Foad9f71a8f2010-12-07 08:25:34 +00003462 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003463
3464 // It's fairly common to write values into signed bitfields
3465 // that, if sign-extended, would end up becoming a different
3466 // value. We don't want to warn about that.
3467 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003468 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003469 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003470 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003471
3472 if (Value == TruncatedValue)
3473 return false;
3474
3475 std::string PrettyValue = Value.toString(10);
3476 std::string PrettyTrunc = TruncatedValue.toString(10);
3477
3478 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3479 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3480 << Init->getSourceRange();
3481
3482 return true;
3483}
3484
John McCallbeb22aa2010-11-09 23:24:47 +00003485/// Analyze the given simple or compound assignment for warning-worthy
3486/// operations.
3487void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3488 // Just recurse on the LHS.
3489 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3490
3491 // We want to recurse on the RHS as normal unless we're assigning to
3492 // a bitfield.
3493 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003494 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3495 E->getOperatorLoc())) {
3496 // Recurse, ignoring any implicit conversions on the RHS.
3497 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3498 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003499 }
3500 }
3501
3502 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3503}
3504
John McCall51313c32010-01-04 23:31:57 +00003505/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003506void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3507 SourceLocation CContext, unsigned diag) {
3508 S.Diag(E->getExprLoc(), diag)
3509 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3510}
3511
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003512/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3513void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3514 unsigned diag) {
3515 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3516}
3517
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003518/// Diagnose an implicit cast from a literal expression. Does not warn when the
3519/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003520void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3521 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003522 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003523 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003524 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003525 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3526 T->hasUnsignedIntegerRepresentation());
3527 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003528 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003529 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003530 return;
3531
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003532 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3533 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003534}
3535
John McCall091f23f2010-11-09 22:22:12 +00003536std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3537 if (!Range.Width) return "0";
3538
3539 llvm::APSInt ValueInRange = Value;
3540 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003541 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003542 return ValueInRange.toString(10);
3543}
3544
Ted Kremenekef9ff882011-03-10 20:03:42 +00003545static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3546 SourceManager &smgr = S.Context.getSourceManager();
3547 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3548}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003549
John McCall323ed742010-05-06 08:58:33 +00003550void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003551 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003552 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003553
John McCall323ed742010-05-06 08:58:33 +00003554 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3555 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3556 if (Source == Target) return;
3557 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003558
Chandler Carruth108f7562011-07-26 05:40:03 +00003559 // If the conversion context location is invalid don't complain. We also
3560 // don't want to emit a warning if the issue occurs from the expansion of
3561 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3562 // delay this check as long as possible. Once we detect we are in that
3563 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003564 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003565 return;
3566
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003567 // Diagnose implicit casts to bool.
3568 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3569 if (isa<StringLiteral>(E))
3570 // Warn on string literal to bool. Checks for string literals in logical
3571 // expressions, for instances, assert(0 && "error here"), is prevented
3572 // by a check in AnalyzeImplicitConversions().
3573 return DiagnoseImpCast(S, E, T, CC,
3574 diag::warn_impcast_string_literal_to_bool);
David Blaikiee37cdc42011-09-29 04:06:47 +00003575 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003576 }
John McCall51313c32010-01-04 23:31:57 +00003577
3578 // Strip vector types.
3579 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003580 if (!isa<VectorType>(Target)) {
3581 if (isFromSystemMacro(S, CC))
3582 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003583 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003584 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003585
3586 // If the vector cast is cast between two vectors of the same size, it is
3587 // a bitcast, not a conversion.
3588 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3589 return;
John McCall51313c32010-01-04 23:31:57 +00003590
3591 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3592 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3593 }
3594
3595 // Strip complex types.
3596 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003597 if (!isa<ComplexType>(Target)) {
3598 if (isFromSystemMacro(S, CC))
3599 return;
3600
John McCallb4eb64d2010-10-08 02:01:28 +00003601 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003602 }
John McCall51313c32010-01-04 23:31:57 +00003603
3604 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3605 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3606 }
3607
3608 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3609 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3610
3611 // If the source is floating point...
3612 if (SourceBT && SourceBT->isFloatingPoint()) {
3613 // ...and the target is floating point...
3614 if (TargetBT && TargetBT->isFloatingPoint()) {
3615 // ...then warn if we're dropping FP rank.
3616
3617 // Builtin FP kinds are ordered by increasing FP rank.
3618 if (SourceBT->getKind() > TargetBT->getKind()) {
3619 // Don't warn about float constants that are precisely
3620 // representable in the target type.
3621 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003622 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003623 // Value might be a float, a float vector, or a float complex.
3624 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003625 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3626 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003627 return;
3628 }
3629
Ted Kremenekef9ff882011-03-10 20:03:42 +00003630 if (isFromSystemMacro(S, CC))
3631 return;
3632
John McCallb4eb64d2010-10-08 02:01:28 +00003633 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003634 }
3635 return;
3636 }
3637
Ted Kremenekef9ff882011-03-10 20:03:42 +00003638 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003639 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003640 if (isFromSystemMacro(S, CC))
3641 return;
3642
Chandler Carrutha5b93322011-02-17 11:05:49 +00003643 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003644 // We also want to warn on, e.g., "int i = -1.234"
3645 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3646 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3647 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3648
Chandler Carruthf65076e2011-04-10 08:36:24 +00003649 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3650 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003651 } else {
3652 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3653 }
3654 }
John McCall51313c32010-01-04 23:31:57 +00003655
3656 return;
3657 }
3658
John McCallf2370c92010-01-06 05:24:50 +00003659 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003660 return;
3661
Richard Trieu1838ca52011-05-29 19:59:02 +00003662 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3663 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3664 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3665 << E->getSourceRange() << clang::SourceRange(CC);
3666 return;
3667 }
3668
John McCall323ed742010-05-06 08:58:33 +00003669 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003670 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003671
3672 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003673 // If the source is a constant, use a default-on diagnostic.
3674 // TODO: this should happen for bitfield stores, too.
3675 llvm::APSInt Value(32);
3676 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003677 if (isFromSystemMacro(S, CC))
3678 return;
3679
John McCall091f23f2010-11-09 22:22:12 +00003680 std::string PrettySourceValue = Value.toString(10);
3681 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3682
Ted Kremenek5e745da2011-10-22 02:37:33 +00003683 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3684 S.PDiag(diag::warn_impcast_integer_precision_constant)
3685 << PrettySourceValue << PrettyTargetValue
3686 << E->getType() << T << E->getSourceRange()
3687 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00003688 return;
3689 }
3690
Chris Lattnerb792b302011-06-14 04:51:15 +00003691 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003692 if (isFromSystemMacro(S, CC))
3693 return;
3694
John McCallf2370c92010-01-06 05:24:50 +00003695 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003696 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3697 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003698 }
3699
3700 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3701 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3702 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003703
3704 if (isFromSystemMacro(S, CC))
3705 return;
3706
John McCall323ed742010-05-06 08:58:33 +00003707 unsigned DiagID = diag::warn_impcast_integer_sign;
3708
3709 // Traditionally, gcc has warned about this under -Wsign-compare.
3710 // We also want to warn about it in -Wconversion.
3711 // So if -Wconversion is off, use a completely identical diagnostic
3712 // in the sign-compare group.
3713 // The conditional-checking code will
3714 if (ICContext) {
3715 DiagID = diag::warn_impcast_integer_sign_conditional;
3716 *ICContext = true;
3717 }
3718
John McCallb4eb64d2010-10-08 02:01:28 +00003719 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003720 }
3721
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003722 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003723 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3724 // type, to give us better diagnostics.
3725 QualType SourceType = E->getType();
3726 if (!S.getLangOptions().CPlusPlus) {
3727 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3728 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3729 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3730 SourceType = S.Context.getTypeDeclType(Enum);
3731 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3732 }
3733 }
3734
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003735 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3736 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3737 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003738 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003739 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003740 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003741 SourceEnum != TargetEnum) {
3742 if (isFromSystemMacro(S, CC))
3743 return;
3744
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003745 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003746 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003747 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003748
John McCall51313c32010-01-04 23:31:57 +00003749 return;
3750}
3751
John McCall323ed742010-05-06 08:58:33 +00003752void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3753
3754void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003755 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003756 E = E->IgnoreParenImpCasts();
3757
3758 if (isa<ConditionalOperator>(E))
3759 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3760
John McCallb4eb64d2010-10-08 02:01:28 +00003761 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003762 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003763 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003764 return;
3765}
3766
3767void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003768 SourceLocation CC = E->getQuestionLoc();
3769
3770 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003771
3772 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003773 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3774 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003775
3776 // If -Wconversion would have warned about either of the candidates
3777 // for a signedness conversion to the context type...
3778 if (!Suspicious) return;
3779
3780 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003781 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3782 CC))
John McCall323ed742010-05-06 08:58:33 +00003783 return;
3784
John McCall323ed742010-05-06 08:58:33 +00003785 // ...then check whether it would have warned about either of the
3786 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003787 if (E->getType() == T) return;
3788
3789 Suspicious = false;
3790 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3791 E->getType(), CC, &Suspicious);
3792 if (!Suspicious)
3793 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003794 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003795}
3796
3797/// AnalyzeImplicitConversions - Find and report any interesting
3798/// implicit conversions in the given expression. There are a couple
3799/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003800void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003801 QualType T = OrigE->getType();
3802 Expr *E = OrigE->IgnoreParenImpCasts();
3803
Douglas Gregorf8b6e152011-10-10 17:38:18 +00003804 if (E->isTypeDependent() || E->isValueDependent())
3805 return;
3806
John McCall323ed742010-05-06 08:58:33 +00003807 // For conditional operators, we analyze the arguments as if they
3808 // were being fed directly into the output.
3809 if (isa<ConditionalOperator>(E)) {
3810 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3811 CheckConditionalOperator(S, CO, T);
3812 return;
3813 }
3814
3815 // Go ahead and check any implicit conversions we might have skipped.
3816 // The non-canonical typecheck is just an optimization;
3817 // CheckImplicitConversion will filter out dead implicit conversions.
3818 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003819 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003820
3821 // Now continue drilling into this expression.
3822
3823 // Skip past explicit casts.
3824 if (isa<ExplicitCastExpr>(E)) {
3825 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003826 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003827 }
3828
John McCallbeb22aa2010-11-09 23:24:47 +00003829 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3830 // Do a somewhat different check with comparison operators.
3831 if (BO->isComparisonOp())
3832 return AnalyzeComparison(S, BO);
3833
3834 // And with assignments and compound assignments.
3835 if (BO->isAssignmentOp())
3836 return AnalyzeAssignment(S, BO);
3837 }
John McCall323ed742010-05-06 08:58:33 +00003838
3839 // These break the otherwise-useful invariant below. Fortunately,
3840 // we don't really need to recurse into them, because any internal
3841 // expressions should have been analyzed already when they were
3842 // built into statements.
3843 if (isa<StmtExpr>(E)) return;
3844
3845 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003846 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003847
3848 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003849 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003850 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3851 bool IsLogicalOperator = BO && BO->isLogicalOp();
3852 for (Stmt::child_range I = E->children(); I; ++I) {
3853 Expr *ChildExpr = cast<Expr>(*I);
3854 if (IsLogicalOperator &&
3855 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3856 // Ignore checking string literals that are in logical operators.
3857 continue;
3858 AnalyzeImplicitConversions(S, ChildExpr, CC);
3859 }
John McCall323ed742010-05-06 08:58:33 +00003860}
3861
3862} // end anonymous namespace
3863
3864/// Diagnoses "dangerous" implicit conversions within the given
3865/// expression (which is a full expression). Implements -Wconversion
3866/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003867///
3868/// \param CC the "context" location of the implicit conversion, i.e.
3869/// the most location of the syntactic entity requiring the implicit
3870/// conversion
3871void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003872 // Don't diagnose in unevaluated contexts.
3873 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3874 return;
3875
3876 // Don't diagnose for value- or type-dependent expressions.
3877 if (E->isTypeDependent() || E->isValueDependent())
3878 return;
3879
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003880 // Check for array bounds violations in cases where the check isn't triggered
3881 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3882 // ArraySubscriptExpr is on the RHS of a variable initialization.
3883 CheckArrayAccess(E);
3884
John McCallb4eb64d2010-10-08 02:01:28 +00003885 // This is not the right CC for (e.g.) a variable initialization.
3886 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003887}
3888
John McCall15d7d122010-11-11 03:21:53 +00003889void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3890 FieldDecl *BitField,
3891 Expr *Init) {
3892 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3893}
3894
Mike Stumpf8c49212010-01-21 03:59:47 +00003895/// CheckParmsForFunctionDef - Check that the parameters of the given
3896/// function are appropriate for the definition of a function. This
3897/// takes care of any checks that cannot be performed on the
3898/// declaration itself, e.g., that the types of each of the function
3899/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003900bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3901 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003902 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003903 for (; P != PEnd; ++P) {
3904 ParmVarDecl *Param = *P;
3905
Mike Stumpf8c49212010-01-21 03:59:47 +00003906 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3907 // function declarator that is part of a function definition of
3908 // that function shall not have incomplete type.
3909 //
3910 // This is also C++ [dcl.fct]p6.
3911 if (!Param->isInvalidDecl() &&
3912 RequireCompleteType(Param->getLocation(), Param->getType(),
3913 diag::err_typecheck_decl_incomplete_type)) {
3914 Param->setInvalidDecl();
3915 HasInvalidParm = true;
3916 }
3917
3918 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3919 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003920 if (CheckParameterNames &&
3921 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003922 !Param->isImplicit() &&
3923 !getLangOptions().CPlusPlus)
3924 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003925
3926 // C99 6.7.5.3p12:
3927 // If the function declarator is not part of a definition of that
3928 // function, parameters may have incomplete type and may use the [*]
3929 // notation in their sequences of declarator specifiers to specify
3930 // variable length array types.
3931 QualType PType = Param->getOriginalType();
3932 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3933 if (AT->getSizeModifier() == ArrayType::Star) {
3934 // FIXME: This diagnosic should point the the '[*]' if source-location
3935 // information is added for it.
3936 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3937 }
3938 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003939 }
3940
3941 return HasInvalidParm;
3942}
John McCallb7f4ffe2010-08-12 21:44:57 +00003943
3944/// CheckCastAlign - Implements -Wcast-align, which warns when a
3945/// pointer cast increases the alignment requirements.
3946void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3947 // This is actually a lot of work to potentially be doing on every
3948 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003949 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3950 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00003951 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00003952 return;
3953
3954 // Ignore dependent types.
3955 if (T->isDependentType() || Op->getType()->isDependentType())
3956 return;
3957
3958 // Require that the destination be a pointer type.
3959 const PointerType *DestPtr = T->getAs<PointerType>();
3960 if (!DestPtr) return;
3961
3962 // If the destination has alignment 1, we're done.
3963 QualType DestPointee = DestPtr->getPointeeType();
3964 if (DestPointee->isIncompleteType()) return;
3965 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3966 if (DestAlign.isOne()) return;
3967
3968 // Require that the source be a pointer type.
3969 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3970 if (!SrcPtr) return;
3971 QualType SrcPointee = SrcPtr->getPointeeType();
3972
3973 // Whitelist casts from cv void*. We already implicitly
3974 // whitelisted casts to cv void*, since they have alignment 1.
3975 // Also whitelist casts involving incomplete types, which implicitly
3976 // includes 'void'.
3977 if (SrcPointee->isIncompleteType()) return;
3978
3979 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3980 if (SrcAlign >= DestAlign) return;
3981
3982 Diag(TRange.getBegin(), diag::warn_cast_align)
3983 << Op->getType() << T
3984 << static_cast<unsigned>(SrcAlign.getQuantity())
3985 << static_cast<unsigned>(DestAlign.getQuantity())
3986 << TRange << Op->getSourceRange();
3987}
3988
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003989static const Type* getElementType(const Expr *BaseExpr) {
3990 const Type* EltType = BaseExpr->getType().getTypePtr();
3991 if (EltType->isAnyPointerType())
3992 return EltType->getPointeeType().getTypePtr();
3993 else if (EltType->isArrayType())
3994 return EltType->getBaseElementTypeUnsafe();
3995 return EltType;
3996}
3997
Chandler Carruthc2684342011-08-05 09:10:50 +00003998/// \brief Check whether this array fits the idiom of a size-one tail padded
3999/// array member of a struct.
4000///
4001/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4002/// commonly used to emulate flexible arrays in C89 code.
4003static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4004 const NamedDecl *ND) {
4005 if (Size != 1 || !ND) return false;
4006
4007 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4008 if (!FD) return false;
4009
4010 // Don't consider sizes resulting from macro expansions or template argument
4011 // substitution to form C89 tail-padded arrays.
4012 ConstantArrayTypeLoc TL =
4013 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4014 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4015 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4016 return false;
4017
4018 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
4019 if (!RD || !RD->isStruct())
4020 return false;
4021
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004022 // See if this is the last field decl in the record.
4023 const Decl *D = FD;
4024 while ((D = D->getNextDeclInContext()))
4025 if (isa<FieldDecl>(D))
4026 return false;
4027 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004028}
4029
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004030void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
4031 bool isSubscript, bool AllowOnePastEnd) {
4032 const Type* EffectiveType = getElementType(BaseExpr);
4033 BaseExpr = BaseExpr->IgnoreParenCasts();
4034 IndexExpr = IndexExpr->IgnoreParenCasts();
4035
Chandler Carruth34064582011-02-17 20:55:08 +00004036 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004037 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004038 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004039 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004040
Chandler Carruth34064582011-02-17 20:55:08 +00004041 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00004042 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004043 llvm::APSInt index;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004044 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004045 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004046
Chandler Carruthba447122011-08-05 08:07:29 +00004047 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004048 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4049 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004050 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004051 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004052
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004053 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004054 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004055 if (!size.isStrictlyPositive())
4056 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004057
4058 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004059 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004060 // Make sure we're comparing apples to apples when comparing index to size
4061 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4062 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004063 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004064 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004065 if (ptrarith_typesize != array_typesize) {
4066 // There's a cast to a different size type involved
4067 uint64_t ratio = array_typesize / ptrarith_typesize;
4068 // TODO: Be smarter about handling cases where array_typesize is not a
4069 // multiple of ptrarith_typesize
4070 if (ptrarith_typesize * ratio == array_typesize)
4071 size *= llvm::APInt(size.getBitWidth(), ratio);
4072 }
4073 }
4074
Chandler Carruth34064582011-02-17 20:55:08 +00004075 if (size.getBitWidth() > index.getBitWidth())
4076 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004077 else if (size.getBitWidth() < index.getBitWidth())
4078 size = size.sext(index.getBitWidth());
4079
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004080 // For array subscripting the index must be less than size, but for pointer
4081 // arithmetic also allow the index (offset) to be equal to size since
4082 // computing the next address after the end of the array is legal and
4083 // commonly done e.g. in C++ iterators and range-based for loops.
4084 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004085 return;
4086
4087 // Also don't warn for arrays of size 1 which are members of some
4088 // structure. These are often used to approximate flexible arrays in C89
4089 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004090 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004091 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004092
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004093 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
4094 if (isSubscript)
4095 DiagID = diag::warn_array_index_exceeds_bounds;
4096
4097 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4098 PDiag(DiagID) << index.toString(10, true)
4099 << size.toString(10, true)
4100 << (unsigned)size.getLimitedValue(~0U)
4101 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004102 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004103 unsigned DiagID = diag::warn_array_index_precedes_bounds;
4104 if (!isSubscript) {
4105 DiagID = diag::warn_ptr_arith_precedes_bounds;
4106 if (index.isNegative()) index = -index;
4107 }
4108
4109 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4110 PDiag(DiagID) << index.toString(10, true)
4111 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004112 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004113
Chandler Carruth35001ca2011-02-17 21:10:52 +00004114 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004115 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4116 PDiag(diag::note_array_index_out_of_bounds)
4117 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004118}
4119
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004120void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004121 int AllowOnePastEnd = 0;
4122 while (expr) {
4123 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004124 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004125 case Stmt::ArraySubscriptExprClass: {
4126 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4127 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
4128 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004129 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004130 }
4131 case Stmt::UnaryOperatorClass: {
4132 // Only unwrap the * and & unary operators
4133 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4134 expr = UO->getSubExpr();
4135 switch (UO->getOpcode()) {
4136 case UO_AddrOf:
4137 AllowOnePastEnd++;
4138 break;
4139 case UO_Deref:
4140 AllowOnePastEnd--;
4141 break;
4142 default:
4143 return;
4144 }
4145 break;
4146 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004147 case Stmt::ConditionalOperatorClass: {
4148 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4149 if (const Expr *lhs = cond->getLHS())
4150 CheckArrayAccess(lhs);
4151 if (const Expr *rhs = cond->getRHS())
4152 CheckArrayAccess(rhs);
4153 return;
4154 }
4155 default:
4156 return;
4157 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004158 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004159}
John McCallf85e1932011-06-15 23:02:42 +00004160
4161//===--- CHECK: Objective-C retain cycles ----------------------------------//
4162
4163namespace {
4164 struct RetainCycleOwner {
4165 RetainCycleOwner() : Variable(0), Indirect(false) {}
4166 VarDecl *Variable;
4167 SourceRange Range;
4168 SourceLocation Loc;
4169 bool Indirect;
4170
4171 void setLocsFrom(Expr *e) {
4172 Loc = e->getExprLoc();
4173 Range = e->getSourceRange();
4174 }
4175 };
4176}
4177
4178/// Consider whether capturing the given variable can possibly lead to
4179/// a retain cycle.
4180static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4181 // In ARC, it's captured strongly iff the variable has __strong
4182 // lifetime. In MRR, it's captured strongly if the variable is
4183 // __block and has an appropriate type.
4184 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4185 return false;
4186
4187 owner.Variable = var;
4188 owner.setLocsFrom(ref);
4189 return true;
4190}
4191
4192static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4193 while (true) {
4194 e = e->IgnoreParens();
4195 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4196 switch (cast->getCastKind()) {
4197 case CK_BitCast:
4198 case CK_LValueBitCast:
4199 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004200 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004201 e = cast->getSubExpr();
4202 continue;
4203
John McCallf85e1932011-06-15 23:02:42 +00004204 default:
4205 return false;
4206 }
4207 }
4208
4209 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4210 ObjCIvarDecl *ivar = ref->getDecl();
4211 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4212 return false;
4213
4214 // Try to find a retain cycle in the base.
4215 if (!findRetainCycleOwner(ref->getBase(), owner))
4216 return false;
4217
4218 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4219 owner.Indirect = true;
4220 return true;
4221 }
4222
4223 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4224 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4225 if (!var) return false;
4226 return considerVariable(var, ref, owner);
4227 }
4228
4229 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4230 owner.Variable = ref->getDecl();
4231 owner.setLocsFrom(ref);
4232 return true;
4233 }
4234
4235 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4236 if (member->isArrow()) return false;
4237
4238 // Don't count this as an indirect ownership.
4239 e = member->getBase();
4240 continue;
4241 }
4242
John McCall4b9c2d22011-11-06 09:01:30 +00004243 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4244 // Only pay attention to pseudo-objects on property references.
4245 ObjCPropertyRefExpr *pre
4246 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4247 ->IgnoreParens());
4248 if (!pre) return false;
4249 if (pre->isImplicitProperty()) return false;
4250 ObjCPropertyDecl *property = pre->getExplicitProperty();
4251 if (!property->isRetaining() &&
4252 !(property->getPropertyIvarDecl() &&
4253 property->getPropertyIvarDecl()->getType()
4254 .getObjCLifetime() == Qualifiers::OCL_Strong))
4255 return false;
4256
4257 owner.Indirect = true;
4258 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4259 ->getSourceExpr());
4260 continue;
4261 }
4262
John McCallf85e1932011-06-15 23:02:42 +00004263 // Array ivars?
4264
4265 return false;
4266 }
4267}
4268
4269namespace {
4270 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4271 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4272 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4273 Variable(variable), Capturer(0) {}
4274
4275 VarDecl *Variable;
4276 Expr *Capturer;
4277
4278 void VisitDeclRefExpr(DeclRefExpr *ref) {
4279 if (ref->getDecl() == Variable && !Capturer)
4280 Capturer = ref;
4281 }
4282
4283 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4284 if (ref->getDecl() == Variable && !Capturer)
4285 Capturer = ref;
4286 }
4287
4288 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4289 if (Capturer) return;
4290 Visit(ref->getBase());
4291 if (Capturer && ref->isFreeIvar())
4292 Capturer = ref;
4293 }
4294
4295 void VisitBlockExpr(BlockExpr *block) {
4296 // Look inside nested blocks
4297 if (block->getBlockDecl()->capturesVariable(Variable))
4298 Visit(block->getBlockDecl()->getBody());
4299 }
4300 };
4301}
4302
4303/// Check whether the given argument is a block which captures a
4304/// variable.
4305static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4306 assert(owner.Variable && owner.Loc.isValid());
4307
4308 e = e->IgnoreParenCasts();
4309 BlockExpr *block = dyn_cast<BlockExpr>(e);
4310 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4311 return 0;
4312
4313 FindCaptureVisitor visitor(S.Context, owner.Variable);
4314 visitor.Visit(block->getBlockDecl()->getBody());
4315 return visitor.Capturer;
4316}
4317
4318static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4319 RetainCycleOwner &owner) {
4320 assert(capturer);
4321 assert(owner.Variable && owner.Loc.isValid());
4322
4323 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4324 << owner.Variable << capturer->getSourceRange();
4325 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4326 << owner.Indirect << owner.Range;
4327}
4328
4329/// Check for a keyword selector that starts with the word 'add' or
4330/// 'set'.
4331static bool isSetterLikeSelector(Selector sel) {
4332 if (sel.isUnarySelector()) return false;
4333
Chris Lattner5f9e2722011-07-23 10:55:15 +00004334 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004335 while (!str.empty() && str.front() == '_') str = str.substr(1);
4336 if (str.startswith("set") || str.startswith("add"))
4337 str = str.substr(3);
4338 else
4339 return false;
4340
4341 if (str.empty()) return true;
4342 return !islower(str.front());
4343}
4344
4345/// Check a message send to see if it's likely to cause a retain cycle.
4346void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4347 // Only check instance methods whose selector looks like a setter.
4348 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4349 return;
4350
4351 // Try to find a variable that the receiver is strongly owned by.
4352 RetainCycleOwner owner;
4353 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4354 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4355 return;
4356 } else {
4357 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4358 owner.Variable = getCurMethodDecl()->getSelfDecl();
4359 owner.Loc = msg->getSuperLoc();
4360 owner.Range = msg->getSuperLoc();
4361 }
4362
4363 // Check whether the receiver is captured by any of the arguments.
4364 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4365 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4366 return diagnoseRetainCycle(*this, capturer, owner);
4367}
4368
4369/// Check a property assign to see if it's likely to cause a retain cycle.
4370void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4371 RetainCycleOwner owner;
4372 if (!findRetainCycleOwner(receiver, owner))
4373 return;
4374
4375 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4376 diagnoseRetainCycle(*this, capturer, owner);
4377}
4378
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004379bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004380 QualType LHS, Expr *RHS) {
4381 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4382 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004383 return false;
4384 // strip off any implicit cast added to get to the one arc-specific
4385 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004386 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004387 Diag(Loc, diag::warn_arc_retained_assign)
4388 << (LT == Qualifiers::OCL_ExplicitNone)
4389 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004390 return true;
4391 }
4392 RHS = cast->getSubExpr();
4393 }
4394 return false;
John McCallf85e1932011-06-15 23:02:42 +00004395}
4396
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004397void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4398 Expr *LHS, Expr *RHS) {
4399 QualType LHSType = LHS->getType();
4400 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4401 return;
4402 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4403 // FIXME. Check for other life times.
4404 if (LT != Qualifiers::OCL_None)
4405 return;
4406
John McCall3c3b7f92011-10-25 17:37:35 +00004407 if (ObjCPropertyRefExpr *PRE
4408 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004409 if (PRE->isImplicitProperty())
4410 return;
4411 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4412 if (!PD)
4413 return;
4414
4415 unsigned Attributes = PD->getPropertyAttributes();
4416 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4417 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004418 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004419 Diag(Loc, diag::warn_arc_retained_property_assign)
4420 << RHS->getSourceRange();
4421 return;
4422 }
4423 RHS = cast->getSubExpr();
4424 }
4425 }
4426}