blob: c4ed0b0e5293befd0b4cfd1bdb03f398d2832018 [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"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000033#include "llvm/ADT/SmallString.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000034#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000035#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000036#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000037#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000038#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000039#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000040using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000041using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000042
Chris Lattner60800082009-02-18 17:49:48 +000043SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000045 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000046 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000047}
48
John McCall8e10f3b2011-02-26 05:39:39 +000049/// Checks that a call expression's argument count is the desired number.
50/// This is useful when doing custom type-checking. Returns true on error.
51static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
52 unsigned argCount = call->getNumArgs();
53 if (argCount == desiredArgCount) return false;
54
55 if (argCount < desiredArgCount)
56 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
57 << 0 /*function call*/ << desiredArgCount << argCount
58 << call->getSourceRange();
59
60 // Highlight all the excess arguments.
61 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
62 call->getArg(argCount - 1)->getLocEnd());
63
64 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
65 << 0 /*function call*/ << desiredArgCount << argCount
66 << call->getArg(1)->getSourceRange();
67}
68
Julien Lerouge77f68bb2011-09-09 22:41:49 +000069/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
70/// annotation is a non wide string literal.
71static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
72 Arg = Arg->IgnoreParenCasts();
73 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
74 if (!Literal || !Literal->isAscii()) {
75 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
76 << Arg->getSourceRange();
77 return true;
78 }
79 return false;
80}
81
John McCall60d7b3a2010-08-24 06:29:42 +000082ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000083Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000084 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000085
Chris Lattner946928f2010-10-01 23:23:24 +000086 // Find out if any arguments are required to be integer constant expressions.
87 unsigned ICEArguments = 0;
88 ASTContext::GetBuiltinTypeError Error;
89 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
90 if (Error != ASTContext::GE_None)
91 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
92
93 // If any arguments are required to be ICE's, check and diagnose.
94 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
95 // Skip arguments not required to be ICE's.
96 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
97
98 llvm::APSInt Result;
99 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
100 return true;
101 ICEArguments &= ~(1 << ArgNo);
102 }
103
Anders Carlssond406bf02009-08-16 01:56:34 +0000104 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000105 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000106 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000107 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000108 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000109 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000110 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000111 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000112 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000113 if (SemaBuiltinVAStart(TheCall))
114 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000115 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000116 case Builtin::BI__builtin_isgreater:
117 case Builtin::BI__builtin_isgreaterequal:
118 case Builtin::BI__builtin_isless:
119 case Builtin::BI__builtin_islessequal:
120 case Builtin::BI__builtin_islessgreater:
121 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000122 if (SemaBuiltinUnorderedCompare(TheCall))
123 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000124 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000125 case Builtin::BI__builtin_fpclassify:
126 if (SemaBuiltinFPClassification(TheCall, 6))
127 return ExprError();
128 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000129 case Builtin::BI__builtin_isfinite:
130 case Builtin::BI__builtin_isinf:
131 case Builtin::BI__builtin_isinf_sign:
132 case Builtin::BI__builtin_isnan:
133 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000134 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000135 return ExprError();
136 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000137 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 return SemaBuiltinShuffleVector(TheCall);
139 // TheCall will be freed by the smart pointer here, but that's fine, since
140 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000141 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000142 if (SemaBuiltinPrefetch(TheCall))
143 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000144 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000145 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000146 if (SemaBuiltinObjectSize(TheCall))
147 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000148 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000149 case Builtin::BI__builtin_longjmp:
150 if (SemaBuiltinLongjmp(TheCall))
151 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000152 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000153
154 case Builtin::BI__builtin_classify_type:
155 if (checkArgCount(*this, TheCall, 1)) return true;
156 TheCall->setType(Context.IntTy);
157 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000158 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000159 if (checkArgCount(*this, TheCall, 1)) return true;
160 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000161 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000162 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000163 case Builtin::BI__sync_fetch_and_add_1:
164 case Builtin::BI__sync_fetch_and_add_2:
165 case Builtin::BI__sync_fetch_and_add_4:
166 case Builtin::BI__sync_fetch_and_add_8:
167 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000168 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000169 case Builtin::BI__sync_fetch_and_sub_1:
170 case Builtin::BI__sync_fetch_and_sub_2:
171 case Builtin::BI__sync_fetch_and_sub_4:
172 case Builtin::BI__sync_fetch_and_sub_8:
173 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000174 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000175 case Builtin::BI__sync_fetch_and_or_1:
176 case Builtin::BI__sync_fetch_and_or_2:
177 case Builtin::BI__sync_fetch_and_or_4:
178 case Builtin::BI__sync_fetch_and_or_8:
179 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000180 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000181 case Builtin::BI__sync_fetch_and_and_1:
182 case Builtin::BI__sync_fetch_and_and_2:
183 case Builtin::BI__sync_fetch_and_and_4:
184 case Builtin::BI__sync_fetch_and_and_8:
185 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000186 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000187 case Builtin::BI__sync_fetch_and_xor_1:
188 case Builtin::BI__sync_fetch_and_xor_2:
189 case Builtin::BI__sync_fetch_and_xor_4:
190 case Builtin::BI__sync_fetch_and_xor_8:
191 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000192 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000193 case Builtin::BI__sync_add_and_fetch_1:
194 case Builtin::BI__sync_add_and_fetch_2:
195 case Builtin::BI__sync_add_and_fetch_4:
196 case Builtin::BI__sync_add_and_fetch_8:
197 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000198 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000199 case Builtin::BI__sync_sub_and_fetch_1:
200 case Builtin::BI__sync_sub_and_fetch_2:
201 case Builtin::BI__sync_sub_and_fetch_4:
202 case Builtin::BI__sync_sub_and_fetch_8:
203 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000204 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000205 case Builtin::BI__sync_and_and_fetch_1:
206 case Builtin::BI__sync_and_and_fetch_2:
207 case Builtin::BI__sync_and_and_fetch_4:
208 case Builtin::BI__sync_and_and_fetch_8:
209 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000210 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000211 case Builtin::BI__sync_or_and_fetch_1:
212 case Builtin::BI__sync_or_and_fetch_2:
213 case Builtin::BI__sync_or_and_fetch_4:
214 case Builtin::BI__sync_or_and_fetch_8:
215 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000216 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000217 case Builtin::BI__sync_xor_and_fetch_1:
218 case Builtin::BI__sync_xor_and_fetch_2:
219 case Builtin::BI__sync_xor_and_fetch_4:
220 case Builtin::BI__sync_xor_and_fetch_8:
221 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000222 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000223 case Builtin::BI__sync_val_compare_and_swap_1:
224 case Builtin::BI__sync_val_compare_and_swap_2:
225 case Builtin::BI__sync_val_compare_and_swap_4:
226 case Builtin::BI__sync_val_compare_and_swap_8:
227 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000228 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000229 case Builtin::BI__sync_bool_compare_and_swap_1:
230 case Builtin::BI__sync_bool_compare_and_swap_2:
231 case Builtin::BI__sync_bool_compare_and_swap_4:
232 case Builtin::BI__sync_bool_compare_and_swap_8:
233 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000234 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000235 case Builtin::BI__sync_lock_test_and_set_1:
236 case Builtin::BI__sync_lock_test_and_set_2:
237 case Builtin::BI__sync_lock_test_and_set_4:
238 case Builtin::BI__sync_lock_test_and_set_8:
239 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000240 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000241 case Builtin::BI__sync_lock_release_1:
242 case Builtin::BI__sync_lock_release_2:
243 case Builtin::BI__sync_lock_release_4:
244 case Builtin::BI__sync_lock_release_8:
245 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000246 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000247 case Builtin::BI__sync_swap_1:
248 case Builtin::BI__sync_swap_2:
249 case Builtin::BI__sync_swap_4:
250 case Builtin::BI__sync_swap_8:
251 case Builtin::BI__sync_swap_16:
Chandler Carruthd2014572010-07-09 18:59:35 +0000252 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000253 case Builtin::BI__atomic_load:
Richard Smithfafbf062012-04-11 17:55:32 +0000254 case Builtin::BI__c11_atomic_load:
Eli Friedman276b0612011-10-11 02:20:01 +0000255 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
256 case Builtin::BI__atomic_store:
Richard Smithfafbf062012-04-11 17:55:32 +0000257 case Builtin::BI__c11_atomic_store:
Eli Friedman276b0612011-10-11 02:20:01 +0000258 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
David Chisnall7a7ee302012-01-16 17:27:18 +0000259 case Builtin::BI__atomic_init:
Richard Smithfafbf062012-04-11 17:55:32 +0000260 case Builtin::BI__c11_atomic_init:
David Chisnall7a7ee302012-01-16 17:27:18 +0000261 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
Eli Friedman276b0612011-10-11 02:20:01 +0000262 case Builtin::BI__atomic_exchange:
Richard Smithfafbf062012-04-11 17:55:32 +0000263 case Builtin::BI__c11_atomic_exchange:
Eli Friedman276b0612011-10-11 02:20:01 +0000264 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
265 case Builtin::BI__atomic_compare_exchange_strong:
Richard Smithfafbf062012-04-11 17:55:32 +0000266 case Builtin::BI__c11_atomic_compare_exchange_strong:
Eli Friedman276b0612011-10-11 02:20:01 +0000267 return SemaAtomicOpsOverloaded(move(TheCallResult),
268 AtomicExpr::CmpXchgStrong);
269 case Builtin::BI__atomic_compare_exchange_weak:
Richard Smithfafbf062012-04-11 17:55:32 +0000270 case Builtin::BI__c11_atomic_compare_exchange_weak:
Eli Friedman276b0612011-10-11 02:20:01 +0000271 return SemaAtomicOpsOverloaded(move(TheCallResult),
272 AtomicExpr::CmpXchgWeak);
273 case Builtin::BI__atomic_fetch_add:
Richard Smithfafbf062012-04-11 17:55:32 +0000274 case Builtin::BI__c11_atomic_fetch_add:
Eli Friedman276b0612011-10-11 02:20:01 +0000275 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
276 case Builtin::BI__atomic_fetch_sub:
Richard Smithfafbf062012-04-11 17:55:32 +0000277 case Builtin::BI__c11_atomic_fetch_sub:
Eli Friedman276b0612011-10-11 02:20:01 +0000278 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
279 case Builtin::BI__atomic_fetch_and:
Richard Smithfafbf062012-04-11 17:55:32 +0000280 case Builtin::BI__c11_atomic_fetch_and:
Eli Friedman276b0612011-10-11 02:20:01 +0000281 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
282 case Builtin::BI__atomic_fetch_or:
Richard Smithfafbf062012-04-11 17:55:32 +0000283 case Builtin::BI__c11_atomic_fetch_or:
Eli Friedman276b0612011-10-11 02:20:01 +0000284 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
285 case Builtin::BI__atomic_fetch_xor:
Richard Smithfafbf062012-04-11 17:55:32 +0000286 case Builtin::BI__c11_atomic_fetch_xor:
Eli Friedman276b0612011-10-11 02:20:01 +0000287 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000288 case Builtin::BI__builtin_annotation:
289 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
290 return ExprError();
291 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000292 }
293
294 // Since the target specific builtins for each arch overlap, only check those
295 // of the arch we are compiling for.
296 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000297 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000298 case llvm::Triple::arm:
299 case llvm::Triple::thumb:
300 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
301 return ExprError();
302 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000303 default:
304 break;
305 }
306 }
307
308 return move(TheCallResult);
309}
310
Nate Begeman61eecf52010-06-14 05:21:25 +0000311// Get the valid immediate range for the specified NEON type code.
312static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000313 NeonTypeFlags Type(t);
314 int IsQuad = Type.isQuad();
315 switch (Type.getEltType()) {
316 case NeonTypeFlags::Int8:
317 case NeonTypeFlags::Poly8:
318 return shift ? 7 : (8 << IsQuad) - 1;
319 case NeonTypeFlags::Int16:
320 case NeonTypeFlags::Poly16:
321 return shift ? 15 : (4 << IsQuad) - 1;
322 case NeonTypeFlags::Int32:
323 return shift ? 31 : (2 << IsQuad) - 1;
324 case NeonTypeFlags::Int64:
325 return shift ? 63 : (1 << IsQuad) - 1;
326 case NeonTypeFlags::Float16:
327 assert(!shift && "cannot shift float types!");
328 return (4 << IsQuad) - 1;
329 case NeonTypeFlags::Float32:
330 assert(!shift && "cannot shift float types!");
331 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000332 }
David Blaikie7530c032012-01-17 06:56:22 +0000333 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000334}
335
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000336/// getNeonEltType - Return the QualType corresponding to the elements of
337/// the vector type specified by the NeonTypeFlags. This is used to check
338/// the pointer arguments for Neon load/store intrinsics.
339static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
340 switch (Flags.getEltType()) {
341 case NeonTypeFlags::Int8:
342 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
343 case NeonTypeFlags::Int16:
344 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
345 case NeonTypeFlags::Int32:
346 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
347 case NeonTypeFlags::Int64:
348 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
349 case NeonTypeFlags::Poly8:
350 return Context.SignedCharTy;
351 case NeonTypeFlags::Poly16:
352 return Context.ShortTy;
353 case NeonTypeFlags::Float16:
354 return Context.UnsignedShortTy;
355 case NeonTypeFlags::Float32:
356 return Context.FloatTy;
357 }
David Blaikie7530c032012-01-17 06:56:22 +0000358 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000359}
360
Nate Begeman26a31422010-06-08 02:47:44 +0000361bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000362 llvm::APSInt Result;
363
Nate Begeman0d15c532010-06-13 04:47:52 +0000364 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000365 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000366 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000367 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000368 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000369#define GET_NEON_OVERLOAD_CHECK
370#include "clang/Basic/arm_neon.inc"
371#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000372 }
373
Nate Begeman0d15c532010-06-13 04:47:52 +0000374 // For NEON intrinsics which are overloaded on vector element type, validate
375 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000376 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000377 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000378 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000379 return true;
380
Bob Wilsonda95f732011-11-08 01:16:11 +0000381 TV = Result.getLimitedValue(64);
382 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000383 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000384 << TheCall->getArg(ImmArg)->getSourceRange();
385 }
386
Bob Wilson46482552011-11-16 21:32:23 +0000387 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000388 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000389 Expr *Arg = TheCall->getArg(PtrArgNum);
390 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
391 Arg = ICE->getSubExpr();
392 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
393 QualType RHSTy = RHS.get()->getType();
394 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
395 if (HasConstPtr)
396 EltTy = EltTy.withConst();
397 QualType LHSTy = Context.getPointerType(EltTy);
398 AssignConvertType ConvTy;
399 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
400 if (RHS.isInvalid())
401 return true;
402 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
403 RHS.get(), AA_Assigning))
404 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000405 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000406
Nate Begeman0d15c532010-06-13 04:47:52 +0000407 // For NEON intrinsics which take an immediate value as part of the
408 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000409 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000410 switch (BuiltinID) {
411 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000412 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
413 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000414 case ARM::BI__builtin_arm_vcvtr_f:
415 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000416#define GET_NEON_IMMEDIATE_CHECK
417#include "clang/Basic/arm_neon.inc"
418#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000419 };
420
Nate Begeman61eecf52010-06-14 05:21:25 +0000421 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000422 if (SemaBuiltinConstantArg(TheCall, i, Result))
423 return true;
424
Nate Begeman61eecf52010-06-14 05:21:25 +0000425 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000426 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000427 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000428 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000429 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000430
Nate Begeman99c40bb2010-08-03 21:32:34 +0000431 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000432 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000433}
Daniel Dunbarde454282008-10-02 18:44:07 +0000434
Anders Carlssond406bf02009-08-16 01:56:34 +0000435/// CheckFunctionCall - Check a direct function call for various correctness
436/// and safety properties not strictly enforced by the C type system.
437bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
438 // Get the IdentifierInfo* for the called function.
439 IdentifierInfo *FnInfo = FDecl->getIdentifier();
440
441 // None of the checks below are needed for functions that don't have
442 // simple names (e.g., C++ conversion functions).
443 if (!FnInfo)
444 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Daniel Dunbarde454282008-10-02 18:44:07 +0000446 // FIXME: This mechanism should be abstracted to be less fragile and
447 // more efficient. For example, just map function ids to custom
448 // handlers.
449
Ted Kremenekc82faca2010-09-09 04:33:05 +0000450 // Printf and scanf checking.
451 for (specific_attr_iterator<FormatAttr>
452 i = FDecl->specific_attr_begin<FormatAttr>(),
453 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000454 CheckFormatArguments(*i, TheCall);
Chris Lattner59907c42007-08-10 20:18:51 +0000455 }
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Ted Kremenekc82faca2010-09-09 04:33:05 +0000457 for (specific_attr_iterator<NonNullAttr>
458 i = FDecl->specific_attr_begin<NonNullAttr>(),
459 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000460 CheckNonNullArguments(*i, TheCall->getArgs(),
461 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000462 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000463
Anna Zaks0a151a12012-01-17 00:37:07 +0000464 unsigned CMId = FDecl->getMemoryFunctionKind();
465 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000466 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000467
Anna Zaksd9b859a2012-01-13 21:52:01 +0000468 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000469 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000470 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000471 else if (CMId == Builtin::BIstrncat)
472 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000473 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000474 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000475
Anders Carlssond406bf02009-08-16 01:56:34 +0000476 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000477}
478
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000479bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
480 Expr **Args, unsigned NumArgs) {
481 for (specific_attr_iterator<FormatAttr>
482 i = Method->specific_attr_begin<FormatAttr>(),
483 e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
484
485 CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
486 Method->getSourceRange());
487 }
488
489 // diagnose nonnull arguments.
490 for (specific_attr_iterator<NonNullAttr>
491 i = Method->specific_attr_begin<NonNullAttr>(),
492 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
493 CheckNonNullArguments(*i, Args, lbrac);
494 }
495
496 return false;
497}
498
Anders Carlssond406bf02009-08-16 01:56:34 +0000499bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
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
Jean-Daniel Dupas43d12512012-01-25 00:55:11 +0000508 // format string checking.
509 for (specific_attr_iterator<FormatAttr>
510 i = NDecl->specific_attr_begin<FormatAttr>(),
511 e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
512 CheckFormatArguments(*i, TheCall);
513 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000514
515 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000516}
517
Eli Friedman276b0612011-10-11 02:20:01 +0000518ExprResult
519Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
520 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
521 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000522
523 // All these operations take one of the following four forms:
Richard Smithfafbf062012-04-11 17:55:32 +0000524 // T __c11_atomic_load(_Atomic(T)*, int) (loads)
525 // T* __c11_atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
526 // int __c11_atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
527 // (cmpxchg)
528 // T __c11_atomic_exchange(_Atomic(T)*, T, int) (everything else)
Eli Friedman276b0612011-10-11 02:20:01 +0000529 // where T is an appropriate type, and the int paremeterss are for orderings.
530 unsigned NumVals = 1;
531 unsigned NumOrders = 1;
532 if (Op == AtomicExpr::Load) {
533 NumVals = 0;
534 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
535 NumVals = 2;
536 NumOrders = 2;
537 }
David Chisnall7a7ee302012-01-16 17:27:18 +0000538 if (Op == AtomicExpr::Init)
539 NumOrders = 0;
Eli Friedman276b0612011-10-11 02:20:01 +0000540
541 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
542 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
543 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
544 << TheCall->getCallee()->getSourceRange();
545 return ExprError();
546 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
547 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
548 diag::err_typecheck_call_too_many_args)
549 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
550 << TheCall->getCallee()->getSourceRange();
551 return ExprError();
552 }
553
554 // Inspect the first argument of the atomic operation. This should always be
555 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000556 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000557 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
558 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
559 if (!pointerType) {
560 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
561 << Ptr->getType() << Ptr->getSourceRange();
562 return ExprError();
563 }
564
565 QualType AtomTy = pointerType->getPointeeType();
566 if (!AtomTy->isAtomicType()) {
567 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
568 << Ptr->getType() << Ptr->getSourceRange();
569 return ExprError();
570 }
571 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
572
573 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
574 !ValType->isIntegerType() && !ValType->isPointerType()) {
575 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
576 << Ptr->getType() << Ptr->getSourceRange();
577 return ExprError();
578 }
579
580 if (!ValType->isIntegerType() &&
581 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
582 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
583 << Ptr->getType() << Ptr->getSourceRange();
584 return ExprError();
585 }
586
587 switch (ValType.getObjCLifetime()) {
588 case Qualifiers::OCL_None:
589 case Qualifiers::OCL_ExplicitNone:
590 // okay
591 break;
592
593 case Qualifiers::OCL_Weak:
594 case Qualifiers::OCL_Strong:
595 case Qualifiers::OCL_Autoreleasing:
596 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
597 << ValType << Ptr->getSourceRange();
598 return ExprError();
599 }
600
601 QualType ResultType = ValType;
David Chisnall7a7ee302012-01-16 17:27:18 +0000602 if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000603 ResultType = Context.VoidTy;
604 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
605 ResultType = Context.BoolTy;
606
607 // The first argument --- the pointer --- has a fixed type; we
608 // deduce the types of the rest of the arguments accordingly. Walk
609 // the remaining arguments, converting them to the deduced value type.
610 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
611 ExprResult Arg = TheCall->getArg(i);
612 QualType Ty;
613 if (i < NumVals+1) {
614 // The second argument to a cmpxchg is a pointer to the data which will
615 // be exchanged. The second argument to a pointer add/subtract is the
616 // amount to add/subtract, which must be a ptrdiff_t. The third
617 // argument to a cmpxchg and the second argument in all other cases
618 // is the type of the value.
619 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
620 Op == AtomicExpr::CmpXchgStrong))
621 Ty = Context.getPointerType(ValType.getUnqualifiedType());
622 else if (!ValType->isIntegerType() &&
623 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
624 Ty = Context.getPointerDiffType();
625 else
626 Ty = ValType;
627 } else {
628 // The order(s) are always converted to int.
629 Ty = Context.IntTy;
630 }
631 InitializedEntity Entity =
632 InitializedEntity::InitializeParameter(Context, Ty, false);
633 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
634 if (Arg.isInvalid())
635 return true;
636 TheCall->setArg(i, Arg.get());
637 }
638
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000639 SmallVector<Expr*, 5> SubExprs;
640 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000641 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000642 SubExprs.push_back(TheCall->getArg(1)); // Order
David Chisnall7a7ee302012-01-16 17:27:18 +0000643 } else if (Op == AtomicExpr::Init) {
644 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000645 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000646 SubExprs.push_back(TheCall->getArg(2)); // Order
647 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000648 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000649 SubExprs.push_back(TheCall->getArg(3)); // Order
650 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000651 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000652 SubExprs.push_back(TheCall->getArg(2)); // Val2
Eli Friedman276b0612011-10-11 02:20:01 +0000653 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000654
655 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
656 SubExprs.data(), SubExprs.size(),
657 ResultType, Op,
658 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000659}
660
661
John McCall5f8d6042011-08-27 01:09:30 +0000662/// checkBuiltinArgument - Given a call to a builtin function, perform
663/// normal type-checking on the given argument, updating the call in
664/// place. This is useful when a builtin function requires custom
665/// type-checking for some of its arguments but not necessarily all of
666/// them.
667///
668/// Returns true on error.
669static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
670 FunctionDecl *Fn = E->getDirectCallee();
671 assert(Fn && "builtin call without direct callee!");
672
673 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
674 InitializedEntity Entity =
675 InitializedEntity::InitializeParameter(S.Context, Param);
676
677 ExprResult Arg = E->getArg(0);
678 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
679 if (Arg.isInvalid())
680 return true;
681
682 E->setArg(ArgIndex, Arg.take());
683 return false;
684}
685
Chris Lattner5caa3702009-05-08 06:58:22 +0000686/// SemaBuiltinAtomicOverloaded - We have a call to a function like
687/// __sync_fetch_and_add, which is an overloaded function based on the pointer
688/// type of its first argument. The main ActOnCallExpr routines have already
689/// promoted the types of arguments because all of these calls are prototyped as
690/// void(...).
691///
692/// This function goes through and does final semantic checking for these
693/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000694ExprResult
695Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000696 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000697 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
698 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
699
700 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000701 if (TheCall->getNumArgs() < 1) {
702 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
703 << 0 << 1 << TheCall->getNumArgs()
704 << TheCall->getCallee()->getSourceRange();
705 return ExprError();
706 }
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Chris Lattner5caa3702009-05-08 06:58:22 +0000708 // Inspect the first argument of the atomic builtin. This should always be
709 // a pointer type, whose element is an integral scalar or pointer type.
710 // Because it is a pointer type, we don't have to worry about any implicit
711 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000712 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000713 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +0000714 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
715 if (FirstArgResult.isInvalid())
716 return ExprError();
717 FirstArg = FirstArgResult.take();
718 TheCall->setArg(0, FirstArg);
719
John McCallf85e1932011-06-15 23:02:42 +0000720 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
721 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000722 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
723 << FirstArg->getType() << FirstArg->getSourceRange();
724 return ExprError();
725 }
Mike Stump1eb44332009-09-09 15:08:12 +0000726
John McCallf85e1932011-06-15 23:02:42 +0000727 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000728 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000729 !ValType->isBlockPointerType()) {
730 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
731 << FirstArg->getType() << FirstArg->getSourceRange();
732 return ExprError();
733 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000734
John McCallf85e1932011-06-15 23:02:42 +0000735 switch (ValType.getObjCLifetime()) {
736 case Qualifiers::OCL_None:
737 case Qualifiers::OCL_ExplicitNone:
738 // okay
739 break;
740
741 case Qualifiers::OCL_Weak:
742 case Qualifiers::OCL_Strong:
743 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000744 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000745 << ValType << FirstArg->getSourceRange();
746 return ExprError();
747 }
748
John McCallb45ae252011-10-05 07:41:44 +0000749 // Strip any qualifiers off ValType.
750 ValType = ValType.getUnqualifiedType();
751
Chandler Carruth8d13d222010-07-18 20:54:12 +0000752 // The majority of builtins return a value, but a few have special return
753 // types, so allow them to override appropriately below.
754 QualType ResultType = ValType;
755
Chris Lattner5caa3702009-05-08 06:58:22 +0000756 // We need to figure out which concrete builtin this maps onto. For example,
757 // __sync_fetch_and_add with a 2 byte object turns into
758 // __sync_fetch_and_add_2.
759#define BUILTIN_ROW(x) \
760 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
761 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Chris Lattner5caa3702009-05-08 06:58:22 +0000763 static const unsigned BuiltinIndices[][5] = {
764 BUILTIN_ROW(__sync_fetch_and_add),
765 BUILTIN_ROW(__sync_fetch_and_sub),
766 BUILTIN_ROW(__sync_fetch_and_or),
767 BUILTIN_ROW(__sync_fetch_and_and),
768 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Chris Lattner5caa3702009-05-08 06:58:22 +0000770 BUILTIN_ROW(__sync_add_and_fetch),
771 BUILTIN_ROW(__sync_sub_and_fetch),
772 BUILTIN_ROW(__sync_and_and_fetch),
773 BUILTIN_ROW(__sync_or_and_fetch),
774 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000775
Chris Lattner5caa3702009-05-08 06:58:22 +0000776 BUILTIN_ROW(__sync_val_compare_and_swap),
777 BUILTIN_ROW(__sync_bool_compare_and_swap),
778 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000779 BUILTIN_ROW(__sync_lock_release),
780 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000781 };
Mike Stump1eb44332009-09-09 15:08:12 +0000782#undef BUILTIN_ROW
783
Chris Lattner5caa3702009-05-08 06:58:22 +0000784 // Determine the index of the size.
785 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000786 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000787 case 1: SizeIndex = 0; break;
788 case 2: SizeIndex = 1; break;
789 case 4: SizeIndex = 2; break;
790 case 8: SizeIndex = 3; break;
791 case 16: SizeIndex = 4; break;
792 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000793 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
794 << FirstArg->getType() << FirstArg->getSourceRange();
795 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Chris Lattner5caa3702009-05-08 06:58:22 +0000798 // Each of these builtins has one pointer argument, followed by some number of
799 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
800 // that we ignore. Find out which row of BuiltinIndices to read from as well
801 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000802 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000803 unsigned BuiltinIndex, NumFixed = 1;
804 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000805 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +0000806 case Builtin::BI__sync_fetch_and_add:
807 case Builtin::BI__sync_fetch_and_add_1:
808 case Builtin::BI__sync_fetch_and_add_2:
809 case Builtin::BI__sync_fetch_and_add_4:
810 case Builtin::BI__sync_fetch_and_add_8:
811 case Builtin::BI__sync_fetch_and_add_16:
812 BuiltinIndex = 0;
813 break;
814
815 case Builtin::BI__sync_fetch_and_sub:
816 case Builtin::BI__sync_fetch_and_sub_1:
817 case Builtin::BI__sync_fetch_and_sub_2:
818 case Builtin::BI__sync_fetch_and_sub_4:
819 case Builtin::BI__sync_fetch_and_sub_8:
820 case Builtin::BI__sync_fetch_and_sub_16:
821 BuiltinIndex = 1;
822 break;
823
824 case Builtin::BI__sync_fetch_and_or:
825 case Builtin::BI__sync_fetch_and_or_1:
826 case Builtin::BI__sync_fetch_and_or_2:
827 case Builtin::BI__sync_fetch_and_or_4:
828 case Builtin::BI__sync_fetch_and_or_8:
829 case Builtin::BI__sync_fetch_and_or_16:
830 BuiltinIndex = 2;
831 break;
832
833 case Builtin::BI__sync_fetch_and_and:
834 case Builtin::BI__sync_fetch_and_and_1:
835 case Builtin::BI__sync_fetch_and_and_2:
836 case Builtin::BI__sync_fetch_and_and_4:
837 case Builtin::BI__sync_fetch_and_and_8:
838 case Builtin::BI__sync_fetch_and_and_16:
839 BuiltinIndex = 3;
840 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Douglas Gregora9766412011-11-28 16:30:08 +0000842 case Builtin::BI__sync_fetch_and_xor:
843 case Builtin::BI__sync_fetch_and_xor_1:
844 case Builtin::BI__sync_fetch_and_xor_2:
845 case Builtin::BI__sync_fetch_and_xor_4:
846 case Builtin::BI__sync_fetch_and_xor_8:
847 case Builtin::BI__sync_fetch_and_xor_16:
848 BuiltinIndex = 4;
849 break;
850
851 case Builtin::BI__sync_add_and_fetch:
852 case Builtin::BI__sync_add_and_fetch_1:
853 case Builtin::BI__sync_add_and_fetch_2:
854 case Builtin::BI__sync_add_and_fetch_4:
855 case Builtin::BI__sync_add_and_fetch_8:
856 case Builtin::BI__sync_add_and_fetch_16:
857 BuiltinIndex = 5;
858 break;
859
860 case Builtin::BI__sync_sub_and_fetch:
861 case Builtin::BI__sync_sub_and_fetch_1:
862 case Builtin::BI__sync_sub_and_fetch_2:
863 case Builtin::BI__sync_sub_and_fetch_4:
864 case Builtin::BI__sync_sub_and_fetch_8:
865 case Builtin::BI__sync_sub_and_fetch_16:
866 BuiltinIndex = 6;
867 break;
868
869 case Builtin::BI__sync_and_and_fetch:
870 case Builtin::BI__sync_and_and_fetch_1:
871 case Builtin::BI__sync_and_and_fetch_2:
872 case Builtin::BI__sync_and_and_fetch_4:
873 case Builtin::BI__sync_and_and_fetch_8:
874 case Builtin::BI__sync_and_and_fetch_16:
875 BuiltinIndex = 7;
876 break;
877
878 case Builtin::BI__sync_or_and_fetch:
879 case Builtin::BI__sync_or_and_fetch_1:
880 case Builtin::BI__sync_or_and_fetch_2:
881 case Builtin::BI__sync_or_and_fetch_4:
882 case Builtin::BI__sync_or_and_fetch_8:
883 case Builtin::BI__sync_or_and_fetch_16:
884 BuiltinIndex = 8;
885 break;
886
887 case Builtin::BI__sync_xor_and_fetch:
888 case Builtin::BI__sync_xor_and_fetch_1:
889 case Builtin::BI__sync_xor_and_fetch_2:
890 case Builtin::BI__sync_xor_and_fetch_4:
891 case Builtin::BI__sync_xor_and_fetch_8:
892 case Builtin::BI__sync_xor_and_fetch_16:
893 BuiltinIndex = 9;
894 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Chris Lattner5caa3702009-05-08 06:58:22 +0000896 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000897 case Builtin::BI__sync_val_compare_and_swap_1:
898 case Builtin::BI__sync_val_compare_and_swap_2:
899 case Builtin::BI__sync_val_compare_and_swap_4:
900 case Builtin::BI__sync_val_compare_and_swap_8:
901 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000902 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000903 NumFixed = 2;
904 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000905
Chris Lattner5caa3702009-05-08 06:58:22 +0000906 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000907 case Builtin::BI__sync_bool_compare_and_swap_1:
908 case Builtin::BI__sync_bool_compare_and_swap_2:
909 case Builtin::BI__sync_bool_compare_and_swap_4:
910 case Builtin::BI__sync_bool_compare_and_swap_8:
911 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000912 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000913 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000914 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000915 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000916
917 case Builtin::BI__sync_lock_test_and_set:
918 case Builtin::BI__sync_lock_test_and_set_1:
919 case Builtin::BI__sync_lock_test_and_set_2:
920 case Builtin::BI__sync_lock_test_and_set_4:
921 case Builtin::BI__sync_lock_test_and_set_8:
922 case Builtin::BI__sync_lock_test_and_set_16:
923 BuiltinIndex = 12;
924 break;
925
Chris Lattner5caa3702009-05-08 06:58:22 +0000926 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000927 case Builtin::BI__sync_lock_release_1:
928 case Builtin::BI__sync_lock_release_2:
929 case Builtin::BI__sync_lock_release_4:
930 case Builtin::BI__sync_lock_release_8:
931 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000932 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000933 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000934 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000935 break;
Douglas Gregora9766412011-11-28 16:30:08 +0000936
937 case Builtin::BI__sync_swap:
938 case Builtin::BI__sync_swap_1:
939 case Builtin::BI__sync_swap_2:
940 case Builtin::BI__sync_swap_4:
941 case Builtin::BI__sync_swap_8:
942 case Builtin::BI__sync_swap_16:
943 BuiltinIndex = 14;
944 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000945 }
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Chris Lattner5caa3702009-05-08 06:58:22 +0000947 // Now that we know how many fixed arguments we expect, first check that we
948 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000949 if (TheCall->getNumArgs() < 1+NumFixed) {
950 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
951 << 0 << 1+NumFixed << TheCall->getNumArgs()
952 << TheCall->getCallee()->getSourceRange();
953 return ExprError();
954 }
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000956 // Get the decl for the concrete builtin from this, we can tell what the
957 // concrete integer type we should convert to is.
958 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
959 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
960 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000961 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000962 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
963 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000964
John McCallf871d0c2010-08-07 06:22:56 +0000965 // The first argument --- the pointer --- has a fixed type; we
966 // deduce the types of the rest of the arguments accordingly. Walk
967 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000968 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000969 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Chris Lattner5caa3702009-05-08 06:58:22 +0000971 // GCC does an implicit conversion to the pointer or integer ValType. This
972 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000973 // Initialize the argument.
974 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
975 ValType, /*consume*/ false);
976 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000977 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000978 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Chris Lattner5caa3702009-05-08 06:58:22 +0000980 // Okay, we have something that *can* be converted to the right type. Check
981 // to see if there is a potentially weird extension going on here. This can
982 // happen when you do an atomic operation on something like an char* and
983 // pass in 42. The 42 gets converted to char. This is even more strange
984 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000985 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000986 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000987 }
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000989 ASTContext& Context = this->getASTContext();
990
991 // Create a new DeclRefExpr to refer to the new decl.
992 DeclRefExpr* NewDRE = DeclRefExpr::Create(
993 Context,
994 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000995 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000996 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +0000997 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000998 DRE->getLocation(),
999 NewBuiltinDecl->getType(),
1000 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Chris Lattner5caa3702009-05-08 06:58:22 +00001002 // Set the callee in the CallExpr.
1003 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001004 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +00001005 if (PromotedCall.isInvalid())
1006 return ExprError();
1007 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001009 // Change the result type of the call to match the original value type. This
1010 // is arbitrary, but the codegen for these builtins ins design to handle it
1011 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001012 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001013
1014 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +00001015}
1016
Chris Lattner69039812009-02-18 06:01:06 +00001017/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001018/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001019/// Note: It might also make sense to do the UTF-16 conversion here (would
1020/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001021bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001022 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001023 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1024
Douglas Gregor5cee1192011-07-27 05:40:30 +00001025 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001026 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1027 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001028 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001029 }
Mike Stump1eb44332009-09-09 15:08:12 +00001030
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001031 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001032 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001033 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001034 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001035 const UTF8 *FromPtr = (UTF8 *)String.data();
1036 UTF16 *ToPtr = &ToBuf[0];
1037
1038 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1039 &ToPtr, ToPtr + NumBytes,
1040 strictConversion);
1041 // Check for conversion failure.
1042 if (Result != conversionOK)
1043 Diag(Arg->getLocStart(),
1044 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1045 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001046 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001047}
1048
Chris Lattnerc27c6652007-12-20 00:05:45 +00001049/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1050/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001051bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1052 Expr *Fn = TheCall->getCallee();
1053 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001054 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001055 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001056 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1057 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001058 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001059 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001060 return true;
1061 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001062
1063 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001064 return Diag(TheCall->getLocEnd(),
1065 diag::err_typecheck_call_too_few_args_at_least)
1066 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001067 }
1068
John McCall5f8d6042011-08-27 01:09:30 +00001069 // Type-check the first argument normally.
1070 if (checkBuiltinArgument(*this, TheCall, 0))
1071 return true;
1072
Chris Lattnerc27c6652007-12-20 00:05:45 +00001073 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001074 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001075 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001076 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001077 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001078 else if (FunctionDecl *FD = getCurFunctionDecl())
1079 isVariadic = FD->isVariadic();
1080 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001081 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Chris Lattnerc27c6652007-12-20 00:05:45 +00001083 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001084 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1085 return true;
1086 }
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Chris Lattner30ce3442007-12-19 23:59:04 +00001088 // Verify that the second argument to the builtin is the last argument of the
1089 // current function or method.
1090 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001091 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001092
Anders Carlsson88cf2262008-02-11 04:20:54 +00001093 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1094 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001095 // FIXME: This isn't correct for methods (results in bogus warning).
1096 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001097 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001098 if (CurBlock)
1099 LastArg = *(CurBlock->TheDecl->param_end()-1);
1100 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001101 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001102 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001103 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001104 SecondArgIsLastNamedArgument = PV == LastArg;
1105 }
1106 }
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Chris Lattner30ce3442007-12-19 23:59:04 +00001108 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001109 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001110 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1111 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001112}
Chris Lattner30ce3442007-12-19 23:59:04 +00001113
Chris Lattner1b9a0792007-12-20 00:26:33 +00001114/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1115/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001116bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1117 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001118 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001119 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001120 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001121 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001122 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001123 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001124 << SourceRange(TheCall->getArg(2)->getLocStart(),
1125 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001126
John Wiegley429bb272011-04-08 18:41:53 +00001127 ExprResult OrigArg0 = TheCall->getArg(0);
1128 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001129
Chris Lattner1b9a0792007-12-20 00:26:33 +00001130 // Do standard promotions between the two arguments, returning their common
1131 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001132 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001133 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1134 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001135
1136 // Make sure any conversions are pushed back into the call; this is
1137 // type safe since unordered compare builtins are declared as "_Bool
1138 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001139 TheCall->setArg(0, OrigArg0.get());
1140 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001141
John Wiegley429bb272011-04-08 18:41:53 +00001142 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001143 return false;
1144
Chris Lattner1b9a0792007-12-20 00:26:33 +00001145 // If the common type isn't a real floating type, then the arguments were
1146 // invalid for this operation.
1147 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001148 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001149 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001150 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1151 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Chris Lattner1b9a0792007-12-20 00:26:33 +00001153 return false;
1154}
1155
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001156/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1157/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001158/// to check everything. We expect the last argument to be a floating point
1159/// value.
1160bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1161 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001162 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001163 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001164 if (TheCall->getNumArgs() > NumArgs)
1165 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001166 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001167 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001168 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001169 (*(TheCall->arg_end()-1))->getLocEnd());
1170
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001171 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Eli Friedman9ac6f622009-08-31 20:06:00 +00001173 if (OrigArg->isTypeDependent())
1174 return false;
1175
Chris Lattner81368fb2010-05-06 05:50:07 +00001176 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001177 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001178 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001179 diag::err_typecheck_call_invalid_unary_fp)
1180 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Chris Lattner81368fb2010-05-06 05:50:07 +00001182 // If this is an implicit conversion from float -> double, remove it.
1183 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1184 Expr *CastArg = Cast->getSubExpr();
1185 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1186 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1187 "promotion from float to double is the only expected cast here");
1188 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001189 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001190 }
1191 }
1192
Eli Friedman9ac6f622009-08-31 20:06:00 +00001193 return false;
1194}
1195
Eli Friedmand38617c2008-05-14 19:38:39 +00001196/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1197// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001198ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001199 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001200 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001201 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001202 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001203 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001204
Nate Begeman37b6a572010-06-08 00:16:34 +00001205 // Determine which of the following types of shufflevector we're checking:
1206 // 1) unary, vector mask: (lhs, mask)
1207 // 2) binary, vector mask: (lhs, rhs, mask)
1208 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1209 QualType resType = TheCall->getArg(0)->getType();
1210 unsigned numElements = 0;
1211
Douglas Gregorcde01732009-05-19 22:10:17 +00001212 if (!TheCall->getArg(0)->isTypeDependent() &&
1213 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001214 QualType LHSType = TheCall->getArg(0)->getType();
1215 QualType RHSType = TheCall->getArg(1)->getType();
1216
1217 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001218 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001219 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001220 TheCall->getArg(1)->getLocEnd());
1221 return ExprError();
1222 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001223
1224 numElements = LHSType->getAs<VectorType>()->getNumElements();
1225 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Nate Begeman37b6a572010-06-08 00:16:34 +00001227 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1228 // with mask. If so, verify that RHS is an integer vector type with the
1229 // same number of elts as lhs.
1230 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001231 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001232 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1233 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1234 << SourceRange(TheCall->getArg(1)->getLocStart(),
1235 TheCall->getArg(1)->getLocEnd());
1236 numResElements = numElements;
1237 }
1238 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001239 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001240 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001241 TheCall->getArg(1)->getLocEnd());
1242 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001243 } else if (numElements != numResElements) {
1244 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001245 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001246 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001247 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001248 }
1249
1250 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001251 if (TheCall->getArg(i)->isTypeDependent() ||
1252 TheCall->getArg(i)->isValueDependent())
1253 continue;
1254
Nate Begeman37b6a572010-06-08 00:16:34 +00001255 llvm::APSInt Result(32);
1256 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1257 return ExprError(Diag(TheCall->getLocStart(),
1258 diag::err_shufflevector_nonconstant_argument)
1259 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001260
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001261 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001262 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001263 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001264 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001265 }
1266
Chris Lattner5f9e2722011-07-23 10:55:15 +00001267 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001268
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001269 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001270 exprs.push_back(TheCall->getArg(i));
1271 TheCall->setArg(i, 0);
1272 }
1273
Nate Begemana88dc302009-08-12 02:10:25 +00001274 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001275 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001276 TheCall->getCallee()->getLocStart(),
1277 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001278}
Chris Lattner30ce3442007-12-19 23:59:04 +00001279
Daniel Dunbar4493f792008-07-21 22:59:13 +00001280/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1281// This is declared to take (const void*, ...) and can take two
1282// optional constant int args.
1283bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001284 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001285
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001286 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001287 return Diag(TheCall->getLocEnd(),
1288 diag::err_typecheck_call_too_many_args_at_most)
1289 << 0 /*function call*/ << 3 << NumArgs
1290 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001291
1292 // Argument 0 is checked for us and the remaining arguments must be
1293 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001294 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001295 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001296
Eli Friedman9aef7262009-12-04 00:30:06 +00001297 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001298 if (SemaBuiltinConstantArg(TheCall, i, Result))
1299 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Daniel Dunbar4493f792008-07-21 22:59:13 +00001301 // FIXME: gcc issues a warning and rewrites these to 0. These
1302 // seems especially odd for the third argument since the default
1303 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001304 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001305 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001306 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001307 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001308 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001309 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001310 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001311 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001312 }
1313 }
1314
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001315 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001316}
1317
Eric Christopher691ebc32010-04-17 02:26:23 +00001318/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1319/// TheCall is a constant expression.
1320bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1321 llvm::APSInt &Result) {
1322 Expr *Arg = TheCall->getArg(ArgNum);
1323 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1324 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1325
1326 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1327
1328 if (!Arg->isIntegerConstantExpr(Result, Context))
1329 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001330 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001331
Chris Lattner21fb98e2009-09-23 06:06:36 +00001332 return false;
1333}
1334
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001335/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1336/// int type). This simply type checks that type is one of the defined
1337/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001338// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001339bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001340 llvm::APSInt Result;
1341
1342 // Check constant-ness first.
1343 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1344 return true;
1345
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001346 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001347 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001348 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1349 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001350 }
1351
1352 return false;
1353}
1354
Eli Friedman586d6a82009-05-03 06:04:26 +00001355/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001356/// This checks that val is a constant 1.
1357bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1358 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001359 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001360
Eric Christopher691ebc32010-04-17 02:26:23 +00001361 // TODO: This is less than ideal. Overload this to take a value.
1362 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1363 return true;
1364
1365 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001366 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1367 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1368
1369 return false;
1370}
1371
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001372// Handle i > 1 ? "x" : "y", recursively.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001373bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1374 unsigned NumArgs, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001375 unsigned format_idx, unsigned firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001376 FormatStringType Type, bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001377 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001378 if (E->isTypeDependent() || E->isValueDependent())
1379 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001380
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001381 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001382
David Blaikiea73cdcb2012-02-10 21:07:25 +00001383 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1384 // Technically -Wformat-nonliteral does not warn about this case.
1385 // The behavior of printf and friends in this case is implementation
1386 // dependent. Ideally if the format string cannot be null then
1387 // it should have a 'nonnull' attribute in the function prototype.
1388 return true;
1389
Ted Kremenekd30ef872009-01-12 23:09:09 +00001390 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001391 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001392 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001393 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001394 return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001395 format_idx, firstDataArg, Type,
Richard Trieu55733de2011-10-28 00:41:25 +00001396 inFunctionCall)
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001397 && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1398 format_idx, firstDataArg, Type,
1399 inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001400 }
1401
1402 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001403 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1404 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001405 }
1406
John McCall56ca35d2011-02-17 10:25:35 +00001407 case Stmt::OpaqueValueExprClass:
1408 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1409 E = src;
1410 goto tryAgain;
1411 }
1412 return false;
1413
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001414 case Stmt::PredefinedExprClass:
1415 // While __func__, etc., are technically not string literals, they
1416 // cannot contain format specifiers and thus are not a security
1417 // liability.
1418 return true;
1419
Ted Kremenek082d9362009-03-20 21:35:28 +00001420 case Stmt::DeclRefExprClass: {
1421 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001422
Ted Kremenek082d9362009-03-20 21:35:28 +00001423 // As an exception, do not flag errors for variables binding to
1424 // const string literals.
1425 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1426 bool isConstant = false;
1427 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001428
Ted Kremenek082d9362009-03-20 21:35:28 +00001429 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1430 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001431 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001432 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001433 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001434 } else if (T->isObjCObjectPointerType()) {
1435 // In ObjC, there is usually no "const ObjectPointer" type,
1436 // so don't check if the pointee type is constant.
1437 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001438 }
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Ted Kremenek082d9362009-03-20 21:35:28 +00001440 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001441 if (const Expr *Init = VD->getAnyInitializer())
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001442 return SemaCheckStringLiteral(Init, Args, NumArgs,
Ted Kremenek826a3452010-07-16 02:11:22 +00001443 HasVAListArg, format_idx, firstDataArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001444 Type, /*inFunctionCall*/false);
Ted Kremenek082d9362009-03-20 21:35:28 +00001445 }
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Anders Carlssond966a552009-06-28 19:55:58 +00001447 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1448 // special check to see if the format string is a function parameter
1449 // of the function calling the printf function. If the function
1450 // has an attribute indicating it is a printf-like function, then we
1451 // should suppress warnings concerning non-literals being used in a call
1452 // to a vprintf function. For example:
1453 //
1454 // void
1455 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1456 // va_list ap;
1457 // va_start(ap, fmt);
1458 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1459 // ...
1460 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001461 if (HasVAListArg) {
1462 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1463 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1464 int PVIndex = PV->getFunctionScopeIndex() + 1;
1465 for (specific_attr_iterator<FormatAttr>
1466 i = ND->specific_attr_begin<FormatAttr>(),
1467 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1468 FormatAttr *PVFormat = *i;
1469 // adjust for implicit parameter
1470 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1471 if (MD->isInstance())
1472 ++PVIndex;
1473 // We also check if the formats are compatible.
1474 // We can't pass a 'scanf' string to a 'printf' function.
1475 if (PVIndex == PVFormat->getFormatIdx() &&
1476 Type == GetFormatStringType(PVFormat))
1477 return true;
1478 }
1479 }
1480 }
1481 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001482 }
Mike Stump1eb44332009-09-09 15:08:12 +00001483
Ted Kremenek082d9362009-03-20 21:35:28 +00001484 return false;
1485 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001486
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001487 case Stmt::CallExprClass:
1488 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001489 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001490 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1491 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1492 unsigned ArgIndex = FA->getFormatIdx();
1493 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1494 if (MD->isInstance())
1495 --ArgIndex;
1496 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001498 return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1499 format_idx, firstDataArg, Type,
1500 inFunctionCall);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001501 }
1502 }
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Anders Carlsson8f031b32009-06-27 04:05:33 +00001504 return false;
1505 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001506 case Stmt::ObjCStringLiteralClass:
1507 case Stmt::StringLiteralClass: {
1508 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Ted Kremenek082d9362009-03-20 21:35:28 +00001510 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001511 StrE = ObjCFExpr->getString();
1512 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001513 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Ted Kremenekd30ef872009-01-12 23:09:09 +00001515 if (StrE) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001516 CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001517 firstDataArg, Type, inFunctionCall);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001518 return true;
1519 }
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Ted Kremenekd30ef872009-01-12 23:09:09 +00001521 return false;
1522 }
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Ted Kremenek082d9362009-03-20 21:35:28 +00001524 default:
1525 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001526 }
1527}
1528
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001529void
Mike Stump1eb44332009-09-09 15:08:12 +00001530Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001531 const Expr * const *ExprArgs,
1532 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001533 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1534 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001535 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001536 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001537 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001538 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001539 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001540 }
1541}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001542
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001543Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1544 return llvm::StringSwitch<FormatStringType>(Format->getType())
1545 .Case("scanf", FST_Scanf)
1546 .Cases("printf", "printf0", FST_Printf)
1547 .Cases("NSString", "CFString", FST_NSString)
1548 .Case("strftime", FST_Strftime)
1549 .Case("strfmon", FST_Strfmon)
1550 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1551 .Default(FST_Unknown);
1552}
1553
Ted Kremenek826a3452010-07-16 02:11:22 +00001554/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1555/// functions) for correct use of format strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001556void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1557 bool IsCXXMember = false;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001558 // The way the format attribute works in GCC, the implicit this argument
1559 // of member functions is counted. However, it doesn't appear in our own
1560 // lists, so decrement format_idx in that case.
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001561 IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001562 CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1563 IsCXXMember, TheCall->getRParenLoc(),
1564 TheCall->getCallee()->getSourceRange());
1565}
1566
1567void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1568 unsigned NumArgs, bool IsCXXMember,
1569 SourceLocation Loc, SourceRange Range) {
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001570 bool HasVAListArg = Format->getFirstArg() == 0;
1571 unsigned format_idx = Format->getFormatIdx() - 1;
1572 unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1573 if (IsCXXMember) {
1574 if (format_idx == 0)
1575 return;
1576 --format_idx;
1577 if(firstDataArg != 0)
1578 --firstDataArg;
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001579 }
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001580 CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1581 firstDataArg, GetFormatStringType(Format), Loc, Range);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001582}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001583
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001584void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1585 bool HasVAListArg, unsigned format_idx,
1586 unsigned firstDataArg, FormatStringType Type,
1587 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001588 // CHECK: printf/scanf-like function is called with no format string.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001589 if (format_idx >= NumArgs) {
1590 Diag(Loc, diag::warn_missing_format_string) << Range;
Ted Kremenek71895b92007-08-14 17:39:48 +00001591 return;
1592 }
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001594 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Chris Lattner59907c42007-08-10 20:18:51 +00001596 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001597 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001598 // Dynamically generated format strings are difficult to
1599 // automatically vet at compile time. Requiring that format strings
1600 // are string literals: (1) permits the checking of format strings by
1601 // the compiler and thereby (2) can practically remove the source of
1602 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001603
Mike Stump1eb44332009-09-09 15:08:12 +00001604 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001605 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001606 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001607 // the same format string checking logic for both ObjC and C strings.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001608 if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001609 format_idx, firstDataArg, Type))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001610 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001611
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001612 // Strftime is particular as it always uses a single 'time' argument,
1613 // so it is safe to pass a non-literal string.
1614 if (Type == FST_Strftime)
1615 return;
1616
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001617 // Do not emit diag when the string param is a macro expansion and the
1618 // format is either NSString or CFString. This is a hack to prevent
1619 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1620 // which are usually used in place of NS and CF string literals.
1621 if (Type == FST_NSString && Args[format_idx]->getLocStart().isMacroID())
1622 return;
1623
Chris Lattner655f1412009-04-29 04:59:47 +00001624 // If there are no arguments specified, warn with -Wformat-security, otherwise
1625 // warn only with -Wformat-nonliteral.
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001626 if (NumArgs == format_idx+1)
1627 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001628 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001629 << OrigFormatExpr->getSourceRange();
1630 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001631 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001632 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001633 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001634}
Ted Kremenek71895b92007-08-14 17:39:48 +00001635
Ted Kremeneke0e53132010-01-28 23:39:18 +00001636namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001637class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1638protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001639 Sema &S;
1640 const StringLiteral *FExpr;
1641 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001642 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001643 const unsigned NumDataArgs;
1644 const bool IsObjCLiteral;
1645 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001646 const bool HasVAListArg;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001647 const Expr * const *Args;
1648 const unsigned NumArgs;
Ted Kremenek0d277352010-01-29 01:06:55 +00001649 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001650 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001651 bool usesPositionalArgs;
1652 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00001653 bool inFunctionCall;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001654public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001655 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001656 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001657 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001658 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001659 Expr **args, unsigned numArgs,
1660 unsigned formatIdx, bool inFunctionCall)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001661 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001662 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001663 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001664 IsObjCLiteral(isObjCLiteral), Beg(beg),
1665 HasVAListArg(hasVAListArg),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001666 Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00001667 usesPositionalArgs(false), atFirstArg(true),
1668 inFunctionCall(inFunctionCall) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001669 CoveredArgs.resize(numDataArgs);
1670 CoveredArgs.reset();
1671 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001672
Ted Kremenek07d161f2010-01-29 01:50:07 +00001673 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001674
Ted Kremenek826a3452010-07-16 02:11:22 +00001675 void HandleIncompleteSpecifier(const char *startSpecifier,
1676 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00001677
1678 void HandleNonStandardLengthModifier(
1679 const analyze_format_string::LengthModifier &LM,
1680 const char *startSpecifier, unsigned specifierLen);
1681
1682 void HandleNonStandardConversionSpecifier(
1683 const analyze_format_string::ConversionSpecifier &CS,
1684 const char *startSpecifier, unsigned specifierLen);
1685
1686 void HandleNonStandardConversionSpecification(
1687 const analyze_format_string::LengthModifier &LM,
1688 const analyze_format_string::ConversionSpecifier &CS,
1689 const char *startSpecifier, unsigned specifierLen);
1690
Hans Wennborgf8562642012-03-09 10:10:54 +00001691 virtual void HandlePosition(const char *startPos, unsigned posLen);
1692
Ted Kremenekefaff192010-02-27 01:41:03 +00001693 virtual void HandleInvalidPosition(const char *startSpecifier,
1694 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001695 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001696
1697 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1698
Ted Kremeneke0e53132010-01-28 23:39:18 +00001699 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001700
Richard Trieu55733de2011-10-28 00:41:25 +00001701 template <typename Range>
1702 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1703 const Expr *ArgumentExpr,
1704 PartialDiagnostic PDiag,
1705 SourceLocation StringLoc,
1706 bool IsStringLocation, Range StringRange,
1707 FixItHint Fixit = FixItHint());
1708
Ted Kremenek826a3452010-07-16 02:11:22 +00001709protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001710 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1711 const char *startSpec,
1712 unsigned specifierLen,
1713 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00001714
1715 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1716 const char *startSpec,
1717 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001718
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001719 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001720 CharSourceRange getSpecifierRange(const char *startSpecifier,
1721 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001722 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001723
Ted Kremenek0d277352010-01-29 01:06:55 +00001724 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001725
1726 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1727 const analyze_format_string::ConversionSpecifier &CS,
1728 const char *startSpecifier, unsigned specifierLen,
1729 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00001730
1731 template <typename Range>
1732 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1733 bool IsStringLocation, Range StringRange,
1734 FixItHint Fixit = FixItHint());
1735
1736 void CheckPositionalAndNonpositionalArgs(
1737 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001738};
1739}
1740
Ted Kremenek826a3452010-07-16 02:11:22 +00001741SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001742 return OrigFormatExpr->getSourceRange();
1743}
1744
Ted Kremenek826a3452010-07-16 02:11:22 +00001745CharSourceRange CheckFormatHandler::
1746getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001747 SourceLocation Start = getLocationOfByte(startSpecifier);
1748 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1749
1750 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001751 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001752
1753 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001754}
1755
Ted Kremenek826a3452010-07-16 02:11:22 +00001756SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001757 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001758}
1759
Ted Kremenek826a3452010-07-16 02:11:22 +00001760void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1761 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00001762 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1763 getLocationOfByte(startSpecifier),
1764 /*IsStringLocation*/true,
1765 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00001766}
1767
Hans Wennborg76517422012-02-22 10:17:01 +00001768void CheckFormatHandler::HandleNonStandardLengthModifier(
1769 const analyze_format_string::LengthModifier &LM,
1770 const char *startSpecifier, unsigned specifierLen) {
1771 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001772 << 0,
Hans Wennborg76517422012-02-22 10:17:01 +00001773 getLocationOfByte(LM.getStart()),
1774 /*IsStringLocation*/true,
1775 getSpecifierRange(startSpecifier, specifierLen));
1776}
1777
1778void CheckFormatHandler::HandleNonStandardConversionSpecifier(
1779 const analyze_format_string::ConversionSpecifier &CS,
1780 const char *startSpecifier, unsigned specifierLen) {
1781 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
Hans Wennborgf8562642012-03-09 10:10:54 +00001782 << 1,
Hans Wennborg76517422012-02-22 10:17:01 +00001783 getLocationOfByte(CS.getStart()),
1784 /*IsStringLocation*/true,
1785 getSpecifierRange(startSpecifier, specifierLen));
1786}
1787
1788void CheckFormatHandler::HandleNonStandardConversionSpecification(
1789 const analyze_format_string::LengthModifier &LM,
1790 const analyze_format_string::ConversionSpecifier &CS,
1791 const char *startSpecifier, unsigned specifierLen) {
1792 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
1793 << LM.toString() << CS.toString(),
1794 getLocationOfByte(LM.getStart()),
1795 /*IsStringLocation*/true,
1796 getSpecifierRange(startSpecifier, specifierLen));
1797}
1798
Hans Wennborgf8562642012-03-09 10:10:54 +00001799void CheckFormatHandler::HandlePosition(const char *startPos,
1800 unsigned posLen) {
1801 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
1802 getLocationOfByte(startPos),
1803 /*IsStringLocation*/true,
1804 getSpecifierRange(startPos, posLen));
1805}
1806
Ted Kremenekefaff192010-02-27 01:41:03 +00001807void
Ted Kremenek826a3452010-07-16 02:11:22 +00001808CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1809 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00001810 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1811 << (unsigned) p,
1812 getLocationOfByte(startPos), /*IsStringLocation*/true,
1813 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001814}
1815
Ted Kremenek826a3452010-07-16 02:11:22 +00001816void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001817 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00001818 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1819 getLocationOfByte(startPos),
1820 /*IsStringLocation*/true,
1821 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00001822}
1823
Ted Kremenek826a3452010-07-16 02:11:22 +00001824void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001825 if (!IsObjCLiteral) {
1826 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00001827 EmitFormatDiagnostic(
1828 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1829 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1830 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00001831 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001832}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001833
Ted Kremenek826a3452010-07-16 02:11:22 +00001834const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001835 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00001836}
1837
1838void CheckFormatHandler::DoneProcessing() {
1839 // Does the number of data arguments exceed the number of
1840 // format conversions in the format string?
1841 if (!HasVAListArg) {
1842 // Find any arguments that weren't covered.
1843 CoveredArgs.flip();
1844 signed notCoveredArg = CoveredArgs.find_first();
1845 if (notCoveredArg >= 0) {
1846 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu55733de2011-10-28 00:41:25 +00001847 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1848 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1849 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek826a3452010-07-16 02:11:22 +00001850 }
1851 }
1852}
1853
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001854bool
1855CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1856 SourceLocation Loc,
1857 const char *startSpec,
1858 unsigned specifierLen,
1859 const char *csStart,
1860 unsigned csLen) {
1861
1862 bool keepGoing = true;
1863 if (argIndex < NumDataArgs) {
1864 // Consider the argument coverered, even though the specifier doesn't
1865 // make sense.
1866 CoveredArgs.set(argIndex);
1867 }
1868 else {
1869 // If argIndex exceeds the number of data arguments we
1870 // don't issue a warning because that is just a cascade of warnings (and
1871 // they may have intended '%%' anyway). We don't want to continue processing
1872 // the format string after this point, however, as we will like just get
1873 // gibberish when trying to match arguments.
1874 keepGoing = false;
1875 }
1876
Richard Trieu55733de2011-10-28 00:41:25 +00001877 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1878 << StringRef(csStart, csLen),
1879 Loc, /*IsStringLocation*/true,
1880 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001881
1882 return keepGoing;
1883}
1884
Richard Trieu55733de2011-10-28 00:41:25 +00001885void
1886CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1887 const char *startSpec,
1888 unsigned specifierLen) {
1889 EmitFormatDiagnostic(
1890 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1891 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1892}
1893
Ted Kremenek666a1972010-07-26 19:45:42 +00001894bool
1895CheckFormatHandler::CheckNumArgs(
1896 const analyze_format_string::FormatSpecifier &FS,
1897 const analyze_format_string::ConversionSpecifier &CS,
1898 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1899
1900 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00001901 PartialDiagnostic PDiag = FS.usesPositionalArg()
1902 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1903 << (argIndex+1) << NumDataArgs)
1904 : S.PDiag(diag::warn_printf_insufficient_data_args);
1905 EmitFormatDiagnostic(
1906 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1907 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00001908 return false;
1909 }
1910 return true;
1911}
1912
Richard Trieu55733de2011-10-28 00:41:25 +00001913template<typename Range>
1914void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1915 SourceLocation Loc,
1916 bool IsStringLocation,
1917 Range StringRange,
1918 FixItHint FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001919 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00001920 Loc, IsStringLocation, StringRange, FixIt);
1921}
1922
1923/// \brief If the format string is not within the funcion call, emit a note
1924/// so that the function call and string are in diagnostic messages.
1925///
1926/// \param inFunctionCall if true, the format string is within the function
1927/// call and only one diagnostic message will be produced. Otherwise, an
1928/// extra note will be emitted pointing to location of the format string.
1929///
1930/// \param ArgumentExpr the expression that is passed as the format string
1931/// argument in the function call. Used for getting locations when two
1932/// diagnostics are emitted.
1933///
1934/// \param PDiag the callee should already have provided any strings for the
1935/// diagnostic message. This function only adds locations and fixits
1936/// to diagnostics.
1937///
1938/// \param Loc primary location for diagnostic. If two diagnostics are
1939/// required, one will be at Loc and a new SourceLocation will be created for
1940/// the other one.
1941///
1942/// \param IsStringLocation if true, Loc points to the format string should be
1943/// used for the note. Otherwise, Loc points to the argument list and will
1944/// be used with PDiag.
1945///
1946/// \param StringRange some or all of the string to highlight. This is
1947/// templated so it can accept either a CharSourceRange or a SourceRange.
1948///
1949/// \param Fixit optional fix it hint for the format string.
1950template<typename Range>
1951void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1952 const Expr *ArgumentExpr,
1953 PartialDiagnostic PDiag,
1954 SourceLocation Loc,
1955 bool IsStringLocation,
1956 Range StringRange,
1957 FixItHint FixIt) {
1958 if (InFunctionCall)
1959 S.Diag(Loc, PDiag) << StringRange << FixIt;
1960 else {
1961 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1962 << ArgumentExpr->getSourceRange();
1963 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1964 diag::note_format_string_defined)
1965 << StringRange << FixIt;
1966 }
1967}
1968
Ted Kremenek826a3452010-07-16 02:11:22 +00001969//===--- CHECK: Printf format string checking ------------------------------===//
1970
1971namespace {
1972class CheckPrintfHandler : public CheckFormatHandler {
1973public:
1974 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1975 const Expr *origFormatExpr, unsigned firstDataArg,
1976 unsigned numDataArgs, bool isObjCLiteral,
1977 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001978 Expr **Args, unsigned NumArgs,
1979 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00001980 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1981 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001982 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00001983
1984
1985 bool HandleInvalidPrintfConversionSpecifier(
1986 const analyze_printf::PrintfSpecifier &FS,
1987 const char *startSpecifier,
1988 unsigned specifierLen);
1989
1990 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1991 const char *startSpecifier,
1992 unsigned specifierLen);
1993
1994 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1995 const char *startSpecifier, unsigned specifierLen);
1996 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1997 const analyze_printf::OptionalAmount &Amt,
1998 unsigned type,
1999 const char *startSpecifier, unsigned specifierLen);
2000 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2001 const analyze_printf::OptionalFlag &flag,
2002 const char *startSpecifier, unsigned specifierLen);
2003 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2004 const analyze_printf::OptionalFlag &ignoredFlag,
2005 const analyze_printf::OptionalFlag &flag,
2006 const char *startSpecifier, unsigned specifierLen);
2007};
2008}
2009
2010bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2011 const analyze_printf::PrintfSpecifier &FS,
2012 const char *startSpecifier,
2013 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002014 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002015 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002016
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002017 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2018 getLocationOfByte(CS.getStart()),
2019 startSpecifier, specifierLen,
2020 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002021}
2022
Ted Kremenek826a3452010-07-16 02:11:22 +00002023bool CheckPrintfHandler::HandleAmount(
2024 const analyze_format_string::OptionalAmount &Amt,
2025 unsigned k, const char *startSpecifier,
2026 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002027
2028 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002029 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002030 unsigned argIndex = Amt.getArgIndex();
2031 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002032 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2033 << k,
2034 getLocationOfByte(Amt.getStart()),
2035 /*IsStringLocation*/true,
2036 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002037 // Don't do any more checking. We will just emit
2038 // spurious errors.
2039 return false;
2040 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002041
Ted Kremenek0d277352010-01-29 01:06:55 +00002042 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002043 // Although not in conformance with C99, we also allow the argument to be
2044 // an 'unsigned int' as that is a reasonably safe case. GCC also
2045 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002046 CoveredArgs.set(argIndex);
2047 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00002048 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002049
2050 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2051 assert(ATR.isValid());
2052
2053 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002054 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborga792aff2011-12-07 10:33:11 +00002055 << k << ATR.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002056 << T << Arg->getSourceRange(),
2057 getLocationOfByte(Amt.getStart()),
2058 /*IsStringLocation*/true,
2059 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002060 // Don't do any more checking. We will just emit
2061 // spurious errors.
2062 return false;
2063 }
2064 }
2065 }
2066 return true;
2067}
Ted Kremenek0d277352010-01-29 01:06:55 +00002068
Tom Caree4ee9662010-06-17 19:00:27 +00002069void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002070 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002071 const analyze_printf::OptionalAmount &Amt,
2072 unsigned type,
2073 const char *startSpecifier,
2074 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002075 const analyze_printf::PrintfConversionSpecifier &CS =
2076 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002077
Richard Trieu55733de2011-10-28 00:41:25 +00002078 FixItHint fixit =
2079 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2080 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2081 Amt.getConstantLength()))
2082 : FixItHint();
2083
2084 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2085 << type << CS.toString(),
2086 getLocationOfByte(Amt.getStart()),
2087 /*IsStringLocation*/true,
2088 getSpecifierRange(startSpecifier, specifierLen),
2089 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002090}
2091
Ted Kremenek826a3452010-07-16 02:11:22 +00002092void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002093 const analyze_printf::OptionalFlag &flag,
2094 const char *startSpecifier,
2095 unsigned specifierLen) {
2096 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002097 const analyze_printf::PrintfConversionSpecifier &CS =
2098 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002099 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2100 << flag.toString() << CS.toString(),
2101 getLocationOfByte(flag.getPosition()),
2102 /*IsStringLocation*/true,
2103 getSpecifierRange(startSpecifier, specifierLen),
2104 FixItHint::CreateRemoval(
2105 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002106}
2107
2108void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002109 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002110 const analyze_printf::OptionalFlag &ignoredFlag,
2111 const analyze_printf::OptionalFlag &flag,
2112 const char *startSpecifier,
2113 unsigned specifierLen) {
2114 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002115 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2116 << ignoredFlag.toString() << flag.toString(),
2117 getLocationOfByte(ignoredFlag.getPosition()),
2118 /*IsStringLocation*/true,
2119 getSpecifierRange(startSpecifier, specifierLen),
2120 FixItHint::CreateRemoval(
2121 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002122}
2123
Ted Kremeneke0e53132010-01-28 23:39:18 +00002124bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002125CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002126 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002127 const char *startSpecifier,
2128 unsigned specifierLen) {
2129
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002130 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002131 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002132 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002133
Ted Kremenekbaa40062010-07-19 22:01:06 +00002134 if (FS.consumesDataArgument()) {
2135 if (atFirstArg) {
2136 atFirstArg = false;
2137 usesPositionalArgs = FS.usesPositionalArg();
2138 }
2139 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002140 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2141 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002142 return false;
2143 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002144 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002145
Ted Kremenekefaff192010-02-27 01:41:03 +00002146 // First check if the field width, precision, and conversion specifier
2147 // have matching data arguments.
2148 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2149 startSpecifier, specifierLen)) {
2150 return false;
2151 }
2152
2153 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2154 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002155 return false;
2156 }
2157
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002158 if (!CS.consumesDataArgument()) {
2159 // FIXME: Technically specifying a precision or field width here
2160 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002161 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002162 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002163
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002164 // Consume the argument.
2165 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002166 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 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002172
2173 // Check for using an Objective-C specific conversion specifier
2174 // in a non-ObjC literal.
2175 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002176 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2177 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002178 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002179
Tom Caree4ee9662010-06-17 19:00:27 +00002180 // Check for invalid use of field width
2181 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002182 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002183 startSpecifier, specifierLen);
2184 }
2185
2186 // Check for invalid use of precision
2187 if (!FS.hasValidPrecision()) {
2188 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2189 startSpecifier, specifierLen);
2190 }
2191
2192 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002193 if (!FS.hasValidThousandsGroupingPrefix())
2194 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002195 if (!FS.hasValidLeadingZeros())
2196 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2197 if (!FS.hasValidPlusPrefix())
2198 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002199 if (!FS.hasValidSpacePrefix())
2200 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002201 if (!FS.hasValidAlternativeForm())
2202 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2203 if (!FS.hasValidLeftJustified())
2204 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2205
2206 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002207 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2208 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2209 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002210 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2211 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2212 startSpecifier, specifierLen);
2213
2214 // Check the length modifier is valid with the given conversion specifier.
2215 const LengthModifier &LM = FS.getLengthModifier();
2216 if (!FS.hasValidLengthModifier())
Richard Trieu55733de2011-10-28 00:41:25 +00002217 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2218 << LM.toString() << CS.toString(),
2219 getLocationOfByte(LM.getStart()),
2220 /*IsStringLocation*/true,
2221 getSpecifierRange(startSpecifier, specifierLen),
2222 FixItHint::CreateRemoval(
2223 getSpecifierRange(LM.getStart(),
2224 LM.getLength())));
Hans Wennborg76517422012-02-22 10:17:01 +00002225 if (!FS.hasStandardLengthModifier())
2226 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002227 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002228 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2229 if (!FS.hasStandardLengthConversionCombination())
2230 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2231 specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002232
2233 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00002234 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00002235 // Issue a warning about this being a possible security issue.
Richard Trieu55733de2011-10-28 00:41:25 +00002236 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2237 getLocationOfByte(CS.getStart()),
2238 /*IsStringLocation*/true,
2239 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremeneke82d8042010-01-29 01:35:25 +00002240 // Continue checking the other format specifiers.
2241 return true;
2242 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002243
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002244 // The remaining checks depend on the data arguments.
2245 if (HasVAListArg)
2246 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002247
Ted Kremenek666a1972010-07-26 19:45:42 +00002248 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002249 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002250
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002251 // Now type check the data expression that matches the
2252 // format specifier.
2253 const Expr *Ex = getDataArg(argIndex);
Nico Weber339b9072012-01-31 01:43:25 +00002254 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2255 IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002256 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2257 // Check if we didn't match because of an implicit cast from a 'char'
2258 // or 'short' to an 'int'. This is done because printf is a varargs
2259 // function.
2260 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002261 if (ICE->getType() == S.Context.IntTy) {
2262 // All further checking is done on the subexpression.
2263 Ex = ICE->getSubExpr();
2264 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002265 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002266 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002267
2268 // We may be able to offer a FixItHint if it is a supported type.
2269 PrintfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002270 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002271 S.Context, IsObjCLiteral);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002272
2273 if (success) {
2274 // Get the fix string from the fixed format specifier
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002275 SmallString<128> buf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002276 llvm::raw_svector_ostream os(buf);
2277 fixedFS.toString(os);
2278
Richard Trieu55733de2011-10-28 00:41:25 +00002279 EmitFormatDiagnostic(
2280 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborga792aff2011-12-07 10:33:11 +00002281 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Richard Trieu55733de2011-10-28 00:41:25 +00002282 << Ex->getSourceRange(),
2283 getLocationOfByte(CS.getStart()),
2284 /*IsStringLocation*/true,
2285 getSpecifierRange(startSpecifier, specifierLen),
2286 FixItHint::CreateReplacement(
2287 getSpecifierRange(startSpecifier, specifierLen),
2288 os.str()));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002289 }
2290 else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002291 EmitFormatDiagnostic(
2292 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2293 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2294 << getSpecifierRange(startSpecifier, specifierLen)
2295 << Ex->getSourceRange(),
2296 getLocationOfByte(CS.getStart()),
2297 true,
2298 getSpecifierRange(startSpecifier, specifierLen));
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002299 }
2300 }
2301
Ted Kremeneke0e53132010-01-28 23:39:18 +00002302 return true;
2303}
2304
Ted Kremenek826a3452010-07-16 02:11:22 +00002305//===--- CHECK: Scanf format string checking ------------------------------===//
2306
2307namespace {
2308class CheckScanfHandler : public CheckFormatHandler {
2309public:
2310 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2311 const Expr *origFormatExpr, unsigned firstDataArg,
2312 unsigned numDataArgs, bool isObjCLiteral,
2313 const char *beg, bool hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002314 Expr **Args, unsigned NumArgs,
2315 unsigned formatIdx, bool inFunctionCall)
Ted Kremenek826a3452010-07-16 02:11:22 +00002316 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2317 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002318 Args, NumArgs, formatIdx, inFunctionCall) {}
Ted Kremenek826a3452010-07-16 02:11:22 +00002319
2320 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2321 const char *startSpecifier,
2322 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002323
2324 bool HandleInvalidScanfConversionSpecifier(
2325 const analyze_scanf::ScanfSpecifier &FS,
2326 const char *startSpecifier,
2327 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00002328
2329 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00002330};
Ted Kremenek07d161f2010-01-29 01:50:07 +00002331}
Ted Kremeneke0e53132010-01-28 23:39:18 +00002332
Ted Kremenekb7c21012010-07-16 18:28:03 +00002333void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2334 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00002335 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2336 getLocationOfByte(end), /*IsStringLocation*/true,
2337 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00002338}
2339
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002340bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2341 const analyze_scanf::ScanfSpecifier &FS,
2342 const char *startSpecifier,
2343 unsigned specifierLen) {
2344
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002345 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002346 FS.getConversionSpecifier();
2347
2348 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2349 getLocationOfByte(CS.getStart()),
2350 startSpecifier, specifierLen,
2351 CS.getStart(), CS.getLength());
2352}
2353
Ted Kremenek826a3452010-07-16 02:11:22 +00002354bool CheckScanfHandler::HandleScanfSpecifier(
2355 const analyze_scanf::ScanfSpecifier &FS,
2356 const char *startSpecifier,
2357 unsigned specifierLen) {
2358
2359 using namespace analyze_scanf;
2360 using namespace analyze_format_string;
2361
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002362 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002363
Ted Kremenekbaa40062010-07-19 22:01:06 +00002364 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2365 // be used to decide if we are using positional arguments consistently.
2366 if (FS.consumesDataArgument()) {
2367 if (atFirstArg) {
2368 atFirstArg = false;
2369 usesPositionalArgs = FS.usesPositionalArg();
2370 }
2371 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002372 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2373 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002374 return false;
2375 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002376 }
2377
2378 // Check if the field with is non-zero.
2379 const OptionalAmount &Amt = FS.getFieldWidth();
2380 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2381 if (Amt.getConstantAmount() == 0) {
2382 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2383 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00002384 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2385 getLocationOfByte(Amt.getStart()),
2386 /*IsStringLocation*/true, R,
2387 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00002388 }
2389 }
2390
2391 if (!FS.consumesDataArgument()) {
2392 // FIXME: Technically specifying a precision or field width here
2393 // makes no sense. Worth issuing a warning at some point.
2394 return true;
2395 }
2396
2397 // Consume the argument.
2398 unsigned argIndex = FS.getArgIndex();
2399 if (argIndex < NumDataArgs) {
2400 // The check to see if the argIndex is valid will come later.
2401 // We set the bit here because we may exit early from this
2402 // function if we encounter some other error.
2403 CoveredArgs.set(argIndex);
2404 }
2405
Ted Kremenek1e51c202010-07-20 20:04:47 +00002406 // Check the length modifier is valid with the given conversion specifier.
2407 const LengthModifier &LM = FS.getLengthModifier();
2408 if (!FS.hasValidLengthModifier()) {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002409 const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2410 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2411 << LM.toString() << CS.toString()
2412 << getSpecifierRange(startSpecifier, specifierLen),
2413 getLocationOfByte(LM.getStart()),
2414 /*IsStringLocation*/true, R,
2415 FixItHint::CreateRemoval(R));
Ted Kremenek1e51c202010-07-20 20:04:47 +00002416 }
2417
Hans Wennborg76517422012-02-22 10:17:01 +00002418 if (!FS.hasStandardLengthModifier())
2419 HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
David Blaikie4e4d0842012-03-11 07:00:24 +00002420 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
Hans Wennborg76517422012-02-22 10:17:01 +00002421 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2422 if (!FS.hasStandardLengthConversionCombination())
2423 HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2424 specifierLen);
2425
Ted Kremenek826a3452010-07-16 02:11:22 +00002426 // The remaining checks depend on the data arguments.
2427 if (HasVAListArg)
2428 return true;
2429
Ted Kremenek666a1972010-07-26 19:45:42 +00002430 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002431 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002432
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002433 // Check that the argument type matches the format specifier.
2434 const Expr *Ex = getDataArg(argIndex);
2435 const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2436 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2437 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00002438 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00002439 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002440
2441 if (success) {
2442 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002443 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002444 llvm::raw_svector_ostream os(buf);
2445 fixedFS.toString(os);
2446
2447 EmitFormatDiagnostic(
2448 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2449 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2450 << Ex->getSourceRange(),
2451 getLocationOfByte(CS.getStart()),
2452 /*IsStringLocation*/true,
2453 getSpecifierRange(startSpecifier, specifierLen),
2454 FixItHint::CreateReplacement(
2455 getSpecifierRange(startSpecifier, specifierLen),
2456 os.str()));
2457 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002458 EmitFormatDiagnostic(
2459 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002460 << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00002461 << Ex->getSourceRange(),
2462 getLocationOfByte(CS.getStart()),
2463 /*IsStringLocation*/true,
2464 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00002465 }
2466 }
2467
Ted Kremenek826a3452010-07-16 02:11:22 +00002468 return true;
2469}
2470
2471void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002472 const Expr *OrigFormatExpr,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002473 Expr **Args, unsigned NumArgs,
2474 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002475 unsigned firstDataArg, FormatStringType Type,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002476 bool inFunctionCall) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002477
Ted Kremeneke0e53132010-01-28 23:39:18 +00002478 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002479 if (!FExpr->isAscii()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002480 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002481 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002482 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2483 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002484 return;
2485 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002486
Ted Kremeneke0e53132010-01-28 23:39:18 +00002487 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002488 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002489 const char *Str = StrRef.data();
2490 unsigned StrLen = StrRef.size();
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002491 const unsigned numDataArgs = NumArgs - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002492
Ted Kremeneke0e53132010-01-28 23:39:18 +00002493 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002494 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00002495 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002496 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00002497 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2498 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00002499 return;
2500 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002501
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002502 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002503 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002504 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002505 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002506 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002507
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002508 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002509 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002510 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002511 } else if (Type == FST_Scanf) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002512 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002513 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002514 Str, HasVAListArg, Args, NumArgs, format_idx,
Richard Trieu55733de2011-10-28 00:41:25 +00002515 inFunctionCall);
Ted Kremenek826a3452010-07-16 02:11:22 +00002516
Hans Wennborgd02deeb2011-12-15 10:25:47 +00002517 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
David Blaikie4e4d0842012-03-11 07:00:24 +00002518 getLangOpts()))
Ted Kremenek826a3452010-07-16 02:11:22 +00002519 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002520 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00002521}
2522
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002523//===--- CHECK: Standard memory functions ---------------------------------===//
2524
Douglas Gregor2a053a32011-05-03 20:05:22 +00002525/// \brief Determine whether the given type is a dynamic class type (e.g.,
2526/// whether it has a vtable).
2527static bool isDynamicClassType(QualType T) {
2528 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2529 if (CXXRecordDecl *Definition = Record->getDefinition())
2530 if (Definition->isDynamicClass())
2531 return true;
2532
2533 return false;
2534}
2535
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002536/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002537/// otherwise returns NULL.
2538static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002539 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002540 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2541 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2542 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002543
Chandler Carruth000d4282011-06-16 09:09:40 +00002544 return 0;
2545}
2546
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002547/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002548static QualType getSizeOfArgType(const Expr* E) {
2549 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2550 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2551 if (SizeOf->getKind() == clang::UETT_SizeOf)
2552 return SizeOf->getTypeOfArgument();
2553
2554 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002555}
2556
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002557/// \brief Check for dangerous or invalid arguments to memset().
2558///
Chandler Carruth929f0132011-06-03 06:23:57 +00002559/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002560/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2561/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002562///
2563/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002564void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00002565 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002566 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00002567 assert(BId != 0);
2568
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002569 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002570 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00002571 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00002572 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002573 return;
2574
Anna Zaks0a151a12012-01-17 00:37:07 +00002575 unsigned LastArg = (BId == Builtin::BImemset ||
2576 BId == Builtin::BIstrndup ? 1 : 2);
2577 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00002578 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002579
2580 // We have special checking when the length is a sizeof expression.
2581 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2582 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2583 llvm::FoldingSetNodeID SizeOfArgID;
2584
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002585 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2586 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002587 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002588
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002589 QualType DestTy = Dest->getType();
2590 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2591 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002592
Chandler Carruth000d4282011-06-16 09:09:40 +00002593 // Never warn about void type pointers. This can be used to suppress
2594 // false positives.
2595 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002596 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002597
Chandler Carruth000d4282011-06-16 09:09:40 +00002598 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2599 // actually comparing the expressions for equality. Because computing the
2600 // expression IDs can be expensive, we only do this if the diagnostic is
2601 // enabled.
2602 if (SizeOfArg &&
2603 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2604 SizeOfArg->getExprLoc())) {
2605 // We only compute IDs for expressions if the warning is enabled, and
2606 // cache the sizeof arg's ID.
2607 if (SizeOfArgID == llvm::FoldingSetNodeID())
2608 SizeOfArg->Profile(SizeOfArgID, Context, true);
2609 llvm::FoldingSetNodeID DestID;
2610 Dest->Profile(DestID, Context, true);
2611 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002612 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2613 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002614 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2615 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2616 if (UnaryOp->getOpcode() == UO_AddrOf)
2617 ActionIdx = 1; // If its an address-of operator, just remove it.
2618 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2619 ActionIdx = 2; // If the pointee's size is sizeof(char),
2620 // suggest an explicit length.
Anna Zaksd9b859a2012-01-13 21:52:01 +00002621 unsigned DestSrcSelect =
Anna Zaks0a151a12012-01-17 00:37:07 +00002622 (BId == Builtin::BIstrndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002623 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2624 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002625 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002626 << Dest->getSourceRange()
2627 << SizeOfArg->getSourceRange());
2628 break;
2629 }
2630 }
2631
2632 // Also check for cases where the sizeof argument is the exact same
2633 // type as the memory argument, and where it points to a user-defined
2634 // record type.
2635 if (SizeOfArgTy != QualType()) {
2636 if (PointeeTy->isRecordType() &&
2637 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2638 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2639 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2640 << FnName << SizeOfArgTy << ArgIdx
2641 << PointeeTy << Dest->getSourceRange()
2642 << LenExpr->getSourceRange());
2643 break;
2644 }
Nico Webere4a1c642011-06-14 16:14:58 +00002645 }
2646
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002647 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00002648 if (isDynamicClassType(PointeeTy)) {
2649
2650 unsigned OperationType = 0;
2651 // "overwritten" if we're warning about the destination for any call
2652 // but memcmp; otherwise a verb appropriate to the call.
2653 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2654 if (BId == Builtin::BImemcpy)
2655 OperationType = 1;
2656 else if(BId == Builtin::BImemmove)
2657 OperationType = 2;
2658 else if (BId == Builtin::BImemcmp)
2659 OperationType = 3;
2660 }
2661
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002662 DiagRuntimeBehavior(
2663 Dest->getExprLoc(), Dest,
2664 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00002665 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00002666 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00002667 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002668 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00002669 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2670 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002671 DiagRuntimeBehavior(
2672 Dest->getExprLoc(), Dest,
2673 PDiag(diag::warn_arc_object_memaccess)
2674 << ArgIdx << FnName << PointeeTy
2675 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002676 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002677 continue;
John McCallf85e1932011-06-15 23:02:42 +00002678
2679 DiagRuntimeBehavior(
2680 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002681 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002682 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2683 break;
2684 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002685 }
2686}
2687
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002688// A little helper routine: ignore addition and subtraction of integer literals.
2689// This intentionally does not ignore all integer constant expressions because
2690// we don't want to remove sizeof().
2691static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2692 Ex = Ex->IgnoreParenCasts();
2693
2694 for (;;) {
2695 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2696 if (!BO || !BO->isAdditiveOp())
2697 break;
2698
2699 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2700 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2701
2702 if (isa<IntegerLiteral>(RHS))
2703 Ex = LHS;
2704 else if (isa<IntegerLiteral>(LHS))
2705 Ex = RHS;
2706 else
2707 break;
2708 }
2709
2710 return Ex;
2711}
2712
2713// Warn if the user has made the 'size' argument to strlcpy or strlcat
2714// be the size of the source, instead of the destination.
2715void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2716 IdentifierInfo *FnName) {
2717
2718 // Don't crash if the user has the wrong number of arguments
2719 if (Call->getNumArgs() != 3)
2720 return;
2721
2722 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2723 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2724 const Expr *CompareWithSrc = NULL;
2725
2726 // Look for 'strlcpy(dst, x, sizeof(x))'
2727 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2728 CompareWithSrc = Ex;
2729 else {
2730 // Look for 'strlcpy(dst, x, strlen(x))'
2731 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00002732 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002733 && SizeCall->getNumArgs() == 1)
2734 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2735 }
2736 }
2737
2738 if (!CompareWithSrc)
2739 return;
2740
2741 // Determine if the argument to sizeof/strlen is equal to the source
2742 // argument. In principle there's all kinds of things you could do
2743 // here, for instance creating an == expression and evaluating it with
2744 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2745 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2746 if (!SrcArgDRE)
2747 return;
2748
2749 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2750 if (!CompareWithSrcDRE ||
2751 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2752 return;
2753
2754 const Expr *OriginalSizeArg = Call->getArg(2);
2755 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2756 << OriginalSizeArg->getSourceRange() << FnName;
2757
2758 // Output a FIXIT hint if the destination is an array (rather than a
2759 // pointer to an array). This could be enhanced to handle some
2760 // pointers if we know the actual size, like if DstArg is 'array+2'
2761 // we could say 'sizeof(array)-2'.
2762 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002763 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002764
Ted Kremenek8f746222011-08-18 22:48:41 +00002765 // Only handle constant-sized or VLAs, but not flexible members.
2766 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2767 // Only issue the FIXIT for arrays of size > 1.
2768 if (CAT->getSize().getSExtValue() <= 1)
2769 return;
2770 } else if (!DstArgTy->isVariableArrayType()) {
2771 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002772 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002773
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002774 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00002775 llvm::raw_svector_ostream OS(sizeString);
2776 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002777 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002778 OS << ")";
2779
2780 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2781 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2782 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002783}
2784
Anna Zaksc36bedc2012-02-01 19:08:57 +00002785/// Check if two expressions refer to the same declaration.
2786static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2787 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2788 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2789 return D1->getDecl() == D2->getDecl();
2790 return false;
2791}
2792
2793static const Expr *getStrlenExprArg(const Expr *E) {
2794 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2795 const FunctionDecl *FD = CE->getDirectCallee();
2796 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2797 return 0;
2798 return CE->getArg(0)->IgnoreParenCasts();
2799 }
2800 return 0;
2801}
2802
2803// Warn on anti-patterns as the 'size' argument to strncat.
2804// The correct size argument should look like following:
2805// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2806void Sema::CheckStrncatArguments(const CallExpr *CE,
2807 IdentifierInfo *FnName) {
2808 // Don't crash if the user has the wrong number of arguments.
2809 if (CE->getNumArgs() < 3)
2810 return;
2811 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2812 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2813 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2814
2815 // Identify common expressions, which are wrongly used as the size argument
2816 // to strncat and may lead to buffer overflows.
2817 unsigned PatternType = 0;
2818 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2819 // - sizeof(dst)
2820 if (referToTheSameDecl(SizeOfArg, DstArg))
2821 PatternType = 1;
2822 // - sizeof(src)
2823 else if (referToTheSameDecl(SizeOfArg, SrcArg))
2824 PatternType = 2;
2825 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
2826 if (BE->getOpcode() == BO_Sub) {
2827 const Expr *L = BE->getLHS()->IgnoreParenCasts();
2828 const Expr *R = BE->getRHS()->IgnoreParenCasts();
2829 // - sizeof(dst) - strlen(dst)
2830 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
2831 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
2832 PatternType = 1;
2833 // - sizeof(src) - (anything)
2834 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
2835 PatternType = 2;
2836 }
2837 }
2838
2839 if (PatternType == 0)
2840 return;
2841
Anna Zaksafdb0412012-02-03 01:27:37 +00002842 // Generate the diagnostic.
2843 SourceLocation SL = LenArg->getLocStart();
2844 SourceRange SR = LenArg->getSourceRange();
2845 SourceManager &SM = PP.getSourceManager();
2846
2847 // If the function is defined as a builtin macro, do not show macro expansion.
2848 if (SM.isMacroArgExpansion(SL)) {
2849 SL = SM.getSpellingLoc(SL);
2850 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
2851 SM.getSpellingLoc(SR.getEnd()));
2852 }
2853
Anna Zaksc36bedc2012-02-01 19:08:57 +00002854 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00002855 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002856 else
Anna Zaksafdb0412012-02-03 01:27:37 +00002857 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002858
2859 // Output a FIXIT hint if the destination is an array (rather than a
2860 // pointer to an array). This could be enhanced to handle some
2861 // pointers if we know the actual size, like if DstArg is 'array+2'
2862 // we could say 'sizeof(array)-2'.
2863 QualType DstArgTy = DstArg->getType();
2864
2865 // Only handle constant-sized or VLAs, but not flexible members.
2866 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2867 // Only issue the FIXIT for arrays of size > 1.
2868 if (CAT->getSize().getSExtValue() <= 1)
2869 return;
2870 } else if (!DstArgTy->isVariableArrayType()) {
2871 return;
2872 }
2873
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00002874 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00002875 llvm::raw_svector_ostream OS(sizeString);
2876 OS << "sizeof(";
2877 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2878 OS << ") - ";
2879 OS << "strlen(";
2880 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2881 OS << ") - 1";
2882
Anna Zaksafdb0412012-02-03 01:27:37 +00002883 Diag(SL, diag::note_strncat_wrong_size)
2884 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00002885}
2886
Ted Kremenek06de2762007-08-17 16:46:58 +00002887//===--- CHECK: Return Address of Stack Variable --------------------------===//
2888
Chris Lattner5f9e2722011-07-23 10:55:15 +00002889static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2890static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002891
2892/// CheckReturnStackAddr - Check if a return statement returns the address
2893/// of a stack variable.
2894void
2895Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2896 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002898 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002899 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002900
2901 // Perform checking for returned stack addresses, local blocks,
2902 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002903 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00002904 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002905 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002906 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002907 stackE = EvalVal(RetValExp, refVars);
2908 }
2909
2910 if (stackE == 0)
2911 return; // Nothing suspicious was found.
2912
2913 SourceLocation diagLoc;
2914 SourceRange diagRange;
2915 if (refVars.empty()) {
2916 diagLoc = stackE->getLocStart();
2917 diagRange = stackE->getSourceRange();
2918 } else {
2919 // We followed through a reference variable. 'stackE' contains the
2920 // problematic expression but we will warn at the return statement pointing
2921 // at the reference variable. We will later display the "trail" of
2922 // reference variables using notes.
2923 diagLoc = refVars[0]->getLocStart();
2924 diagRange = refVars[0]->getSourceRange();
2925 }
2926
2927 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2928 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2929 : diag::warn_ret_stack_addr)
2930 << DR->getDecl()->getDeclName() << diagRange;
2931 } else if (isa<BlockExpr>(stackE)) { // local block.
2932 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2933 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2934 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2935 } else { // local temporary.
2936 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2937 : diag::warn_ret_local_temp_addr)
2938 << diagRange;
2939 }
2940
2941 // Display the "trail" of reference variables that we followed until we
2942 // found the problematic expression using notes.
2943 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2944 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2945 // If this var binds to another reference var, show the range of the next
2946 // var, otherwise the var binds to the problematic expression, in which case
2947 // show the range of the expression.
2948 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2949 : stackE->getSourceRange();
2950 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2951 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002952 }
2953}
2954
2955/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2956/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002957/// to a location on the stack, a local block, an address of a label, or a
2958/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002959/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002960/// encounter a subexpression that (1) clearly does not lead to one of the
2961/// above problematic expressions (2) is something we cannot determine leads to
2962/// a problematic expression based on such local checking.
2963///
2964/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2965/// the expression that they point to. Such variables are added to the
2966/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002967///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002968/// EvalAddr processes expressions that are pointers that are used as
2969/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002970/// At the base case of the recursion is a check for the above problematic
2971/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002972///
2973/// This implementation handles:
2974///
2975/// * pointer-to-pointer casts
2976/// * implicit conversions from array references to pointers
2977/// * taking the address of fields
2978/// * arbitrary interplay between "&" and "*" operators
2979/// * pointer arithmetic from an address of a stack variable
2980/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002981static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002982 if (E->isTypeDependent())
2983 return NULL;
2984
Ted Kremenek06de2762007-08-17 16:46:58 +00002985 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002986 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002987 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002988 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002989 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002990
Peter Collingbournef111d932011-04-15 00:35:48 +00002991 E = E->IgnoreParens();
2992
Ted Kremenek06de2762007-08-17 16:46:58 +00002993 // Our "symbolic interpreter" is just a dispatch off the currently
2994 // viewed AST node. We then recursively traverse the AST by calling
2995 // EvalAddr and EvalVal appropriately.
2996 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002997 case Stmt::DeclRefExprClass: {
2998 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2999
3000 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3001 // If this is a reference variable, follow through to the expression that
3002 // it points to.
3003 if (V->hasLocalStorage() &&
3004 V->getType()->isReferenceType() && V->hasInit()) {
3005 // Add the reference variable to the "trail".
3006 refVars.push_back(DR);
3007 return EvalAddr(V->getInit(), refVars);
3008 }
3009
3010 return NULL;
3011 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003012
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003013 case Stmt::UnaryOperatorClass: {
3014 // The only unary operator that make sense to handle here
3015 // is AddrOf. All others don't make sense as pointers.
3016 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003017
John McCall2de56d12010-08-25 11:45:40 +00003018 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003019 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003020 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003021 return NULL;
3022 }
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003024 case Stmt::BinaryOperatorClass: {
3025 // Handle pointer arithmetic. All other binary operators are not valid
3026 // in this context.
3027 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003028 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003029
John McCall2de56d12010-08-25 11:45:40 +00003030 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003031 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003032
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003033 Expr *Base = B->getLHS();
3034
3035 // Determine which argument is the real pointer base. It could be
3036 // the RHS argument instead of the LHS.
3037 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003038
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003039 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003040 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003041 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003042
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003043 // For conditional operators we need to see if either the LHS or RHS are
3044 // valid DeclRefExpr*s. If one of them is valid, we return it.
3045 case Stmt::ConditionalOperatorClass: {
3046 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003048 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003049 if (Expr *lhsExpr = C->getLHS()) {
3050 // In C++, we can have a throw-expression, which has 'void' type.
3051 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003052 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003053 return LHS;
3054 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003055
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003056 // In C++, we can have a throw-expression, which has 'void' type.
3057 if (C->getRHS()->getType()->isVoidType())
3058 return NULL;
3059
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003060 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003061 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003062
3063 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003064 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003065 return E; // local block.
3066 return NULL;
3067
3068 case Stmt::AddrLabelExprClass:
3069 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003070
John McCall80ee6e82011-11-10 05:35:25 +00003071 case Stmt::ExprWithCleanupsClass:
3072 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3073
Ted Kremenek54b52742008-08-07 00:49:01 +00003074 // For casts, we need to handle conversions from arrays to
3075 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003076 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003077 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003078 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003079 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003080 case Stmt::CXXStaticCastExprClass:
3081 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003082 case Stmt::CXXConstCastExprClass:
3083 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003084 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3085 switch (cast<CastExpr>(E)->getCastKind()) {
3086 case CK_BitCast:
3087 case CK_LValueToRValue:
3088 case CK_NoOp:
3089 case CK_BaseToDerived:
3090 case CK_DerivedToBase:
3091 case CK_UncheckedDerivedToBase:
3092 case CK_Dynamic:
3093 case CK_CPointerToObjCPointerCast:
3094 case CK_BlockPointerToObjCPointerCast:
3095 case CK_AnyPointerToBlockPointerCast:
3096 return EvalAddr(SubExpr, refVars);
3097
3098 case CK_ArrayToPointerDecay:
3099 return EvalVal(SubExpr, refVars);
3100
3101 default:
3102 return 0;
3103 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003104 }
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Douglas Gregor03e80032011-06-21 17:03:29 +00003106 case Stmt::MaterializeTemporaryExprClass:
3107 if (Expr *Result = EvalAddr(
3108 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3109 refVars))
3110 return Result;
3111
3112 return E;
3113
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003114 // Everything else: we simply don't reason about them.
3115 default:
3116 return NULL;
3117 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003118}
Mike Stump1eb44332009-09-09 15:08:12 +00003119
Ted Kremenek06de2762007-08-17 16:46:58 +00003120
3121/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3122/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003123static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003124do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003125 // We should only be called for evaluating non-pointer expressions, or
3126 // expressions with a pointer type that are not used as references but instead
3127 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003128
Ted Kremenek06de2762007-08-17 16:46:58 +00003129 // Our "symbolic interpreter" is just a dispatch off the currently
3130 // viewed AST node. We then recursively traverse the AST by calling
3131 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003132
3133 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003134 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003135 case Stmt::ImplicitCastExprClass: {
3136 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003137 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003138 E = IE->getSubExpr();
3139 continue;
3140 }
3141 return NULL;
3142 }
3143
John McCall80ee6e82011-11-10 05:35:25 +00003144 case Stmt::ExprWithCleanupsClass:
3145 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3146
Douglas Gregora2813ce2009-10-23 18:54:35 +00003147 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003148 // When we hit a DeclRefExpr we are looking at code that refers to a
3149 // variable's name. If it's not a reference variable we check if it has
3150 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003151 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003152
Ted Kremenek06de2762007-08-17 16:46:58 +00003153 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003154 if (V->hasLocalStorage()) {
3155 if (!V->getType()->isReferenceType())
3156 return DR;
3157
3158 // Reference variable, follow through to the expression that
3159 // it points to.
3160 if (V->hasInit()) {
3161 // Add the reference variable to the "trail".
3162 refVars.push_back(DR);
3163 return EvalVal(V->getInit(), refVars);
3164 }
3165 }
Mike Stump1eb44332009-09-09 15:08:12 +00003166
Ted Kremenek06de2762007-08-17 16:46:58 +00003167 return NULL;
3168 }
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Ted Kremenek06de2762007-08-17 16:46:58 +00003170 case Stmt::UnaryOperatorClass: {
3171 // The only unary operator that make sense to handle here
3172 // is Deref. All others don't resolve to a "name." This includes
3173 // handling all sorts of rvalues passed to a unary operator.
3174 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003175
John McCall2de56d12010-08-25 11:45:40 +00003176 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003177 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003178
3179 return NULL;
3180 }
Mike Stump1eb44332009-09-09 15:08:12 +00003181
Ted Kremenek06de2762007-08-17 16:46:58 +00003182 case Stmt::ArraySubscriptExprClass: {
3183 // Array subscripts are potential references to data on the stack. We
3184 // retrieve the DeclRefExpr* for the array variable if it indeed
3185 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003186 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003187 }
Mike Stump1eb44332009-09-09 15:08:12 +00003188
Ted Kremenek06de2762007-08-17 16:46:58 +00003189 case Stmt::ConditionalOperatorClass: {
3190 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003191 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003192 ConditionalOperator *C = cast<ConditionalOperator>(E);
3193
Anders Carlsson39073232007-11-30 19:04:31 +00003194 // Handle the GNU extension for missing LHS.
3195 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003196 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00003197 return LHS;
3198
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003199 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003200 }
Mike Stump1eb44332009-09-09 15:08:12 +00003201
Ted Kremenek06de2762007-08-17 16:46:58 +00003202 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003203 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003204 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003205
Ted Kremenek06de2762007-08-17 16:46:58 +00003206 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003207 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003208 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003209
3210 // Check whether the member type is itself a reference, in which case
3211 // we're not going to refer to the member, but to what the member refers to.
3212 if (M->getMemberDecl()->getType()->isReferenceType())
3213 return NULL;
3214
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003215 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00003216 }
Mike Stump1eb44332009-09-09 15:08:12 +00003217
Douglas Gregor03e80032011-06-21 17:03:29 +00003218 case Stmt::MaterializeTemporaryExprClass:
3219 if (Expr *Result = EvalVal(
3220 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3221 refVars))
3222 return Result;
3223
3224 return E;
3225
Ted Kremenek06de2762007-08-17 16:46:58 +00003226 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003227 // Check that we don't return or take the address of a reference to a
3228 // temporary. This is only useful in C++.
3229 if (!E->isTypeDependent() && E->isRValue())
3230 return E;
3231
3232 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003233 return NULL;
3234 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003235} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003236}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003237
3238//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3239
3240/// Check for comparisons of floating point operands using != and ==.
3241/// Issue a warning if these are no self-comparisons, as they are not likely
3242/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003243void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003244 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00003245
Richard Trieudd225092011-09-15 21:56:47 +00003246 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3247 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003248
3249 // Special case: check for x == x (which is OK).
3250 // Do not emit warnings for such cases.
3251 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3252 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3253 if (DRL->getDecl() == DRR->getDecl())
3254 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003255
3256
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003257 // Special case: check for comparisons against literals that can be exactly
3258 // represented by APFloat. In such cases, do not emit a warning. This
3259 // is a heuristic: often comparison against such literals are used to
3260 // detect if a value in a variable has not changed. This clearly can
3261 // lead to false negatives.
3262 if (EmitWarning) {
3263 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3264 if (FLL->isExact())
3265 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003266 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00003267 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3268 if (FLR->isExact())
3269 EmitWarning = false;
3270 }
3271 }
Mike Stump1eb44332009-09-09 15:08:12 +00003272
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003273 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00003274 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003275 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003276 if (CL->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003277 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003278
Sebastian Redl0eb23302009-01-19 00:08:26 +00003279 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003280 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Richard Smith180f4792011-11-10 06:34:14 +00003281 if (CR->isBuiltinCall())
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003282 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003284 // Emit the diagnostic.
3285 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00003286 Diag(Loc, diag::warn_floatingpoint_eq)
3287 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003288}
John McCallba26e582010-01-04 23:21:16 +00003289
John McCallf2370c92010-01-06 05:24:50 +00003290//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3291//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00003292
John McCallf2370c92010-01-06 05:24:50 +00003293namespace {
John McCallba26e582010-01-04 23:21:16 +00003294
John McCallf2370c92010-01-06 05:24:50 +00003295/// Structure recording the 'active' range of an integer-valued
3296/// expression.
3297struct IntRange {
3298 /// The number of bits active in the int.
3299 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00003300
John McCallf2370c92010-01-06 05:24:50 +00003301 /// True if the int is known not to have negative values.
3302 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00003303
John McCallf2370c92010-01-06 05:24:50 +00003304 IntRange(unsigned Width, bool NonNegative)
3305 : Width(Width), NonNegative(NonNegative)
3306 {}
John McCallba26e582010-01-04 23:21:16 +00003307
John McCall1844a6e2010-11-10 23:38:19 +00003308 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00003309 static IntRange forBoolType() {
3310 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00003311 }
3312
John McCall1844a6e2010-11-10 23:38:19 +00003313 /// Returns the range of an opaque value of the given integral type.
3314 static IntRange forValueOfType(ASTContext &C, QualType T) {
3315 return forValueOfCanonicalType(C,
3316 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00003317 }
3318
John McCall1844a6e2010-11-10 23:38:19 +00003319 /// Returns the range of an opaque value of a canonical integral type.
3320 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00003321 assert(T->isCanonicalUnqualified());
3322
3323 if (const VectorType *VT = dyn_cast<VectorType>(T))
3324 T = VT->getElementType().getTypePtr();
3325 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3326 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00003327
John McCall091f23f2010-11-09 22:22:12 +00003328 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00003329 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3330 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00003331 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00003332 return IntRange(C.getIntWidth(QualType(T, 0)), false);
3333
John McCall323ed742010-05-06 08:58:33 +00003334 unsigned NumPositive = Enum->getNumPositiveBits();
3335 unsigned NumNegative = Enum->getNumNegativeBits();
3336
3337 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3338 }
John McCallf2370c92010-01-06 05:24:50 +00003339
3340 const BuiltinType *BT = cast<BuiltinType>(T);
3341 assert(BT->isInteger());
3342
3343 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3344 }
3345
John McCall1844a6e2010-11-10 23:38:19 +00003346 /// Returns the "target" range of a canonical integral type, i.e.
3347 /// the range of values expressible in the type.
3348 ///
3349 /// This matches forValueOfCanonicalType except that enums have the
3350 /// full range of their type, not the range of their enumerators.
3351 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3352 assert(T->isCanonicalUnqualified());
3353
3354 if (const VectorType *VT = dyn_cast<VectorType>(T))
3355 T = VT->getElementType().getTypePtr();
3356 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3357 T = CT->getElementType().getTypePtr();
3358 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00003359 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00003360
3361 const BuiltinType *BT = cast<BuiltinType>(T);
3362 assert(BT->isInteger());
3363
3364 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3365 }
3366
3367 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003368 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00003369 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00003370 L.NonNegative && R.NonNegative);
3371 }
3372
John McCall1844a6e2010-11-10 23:38:19 +00003373 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00003374 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00003375 return IntRange(std::min(L.Width, R.Width),
3376 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00003377 }
3378};
3379
Ted Kremenek0692a192012-01-31 05:37:37 +00003380static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3381 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003382 if (value.isSigned() && value.isNegative())
3383 return IntRange(value.getMinSignedBits(), false);
3384
3385 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00003386 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003387
3388 // isNonNegative() just checks the sign bit without considering
3389 // signedness.
3390 return IntRange(value.getActiveBits(), true);
3391}
3392
Ted Kremenek0692a192012-01-31 05:37:37 +00003393static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3394 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003395 if (result.isInt())
3396 return GetValueRange(C, result.getInt(), MaxWidth);
3397
3398 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00003399 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3400 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3401 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3402 R = IntRange::join(R, El);
3403 }
John McCallf2370c92010-01-06 05:24:50 +00003404 return R;
3405 }
3406
3407 if (result.isComplexInt()) {
3408 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3409 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3410 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00003411 }
3412
3413 // This can happen with lossless casts to intptr_t of "based" lvalues.
3414 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00003415 // FIXME: The only reason we need to pass the type in here is to get
3416 // the sign right on this one case. It would be nice if APValue
3417 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00003418 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003419 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00003420}
John McCallf2370c92010-01-06 05:24:50 +00003421
3422/// Pseudo-evaluate the given integer expression, estimating the
3423/// range of values it might take.
3424///
3425/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00003426static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00003427 E = E->IgnoreParens();
3428
3429 // Try a full evaluation first.
3430 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00003431 if (E->EvaluateAsRValue(result, C))
John McCall0acc3112010-01-06 22:57:21 +00003432 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00003433
3434 // I think we only want to look through implicit casts here; if the
3435 // user has an explicit widening cast, we should treat the value as
3436 // being of the new, wider type.
3437 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00003438 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00003439 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3440
John McCall1844a6e2010-11-10 23:38:19 +00003441 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00003442
John McCall2de56d12010-08-25 11:45:40 +00003443 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00003444
John McCallf2370c92010-01-06 05:24:50 +00003445 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00003446 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00003447 return OutputTypeRange;
3448
3449 IntRange SubRange
3450 = GetExprRange(C, CE->getSubExpr(),
3451 std::min(MaxWidth, OutputTypeRange.Width));
3452
3453 // Bail out if the subexpr's range is as wide as the cast type.
3454 if (SubRange.Width >= OutputTypeRange.Width)
3455 return OutputTypeRange;
3456
3457 // Otherwise, we take the smaller width, and we're non-negative if
3458 // either the output type or the subexpr is.
3459 return IntRange(SubRange.Width,
3460 SubRange.NonNegative || OutputTypeRange.NonNegative);
3461 }
3462
3463 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3464 // If we can fold the condition, just take that operand.
3465 bool CondResult;
3466 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3467 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3468 : CO->getFalseExpr(),
3469 MaxWidth);
3470
3471 // Otherwise, conservatively merge.
3472 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3473 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3474 return IntRange::join(L, R);
3475 }
3476
3477 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3478 switch (BO->getOpcode()) {
3479
3480 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00003481 case BO_LAnd:
3482 case BO_LOr:
3483 case BO_LT:
3484 case BO_GT:
3485 case BO_LE:
3486 case BO_GE:
3487 case BO_EQ:
3488 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00003489 return IntRange::forBoolType();
3490
John McCall862ff872011-07-13 06:35:24 +00003491 // The type of the assignments is the type of the LHS, so the RHS
3492 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00003493 case BO_MulAssign:
3494 case BO_DivAssign:
3495 case BO_RemAssign:
3496 case BO_AddAssign:
3497 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00003498 case BO_XorAssign:
3499 case BO_OrAssign:
3500 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00003501 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00003502
John McCall862ff872011-07-13 06:35:24 +00003503 // Simple assignments just pass through the RHS, which will have
3504 // been coerced to the LHS type.
3505 case BO_Assign:
3506 // TODO: bitfields?
3507 return GetExprRange(C, BO->getRHS(), MaxWidth);
3508
John McCallf2370c92010-01-06 05:24:50 +00003509 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003510 case BO_PtrMemD:
3511 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00003512 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003513
John McCall60fad452010-01-06 22:07:33 +00003514 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00003515 case BO_And:
3516 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00003517 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3518 GetExprRange(C, BO->getRHS(), MaxWidth));
3519
John McCallf2370c92010-01-06 05:24:50 +00003520 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00003521 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00003522 // ...except that we want to treat '1 << (blah)' as logically
3523 // positive. It's an important idiom.
3524 if (IntegerLiteral *I
3525 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3526 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00003527 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00003528 return IntRange(R.Width, /*NonNegative*/ true);
3529 }
3530 }
3531 // fallthrough
3532
John McCall2de56d12010-08-25 11:45:40 +00003533 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00003534 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003535
John McCall60fad452010-01-06 22:07:33 +00003536 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003537 case BO_Shr:
3538 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003539 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3540
3541 // If the shift amount is a positive constant, drop the width by
3542 // that much.
3543 llvm::APSInt shift;
3544 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3545 shift.isNonNegative()) {
3546 unsigned zext = shift.getZExtValue();
3547 if (zext >= L.Width)
3548 L.Width = (L.NonNegative ? 0 : 1);
3549 else
3550 L.Width -= zext;
3551 }
3552
3553 return L;
3554 }
3555
3556 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003557 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003558 return GetExprRange(C, BO->getRHS(), MaxWidth);
3559
John McCall60fad452010-01-06 22:07:33 +00003560 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003561 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003562 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003563 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003564 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003565
John McCall00fe7612011-07-14 22:39:48 +00003566 // The width of a division result is mostly determined by the size
3567 // of the LHS.
3568 case BO_Div: {
3569 // Don't 'pre-truncate' the operands.
3570 unsigned opWidth = C.getIntWidth(E->getType());
3571 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3572
3573 // If the divisor is constant, use that.
3574 llvm::APSInt divisor;
3575 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3576 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3577 if (log2 >= L.Width)
3578 L.Width = (L.NonNegative ? 0 : 1);
3579 else
3580 L.Width = std::min(L.Width - log2, MaxWidth);
3581 return L;
3582 }
3583
3584 // Otherwise, just use the LHS's width.
3585 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3586 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3587 }
3588
3589 // The result of a remainder can't be larger than the result of
3590 // either side.
3591 case BO_Rem: {
3592 // Don't 'pre-truncate' the operands.
3593 unsigned opWidth = C.getIntWidth(E->getType());
3594 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3595 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3596
3597 IntRange meet = IntRange::meet(L, R);
3598 meet.Width = std::min(meet.Width, MaxWidth);
3599 return meet;
3600 }
3601
3602 // The default behavior is okay for these.
3603 case BO_Mul:
3604 case BO_Add:
3605 case BO_Xor:
3606 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003607 break;
3608 }
3609
John McCall00fe7612011-07-14 22:39:48 +00003610 // The default case is to treat the operation as if it were closed
3611 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003612 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3613 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3614 return IntRange::join(L, R);
3615 }
3616
3617 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3618 switch (UO->getOpcode()) {
3619 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003620 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003621 return IntRange::forBoolType();
3622
3623 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003624 case UO_Deref:
3625 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003626 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003627
3628 default:
3629 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3630 }
3631 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003632
3633 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003634 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003635 }
John McCallf2370c92010-01-06 05:24:50 +00003636
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003637 if (FieldDecl *BitField = E->getBitField())
3638 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003639 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003640
John McCall1844a6e2010-11-10 23:38:19 +00003641 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003642}
John McCall51313c32010-01-04 23:31:57 +00003643
Ted Kremenek0692a192012-01-31 05:37:37 +00003644static IntRange GetExprRange(ASTContext &C, Expr *E) {
John McCall323ed742010-05-06 08:58:33 +00003645 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3646}
3647
John McCall51313c32010-01-04 23:31:57 +00003648/// Checks whether the given value, which currently has the given
3649/// source semantics, has the same value when coerced through the
3650/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00003651static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3652 const llvm::fltSemantics &Src,
3653 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003654 llvm::APFloat truncated = value;
3655
3656 bool ignored;
3657 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3658 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3659
3660 return truncated.bitwiseIsEqual(value);
3661}
3662
3663/// Checks whether the given value, which currently has the given
3664/// source semantics, has the same value when coerced through the
3665/// target semantics.
3666///
3667/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00003668static bool IsSameFloatAfterCast(const APValue &value,
3669 const llvm::fltSemantics &Src,
3670 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003671 if (value.isFloat())
3672 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3673
3674 if (value.isVector()) {
3675 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3676 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3677 return false;
3678 return true;
3679 }
3680
3681 assert(value.isComplexFloat());
3682 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3683 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3684}
3685
Ted Kremenek0692a192012-01-31 05:37:37 +00003686static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003687
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003688static bool IsZero(Sema &S, Expr *E) {
3689 // Suppress cases where we are comparing against an enum constant.
3690 if (const DeclRefExpr *DR =
3691 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3692 if (isa<EnumConstantDecl>(DR->getDecl()))
3693 return false;
3694
3695 // Suppress cases where the '0' value is expanded from a macro.
3696 if (E->getLocStart().isMacroID())
3697 return false;
3698
John McCall323ed742010-05-06 08:58:33 +00003699 llvm::APSInt Value;
3700 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3701}
3702
John McCall372e1032010-10-06 00:25:24 +00003703static bool HasEnumType(Expr *E) {
3704 // Strip off implicit integral promotions.
3705 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003706 if (ICE->getCastKind() != CK_IntegralCast &&
3707 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003708 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003709 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003710 }
3711
3712 return E->getType()->isEnumeralType();
3713}
3714
Ted Kremenek0692a192012-01-31 05:37:37 +00003715static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003716 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003717 if (E->isValueDependent())
3718 return;
3719
John McCall2de56d12010-08-25 11:45:40 +00003720 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003721 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003722 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003723 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003724 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003725 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003726 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003727 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003728 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003729 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003730 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003731 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003732 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003733 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003734 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003735 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3736 }
3737}
3738
3739/// Analyze the operands of the given comparison. Implements the
3740/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00003741static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003742 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3743 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003744}
John McCall51313c32010-01-04 23:31:57 +00003745
John McCallba26e582010-01-04 23:21:16 +00003746/// \brief Implements -Wsign-compare.
3747///
Richard Trieudd225092011-09-15 21:56:47 +00003748/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00003749static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00003750 // The type the comparison is being performed in.
3751 QualType T = E->getLHS()->getType();
3752 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3753 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003754
John McCall323ed742010-05-06 08:58:33 +00003755 // We don't do anything special if this isn't an unsigned integral
3756 // comparison: we're only interested in integral comparisons, and
3757 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003758 //
3759 // We also don't care about value-dependent expressions or expressions
3760 // whose result is a constant.
3761 if (!T->hasUnsignedIntegerRepresentation()
3762 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003763 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003764
Richard Trieudd225092011-09-15 21:56:47 +00003765 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3766 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003767
John McCall323ed742010-05-06 08:58:33 +00003768 // Check to see if one of the (unmodified) operands is of different
3769 // signedness.
3770 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003771 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3772 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003773 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003774 signedOperand = LHS;
3775 unsignedOperand = RHS;
3776 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3777 signedOperand = RHS;
3778 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003779 } else {
John McCall323ed742010-05-06 08:58:33 +00003780 CheckTrivialUnsignedComparison(S, E);
3781 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003782 }
3783
John McCall323ed742010-05-06 08:58:33 +00003784 // Otherwise, calculate the effective range of the signed operand.
3785 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003786
John McCall323ed742010-05-06 08:58:33 +00003787 // Go ahead and analyze implicit conversions in the operands. Note
3788 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003789 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3790 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003791
John McCall323ed742010-05-06 08:58:33 +00003792 // If the signed range is non-negative, -Wsign-compare won't fire,
3793 // but we should still check for comparisons which are always true
3794 // or false.
3795 if (signedRange.NonNegative)
3796 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003797
3798 // For (in)equality comparisons, if the unsigned operand is a
3799 // constant which cannot collide with a overflowed signed operand,
3800 // then reinterpreting the signed operand as unsigned will not
3801 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003802 if (E->isEqualityOp()) {
3803 unsigned comparisonWidth = S.Context.getIntWidth(T);
3804 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003805
John McCall323ed742010-05-06 08:58:33 +00003806 // We should never be unable to prove that the unsigned operand is
3807 // non-negative.
3808 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3809
3810 if (unsignedRange.Width < comparisonWidth)
3811 return;
3812 }
3813
3814 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003815 << LHS->getType() << RHS->getType()
3816 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003817}
3818
John McCall15d7d122010-11-11 03:21:53 +00003819/// Analyzes an attempt to assign the given value to a bitfield.
3820///
3821/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00003822static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3823 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00003824 assert(Bitfield->isBitField());
3825 if (Bitfield->isInvalidDecl())
3826 return false;
3827
John McCall91b60142010-11-11 05:33:51 +00003828 // White-list bool bitfields.
3829 if (Bitfield->getType()->isBooleanType())
3830 return false;
3831
Douglas Gregor46ff3032011-02-04 13:09:01 +00003832 // Ignore value- or type-dependent expressions.
3833 if (Bitfield->getBitWidth()->isValueDependent() ||
3834 Bitfield->getBitWidth()->isTypeDependent() ||
3835 Init->isValueDependent() ||
3836 Init->isTypeDependent())
3837 return false;
3838
John McCall15d7d122010-11-11 03:21:53 +00003839 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3840
Richard Smith80d4b552011-12-28 19:48:30 +00003841 llvm::APSInt Value;
3842 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00003843 return false;
3844
John McCall15d7d122010-11-11 03:21:53 +00003845 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003846 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003847
3848 if (OriginalWidth <= FieldWidth)
3849 return false;
3850
Eli Friedman3a643af2012-01-26 23:11:39 +00003851 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00003852 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00003853 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00003854
Eli Friedman3a643af2012-01-26 23:11:39 +00003855 // Check whether the stored value is equal to the original value.
3856 TruncatedValue = TruncatedValue.extend(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003857 if (Value == TruncatedValue)
3858 return false;
3859
Eli Friedman3a643af2012-01-26 23:11:39 +00003860 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00003861 // therefore don't strictly fit into a signed bitfield of width 1.
3862 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00003863 return false;
3864
John McCall15d7d122010-11-11 03:21:53 +00003865 std::string PrettyValue = Value.toString(10);
3866 std::string PrettyTrunc = TruncatedValue.toString(10);
3867
3868 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3869 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3870 << Init->getSourceRange();
3871
3872 return true;
3873}
3874
John McCallbeb22aa2010-11-09 23:24:47 +00003875/// Analyze the given simple or compound assignment for warning-worthy
3876/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00003877static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00003878 // Just recurse on the LHS.
3879 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3880
3881 // We want to recurse on the RHS as normal unless we're assigning to
3882 // a bitfield.
3883 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003884 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3885 E->getOperatorLoc())) {
3886 // Recurse, ignoring any implicit conversions on the RHS.
3887 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3888 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003889 }
3890 }
3891
3892 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3893}
3894
John McCall51313c32010-01-04 23:31:57 +00003895/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00003896static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00003897 SourceLocation CContext, unsigned diag,
3898 bool pruneControlFlow = false) {
3899 if (pruneControlFlow) {
3900 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3901 S.PDiag(diag)
3902 << SourceType << T << E->getSourceRange()
3903 << SourceRange(CContext));
3904 return;
3905 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003906 S.Diag(E->getExprLoc(), diag)
3907 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3908}
3909
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003910/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00003911static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00003912 SourceLocation CContext, unsigned diag,
3913 bool pruneControlFlow = false) {
3914 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003915}
3916
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003917/// Diagnose an implicit cast from a literal expression. Does not warn when the
3918/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003919void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3920 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003921 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003922 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003923 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003924 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3925 T->hasUnsignedIntegerRepresentation());
3926 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003927 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003928 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003929 return;
3930
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003931 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3932 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003933}
3934
John McCall091f23f2010-11-09 22:22:12 +00003935std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3936 if (!Range.Width) return "0";
3937
3938 llvm::APSInt ValueInRange = Value;
3939 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003940 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003941 return ValueInRange.toString(10);
3942}
3943
John McCall323ed742010-05-06 08:58:33 +00003944void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003945 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003946 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003947
John McCall323ed742010-05-06 08:58:33 +00003948 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3949 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3950 if (Source == Target) return;
3951 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003952
Chandler Carruth108f7562011-07-26 05:40:03 +00003953 // If the conversion context location is invalid don't complain. We also
3954 // don't want to emit a warning if the issue occurs from the expansion of
3955 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3956 // delay this check as long as possible. Once we detect we are in that
3957 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003958 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003959 return;
3960
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003961 // Diagnose implicit casts to bool.
3962 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3963 if (isa<StringLiteral>(E))
3964 // Warn on string literal to bool. Checks for string literals in logical
3965 // expressions, for instances, assert(0 && "error here"), is prevented
3966 // by a check in AnalyzeImplicitConversions().
3967 return DiagnoseImpCast(S, E, T, CC,
3968 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00003969 if (Source->isFunctionType()) {
3970 // Warn on function to bool. Checks free functions and static member
3971 // functions. Weakly imported functions are excluded from the check,
3972 // since it's common to test their value to check whether the linker
3973 // found a definition for them.
3974 ValueDecl *D = 0;
3975 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3976 D = R->getDecl();
3977 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3978 D = M->getMemberDecl();
3979 }
3980
3981 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00003982 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3983 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3984 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00003985 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3986 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3987 QualType ReturnType;
3988 UnresolvedSet<4> NonTemplateOverloads;
3989 S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3990 if (!ReturnType.isNull()
3991 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3992 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3993 << FixItHint::CreateInsertion(
3994 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00003995 return;
3996 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00003997 }
3998 }
David Blaikiee37cdc42011-09-29 04:06:47 +00003999 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004000 }
John McCall51313c32010-01-04 23:31:57 +00004001
4002 // Strip vector types.
4003 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004004 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004005 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004006 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004007 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004008 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004009
4010 // If the vector cast is cast between two vectors of the same size, it is
4011 // a bitcast, not a conversion.
4012 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4013 return;
John McCall51313c32010-01-04 23:31:57 +00004014
4015 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4016 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4017 }
4018
4019 // Strip complex types.
4020 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004021 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004022 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004023 return;
4024
John McCallb4eb64d2010-10-08 02:01:28 +00004025 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004026 }
John McCall51313c32010-01-04 23:31:57 +00004027
4028 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4029 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4030 }
4031
4032 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4033 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4034
4035 // If the source is floating point...
4036 if (SourceBT && SourceBT->isFloatingPoint()) {
4037 // ...and the target is floating point...
4038 if (TargetBT && TargetBT->isFloatingPoint()) {
4039 // ...then warn if we're dropping FP rank.
4040
4041 // Builtin FP kinds are ordered by increasing FP rank.
4042 if (SourceBT->getKind() > TargetBT->getKind()) {
4043 // Don't warn about float constants that are precisely
4044 // representable in the target type.
4045 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004046 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004047 // Value might be a float, a float vector, or a float complex.
4048 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004049 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4050 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004051 return;
4052 }
4053
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004054 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004055 return;
4056
John McCallb4eb64d2010-10-08 02:01:28 +00004057 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004058 }
4059 return;
4060 }
4061
Ted Kremenekef9ff882011-03-10 20:03:42 +00004062 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00004063 if ((TargetBT && TargetBT->isInteger())) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004064 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004065 return;
4066
Chandler Carrutha5b93322011-02-17 11:05:49 +00004067 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004068 // We also want to warn on, e.g., "int i = -1.234"
4069 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4070 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4071 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4072
Chandler Carruthf65076e2011-04-10 08:36:24 +00004073 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4074 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00004075 } else {
4076 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4077 }
4078 }
John McCall51313c32010-01-04 23:31:57 +00004079
4080 return;
4081 }
4082
John McCallf2370c92010-01-06 05:24:50 +00004083 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00004084 return;
4085
Richard Trieu1838ca52011-05-29 19:59:02 +00004086 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
4087 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
David Blaikieb1360492012-03-16 20:30:12 +00004088 SourceLocation Loc = E->getSourceRange().getBegin();
4089 if (Loc.isMacroID())
4090 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
4091 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
4092 << T << Loc << clang::SourceRange(CC);
Richard Trieu1838ca52011-05-29 19:59:02 +00004093 return;
4094 }
4095
John McCall323ed742010-05-06 08:58:33 +00004096 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00004097 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00004098
4099 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00004100 // If the source is a constant, use a default-on diagnostic.
4101 // TODO: this should happen for bitfield stores, too.
4102 llvm::APSInt Value(32);
4103 if (E->isIntegerConstantExpr(Value, S.Context)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004104 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004105 return;
4106
John McCall091f23f2010-11-09 22:22:12 +00004107 std::string PrettySourceValue = Value.toString(10);
4108 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4109
Ted Kremenek5e745da2011-10-22 02:37:33 +00004110 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4111 S.PDiag(diag::warn_impcast_integer_precision_constant)
4112 << PrettySourceValue << PrettyTargetValue
4113 << E->getType() << T << E->getSourceRange()
4114 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00004115 return;
4116 }
4117
Chris Lattnerb792b302011-06-14 04:51:15 +00004118 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004119 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004120 return;
4121
John McCallf2370c92010-01-06 05:24:50 +00004122 if (SourceRange.Width == 64 && TargetRange.Width == 32)
Anna Zaksc36bedc2012-02-01 19:08:57 +00004123 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4124 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00004125 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00004126 }
4127
4128 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4129 (!TargetRange.NonNegative && SourceRange.NonNegative &&
4130 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004131
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004132 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004133 return;
4134
John McCall323ed742010-05-06 08:58:33 +00004135 unsigned DiagID = diag::warn_impcast_integer_sign;
4136
4137 // Traditionally, gcc has warned about this under -Wsign-compare.
4138 // We also want to warn about it in -Wconversion.
4139 // So if -Wconversion is off, use a completely identical diagnostic
4140 // in the sign-compare group.
4141 // The conditional-checking code will
4142 if (ICContext) {
4143 DiagID = diag::warn_impcast_integer_sign_conditional;
4144 *ICContext = true;
4145 }
4146
John McCallb4eb64d2010-10-08 02:01:28 +00004147 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00004148 }
4149
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004150 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004151 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4152 // type, to give us better diagnostics.
4153 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00004154 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004155 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4156 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4157 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4158 SourceType = S.Context.getTypeDeclType(Enum);
4159 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4160 }
4161 }
4162
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004163 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4164 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4165 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004166 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004167 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00004168 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00004169 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004170 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004171 return;
4172
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004173 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004174 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004175 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00004176
John McCall51313c32010-01-04 23:31:57 +00004177 return;
4178}
4179
John McCall323ed742010-05-06 08:58:33 +00004180void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
4181
4182void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00004183 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00004184 E = E->IgnoreParenImpCasts();
4185
4186 if (isa<ConditionalOperator>(E))
4187 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4188
John McCallb4eb64d2010-10-08 02:01:28 +00004189 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004190 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004191 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00004192 return;
4193}
4194
4195void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00004196 SourceLocation CC = E->getQuestionLoc();
4197
4198 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00004199
4200 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00004201 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4202 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004203
4204 // If -Wconversion would have warned about either of the candidates
4205 // for a signedness conversion to the context type...
4206 if (!Suspicious) return;
4207
4208 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004209 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4210 CC))
John McCall323ed742010-05-06 08:58:33 +00004211 return;
4212
John McCall323ed742010-05-06 08:58:33 +00004213 // ...then check whether it would have warned about either of the
4214 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00004215 if (E->getType() == T) return;
4216
4217 Suspicious = false;
4218 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4219 E->getType(), CC, &Suspicious);
4220 if (!Suspicious)
4221 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00004222 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00004223}
4224
4225/// AnalyzeImplicitConversions - Find and report any interesting
4226/// implicit conversions in the given expression. There are a couple
4227/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004228void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004229 QualType T = OrigE->getType();
4230 Expr *E = OrigE->IgnoreParenImpCasts();
4231
Douglas Gregorf8b6e152011-10-10 17:38:18 +00004232 if (E->isTypeDependent() || E->isValueDependent())
4233 return;
4234
John McCall323ed742010-05-06 08:58:33 +00004235 // For conditional operators, we analyze the arguments as if they
4236 // were being fed directly into the output.
4237 if (isa<ConditionalOperator>(E)) {
4238 ConditionalOperator *CO = cast<ConditionalOperator>(E);
4239 CheckConditionalOperator(S, CO, T);
4240 return;
4241 }
4242
4243 // Go ahead and check any implicit conversions we might have skipped.
4244 // The non-canonical typecheck is just an optimization;
4245 // CheckImplicitConversion will filter out dead implicit conversions.
4246 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00004247 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00004248
4249 // Now continue drilling into this expression.
4250
4251 // Skip past explicit casts.
4252 if (isa<ExplicitCastExpr>(E)) {
4253 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00004254 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004255 }
4256
John McCallbeb22aa2010-11-09 23:24:47 +00004257 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4258 // Do a somewhat different check with comparison operators.
4259 if (BO->isComparisonOp())
4260 return AnalyzeComparison(S, BO);
4261
Eli Friedman0fa06382012-01-26 23:34:06 +00004262 // And with simple assignments.
4263 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00004264 return AnalyzeAssignment(S, BO);
4265 }
John McCall323ed742010-05-06 08:58:33 +00004266
4267 // These break the otherwise-useful invariant below. Fortunately,
4268 // we don't really need to recurse into them, because any internal
4269 // expressions should have been analyzed already when they were
4270 // built into statements.
4271 if (isa<StmtExpr>(E)) return;
4272
4273 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004274 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00004275
4276 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00004277 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004278 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4279 bool IsLogicalOperator = BO && BO->isLogicalOp();
4280 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00004281 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00004282 if (!ChildExpr)
4283 continue;
4284
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004285 if (IsLogicalOperator &&
4286 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4287 // Ignore checking string literals that are in logical operators.
4288 continue;
4289 AnalyzeImplicitConversions(S, ChildExpr, CC);
4290 }
John McCall323ed742010-05-06 08:58:33 +00004291}
4292
4293} // end anonymous namespace
4294
4295/// Diagnoses "dangerous" implicit conversions within the given
4296/// expression (which is a full expression). Implements -Wconversion
4297/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00004298///
4299/// \param CC the "context" location of the implicit conversion, i.e.
4300/// the most location of the syntactic entity requiring the implicit
4301/// conversion
4302void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00004303 // Don't diagnose in unevaluated contexts.
4304 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4305 return;
4306
4307 // Don't diagnose for value- or type-dependent expressions.
4308 if (E->isTypeDependent() || E->isValueDependent())
4309 return;
4310
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004311 // Check for array bounds violations in cases where the check isn't triggered
4312 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4313 // ArraySubscriptExpr is on the RHS of a variable initialization.
4314 CheckArrayAccess(E);
4315
John McCallb4eb64d2010-10-08 02:01:28 +00004316 // This is not the right CC for (e.g.) a variable initialization.
4317 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00004318}
4319
John McCall15d7d122010-11-11 03:21:53 +00004320void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4321 FieldDecl *BitField,
4322 Expr *Init) {
4323 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4324}
4325
Mike Stumpf8c49212010-01-21 03:59:47 +00004326/// CheckParmsForFunctionDef - Check that the parameters of the given
4327/// function are appropriate for the definition of a function. This
4328/// takes care of any checks that cannot be performed on the
4329/// declaration itself, e.g., that the types of each of the function
4330/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004331bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4332 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00004333 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00004334 for (; P != PEnd; ++P) {
4335 ParmVarDecl *Param = *P;
4336
Mike Stumpf8c49212010-01-21 03:59:47 +00004337 // C99 6.7.5.3p4: the parameters in a parameter type list in a
4338 // function declarator that is part of a function definition of
4339 // that function shall not have incomplete type.
4340 //
4341 // This is also C++ [dcl.fct]p6.
4342 if (!Param->isInvalidDecl() &&
4343 RequireCompleteType(Param->getLocation(), Param->getType(),
4344 diag::err_typecheck_decl_incomplete_type)) {
4345 Param->setInvalidDecl();
4346 HasInvalidParm = true;
4347 }
4348
4349 // C99 6.9.1p5: If the declarator includes a parameter type list, the
4350 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00004351 if (CheckParameterNames &&
4352 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00004353 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00004354 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00004355 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00004356
4357 // C99 6.7.5.3p12:
4358 // If the function declarator is not part of a definition of that
4359 // function, parameters may have incomplete type and may use the [*]
4360 // notation in their sequences of declarator specifiers to specify
4361 // variable length array types.
4362 QualType PType = Param->getOriginalType();
4363 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4364 if (AT->getSizeModifier() == ArrayType::Star) {
4365 // FIXME: This diagnosic should point the the '[*]' if source-location
4366 // information is added for it.
4367 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4368 }
4369 }
Mike Stumpf8c49212010-01-21 03:59:47 +00004370 }
4371
4372 return HasInvalidParm;
4373}
John McCallb7f4ffe2010-08-12 21:44:57 +00004374
4375/// CheckCastAlign - Implements -Wcast-align, which warns when a
4376/// pointer cast increases the alignment requirements.
4377void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4378 // This is actually a lot of work to potentially be doing on every
4379 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00004380 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4381 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00004382 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00004383 return;
4384
4385 // Ignore dependent types.
4386 if (T->isDependentType() || Op->getType()->isDependentType())
4387 return;
4388
4389 // Require that the destination be a pointer type.
4390 const PointerType *DestPtr = T->getAs<PointerType>();
4391 if (!DestPtr) return;
4392
4393 // If the destination has alignment 1, we're done.
4394 QualType DestPointee = DestPtr->getPointeeType();
4395 if (DestPointee->isIncompleteType()) return;
4396 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4397 if (DestAlign.isOne()) return;
4398
4399 // Require that the source be a pointer type.
4400 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4401 if (!SrcPtr) return;
4402 QualType SrcPointee = SrcPtr->getPointeeType();
4403
4404 // Whitelist casts from cv void*. We already implicitly
4405 // whitelisted casts to cv void*, since they have alignment 1.
4406 // Also whitelist casts involving incomplete types, which implicitly
4407 // includes 'void'.
4408 if (SrcPointee->isIncompleteType()) return;
4409
4410 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4411 if (SrcAlign >= DestAlign) return;
4412
4413 Diag(TRange.getBegin(), diag::warn_cast_align)
4414 << Op->getType() << T
4415 << static_cast<unsigned>(SrcAlign.getQuantity())
4416 << static_cast<unsigned>(DestAlign.getQuantity())
4417 << TRange << Op->getSourceRange();
4418}
4419
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004420static const Type* getElementType(const Expr *BaseExpr) {
4421 const Type* EltType = BaseExpr->getType().getTypePtr();
4422 if (EltType->isAnyPointerType())
4423 return EltType->getPointeeType().getTypePtr();
4424 else if (EltType->isArrayType())
4425 return EltType->getBaseElementTypeUnsafe();
4426 return EltType;
4427}
4428
Chandler Carruthc2684342011-08-05 09:10:50 +00004429/// \brief Check whether this array fits the idiom of a size-one tail padded
4430/// array member of a struct.
4431///
4432/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4433/// commonly used to emulate flexible arrays in C89 code.
4434static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4435 const NamedDecl *ND) {
4436 if (Size != 1 || !ND) return false;
4437
4438 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4439 if (!FD) return false;
4440
4441 // Don't consider sizes resulting from macro expansions or template argument
4442 // substitution to form C89 tail-padded arrays.
4443 ConstantArrayTypeLoc TL =
4444 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4445 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4446 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4447 return false;
4448
4449 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00004450 if (!RD) return false;
4451 if (RD->isUnion()) return false;
4452 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4453 if (!CRD->isStandardLayout()) return false;
4454 }
Chandler Carruthc2684342011-08-05 09:10:50 +00004455
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00004456 // See if this is the last field decl in the record.
4457 const Decl *D = FD;
4458 while ((D = D->getNextDeclInContext()))
4459 if (isa<FieldDecl>(D))
4460 return false;
4461 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00004462}
4463
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004464void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004465 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00004466 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00004467 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004468 if (IndexExpr->isValueDependent())
4469 return;
4470
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00004471 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004472 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00004473 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004474 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00004475 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00004476 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00004477
Chandler Carruth34064582011-02-17 20:55:08 +00004478 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004479 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00004480 return;
Richard Smith25b009a2011-12-16 19:31:14 +00004481 if (IndexNegated)
4482 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004483
Chandler Carruthba447122011-08-05 08:07:29 +00004484 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00004485 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4486 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00004487 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00004488 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00004489
Ted Kremenek9e060ca2011-02-23 23:06:04 +00004490 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00004491 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00004492 if (!size.isStrictlyPositive())
4493 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004494
4495 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00004496 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004497 // Make sure we're comparing apples to apples when comparing index to size
4498 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4499 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00004500 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00004501 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004502 if (ptrarith_typesize != array_typesize) {
4503 // There's a cast to a different size type involved
4504 uint64_t ratio = array_typesize / ptrarith_typesize;
4505 // TODO: Be smarter about handling cases where array_typesize is not a
4506 // multiple of ptrarith_typesize
4507 if (ptrarith_typesize * ratio == array_typesize)
4508 size *= llvm::APInt(size.getBitWidth(), ratio);
4509 }
4510 }
4511
Chandler Carruth34064582011-02-17 20:55:08 +00004512 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004513 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004514 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00004515 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00004516
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004517 // For array subscripting the index must be less than size, but for pointer
4518 // arithmetic also allow the index (offset) to be equal to size since
4519 // computing the next address after the end of the array is legal and
4520 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00004521 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00004522 return;
4523
4524 // Also don't warn for arrays of size 1 which are members of some
4525 // structure. These are often used to approximate flexible arrays in C89
4526 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004527 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00004528 return;
Chandler Carruth34064582011-02-17 20:55:08 +00004529
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004530 // Suppress the warning if the subscript expression (as identified by the
4531 // ']' location) and the index expression are both from macro expansions
4532 // within a system header.
4533 if (ASE) {
4534 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4535 ASE->getRBracketLoc());
4536 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4537 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4538 IndexExpr->getLocStart());
4539 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4540 return;
4541 }
4542 }
4543
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004544 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004545 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004546 DiagID = diag::warn_array_index_exceeds_bounds;
4547
4548 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4549 PDiag(DiagID) << index.toString(10, true)
4550 << size.toString(10, true)
4551 << (unsigned)size.getLimitedValue(~0U)
4552 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00004553 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004554 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004555 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004556 DiagID = diag::warn_ptr_arith_precedes_bounds;
4557 if (index.isNegative()) index = -index;
4558 }
4559
4560 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4561 PDiag(DiagID) << index.toString(10, true)
4562 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004563 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00004564
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00004565 if (!ND) {
4566 // Try harder to find a NamedDecl to point at in the note.
4567 while (const ArraySubscriptExpr *ASE =
4568 dyn_cast<ArraySubscriptExpr>(BaseExpr))
4569 BaseExpr = ASE->getBase()->IgnoreParenCasts();
4570 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4571 ND = dyn_cast<NamedDecl>(DRE->getDecl());
4572 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4573 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4574 }
4575
Chandler Carruth35001ca2011-02-17 21:10:52 +00004576 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004577 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4578 PDiag(diag::note_array_index_out_of_bounds)
4579 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00004580}
4581
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004582void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004583 int AllowOnePastEnd = 0;
4584 while (expr) {
4585 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004586 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004587 case Stmt::ArraySubscriptExprClass: {
4588 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00004589 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004590 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004591 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00004592 }
4593 case Stmt::UnaryOperatorClass: {
4594 // Only unwrap the * and & unary operators
4595 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4596 expr = UO->getSubExpr();
4597 switch (UO->getOpcode()) {
4598 case UO_AddrOf:
4599 AllowOnePastEnd++;
4600 break;
4601 case UO_Deref:
4602 AllowOnePastEnd--;
4603 break;
4604 default:
4605 return;
4606 }
4607 break;
4608 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004609 case Stmt::ConditionalOperatorClass: {
4610 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4611 if (const Expr *lhs = cond->getLHS())
4612 CheckArrayAccess(lhs);
4613 if (const Expr *rhs = cond->getRHS())
4614 CheckArrayAccess(rhs);
4615 return;
4616 }
4617 default:
4618 return;
4619 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004620 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004621}
John McCallf85e1932011-06-15 23:02:42 +00004622
4623//===--- CHECK: Objective-C retain cycles ----------------------------------//
4624
4625namespace {
4626 struct RetainCycleOwner {
4627 RetainCycleOwner() : Variable(0), Indirect(false) {}
4628 VarDecl *Variable;
4629 SourceRange Range;
4630 SourceLocation Loc;
4631 bool Indirect;
4632
4633 void setLocsFrom(Expr *e) {
4634 Loc = e->getExprLoc();
4635 Range = e->getSourceRange();
4636 }
4637 };
4638}
4639
4640/// Consider whether capturing the given variable can possibly lead to
4641/// a retain cycle.
4642static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4643 // In ARC, it's captured strongly iff the variable has __strong
4644 // lifetime. In MRR, it's captured strongly if the variable is
4645 // __block and has an appropriate type.
4646 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4647 return false;
4648
4649 owner.Variable = var;
4650 owner.setLocsFrom(ref);
4651 return true;
4652}
4653
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004654static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00004655 while (true) {
4656 e = e->IgnoreParens();
4657 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4658 switch (cast->getCastKind()) {
4659 case CK_BitCast:
4660 case CK_LValueBitCast:
4661 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004662 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004663 e = cast->getSubExpr();
4664 continue;
4665
John McCallf85e1932011-06-15 23:02:42 +00004666 default:
4667 return false;
4668 }
4669 }
4670
4671 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4672 ObjCIvarDecl *ivar = ref->getDecl();
4673 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4674 return false;
4675
4676 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004677 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004678 return false;
4679
4680 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4681 owner.Indirect = true;
4682 return true;
4683 }
4684
4685 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4686 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4687 if (!var) return false;
4688 return considerVariable(var, ref, owner);
4689 }
4690
John McCallf85e1932011-06-15 23:02:42 +00004691 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4692 if (member->isArrow()) return false;
4693
4694 // Don't count this as an indirect ownership.
4695 e = member->getBase();
4696 continue;
4697 }
4698
John McCall4b9c2d22011-11-06 09:01:30 +00004699 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4700 // Only pay attention to pseudo-objects on property references.
4701 ObjCPropertyRefExpr *pre
4702 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4703 ->IgnoreParens());
4704 if (!pre) return false;
4705 if (pre->isImplicitProperty()) return false;
4706 ObjCPropertyDecl *property = pre->getExplicitProperty();
4707 if (!property->isRetaining() &&
4708 !(property->getPropertyIvarDecl() &&
4709 property->getPropertyIvarDecl()->getType()
4710 .getObjCLifetime() == Qualifiers::OCL_Strong))
4711 return false;
4712
4713 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004714 if (pre->isSuperReceiver()) {
4715 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4716 if (!owner.Variable)
4717 return false;
4718 owner.Loc = pre->getLocation();
4719 owner.Range = pre->getSourceRange();
4720 return true;
4721 }
John McCall4b9c2d22011-11-06 09:01:30 +00004722 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4723 ->getSourceExpr());
4724 continue;
4725 }
4726
John McCallf85e1932011-06-15 23:02:42 +00004727 // Array ivars?
4728
4729 return false;
4730 }
4731}
4732
4733namespace {
4734 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4735 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4736 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4737 Variable(variable), Capturer(0) {}
4738
4739 VarDecl *Variable;
4740 Expr *Capturer;
4741
4742 void VisitDeclRefExpr(DeclRefExpr *ref) {
4743 if (ref->getDecl() == Variable && !Capturer)
4744 Capturer = ref;
4745 }
4746
John McCallf85e1932011-06-15 23:02:42 +00004747 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4748 if (Capturer) return;
4749 Visit(ref->getBase());
4750 if (Capturer && ref->isFreeIvar())
4751 Capturer = ref;
4752 }
4753
4754 void VisitBlockExpr(BlockExpr *block) {
4755 // Look inside nested blocks
4756 if (block->getBlockDecl()->capturesVariable(Variable))
4757 Visit(block->getBlockDecl()->getBody());
4758 }
4759 };
4760}
4761
4762/// Check whether the given argument is a block which captures a
4763/// variable.
4764static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4765 assert(owner.Variable && owner.Loc.isValid());
4766
4767 e = e->IgnoreParenCasts();
4768 BlockExpr *block = dyn_cast<BlockExpr>(e);
4769 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4770 return 0;
4771
4772 FindCaptureVisitor visitor(S.Context, owner.Variable);
4773 visitor.Visit(block->getBlockDecl()->getBody());
4774 return visitor.Capturer;
4775}
4776
4777static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4778 RetainCycleOwner &owner) {
4779 assert(capturer);
4780 assert(owner.Variable && owner.Loc.isValid());
4781
4782 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4783 << owner.Variable << capturer->getSourceRange();
4784 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4785 << owner.Indirect << owner.Range;
4786}
4787
4788/// Check for a keyword selector that starts with the word 'add' or
4789/// 'set'.
4790static bool isSetterLikeSelector(Selector sel) {
4791 if (sel.isUnarySelector()) return false;
4792
Chris Lattner5f9e2722011-07-23 10:55:15 +00004793 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004794 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004795 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00004796 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00004797 else if (str.startswith("add")) {
4798 // Specially whitelist 'addOperationWithBlock:'.
4799 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4800 return false;
4801 str = str.substr(3);
4802 }
John McCallf85e1932011-06-15 23:02:42 +00004803 else
4804 return false;
4805
4806 if (str.empty()) return true;
4807 return !islower(str.front());
4808}
4809
4810/// Check a message send to see if it's likely to cause a retain cycle.
4811void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4812 // Only check instance methods whose selector looks like a setter.
4813 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4814 return;
4815
4816 // Try to find a variable that the receiver is strongly owned by.
4817 RetainCycleOwner owner;
4818 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004819 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00004820 return;
4821 } else {
4822 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4823 owner.Variable = getCurMethodDecl()->getSelfDecl();
4824 owner.Loc = msg->getSuperLoc();
4825 owner.Range = msg->getSuperLoc();
4826 }
4827
4828 // Check whether the receiver is captured by any of the arguments.
4829 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4830 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4831 return diagnoseRetainCycle(*this, capturer, owner);
4832}
4833
4834/// Check a property assign to see if it's likely to cause a retain cycle.
4835void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4836 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00004837 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00004838 return;
4839
4840 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4841 diagnoseRetainCycle(*this, capturer, owner);
4842}
4843
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004844bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004845 QualType LHS, Expr *RHS) {
4846 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4847 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004848 return false;
4849 // strip off any implicit cast added to get to the one arc-specific
4850 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004851 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004852 Diag(Loc, diag::warn_arc_retained_assign)
4853 << (LT == Qualifiers::OCL_ExplicitNone)
4854 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004855 return true;
4856 }
4857 RHS = cast->getSubExpr();
4858 }
4859 return false;
John McCallf85e1932011-06-15 23:02:42 +00004860}
4861
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004862void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4863 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004864 QualType LHSType;
4865 // PropertyRef on LHS type need be directly obtained from
4866 // its declaration as it has a PsuedoType.
4867 ObjCPropertyRefExpr *PRE
4868 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4869 if (PRE && !PRE->isImplicitProperty()) {
4870 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4871 if (PD)
4872 LHSType = PD->getType();
4873 }
4874
4875 if (LHSType.isNull())
4876 LHSType = LHS->getType();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004877 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4878 return;
4879 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4880 // FIXME. Check for other life times.
4881 if (LT != Qualifiers::OCL_None)
4882 return;
4883
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004884 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004885 if (PRE->isImplicitProperty())
4886 return;
4887 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4888 if (!PD)
4889 return;
4890
4891 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004892 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
4893 // when 'assign' attribute was not explicitly specified
4894 // by user, ignore it and rely on property type itself
4895 // for lifetime info.
4896 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
4897 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
4898 LHSType->isObjCRetainableType())
4899 return;
4900
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004901 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004902 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004903 Diag(Loc, diag::warn_arc_retained_property_assign)
4904 << RHS->getSourceRange();
4905 return;
4906 }
4907 RHS = cast->getSubExpr();
4908 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00004909 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004910 }
4911}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00004912
4913//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
4914
4915namespace {
4916bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
4917 SourceLocation StmtLoc,
4918 const NullStmt *Body) {
4919 // Do not warn if the body is a macro that expands to nothing, e.g:
4920 //
4921 // #define CALL(x)
4922 // if (condition)
4923 // CALL(0);
4924 //
4925 if (Body->hasLeadingEmptyMacro())
4926 return false;
4927
4928 // Get line numbers of statement and body.
4929 bool StmtLineInvalid;
4930 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
4931 &StmtLineInvalid);
4932 if (StmtLineInvalid)
4933 return false;
4934
4935 bool BodyLineInvalid;
4936 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
4937 &BodyLineInvalid);
4938 if (BodyLineInvalid)
4939 return false;
4940
4941 // Warn if null statement and body are on the same line.
4942 if (StmtLine != BodyLine)
4943 return false;
4944
4945 return true;
4946}
4947} // Unnamed namespace
4948
4949void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4950 const Stmt *Body,
4951 unsigned DiagID) {
4952 // Since this is a syntactic check, don't emit diagnostic for template
4953 // instantiations, this just adds noise.
4954 if (CurrentInstantiationScope)
4955 return;
4956
4957 // The body should be a null statement.
4958 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
4959 if (!NBody)
4960 return;
4961
4962 // Do the usual checks.
4963 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
4964 return;
4965
4966 Diag(NBody->getSemiLoc(), DiagID);
4967 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
4968}
4969
4970void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
4971 const Stmt *PossibleBody) {
4972 assert(!CurrentInstantiationScope); // Ensured by caller
4973
4974 SourceLocation StmtLoc;
4975 const Stmt *Body;
4976 unsigned DiagID;
4977 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
4978 StmtLoc = FS->getRParenLoc();
4979 Body = FS->getBody();
4980 DiagID = diag::warn_empty_for_body;
4981 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
4982 StmtLoc = WS->getCond()->getSourceRange().getEnd();
4983 Body = WS->getBody();
4984 DiagID = diag::warn_empty_while_body;
4985 } else
4986 return; // Neither `for' nor `while'.
4987
4988 // The body should be a null statement.
4989 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
4990 if (!NBody)
4991 return;
4992
4993 // Skip expensive checks if diagnostic is disabled.
4994 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
4995 DiagnosticsEngine::Ignored)
4996 return;
4997
4998 // Do the usual checks.
4999 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
5000 return;
5001
5002 // `for(...);' and `while(...);' are popular idioms, so in order to keep
5003 // noise level low, emit diagnostics only if for/while is followed by a
5004 // CompoundStmt, e.g.:
5005 // for (int i = 0; i < n; i++);
5006 // {
5007 // a(i);
5008 // }
5009 // or if for/while is followed by a statement with more indentation
5010 // than for/while itself:
5011 // for (int i = 0; i < n; i++);
5012 // a(i);
5013 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5014 if (!ProbableTypo) {
5015 bool BodyColInvalid;
5016 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5017 PossibleBody->getLocStart(),
5018 &BodyColInvalid);
5019 if (BodyColInvalid)
5020 return;
5021
5022 bool StmtColInvalid;
5023 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5024 S->getLocStart(),
5025 &StmtColInvalid);
5026 if (StmtColInvalid)
5027 return;
5028
5029 if (BodyCol > StmtCol)
5030 ProbableTypo = true;
5031 }
5032
5033 if (ProbableTypo) {
5034 Diag(NBody->getSemiLoc(), DiagID);
5035 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5036 }
5037}