blob: d14549c9e8c52882d5a12223bc32a54be2af6736 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
Peter Collingbournef7706832014-12-12 23:41:25 +0000142static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143 if (checkArgCount(S, BuiltinCall, 2))
144 return true;
145
146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148 Expr *Call = BuiltinCall->getArg(0);
149 Expr *Chain = BuiltinCall->getArg(1);
150
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
154 return true;
155 }
156
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
161 return true;
162 }
163
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
169 return true;
170 }
171
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
175 return true;
176 }
177
178 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179 if (ChainResult.isInvalid())
180 return true;
181 if (!ChainResult.get()->getType()->isPointerType()) {
182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
184 return true;
185 }
186
187 QualType ReturnTy = CE->getCallReturnType();
188 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189 QualType BuiltinTy = S.Context.getFunctionType(
190 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
192
193 Builtin =
194 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
195
196 BuiltinCall->setType(CE->getType());
197 BuiltinCall->setValueKind(CE->getValueKind());
198 BuiltinCall->setObjectKind(CE->getObjectKind());
199 BuiltinCall->setCallee(Builtin);
200 BuiltinCall->setArg(1, ChainResult.get());
201
202 return false;
203}
204
John McCalldadc5752010-08-24 06:29:42 +0000205ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000206Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
207 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000208 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000209
Chris Lattner3be167f2010-10-01 23:23:24 +0000210 // Find out if any arguments are required to be integer constant expressions.
211 unsigned ICEArguments = 0;
212 ASTContext::GetBuiltinTypeError Error;
213 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
214 if (Error != ASTContext::GE_None)
215 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
216
217 // If any arguments are required to be ICE's, check and diagnose.
218 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
219 // Skip arguments not required to be ICE's.
220 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
221
222 llvm::APSInt Result;
223 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
224 return true;
225 ICEArguments &= ~(1 << ArgNo);
226 }
227
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000228 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000229 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000230 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000231 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000232 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000233 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000234 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000235 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000236 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000237 if (SemaBuiltinVAStart(TheCall))
238 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000239 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000240 case Builtin::BI__va_start: {
241 switch (Context.getTargetInfo().getTriple().getArch()) {
242 case llvm::Triple::arm:
243 case llvm::Triple::thumb:
244 if (SemaBuiltinVAStartARM(TheCall))
245 return ExprError();
246 break;
247 default:
248 if (SemaBuiltinVAStart(TheCall))
249 return ExprError();
250 break;
251 }
252 break;
253 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000254 case Builtin::BI__builtin_isgreater:
255 case Builtin::BI__builtin_isgreaterequal:
256 case Builtin::BI__builtin_isless:
257 case Builtin::BI__builtin_islessequal:
258 case Builtin::BI__builtin_islessgreater:
259 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000260 if (SemaBuiltinUnorderedCompare(TheCall))
261 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000262 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000263 case Builtin::BI__builtin_fpclassify:
264 if (SemaBuiltinFPClassification(TheCall, 6))
265 return ExprError();
266 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000267 case Builtin::BI__builtin_isfinite:
268 case Builtin::BI__builtin_isinf:
269 case Builtin::BI__builtin_isinf_sign:
270 case Builtin::BI__builtin_isnan:
271 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000272 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000273 return ExprError();
274 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000275 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000276 return SemaBuiltinShuffleVector(TheCall);
277 // TheCall will be freed by the smart pointer here, but that's fine, since
278 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000279 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000280 if (SemaBuiltinPrefetch(TheCall))
281 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000282 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000283 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000284 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000285 if (SemaBuiltinAssume(TheCall))
286 return ExprError();
287 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000288 case Builtin::BI__builtin_assume_aligned:
289 if (SemaBuiltinAssumeAligned(TheCall))
290 return ExprError();
291 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000292 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000293 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000294 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000295 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000296 case Builtin::BI__builtin_longjmp:
297 if (SemaBuiltinLongjmp(TheCall))
298 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000299 break;
John McCallbebede42011-02-26 05:39:39 +0000300
301 case Builtin::BI__builtin_classify_type:
302 if (checkArgCount(*this, TheCall, 1)) return true;
303 TheCall->setType(Context.IntTy);
304 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000305 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000306 if (checkArgCount(*this, TheCall, 1)) return true;
307 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000308 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000309 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000310 case Builtin::BI__sync_fetch_and_add_1:
311 case Builtin::BI__sync_fetch_and_add_2:
312 case Builtin::BI__sync_fetch_and_add_4:
313 case Builtin::BI__sync_fetch_and_add_8:
314 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000315 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000316 case Builtin::BI__sync_fetch_and_sub_1:
317 case Builtin::BI__sync_fetch_and_sub_2:
318 case Builtin::BI__sync_fetch_and_sub_4:
319 case Builtin::BI__sync_fetch_and_sub_8:
320 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000321 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000322 case Builtin::BI__sync_fetch_and_or_1:
323 case Builtin::BI__sync_fetch_and_or_2:
324 case Builtin::BI__sync_fetch_and_or_4:
325 case Builtin::BI__sync_fetch_and_or_8:
326 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000327 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000328 case Builtin::BI__sync_fetch_and_and_1:
329 case Builtin::BI__sync_fetch_and_and_2:
330 case Builtin::BI__sync_fetch_and_and_4:
331 case Builtin::BI__sync_fetch_and_and_8:
332 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000333 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000334 case Builtin::BI__sync_fetch_and_xor_1:
335 case Builtin::BI__sync_fetch_and_xor_2:
336 case Builtin::BI__sync_fetch_and_xor_4:
337 case Builtin::BI__sync_fetch_and_xor_8:
338 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000339 case Builtin::BI__sync_fetch_and_nand:
340 case Builtin::BI__sync_fetch_and_nand_1:
341 case Builtin::BI__sync_fetch_and_nand_2:
342 case Builtin::BI__sync_fetch_and_nand_4:
343 case Builtin::BI__sync_fetch_and_nand_8:
344 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000345 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000346 case Builtin::BI__sync_add_and_fetch_1:
347 case Builtin::BI__sync_add_and_fetch_2:
348 case Builtin::BI__sync_add_and_fetch_4:
349 case Builtin::BI__sync_add_and_fetch_8:
350 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000351 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000352 case Builtin::BI__sync_sub_and_fetch_1:
353 case Builtin::BI__sync_sub_and_fetch_2:
354 case Builtin::BI__sync_sub_and_fetch_4:
355 case Builtin::BI__sync_sub_and_fetch_8:
356 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000357 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000358 case Builtin::BI__sync_and_and_fetch_1:
359 case Builtin::BI__sync_and_and_fetch_2:
360 case Builtin::BI__sync_and_and_fetch_4:
361 case Builtin::BI__sync_and_and_fetch_8:
362 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000363 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000364 case Builtin::BI__sync_or_and_fetch_1:
365 case Builtin::BI__sync_or_and_fetch_2:
366 case Builtin::BI__sync_or_and_fetch_4:
367 case Builtin::BI__sync_or_and_fetch_8:
368 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000369 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000370 case Builtin::BI__sync_xor_and_fetch_1:
371 case Builtin::BI__sync_xor_and_fetch_2:
372 case Builtin::BI__sync_xor_and_fetch_4:
373 case Builtin::BI__sync_xor_and_fetch_8:
374 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000375 case Builtin::BI__sync_nand_and_fetch:
376 case Builtin::BI__sync_nand_and_fetch_1:
377 case Builtin::BI__sync_nand_and_fetch_2:
378 case Builtin::BI__sync_nand_and_fetch_4:
379 case Builtin::BI__sync_nand_and_fetch_8:
380 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000381 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000382 case Builtin::BI__sync_val_compare_and_swap_1:
383 case Builtin::BI__sync_val_compare_and_swap_2:
384 case Builtin::BI__sync_val_compare_and_swap_4:
385 case Builtin::BI__sync_val_compare_and_swap_8:
386 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000387 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000388 case Builtin::BI__sync_bool_compare_and_swap_1:
389 case Builtin::BI__sync_bool_compare_and_swap_2:
390 case Builtin::BI__sync_bool_compare_and_swap_4:
391 case Builtin::BI__sync_bool_compare_and_swap_8:
392 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000393 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000394 case Builtin::BI__sync_lock_test_and_set_1:
395 case Builtin::BI__sync_lock_test_and_set_2:
396 case Builtin::BI__sync_lock_test_and_set_4:
397 case Builtin::BI__sync_lock_test_and_set_8:
398 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000399 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000400 case Builtin::BI__sync_lock_release_1:
401 case Builtin::BI__sync_lock_release_2:
402 case Builtin::BI__sync_lock_release_4:
403 case Builtin::BI__sync_lock_release_8:
404 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000405 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000406 case Builtin::BI__sync_swap_1:
407 case Builtin::BI__sync_swap_2:
408 case Builtin::BI__sync_swap_4:
409 case Builtin::BI__sync_swap_8:
410 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000411 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000412#define BUILTIN(ID, TYPE, ATTRS)
413#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
414 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000415 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000416#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000417 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000418 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000419 return ExprError();
420 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000421 case Builtin::BI__builtin_addressof:
422 if (SemaBuiltinAddressof(*this, TheCall))
423 return ExprError();
424 break;
Richard Smith760520b2014-06-03 23:27:44 +0000425 case Builtin::BI__builtin_operator_new:
426 case Builtin::BI__builtin_operator_delete:
427 if (!getLangOpts().CPlusPlus) {
428 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
429 << (BuiltinID == Builtin::BI__builtin_operator_new
430 ? "__builtin_operator_new"
431 : "__builtin_operator_delete")
432 << "C++";
433 return ExprError();
434 }
435 // CodeGen assumes it can find the global new and delete to call,
436 // so ensure that they are declared.
437 DeclareGlobalNewDelete();
438 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000439
440 // check secure string manipulation functions where overflows
441 // are detectable at compile time
442 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000443 case Builtin::BI__builtin___memmove_chk:
444 case Builtin::BI__builtin___memset_chk:
445 case Builtin::BI__builtin___strlcat_chk:
446 case Builtin::BI__builtin___strlcpy_chk:
447 case Builtin::BI__builtin___strncat_chk:
448 case Builtin::BI__builtin___strncpy_chk:
449 case Builtin::BI__builtin___stpncpy_chk:
450 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
451 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000452 case Builtin::BI__builtin___memccpy_chk:
453 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
454 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000455 case Builtin::BI__builtin___snprintf_chk:
456 case Builtin::BI__builtin___vsnprintf_chk:
457 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
458 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000459
460 case Builtin::BI__builtin_call_with_static_chain:
461 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
462 return ExprError();
463 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000464 }
Richard Smith760520b2014-06-03 23:27:44 +0000465
Nate Begeman4904e322010-06-08 02:47:44 +0000466 // Since the target specific builtins for each arch overlap, only check those
467 // of the arch we are compiling for.
468 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000469 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000470 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000471 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000472 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000473 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000474 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
475 return ExprError();
476 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000477 case llvm::Triple::aarch64:
478 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000479 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000480 return ExprError();
481 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000482 case llvm::Triple::mips:
483 case llvm::Triple::mipsel:
484 case llvm::Triple::mips64:
485 case llvm::Triple::mips64el:
486 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
487 return ExprError();
488 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000489 case llvm::Triple::x86:
490 case llvm::Triple::x86_64:
491 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
492 return ExprError();
493 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000494 default:
495 break;
496 }
497 }
498
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000499 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000500}
501
Nate Begeman91e1fea2010-06-14 05:21:25 +0000502// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000503static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000504 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000505 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000506 switch (Type.getEltType()) {
507 case NeonTypeFlags::Int8:
508 case NeonTypeFlags::Poly8:
509 return shift ? 7 : (8 << IsQuad) - 1;
510 case NeonTypeFlags::Int16:
511 case NeonTypeFlags::Poly16:
512 return shift ? 15 : (4 << IsQuad) - 1;
513 case NeonTypeFlags::Int32:
514 return shift ? 31 : (2 << IsQuad) - 1;
515 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000516 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000517 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000518 case NeonTypeFlags::Poly128:
519 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000520 case NeonTypeFlags::Float16:
521 assert(!shift && "cannot shift float types!");
522 return (4 << IsQuad) - 1;
523 case NeonTypeFlags::Float32:
524 assert(!shift && "cannot shift float types!");
525 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000526 case NeonTypeFlags::Float64:
527 assert(!shift && "cannot shift float types!");
528 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000529 }
David Blaikie8a40f702012-01-17 06:56:22 +0000530 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000531}
532
Bob Wilsone4d77232011-11-08 05:04:11 +0000533/// getNeonEltType - Return the QualType corresponding to the elements of
534/// the vector type specified by the NeonTypeFlags. This is used to check
535/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000536static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000537 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000538 switch (Flags.getEltType()) {
539 case NeonTypeFlags::Int8:
540 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
541 case NeonTypeFlags::Int16:
542 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
543 case NeonTypeFlags::Int32:
544 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
545 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000546 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000547 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
548 else
549 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
550 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000551 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000552 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000553 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000554 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000555 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000556 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000557 case NeonTypeFlags::Poly128:
558 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000559 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000560 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000561 case NeonTypeFlags::Float32:
562 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000563 case NeonTypeFlags::Float64:
564 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000565 }
David Blaikie8a40f702012-01-17 06:56:22 +0000566 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000567}
568
Tim Northover12670412014-02-19 10:37:05 +0000569bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000570 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000571 uint64_t mask = 0;
572 unsigned TV = 0;
573 int PtrArgNum = -1;
574 bool HasConstPtr = false;
575 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000576#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000577#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000578#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000579 }
580
581 // For NEON intrinsics which are overloaded on vector element type, validate
582 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000583 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000584 if (mask) {
585 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
586 return true;
587
588 TV = Result.getLimitedValue(64);
589 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
590 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000591 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000592 }
593
594 if (PtrArgNum >= 0) {
595 // Check that pointer arguments have the specified type.
596 Expr *Arg = TheCall->getArg(PtrArgNum);
597 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
598 Arg = ICE->getSubExpr();
599 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
600 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000601
Tim Northovera2ee4332014-03-29 15:09:45 +0000602 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000603 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000604 bool IsInt64Long =
605 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
606 QualType EltTy =
607 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000608 if (HasConstPtr)
609 EltTy = EltTy.withConst();
610 QualType LHSTy = Context.getPointerType(EltTy);
611 AssignConvertType ConvTy;
612 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
613 if (RHS.isInvalid())
614 return true;
615 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
616 RHS.get(), AA_Assigning))
617 return true;
618 }
619
620 // For NEON intrinsics which take an immediate value as part of the
621 // instruction, range check them here.
622 unsigned i = 0, l = 0, u = 0;
623 switch (BuiltinID) {
624 default:
625 return false;
Tim Northover12670412014-02-19 10:37:05 +0000626#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000627#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000628#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000629 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000630
Richard Sandiford28940af2014-04-16 08:47:51 +0000631 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000632}
633
Tim Northovera2ee4332014-03-29 15:09:45 +0000634bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
635 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000636 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000637 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000638 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000639 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000640 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000641 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
642 BuiltinID == AArch64::BI__builtin_arm_strex ||
643 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000644 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000645 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000646 BuiltinID == ARM::BI__builtin_arm_ldaex ||
647 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
648 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000649
650 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
651
652 // Ensure that we have the proper number of arguments.
653 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
654 return true;
655
656 // Inspect the pointer argument of the atomic builtin. This should always be
657 // a pointer type, whose element is an integral scalar or pointer type.
658 // Because it is a pointer type, we don't have to worry about any implicit
659 // casts here.
660 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
661 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
662 if (PointerArgRes.isInvalid())
663 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000664 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000665
666 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
667 if (!pointerType) {
668 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
669 << PointerArg->getType() << PointerArg->getSourceRange();
670 return true;
671 }
672
673 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
674 // task is to insert the appropriate casts into the AST. First work out just
675 // what the appropriate type is.
676 QualType ValType = pointerType->getPointeeType();
677 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
678 if (IsLdrex)
679 AddrType.addConst();
680
681 // Issue a warning if the cast is dodgy.
682 CastKind CastNeeded = CK_NoOp;
683 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
684 CastNeeded = CK_BitCast;
685 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
686 << PointerArg->getType()
687 << Context.getPointerType(AddrType)
688 << AA_Passing << PointerArg->getSourceRange();
689 }
690
691 // Finally, do the cast and replace the argument with the corrected version.
692 AddrType = Context.getPointerType(AddrType);
693 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
694 if (PointerArgRes.isInvalid())
695 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000696 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000697
698 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
699
700 // In general, we allow ints, floats and pointers to be loaded and stored.
701 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
702 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
703 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
704 << PointerArg->getType() << PointerArg->getSourceRange();
705 return true;
706 }
707
708 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000709 if (Context.getTypeSize(ValType) > MaxWidth) {
710 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000711 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
712 << PointerArg->getType() << PointerArg->getSourceRange();
713 return true;
714 }
715
716 switch (ValType.getObjCLifetime()) {
717 case Qualifiers::OCL_None:
718 case Qualifiers::OCL_ExplicitNone:
719 // okay
720 break;
721
722 case Qualifiers::OCL_Weak:
723 case Qualifiers::OCL_Strong:
724 case Qualifiers::OCL_Autoreleasing:
725 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
726 << ValType << PointerArg->getSourceRange();
727 return true;
728 }
729
730
731 if (IsLdrex) {
732 TheCall->setType(ValType);
733 return false;
734 }
735
736 // Initialize the argument to be stored.
737 ExprResult ValArg = TheCall->getArg(0);
738 InitializedEntity Entity = InitializedEntity::InitializeParameter(
739 Context, ValType, /*consume*/ false);
740 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
741 if (ValArg.isInvalid())
742 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000743 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000744
745 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
746 // but the custom checker bypasses all default analysis.
747 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000748 return false;
749}
750
Nate Begeman4904e322010-06-08 02:47:44 +0000751bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000752 llvm::APSInt Result;
753
Tim Northover6aacd492013-07-16 09:47:53 +0000754 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000755 BuiltinID == ARM::BI__builtin_arm_ldaex ||
756 BuiltinID == ARM::BI__builtin_arm_strex ||
757 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000758 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000759 }
760
Yi Kong26d104a2014-08-13 19:18:14 +0000761 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
762 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
763 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
764 }
765
Tim Northover12670412014-02-19 10:37:05 +0000766 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
767 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000768
Yi Kong4efadfb2014-07-03 16:01:25 +0000769 // For intrinsics which take an immediate value as part of the instruction,
770 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000771 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000772 switch (BuiltinID) {
773 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000774 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
775 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000776 case ARM::BI__builtin_arm_vcvtr_f:
777 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000778 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000779 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000780 case ARM::BI__builtin_arm_isb:
781 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000782 }
Nate Begemand773fe62010-06-13 04:47:52 +0000783
Nate Begemanf568b072010-08-03 21:32:34 +0000784 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000785 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000786}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000787
Tim Northover573cbee2014-05-24 12:52:07 +0000788bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000789 CallExpr *TheCall) {
790 llvm::APSInt Result;
791
Tim Northover573cbee2014-05-24 12:52:07 +0000792 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000793 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
794 BuiltinID == AArch64::BI__builtin_arm_strex ||
795 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000796 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
797 }
798
Yi Konga5548432014-08-13 19:18:20 +0000799 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
800 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
801 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
802 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
803 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
804 }
805
Tim Northovera2ee4332014-03-29 15:09:45 +0000806 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
807 return true;
808
Yi Kong19a29ac2014-07-17 10:52:06 +0000809 // For intrinsics which take an immediate value as part of the instruction,
810 // range check them here.
811 unsigned i = 0, l = 0, u = 0;
812 switch (BuiltinID) {
813 default: return false;
814 case AArch64::BI__builtin_arm_dmb:
815 case AArch64::BI__builtin_arm_dsb:
816 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
817 }
818
Yi Kong19a29ac2014-07-17 10:52:06 +0000819 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000820}
821
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000822bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
823 unsigned i = 0, l = 0, u = 0;
824 switch (BuiltinID) {
825 default: return false;
826 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
827 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000828 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
829 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
830 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
831 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
832 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000833 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000834
Richard Sandiford28940af2014-04-16 08:47:51 +0000835 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000836}
837
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000838bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000839 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000840 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000841 default: return false;
842 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
843 case X86::BI__builtin_ia32_cmpps:
844 case X86::BI__builtin_ia32_cmpss:
845 case X86::BI__builtin_ia32_cmppd:
846 case X86::BI__builtin_ia32_cmpsd: i = 2; l = 0; u = 31; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000847 }
Craig Topperdd84ec52014-12-27 07:00:08 +0000848 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000849}
850
Richard Smith55ce3522012-06-25 20:30:08 +0000851/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
852/// parameter with the FormatAttr's correct format_idx and firstDataArg.
853/// Returns true when the format fits the function and the FormatStringInfo has
854/// been populated.
855bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
856 FormatStringInfo *FSI) {
857 FSI->HasVAListArg = Format->getFirstArg() == 0;
858 FSI->FormatIdx = Format->getFormatIdx() - 1;
859 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000860
Richard Smith55ce3522012-06-25 20:30:08 +0000861 // The way the format attribute works in GCC, the implicit this argument
862 // of member functions is counted. However, it doesn't appear in our own
863 // lists, so decrement format_idx in that case.
864 if (IsCXXMember) {
865 if(FSI->FormatIdx == 0)
866 return false;
867 --FSI->FormatIdx;
868 if (FSI->FirstDataArg != 0)
869 --FSI->FirstDataArg;
870 }
871 return true;
872}
Mike Stump11289f42009-09-09 15:08:12 +0000873
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000874/// Checks if a the given expression evaluates to null.
875///
876/// \brief Returns true if the value evaluates to null.
877static bool CheckNonNullExpr(Sema &S,
878 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000879 // As a special case, transparent unions initialized with zero are
880 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000881 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000882 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
883 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000884 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000885 if (const InitListExpr *ILE =
886 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000887 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000888 }
889
890 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000891 return (!Expr->isValueDependent() &&
892 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
893 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000894}
895
896static void CheckNonNullArgument(Sema &S,
897 const Expr *ArgExpr,
898 SourceLocation CallSiteLoc) {
899 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000900 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
901}
902
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000903bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
904 FormatStringInfo FSI;
905 if ((GetFormatStringType(Format) == FST_NSString) &&
906 getFormatStringInfo(Format, false, &FSI)) {
907 Idx = FSI.FormatIdx;
908 return true;
909 }
910 return false;
911}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000912/// \brief Diagnose use of %s directive in an NSString which is being passed
913/// as formatting string to formatting method.
914static void
915DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
916 const NamedDecl *FDecl,
917 Expr **Args,
918 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000919 unsigned Idx = 0;
920 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000921 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
922 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000923 Idx = 2;
924 Format = true;
925 }
926 else
927 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
928 if (S.GetFormatNSStringIdx(I, Idx)) {
929 Format = true;
930 break;
931 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000932 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +0000933 if (!Format || NumArgs <= Idx)
934 return;
935 const Expr *FormatExpr = Args[Idx];
936 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
937 FormatExpr = CSCE->getSubExpr();
938 const StringLiteral *FormatString;
939 if (const ObjCStringLiteral *OSL =
940 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
941 FormatString = OSL->getString();
942 else
943 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
944 if (!FormatString)
945 return;
946 if (S.FormatStringHasSArg(FormatString)) {
947 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
948 << "%s" << 1 << 1;
949 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
950 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +0000951 }
952}
953
Ted Kremenek2bc73332014-01-17 06:24:43 +0000954static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000955 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +0000956 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000957 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000958 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +0000959 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000960 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +0000961 if (!NonNull->args_size()) {
962 // Easy case: all pointer arguments are nonnull.
963 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +0000964 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +0000965 CheckNonNullArgument(S, Arg, CallSiteLoc);
966 return;
967 }
968
969 for (unsigned Val : NonNull->args()) {
970 if (Val >= Args.size())
971 continue;
972 if (NonNullArgs.empty())
973 NonNullArgs.resize(Args.size());
974 NonNullArgs.set(Val);
975 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000976 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000977
978 // Check the attributes on the parameters.
979 ArrayRef<ParmVarDecl*> parms;
980 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
981 parms = FD->parameters();
982 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
983 parms = MD->parameters();
984
Richard Smith588bd9b2014-08-27 04:59:42 +0000985 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +0000986 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +0000987 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000988 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +0000989 if (PVD->hasAttr<NonNullAttr>() ||
990 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
991 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +0000992 }
Richard Smith588bd9b2014-08-27 04:59:42 +0000993
994 // In case this is a variadic call, check any remaining arguments.
995 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
996 if (NonNullArgs[ArgIndex])
997 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000998}
999
Richard Smith55ce3522012-06-25 20:30:08 +00001000/// Handles the checks for format strings, non-POD arguments to vararg
1001/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001002void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1003 unsigned NumParams, bool IsMemberFunction,
1004 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001005 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001006 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001007 if (CurContext->isDependentContext())
1008 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001009
Ted Kremenekb8176da2010-09-09 04:33:05 +00001010 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001011 llvm::SmallBitVector CheckedVarArgs;
1012 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001013 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001014 // Only create vector if there are format attributes.
1015 CheckedVarArgs.resize(Args.size());
1016
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001017 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001018 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001019 }
Richard Smithd7293d72013-08-05 18:49:43 +00001020 }
Richard Smith55ce3522012-06-25 20:30:08 +00001021
1022 // Refuse POD arguments that weren't caught by the format string
1023 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001024 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001025 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001026 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001027 if (const Expr *Arg = Args[ArgIdx]) {
1028 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1029 checkVariadicArgument(Arg, CallType);
1030 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001031 }
Richard Smithd7293d72013-08-05 18:49:43 +00001032 }
Mike Stump11289f42009-09-09 15:08:12 +00001033
Richard Trieu41bc0992013-06-22 00:20:41 +00001034 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001035 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001036
Richard Trieu41bc0992013-06-22 00:20:41 +00001037 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001038 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1039 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001040 }
Richard Smith55ce3522012-06-25 20:30:08 +00001041}
1042
1043/// CheckConstructorCall - Check a constructor call for correctness and safety
1044/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001045void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1046 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001047 const FunctionProtoType *Proto,
1048 SourceLocation Loc) {
1049 VariadicCallType CallType =
1050 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001051 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001052 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1053}
1054
1055/// CheckFunctionCall - Check a direct function call for various correctness
1056/// and safety properties not strictly enforced by the C type system.
1057bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1058 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001059 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1060 isa<CXXMethodDecl>(FDecl);
1061 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1062 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001063 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1064 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001065 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001066 Expr** Args = TheCall->getArgs();
1067 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001068 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001069 // If this is a call to a member operator, hide the first argument
1070 // from checkCall.
1071 // FIXME: Our choice of AST representation here is less than ideal.
1072 ++Args;
1073 --NumArgs;
1074 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001075 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001076 IsMemberFunction, TheCall->getRParenLoc(),
1077 TheCall->getCallee()->getSourceRange(), CallType);
1078
1079 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1080 // None of the checks below are needed for functions that don't have
1081 // simple names (e.g., C++ conversion functions).
1082 if (!FnInfo)
1083 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001084
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001085 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001086 if (getLangOpts().ObjC1)
1087 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001088
Anna Zaks22122702012-01-17 00:37:07 +00001089 unsigned CMId = FDecl->getMemoryFunctionKind();
1090 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001091 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001092
Anna Zaks201d4892012-01-13 21:52:01 +00001093 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001094 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001095 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001096 else if (CMId == Builtin::BIstrncat)
1097 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001098 else
Anna Zaks22122702012-01-17 00:37:07 +00001099 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001100
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001101 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001102}
1103
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001104bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001105 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001106 VariadicCallType CallType =
1107 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001108
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001109 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001110 /*IsMemberFunction=*/false,
1111 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001112
1113 return false;
1114}
1115
Richard Trieu664c4c62013-06-20 21:03:13 +00001116bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1117 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001118 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1119 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001120 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001121
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001122 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001123 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001124 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001125
Richard Trieu664c4c62013-06-20 21:03:13 +00001126 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001127 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001128 CallType = VariadicDoesNotApply;
1129 } else if (Ty->isBlockPointerType()) {
1130 CallType = VariadicBlock;
1131 } else { // Ty->isFunctionPointerType()
1132 CallType = VariadicFunction;
1133 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001134 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001135
Craig Topper8c2a2a02014-08-30 16:55:39 +00001136 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1137 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001138 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001139 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001140
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001141 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001142}
1143
Richard Trieu41bc0992013-06-22 00:20:41 +00001144/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1145/// such as function pointers returned from functions.
1146bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001147 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001148 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001149 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001150
Craig Topperc3ec1492014-05-26 06:22:03 +00001151 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001152 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001153 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001154 TheCall->getCallee()->getSourceRange(), CallType);
1155
1156 return false;
1157}
1158
Tim Northovere94a34c2014-03-11 10:49:14 +00001159static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1160 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1161 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1162 return false;
1163
1164 switch (Op) {
1165 case AtomicExpr::AO__c11_atomic_init:
1166 llvm_unreachable("There is no ordering argument for an init");
1167
1168 case AtomicExpr::AO__c11_atomic_load:
1169 case AtomicExpr::AO__atomic_load_n:
1170 case AtomicExpr::AO__atomic_load:
1171 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1172 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1173
1174 case AtomicExpr::AO__c11_atomic_store:
1175 case AtomicExpr::AO__atomic_store:
1176 case AtomicExpr::AO__atomic_store_n:
1177 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1178 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1179 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1180
1181 default:
1182 return true;
1183 }
1184}
1185
Richard Smithfeea8832012-04-12 05:08:17 +00001186ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1187 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001188 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1189 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001190
Richard Smithfeea8832012-04-12 05:08:17 +00001191 // All these operations take one of the following forms:
1192 enum {
1193 // C __c11_atomic_init(A *, C)
1194 Init,
1195 // C __c11_atomic_load(A *, int)
1196 Load,
1197 // void __atomic_load(A *, CP, int)
1198 Copy,
1199 // C __c11_atomic_add(A *, M, int)
1200 Arithmetic,
1201 // C __atomic_exchange_n(A *, CP, int)
1202 Xchg,
1203 // void __atomic_exchange(A *, C *, CP, int)
1204 GNUXchg,
1205 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1206 C11CmpXchg,
1207 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1208 GNUCmpXchg
1209 } Form = Init;
1210 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1211 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1212 // where:
1213 // C is an appropriate type,
1214 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1215 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1216 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1217 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001218
Richard Smithfeea8832012-04-12 05:08:17 +00001219 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1220 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1221 && "need to update code for modified C11 atomics");
1222 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1223 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1224 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1225 Op == AtomicExpr::AO__atomic_store_n ||
1226 Op == AtomicExpr::AO__atomic_exchange_n ||
1227 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1228 bool IsAddSub = false;
1229
1230 switch (Op) {
1231 case AtomicExpr::AO__c11_atomic_init:
1232 Form = Init;
1233 break;
1234
1235 case AtomicExpr::AO__c11_atomic_load:
1236 case AtomicExpr::AO__atomic_load_n:
1237 Form = Load;
1238 break;
1239
1240 case AtomicExpr::AO__c11_atomic_store:
1241 case AtomicExpr::AO__atomic_load:
1242 case AtomicExpr::AO__atomic_store:
1243 case AtomicExpr::AO__atomic_store_n:
1244 Form = Copy;
1245 break;
1246
1247 case AtomicExpr::AO__c11_atomic_fetch_add:
1248 case AtomicExpr::AO__c11_atomic_fetch_sub:
1249 case AtomicExpr::AO__atomic_fetch_add:
1250 case AtomicExpr::AO__atomic_fetch_sub:
1251 case AtomicExpr::AO__atomic_add_fetch:
1252 case AtomicExpr::AO__atomic_sub_fetch:
1253 IsAddSub = true;
1254 // Fall through.
1255 case AtomicExpr::AO__c11_atomic_fetch_and:
1256 case AtomicExpr::AO__c11_atomic_fetch_or:
1257 case AtomicExpr::AO__c11_atomic_fetch_xor:
1258 case AtomicExpr::AO__atomic_fetch_and:
1259 case AtomicExpr::AO__atomic_fetch_or:
1260 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001261 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001262 case AtomicExpr::AO__atomic_and_fetch:
1263 case AtomicExpr::AO__atomic_or_fetch:
1264 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001265 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001266 Form = Arithmetic;
1267 break;
1268
1269 case AtomicExpr::AO__c11_atomic_exchange:
1270 case AtomicExpr::AO__atomic_exchange_n:
1271 Form = Xchg;
1272 break;
1273
1274 case AtomicExpr::AO__atomic_exchange:
1275 Form = GNUXchg;
1276 break;
1277
1278 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1279 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1280 Form = C11CmpXchg;
1281 break;
1282
1283 case AtomicExpr::AO__atomic_compare_exchange:
1284 case AtomicExpr::AO__atomic_compare_exchange_n:
1285 Form = GNUCmpXchg;
1286 break;
1287 }
1288
1289 // Check we have the right number of arguments.
1290 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001291 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001292 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001293 << TheCall->getCallee()->getSourceRange();
1294 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001295 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1296 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001297 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001298 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001299 << TheCall->getCallee()->getSourceRange();
1300 return ExprError();
1301 }
1302
Richard Smithfeea8832012-04-12 05:08:17 +00001303 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001304 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001305 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1306 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1307 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001308 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001309 << Ptr->getType() << Ptr->getSourceRange();
1310 return ExprError();
1311 }
1312
Richard Smithfeea8832012-04-12 05:08:17 +00001313 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1314 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1315 QualType ValType = AtomTy; // 'C'
1316 if (IsC11) {
1317 if (!AtomTy->isAtomicType()) {
1318 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1319 << Ptr->getType() << Ptr->getSourceRange();
1320 return ExprError();
1321 }
Richard Smithe00921a2012-09-15 06:09:58 +00001322 if (AtomTy.isConstQualified()) {
1323 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1324 << Ptr->getType() << Ptr->getSourceRange();
1325 return ExprError();
1326 }
Richard Smithfeea8832012-04-12 05:08:17 +00001327 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001328 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001329
Richard Smithfeea8832012-04-12 05:08:17 +00001330 // For an arithmetic operation, the implied arithmetic must be well-formed.
1331 if (Form == Arithmetic) {
1332 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1333 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1334 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1335 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1336 return ExprError();
1337 }
1338 if (!IsAddSub && !ValType->isIntegerType()) {
1339 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1340 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1341 return ExprError();
1342 }
1343 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1344 // For __atomic_*_n operations, the value type must be a scalar integral or
1345 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001346 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001347 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1348 return ExprError();
1349 }
1350
Eli Friedmanaa769812013-09-11 03:49:34 +00001351 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1352 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001353 // For GNU atomics, require a trivially-copyable type. This is not part of
1354 // the GNU atomics specification, but we enforce it for sanity.
1355 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001356 << Ptr->getType() << Ptr->getSourceRange();
1357 return ExprError();
1358 }
1359
Richard Smithfeea8832012-04-12 05:08:17 +00001360 // FIXME: For any builtin other than a load, the ValType must not be
1361 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001362
1363 switch (ValType.getObjCLifetime()) {
1364 case Qualifiers::OCL_None:
1365 case Qualifiers::OCL_ExplicitNone:
1366 // okay
1367 break;
1368
1369 case Qualifiers::OCL_Weak:
1370 case Qualifiers::OCL_Strong:
1371 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001372 // FIXME: Can this happen? By this point, ValType should be known
1373 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001374 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1375 << ValType << Ptr->getSourceRange();
1376 return ExprError();
1377 }
1378
1379 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001380 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001381 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001382 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001383 ResultType = Context.BoolTy;
1384
Richard Smithfeea8832012-04-12 05:08:17 +00001385 // The type of a parameter passed 'by value'. In the GNU atomics, such
1386 // arguments are actually passed as pointers.
1387 QualType ByValType = ValType; // 'CP'
1388 if (!IsC11 && !IsN)
1389 ByValType = Ptr->getType();
1390
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001391 // The first argument --- the pointer --- has a fixed type; we
1392 // deduce the types of the rest of the arguments accordingly. Walk
1393 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001394 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001395 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001396 if (i < NumVals[Form] + 1) {
1397 switch (i) {
1398 case 1:
1399 // The second argument is the non-atomic operand. For arithmetic, this
1400 // is always passed by value, and for a compare_exchange it is always
1401 // passed by address. For the rest, GNU uses by-address and C11 uses
1402 // by-value.
1403 assert(Form != Load);
1404 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1405 Ty = ValType;
1406 else if (Form == Copy || Form == Xchg)
1407 Ty = ByValType;
1408 else if (Form == Arithmetic)
1409 Ty = Context.getPointerDiffType();
1410 else
1411 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1412 break;
1413 case 2:
1414 // The third argument to compare_exchange / GNU exchange is a
1415 // (pointer to a) desired value.
1416 Ty = ByValType;
1417 break;
1418 case 3:
1419 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1420 Ty = Context.BoolTy;
1421 break;
1422 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001423 } else {
1424 // The order(s) are always converted to int.
1425 Ty = Context.IntTy;
1426 }
Richard Smithfeea8832012-04-12 05:08:17 +00001427
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001428 InitializedEntity Entity =
1429 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001430 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001431 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1432 if (Arg.isInvalid())
1433 return true;
1434 TheCall->setArg(i, Arg.get());
1435 }
1436
Richard Smithfeea8832012-04-12 05:08:17 +00001437 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001438 SmallVector<Expr*, 5> SubExprs;
1439 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001440 switch (Form) {
1441 case Init:
1442 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001443 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001444 break;
1445 case Load:
1446 SubExprs.push_back(TheCall->getArg(1)); // Order
1447 break;
1448 case Copy:
1449 case Arithmetic:
1450 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001451 SubExprs.push_back(TheCall->getArg(2)); // Order
1452 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001453 break;
1454 case GNUXchg:
1455 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1456 SubExprs.push_back(TheCall->getArg(3)); // Order
1457 SubExprs.push_back(TheCall->getArg(1)); // Val1
1458 SubExprs.push_back(TheCall->getArg(2)); // Val2
1459 break;
1460 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001461 SubExprs.push_back(TheCall->getArg(3)); // Order
1462 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001463 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001464 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001465 break;
1466 case GNUCmpXchg:
1467 SubExprs.push_back(TheCall->getArg(4)); // Order
1468 SubExprs.push_back(TheCall->getArg(1)); // Val1
1469 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1470 SubExprs.push_back(TheCall->getArg(2)); // Val2
1471 SubExprs.push_back(TheCall->getArg(3)); // Weak
1472 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001473 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001474
1475 if (SubExprs.size() >= 2 && Form != Init) {
1476 llvm::APSInt Result(32);
1477 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1478 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001479 Diag(SubExprs[1]->getLocStart(),
1480 diag::warn_atomic_op_has_invalid_memory_order)
1481 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001482 }
1483
Fariborz Jahanian615de762013-05-28 17:37:39 +00001484 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1485 SubExprs, ResultType, Op,
1486 TheCall->getRParenLoc());
1487
1488 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1489 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1490 Context.AtomicUsesUnsupportedLibcall(AE))
1491 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1492 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001493
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001494 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001495}
1496
1497
John McCall29ad95b2011-08-27 01:09:30 +00001498/// checkBuiltinArgument - Given a call to a builtin function, perform
1499/// normal type-checking on the given argument, updating the call in
1500/// place. This is useful when a builtin function requires custom
1501/// type-checking for some of its arguments but not necessarily all of
1502/// them.
1503///
1504/// Returns true on error.
1505static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1506 FunctionDecl *Fn = E->getDirectCallee();
1507 assert(Fn && "builtin call without direct callee!");
1508
1509 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1510 InitializedEntity Entity =
1511 InitializedEntity::InitializeParameter(S.Context, Param);
1512
1513 ExprResult Arg = E->getArg(0);
1514 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1515 if (Arg.isInvalid())
1516 return true;
1517
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001518 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001519 return false;
1520}
1521
Chris Lattnerdc046542009-05-08 06:58:22 +00001522/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1523/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1524/// type of its first argument. The main ActOnCallExpr routines have already
1525/// promoted the types of arguments because all of these calls are prototyped as
1526/// void(...).
1527///
1528/// This function goes through and does final semantic checking for these
1529/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001530ExprResult
1531Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001532 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001533 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1534 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1535
1536 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001537 if (TheCall->getNumArgs() < 1) {
1538 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1539 << 0 << 1 << TheCall->getNumArgs()
1540 << TheCall->getCallee()->getSourceRange();
1541 return ExprError();
1542 }
Mike Stump11289f42009-09-09 15:08:12 +00001543
Chris Lattnerdc046542009-05-08 06:58:22 +00001544 // Inspect the first argument of the atomic builtin. This should always be
1545 // a pointer type, whose element is an integral scalar or pointer type.
1546 // Because it is a pointer type, we don't have to worry about any implicit
1547 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001548 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001549 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001550 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1551 if (FirstArgResult.isInvalid())
1552 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001553 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001554 TheCall->setArg(0, FirstArg);
1555
John McCall31168b02011-06-15 23:02:42 +00001556 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1557 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001558 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1559 << FirstArg->getType() << FirstArg->getSourceRange();
1560 return ExprError();
1561 }
Mike Stump11289f42009-09-09 15:08:12 +00001562
John McCall31168b02011-06-15 23:02:42 +00001563 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001564 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001565 !ValType->isBlockPointerType()) {
1566 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1567 << FirstArg->getType() << FirstArg->getSourceRange();
1568 return ExprError();
1569 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001570
John McCall31168b02011-06-15 23:02:42 +00001571 switch (ValType.getObjCLifetime()) {
1572 case Qualifiers::OCL_None:
1573 case Qualifiers::OCL_ExplicitNone:
1574 // okay
1575 break;
1576
1577 case Qualifiers::OCL_Weak:
1578 case Qualifiers::OCL_Strong:
1579 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001580 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001581 << ValType << FirstArg->getSourceRange();
1582 return ExprError();
1583 }
1584
John McCallb50451a2011-10-05 07:41:44 +00001585 // Strip any qualifiers off ValType.
1586 ValType = ValType.getUnqualifiedType();
1587
Chandler Carruth3973af72010-07-18 20:54:12 +00001588 // The majority of builtins return a value, but a few have special return
1589 // types, so allow them to override appropriately below.
1590 QualType ResultType = ValType;
1591
Chris Lattnerdc046542009-05-08 06:58:22 +00001592 // We need to figure out which concrete builtin this maps onto. For example,
1593 // __sync_fetch_and_add with a 2 byte object turns into
1594 // __sync_fetch_and_add_2.
1595#define BUILTIN_ROW(x) \
1596 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1597 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001598
Chris Lattnerdc046542009-05-08 06:58:22 +00001599 static const unsigned BuiltinIndices[][5] = {
1600 BUILTIN_ROW(__sync_fetch_and_add),
1601 BUILTIN_ROW(__sync_fetch_and_sub),
1602 BUILTIN_ROW(__sync_fetch_and_or),
1603 BUILTIN_ROW(__sync_fetch_and_and),
1604 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001605 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001606
Chris Lattnerdc046542009-05-08 06:58:22 +00001607 BUILTIN_ROW(__sync_add_and_fetch),
1608 BUILTIN_ROW(__sync_sub_and_fetch),
1609 BUILTIN_ROW(__sync_and_and_fetch),
1610 BUILTIN_ROW(__sync_or_and_fetch),
1611 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001612 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001613
Chris Lattnerdc046542009-05-08 06:58:22 +00001614 BUILTIN_ROW(__sync_val_compare_and_swap),
1615 BUILTIN_ROW(__sync_bool_compare_and_swap),
1616 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001617 BUILTIN_ROW(__sync_lock_release),
1618 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001619 };
Mike Stump11289f42009-09-09 15:08:12 +00001620#undef BUILTIN_ROW
1621
Chris Lattnerdc046542009-05-08 06:58:22 +00001622 // Determine the index of the size.
1623 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001624 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001625 case 1: SizeIndex = 0; break;
1626 case 2: SizeIndex = 1; break;
1627 case 4: SizeIndex = 2; break;
1628 case 8: SizeIndex = 3; break;
1629 case 16: SizeIndex = 4; break;
1630 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001631 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1632 << FirstArg->getType() << FirstArg->getSourceRange();
1633 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001634 }
Mike Stump11289f42009-09-09 15:08:12 +00001635
Chris Lattnerdc046542009-05-08 06:58:22 +00001636 // Each of these builtins has one pointer argument, followed by some number of
1637 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1638 // that we ignore. Find out which row of BuiltinIndices to read from as well
1639 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001640 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001641 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001642 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001643 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001644 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001645 case Builtin::BI__sync_fetch_and_add:
1646 case Builtin::BI__sync_fetch_and_add_1:
1647 case Builtin::BI__sync_fetch_and_add_2:
1648 case Builtin::BI__sync_fetch_and_add_4:
1649 case Builtin::BI__sync_fetch_and_add_8:
1650 case Builtin::BI__sync_fetch_and_add_16:
1651 BuiltinIndex = 0;
1652 break;
1653
1654 case Builtin::BI__sync_fetch_and_sub:
1655 case Builtin::BI__sync_fetch_and_sub_1:
1656 case Builtin::BI__sync_fetch_and_sub_2:
1657 case Builtin::BI__sync_fetch_and_sub_4:
1658 case Builtin::BI__sync_fetch_and_sub_8:
1659 case Builtin::BI__sync_fetch_and_sub_16:
1660 BuiltinIndex = 1;
1661 break;
1662
1663 case Builtin::BI__sync_fetch_and_or:
1664 case Builtin::BI__sync_fetch_and_or_1:
1665 case Builtin::BI__sync_fetch_and_or_2:
1666 case Builtin::BI__sync_fetch_and_or_4:
1667 case Builtin::BI__sync_fetch_and_or_8:
1668 case Builtin::BI__sync_fetch_and_or_16:
1669 BuiltinIndex = 2;
1670 break;
1671
1672 case Builtin::BI__sync_fetch_and_and:
1673 case Builtin::BI__sync_fetch_and_and_1:
1674 case Builtin::BI__sync_fetch_and_and_2:
1675 case Builtin::BI__sync_fetch_and_and_4:
1676 case Builtin::BI__sync_fetch_and_and_8:
1677 case Builtin::BI__sync_fetch_and_and_16:
1678 BuiltinIndex = 3;
1679 break;
Mike Stump11289f42009-09-09 15:08:12 +00001680
Douglas Gregor73722482011-11-28 16:30:08 +00001681 case Builtin::BI__sync_fetch_and_xor:
1682 case Builtin::BI__sync_fetch_and_xor_1:
1683 case Builtin::BI__sync_fetch_and_xor_2:
1684 case Builtin::BI__sync_fetch_and_xor_4:
1685 case Builtin::BI__sync_fetch_and_xor_8:
1686 case Builtin::BI__sync_fetch_and_xor_16:
1687 BuiltinIndex = 4;
1688 break;
1689
Hal Finkeld2208b52014-10-02 20:53:50 +00001690 case Builtin::BI__sync_fetch_and_nand:
1691 case Builtin::BI__sync_fetch_and_nand_1:
1692 case Builtin::BI__sync_fetch_and_nand_2:
1693 case Builtin::BI__sync_fetch_and_nand_4:
1694 case Builtin::BI__sync_fetch_and_nand_8:
1695 case Builtin::BI__sync_fetch_and_nand_16:
1696 BuiltinIndex = 5;
1697 WarnAboutSemanticsChange = true;
1698 break;
1699
Douglas Gregor73722482011-11-28 16:30:08 +00001700 case Builtin::BI__sync_add_and_fetch:
1701 case Builtin::BI__sync_add_and_fetch_1:
1702 case Builtin::BI__sync_add_and_fetch_2:
1703 case Builtin::BI__sync_add_and_fetch_4:
1704 case Builtin::BI__sync_add_and_fetch_8:
1705 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001706 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001707 break;
1708
1709 case Builtin::BI__sync_sub_and_fetch:
1710 case Builtin::BI__sync_sub_and_fetch_1:
1711 case Builtin::BI__sync_sub_and_fetch_2:
1712 case Builtin::BI__sync_sub_and_fetch_4:
1713 case Builtin::BI__sync_sub_and_fetch_8:
1714 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001715 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001716 break;
1717
1718 case Builtin::BI__sync_and_and_fetch:
1719 case Builtin::BI__sync_and_and_fetch_1:
1720 case Builtin::BI__sync_and_and_fetch_2:
1721 case Builtin::BI__sync_and_and_fetch_4:
1722 case Builtin::BI__sync_and_and_fetch_8:
1723 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001724 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001725 break;
1726
1727 case Builtin::BI__sync_or_and_fetch:
1728 case Builtin::BI__sync_or_and_fetch_1:
1729 case Builtin::BI__sync_or_and_fetch_2:
1730 case Builtin::BI__sync_or_and_fetch_4:
1731 case Builtin::BI__sync_or_and_fetch_8:
1732 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001733 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001734 break;
1735
1736 case Builtin::BI__sync_xor_and_fetch:
1737 case Builtin::BI__sync_xor_and_fetch_1:
1738 case Builtin::BI__sync_xor_and_fetch_2:
1739 case Builtin::BI__sync_xor_and_fetch_4:
1740 case Builtin::BI__sync_xor_and_fetch_8:
1741 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001742 BuiltinIndex = 10;
1743 break;
1744
1745 case Builtin::BI__sync_nand_and_fetch:
1746 case Builtin::BI__sync_nand_and_fetch_1:
1747 case Builtin::BI__sync_nand_and_fetch_2:
1748 case Builtin::BI__sync_nand_and_fetch_4:
1749 case Builtin::BI__sync_nand_and_fetch_8:
1750 case Builtin::BI__sync_nand_and_fetch_16:
1751 BuiltinIndex = 11;
1752 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001753 break;
Mike Stump11289f42009-09-09 15:08:12 +00001754
Chris Lattnerdc046542009-05-08 06:58:22 +00001755 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001756 case Builtin::BI__sync_val_compare_and_swap_1:
1757 case Builtin::BI__sync_val_compare_and_swap_2:
1758 case Builtin::BI__sync_val_compare_and_swap_4:
1759 case Builtin::BI__sync_val_compare_and_swap_8:
1760 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001761 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001762 NumFixed = 2;
1763 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001764
Chris Lattnerdc046542009-05-08 06:58:22 +00001765 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001766 case Builtin::BI__sync_bool_compare_and_swap_1:
1767 case Builtin::BI__sync_bool_compare_and_swap_2:
1768 case Builtin::BI__sync_bool_compare_and_swap_4:
1769 case Builtin::BI__sync_bool_compare_and_swap_8:
1770 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001771 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001772 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001773 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001774 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001775
1776 case Builtin::BI__sync_lock_test_and_set:
1777 case Builtin::BI__sync_lock_test_and_set_1:
1778 case Builtin::BI__sync_lock_test_and_set_2:
1779 case Builtin::BI__sync_lock_test_and_set_4:
1780 case Builtin::BI__sync_lock_test_and_set_8:
1781 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001782 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001783 break;
1784
Chris Lattnerdc046542009-05-08 06:58:22 +00001785 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001786 case Builtin::BI__sync_lock_release_1:
1787 case Builtin::BI__sync_lock_release_2:
1788 case Builtin::BI__sync_lock_release_4:
1789 case Builtin::BI__sync_lock_release_8:
1790 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001791 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001792 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001793 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001794 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001795
1796 case Builtin::BI__sync_swap:
1797 case Builtin::BI__sync_swap_1:
1798 case Builtin::BI__sync_swap_2:
1799 case Builtin::BI__sync_swap_4:
1800 case Builtin::BI__sync_swap_8:
1801 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001802 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001803 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001804 }
Mike Stump11289f42009-09-09 15:08:12 +00001805
Chris Lattnerdc046542009-05-08 06:58:22 +00001806 // Now that we know how many fixed arguments we expect, first check that we
1807 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001808 if (TheCall->getNumArgs() < 1+NumFixed) {
1809 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1810 << 0 << 1+NumFixed << TheCall->getNumArgs()
1811 << TheCall->getCallee()->getSourceRange();
1812 return ExprError();
1813 }
Mike Stump11289f42009-09-09 15:08:12 +00001814
Hal Finkeld2208b52014-10-02 20:53:50 +00001815 if (WarnAboutSemanticsChange) {
1816 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1817 << TheCall->getCallee()->getSourceRange();
1818 }
1819
Chris Lattner5b9241b2009-05-08 15:36:58 +00001820 // Get the decl for the concrete builtin from this, we can tell what the
1821 // concrete integer type we should convert to is.
1822 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1823 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001824 FunctionDecl *NewBuiltinDecl;
1825 if (NewBuiltinID == BuiltinID)
1826 NewBuiltinDecl = FDecl;
1827 else {
1828 // Perform builtin lookup to avoid redeclaring it.
1829 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1830 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1831 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1832 assert(Res.getFoundDecl());
1833 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001834 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001835 return ExprError();
1836 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001837
John McCallcf142162010-08-07 06:22:56 +00001838 // The first argument --- the pointer --- has a fixed type; we
1839 // deduce the types of the rest of the arguments accordingly. Walk
1840 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001841 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001842 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001843
Chris Lattnerdc046542009-05-08 06:58:22 +00001844 // GCC does an implicit conversion to the pointer or integer ValType. This
1845 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001846 // Initialize the argument.
1847 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1848 ValType, /*consume*/ false);
1849 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001850 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001851 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001852
Chris Lattnerdc046542009-05-08 06:58:22 +00001853 // Okay, we have something that *can* be converted to the right type. Check
1854 // to see if there is a potentially weird extension going on here. This can
1855 // happen when you do an atomic operation on something like an char* and
1856 // pass in 42. The 42 gets converted to char. This is even more strange
1857 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001858 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001859 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001860 }
Mike Stump11289f42009-09-09 15:08:12 +00001861
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001862 ASTContext& Context = this->getASTContext();
1863
1864 // Create a new DeclRefExpr to refer to the new decl.
1865 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1866 Context,
1867 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001868 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001869 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001870 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001871 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001872 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001873 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001874
Chris Lattnerdc046542009-05-08 06:58:22 +00001875 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001876 // FIXME: This loses syntactic information.
1877 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1878 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1879 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001880 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001881
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001882 // Change the result type of the call to match the original value type. This
1883 // is arbitrary, but the codegen for these builtins ins design to handle it
1884 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001885 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001886
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001887 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001888}
1889
Chris Lattner6436fb62009-02-18 06:01:06 +00001890/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001891/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001892/// Note: It might also make sense to do the UTF-16 conversion here (would
1893/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001894bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001895 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001896 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1897
Douglas Gregorfb65e592011-07-27 05:40:30 +00001898 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001899 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1900 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001901 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001902 }
Mike Stump11289f42009-09-09 15:08:12 +00001903
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001904 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001905 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001906 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001907 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001908 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001909 UTF16 *ToPtr = &ToBuf[0];
1910
1911 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1912 &ToPtr, ToPtr + NumBytes,
1913 strictConversion);
1914 // Check for conversion failure.
1915 if (Result != conversionOK)
1916 Diag(Arg->getLocStart(),
1917 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1918 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001919 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001920}
1921
Chris Lattnere202e6a2007-12-20 00:05:45 +00001922/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1923/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001924bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1925 Expr *Fn = TheCall->getCallee();
1926 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001927 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001928 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001929 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1930 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001931 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001932 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001933 return true;
1934 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001935
1936 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001937 return Diag(TheCall->getLocEnd(),
1938 diag::err_typecheck_call_too_few_args_at_least)
1939 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001940 }
1941
John McCall29ad95b2011-08-27 01:09:30 +00001942 // Type-check the first argument normally.
1943 if (checkBuiltinArgument(*this, TheCall, 0))
1944 return true;
1945
Chris Lattnere202e6a2007-12-20 00:05:45 +00001946 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001947 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001948 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001949 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001950 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001951 else if (FunctionDecl *FD = getCurFunctionDecl())
1952 isVariadic = FD->isVariadic();
1953 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001954 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001955
Chris Lattnere202e6a2007-12-20 00:05:45 +00001956 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001957 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1958 return true;
1959 }
Mike Stump11289f42009-09-09 15:08:12 +00001960
Chris Lattner43be2e62007-12-19 23:59:04 +00001961 // Verify that the second argument to the builtin is the last argument of the
1962 // current function or method.
1963 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001964 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001965
Nico Weber9eea7642013-05-24 23:31:57 +00001966 // These are valid if SecondArgIsLastNamedArgument is false after the next
1967 // block.
1968 QualType Type;
1969 SourceLocation ParamLoc;
1970
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001971 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1972 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001973 // FIXME: This isn't correct for methods (results in bogus warning).
1974 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001975 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001976 if (CurBlock)
1977 LastArg = *(CurBlock->TheDecl->param_end()-1);
1978 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001979 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001980 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001981 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001982 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001983
1984 Type = PV->getType();
1985 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001986 }
1987 }
Mike Stump11289f42009-09-09 15:08:12 +00001988
Chris Lattner43be2e62007-12-19 23:59:04 +00001989 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001990 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001991 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001992 else if (Type->isReferenceType()) {
1993 Diag(Arg->getLocStart(),
1994 diag::warn_va_start_of_reference_type_is_undefined);
1995 Diag(ParamLoc, diag::note_parameter_type) << Type;
1996 }
1997
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001998 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001999 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002000}
Chris Lattner43be2e62007-12-19 23:59:04 +00002001
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002002bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2003 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2004 // const char *named_addr);
2005
2006 Expr *Func = Call->getCallee();
2007
2008 if (Call->getNumArgs() < 3)
2009 return Diag(Call->getLocEnd(),
2010 diag::err_typecheck_call_too_few_args_at_least)
2011 << 0 /*function call*/ << 3 << Call->getNumArgs();
2012
2013 // Determine whether the current function is variadic or not.
2014 bool IsVariadic;
2015 if (BlockScopeInfo *CurBlock = getCurBlock())
2016 IsVariadic = CurBlock->TheDecl->isVariadic();
2017 else if (FunctionDecl *FD = getCurFunctionDecl())
2018 IsVariadic = FD->isVariadic();
2019 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2020 IsVariadic = MD->isVariadic();
2021 else
2022 llvm_unreachable("unexpected statement type");
2023
2024 if (!IsVariadic) {
2025 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2026 return true;
2027 }
2028
2029 // Type-check the first argument normally.
2030 if (checkBuiltinArgument(*this, Call, 0))
2031 return true;
2032
2033 static const struct {
2034 unsigned ArgNo;
2035 QualType Type;
2036 } ArgumentTypes[] = {
2037 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2038 { 2, Context.getSizeType() },
2039 };
2040
2041 for (const auto &AT : ArgumentTypes) {
2042 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2043 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2044 continue;
2045 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2046 << Arg->getType() << AT.Type << 1 /* different class */
2047 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2048 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2049 }
2050
2051 return false;
2052}
2053
Chris Lattner2da14fb2007-12-20 00:26:33 +00002054/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2055/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002056bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2057 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002058 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002059 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002060 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002061 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002062 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002063 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002064 << SourceRange(TheCall->getArg(2)->getLocStart(),
2065 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002066
John Wiegley01296292011-04-08 18:41:53 +00002067 ExprResult OrigArg0 = TheCall->getArg(0);
2068 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002069
Chris Lattner2da14fb2007-12-20 00:26:33 +00002070 // Do standard promotions between the two arguments, returning their common
2071 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002072 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002073 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2074 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002075
2076 // Make sure any conversions are pushed back into the call; this is
2077 // type safe since unordered compare builtins are declared as "_Bool
2078 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002079 TheCall->setArg(0, OrigArg0.get());
2080 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002081
John Wiegley01296292011-04-08 18:41:53 +00002082 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002083 return false;
2084
Chris Lattner2da14fb2007-12-20 00:26:33 +00002085 // If the common type isn't a real floating type, then the arguments were
2086 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002087 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002088 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002089 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002090 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2091 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002092
Chris Lattner2da14fb2007-12-20 00:26:33 +00002093 return false;
2094}
2095
Benjamin Kramer634fc102010-02-15 22:42:31 +00002096/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2097/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002098/// to check everything. We expect the last argument to be a floating point
2099/// value.
2100bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2101 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002102 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002103 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002104 if (TheCall->getNumArgs() > NumArgs)
2105 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002106 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002107 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002108 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002109 (*(TheCall->arg_end()-1))->getLocEnd());
2110
Benjamin Kramer64aae502010-02-16 10:07:31 +00002111 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002112
Eli Friedman7e4faac2009-08-31 20:06:00 +00002113 if (OrigArg->isTypeDependent())
2114 return false;
2115
Chris Lattner68784ef2010-05-06 05:50:07 +00002116 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002117 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002118 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002119 diag::err_typecheck_call_invalid_unary_fp)
2120 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002121
Chris Lattner68784ef2010-05-06 05:50:07 +00002122 // If this is an implicit conversion from float -> double, remove it.
2123 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2124 Expr *CastArg = Cast->getSubExpr();
2125 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2126 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2127 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002128 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002129 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002130 }
2131 }
2132
Eli Friedman7e4faac2009-08-31 20:06:00 +00002133 return false;
2134}
2135
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002136/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2137// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002138ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002139 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002140 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002141 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002142 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2143 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002144
Nate Begemana0110022010-06-08 00:16:34 +00002145 // Determine which of the following types of shufflevector we're checking:
2146 // 1) unary, vector mask: (lhs, mask)
2147 // 2) binary, vector mask: (lhs, rhs, mask)
2148 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2149 QualType resType = TheCall->getArg(0)->getType();
2150 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002151
Douglas Gregorc25f7662009-05-19 22:10:17 +00002152 if (!TheCall->getArg(0)->isTypeDependent() &&
2153 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002154 QualType LHSType = TheCall->getArg(0)->getType();
2155 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002156
Craig Topperbaca3892013-07-29 06:47:04 +00002157 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2158 return ExprError(Diag(TheCall->getLocStart(),
2159 diag::err_shufflevector_non_vector)
2160 << SourceRange(TheCall->getArg(0)->getLocStart(),
2161 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002162
Nate Begemana0110022010-06-08 00:16:34 +00002163 numElements = LHSType->getAs<VectorType>()->getNumElements();
2164 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002165
Nate Begemana0110022010-06-08 00:16:34 +00002166 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2167 // with mask. If so, verify that RHS is an integer vector type with the
2168 // same number of elts as lhs.
2169 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002170 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002171 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002172 return ExprError(Diag(TheCall->getLocStart(),
2173 diag::err_shufflevector_incompatible_vector)
2174 << SourceRange(TheCall->getArg(1)->getLocStart(),
2175 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002176 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002177 return ExprError(Diag(TheCall->getLocStart(),
2178 diag::err_shufflevector_incompatible_vector)
2179 << SourceRange(TheCall->getArg(0)->getLocStart(),
2180 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002181 } else if (numElements != numResElements) {
2182 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002183 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002184 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002185 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002186 }
2187
2188 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002189 if (TheCall->getArg(i)->isTypeDependent() ||
2190 TheCall->getArg(i)->isValueDependent())
2191 continue;
2192
Nate Begemana0110022010-06-08 00:16:34 +00002193 llvm::APSInt Result(32);
2194 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2195 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002196 diag::err_shufflevector_nonconstant_argument)
2197 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002198
Craig Topper50ad5b72013-08-03 17:40:38 +00002199 // Allow -1 which will be translated to undef in the IR.
2200 if (Result.isSigned() && Result.isAllOnesValue())
2201 continue;
2202
Chris Lattner7ab824e2008-08-10 02:05:13 +00002203 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002204 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002205 diag::err_shufflevector_argument_too_large)
2206 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002207 }
2208
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002209 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002210
Chris Lattner7ab824e2008-08-10 02:05:13 +00002211 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002212 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002213 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002214 }
2215
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002216 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2217 TheCall->getCallee()->getLocStart(),
2218 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002219}
Chris Lattner43be2e62007-12-19 23:59:04 +00002220
Hal Finkelc4d7c822013-09-18 03:29:45 +00002221/// SemaConvertVectorExpr - Handle __builtin_convertvector
2222ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2223 SourceLocation BuiltinLoc,
2224 SourceLocation RParenLoc) {
2225 ExprValueKind VK = VK_RValue;
2226 ExprObjectKind OK = OK_Ordinary;
2227 QualType DstTy = TInfo->getType();
2228 QualType SrcTy = E->getType();
2229
2230 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2231 return ExprError(Diag(BuiltinLoc,
2232 diag::err_convertvector_non_vector)
2233 << E->getSourceRange());
2234 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2235 return ExprError(Diag(BuiltinLoc,
2236 diag::err_convertvector_non_vector_type));
2237
2238 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2239 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2240 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2241 if (SrcElts != DstElts)
2242 return ExprError(Diag(BuiltinLoc,
2243 diag::err_convertvector_incompatible_vector)
2244 << E->getSourceRange());
2245 }
2246
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002247 return new (Context)
2248 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002249}
2250
Daniel Dunbarb7257262008-07-21 22:59:13 +00002251/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2252// This is declared to take (const void*, ...) and can take two
2253// optional constant int args.
2254bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002255 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002256
Chris Lattner3b054132008-11-19 05:08:23 +00002257 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002258 return Diag(TheCall->getLocEnd(),
2259 diag::err_typecheck_call_too_many_args_at_most)
2260 << 0 /*function call*/ << 3 << NumArgs
2261 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002262
2263 // Argument 0 is checked for us and the remaining arguments must be
2264 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002265 for (unsigned i = 1; i != NumArgs; ++i)
2266 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002267 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002268
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002269 return false;
2270}
2271
Hal Finkelf0417332014-07-17 14:25:55 +00002272/// SemaBuiltinAssume - Handle __assume (MS Extension).
2273// __assume does not evaluate its arguments, and should warn if its argument
2274// has side effects.
2275bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2276 Expr *Arg = TheCall->getArg(0);
2277 if (Arg->isInstantiationDependent()) return false;
2278
2279 if (Arg->HasSideEffects(Context))
2280 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002281 << Arg->getSourceRange()
2282 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2283
2284 return false;
2285}
2286
2287/// Handle __builtin_assume_aligned. This is declared
2288/// as (const void*, size_t, ...) and can take one optional constant int arg.
2289bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2290 unsigned NumArgs = TheCall->getNumArgs();
2291
2292 if (NumArgs > 3)
2293 return Diag(TheCall->getLocEnd(),
2294 diag::err_typecheck_call_too_many_args_at_most)
2295 << 0 /*function call*/ << 3 << NumArgs
2296 << TheCall->getSourceRange();
2297
2298 // The alignment must be a constant integer.
2299 Expr *Arg = TheCall->getArg(1);
2300
2301 // We can't check the value of a dependent argument.
2302 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2303 llvm::APSInt Result;
2304 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2305 return true;
2306
2307 if (!Result.isPowerOf2())
2308 return Diag(TheCall->getLocStart(),
2309 diag::err_alignment_not_power_of_two)
2310 << Arg->getSourceRange();
2311 }
2312
2313 if (NumArgs > 2) {
2314 ExprResult Arg(TheCall->getArg(2));
2315 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2316 Context.getSizeType(), false);
2317 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2318 if (Arg.isInvalid()) return true;
2319 TheCall->setArg(2, Arg.get());
2320 }
Hal Finkelf0417332014-07-17 14:25:55 +00002321
2322 return false;
2323}
2324
Eric Christopher8d0c6212010-04-17 02:26:23 +00002325/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2326/// TheCall is a constant expression.
2327bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2328 llvm::APSInt &Result) {
2329 Expr *Arg = TheCall->getArg(ArgNum);
2330 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2331 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2332
2333 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2334
2335 if (!Arg->isIntegerConstantExpr(Result, Context))
2336 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002337 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002338
Chris Lattnerd545ad12009-09-23 06:06:36 +00002339 return false;
2340}
2341
Richard Sandiford28940af2014-04-16 08:47:51 +00002342/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2343/// TheCall is a constant expression in the range [Low, High].
2344bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2345 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002346 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002347
2348 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002349 Expr *Arg = TheCall->getArg(ArgNum);
2350 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002351 return false;
2352
Eric Christopher8d0c6212010-04-17 02:26:23 +00002353 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002354 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002355 return true;
2356
Richard Sandiford28940af2014-04-16 08:47:51 +00002357 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002358 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002359 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002360
2361 return false;
2362}
2363
Eli Friedmanc97d0142009-05-03 06:04:26 +00002364/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002365/// This checks that val is a constant 1.
2366bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2367 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002368 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002369
Eric Christopher8d0c6212010-04-17 02:26:23 +00002370 // TODO: This is less than ideal. Overload this to take a value.
2371 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2372 return true;
2373
2374 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002375 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2376 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2377
2378 return false;
2379}
2380
Richard Smithd7293d72013-08-05 18:49:43 +00002381namespace {
2382enum StringLiteralCheckType {
2383 SLCT_NotALiteral,
2384 SLCT_UncheckedLiteral,
2385 SLCT_CheckedLiteral
2386};
2387}
2388
Richard Smith55ce3522012-06-25 20:30:08 +00002389// Determine if an expression is a string literal or constant string.
2390// If this function returns false on the arguments to a function expecting a
2391// format string, we will usually need to emit a warning.
2392// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002393static StringLiteralCheckType
2394checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2395 bool HasVAListArg, unsigned format_idx,
2396 unsigned firstDataArg, Sema::FormatStringType Type,
2397 Sema::VariadicCallType CallType, bool InFunctionCall,
2398 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002399 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002400 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002401 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002402
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002403 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002404
Richard Smithd7293d72013-08-05 18:49:43 +00002405 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002406 // Technically -Wformat-nonliteral does not warn about this case.
2407 // The behavior of printf and friends in this case is implementation
2408 // dependent. Ideally if the format string cannot be null then
2409 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002410 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002411
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002412 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002413 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002414 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002415 // The expression is a literal if both sub-expressions were, and it was
2416 // completely checked only if both sub-expressions were checked.
2417 const AbstractConditionalOperator *C =
2418 cast<AbstractConditionalOperator>(E);
2419 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002420 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002421 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002422 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002423 if (Left == SLCT_NotALiteral)
2424 return SLCT_NotALiteral;
2425 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002426 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002427 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002428 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002429 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002430 }
2431
2432 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002433 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2434 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002435 }
2436
John McCallc07a0c72011-02-17 10:25:35 +00002437 case Stmt::OpaqueValueExprClass:
2438 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2439 E = src;
2440 goto tryAgain;
2441 }
Richard Smith55ce3522012-06-25 20:30:08 +00002442 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002443
Ted Kremeneka8890832011-02-24 23:03:04 +00002444 case Stmt::PredefinedExprClass:
2445 // While __func__, etc., are technically not string literals, they
2446 // cannot contain format specifiers and thus are not a security
2447 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002448 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002449
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002450 case Stmt::DeclRefExprClass: {
2451 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002452
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002453 // As an exception, do not flag errors for variables binding to
2454 // const string literals.
2455 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2456 bool isConstant = false;
2457 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002458
Richard Smithd7293d72013-08-05 18:49:43 +00002459 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2460 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002461 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002462 isConstant = T.isConstant(S.Context) &&
2463 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002464 } else if (T->isObjCObjectPointerType()) {
2465 // In ObjC, there is usually no "const ObjectPointer" type,
2466 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002467 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002468 }
Mike Stump11289f42009-09-09 15:08:12 +00002469
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002470 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002471 if (const Expr *Init = VD->getAnyInitializer()) {
2472 // Look through initializers like const char c[] = { "foo" }
2473 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2474 if (InitList->isStringLiteralInit())
2475 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2476 }
Richard Smithd7293d72013-08-05 18:49:43 +00002477 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002478 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002479 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002480 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002481 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002482 }
Mike Stump11289f42009-09-09 15:08:12 +00002483
Anders Carlssonb012ca92009-06-28 19:55:58 +00002484 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2485 // special check to see if the format string is a function parameter
2486 // of the function calling the printf function. If the function
2487 // has an attribute indicating it is a printf-like function, then we
2488 // should suppress warnings concerning non-literals being used in a call
2489 // to a vprintf function. For example:
2490 //
2491 // void
2492 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2493 // va_list ap;
2494 // va_start(ap, fmt);
2495 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2496 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002497 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002498 if (HasVAListArg) {
2499 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2500 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2501 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002502 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002503 // adjust for implicit parameter
2504 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2505 if (MD->isInstance())
2506 ++PVIndex;
2507 // We also check if the formats are compatible.
2508 // We can't pass a 'scanf' string to a 'printf' function.
2509 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002510 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002511 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002512 }
2513 }
2514 }
2515 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002516 }
Mike Stump11289f42009-09-09 15:08:12 +00002517
Richard Smith55ce3522012-06-25 20:30:08 +00002518 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002519 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002520
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002521 case Stmt::CallExprClass:
2522 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002523 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002524 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2525 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2526 unsigned ArgIndex = FA->getFormatIdx();
2527 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2528 if (MD->isInstance())
2529 --ArgIndex;
2530 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002531
Richard Smithd7293d72013-08-05 18:49:43 +00002532 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002533 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002534 Type, CallType, InFunctionCall,
2535 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002536 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2537 unsigned BuiltinID = FD->getBuiltinID();
2538 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2539 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2540 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002541 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002542 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002543 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002544 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002545 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002546 }
2547 }
Mike Stump11289f42009-09-09 15:08:12 +00002548
Richard Smith55ce3522012-06-25 20:30:08 +00002549 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002550 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002551 case Stmt::ObjCStringLiteralClass:
2552 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002553 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002554
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002555 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002556 StrE = ObjCFExpr->getString();
2557 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002558 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002559
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002560 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002561 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2562 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002563 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002564 }
Mike Stump11289f42009-09-09 15:08:12 +00002565
Richard Smith55ce3522012-06-25 20:30:08 +00002566 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002567 }
Mike Stump11289f42009-09-09 15:08:12 +00002568
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002569 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002570 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002571 }
2572}
2573
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002574Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002575 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002576 .Case("scanf", FST_Scanf)
2577 .Cases("printf", "printf0", FST_Printf)
2578 .Cases("NSString", "CFString", FST_NSString)
2579 .Case("strftime", FST_Strftime)
2580 .Case("strfmon", FST_Strfmon)
2581 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2582 .Default(FST_Unknown);
2583}
2584
Jordan Rose3e0ec582012-07-19 18:10:23 +00002585/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002586/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002587/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002588bool Sema::CheckFormatArguments(const FormatAttr *Format,
2589 ArrayRef<const Expr *> Args,
2590 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002591 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002592 SourceLocation Loc, SourceRange Range,
2593 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002594 FormatStringInfo FSI;
2595 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002596 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002597 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002598 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002599 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002600}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002601
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002602bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002603 bool HasVAListArg, unsigned format_idx,
2604 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002605 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002606 SourceLocation Loc, SourceRange Range,
2607 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002608 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002609 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002610 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002611 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002612 }
Mike Stump11289f42009-09-09 15:08:12 +00002613
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002614 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002615
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002616 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002617 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002618 // Dynamically generated format strings are difficult to
2619 // automatically vet at compile time. Requiring that format strings
2620 // are string literals: (1) permits the checking of format strings by
2621 // the compiler and thereby (2) can practically remove the source of
2622 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002623
Mike Stump11289f42009-09-09 15:08:12 +00002624 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002625 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002626 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002627 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002628 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002629 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2630 format_idx, firstDataArg, Type, CallType,
2631 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002632 if (CT != SLCT_NotALiteral)
2633 // Literal format string found, check done!
2634 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002635
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002636 // Strftime is particular as it always uses a single 'time' argument,
2637 // so it is safe to pass a non-literal string.
2638 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002639 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002640
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002641 // Do not emit diag when the string param is a macro expansion and the
2642 // format is either NSString or CFString. This is a hack to prevent
2643 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2644 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002645 if (Type == FST_NSString &&
2646 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002647 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002648
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002649 // If there are no arguments specified, warn with -Wformat-security, otherwise
2650 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002651 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002652 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002653 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002654 << OrigFormatExpr->getSourceRange();
2655 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002656 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002657 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002658 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002659 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002660}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002661
Ted Kremenekab278de2010-01-28 23:39:18 +00002662namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002663class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2664protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002665 Sema &S;
2666 const StringLiteral *FExpr;
2667 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002668 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002669 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002670 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002671 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002672 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002673 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002674 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002675 bool usesPositionalArgs;
2676 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002677 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002678 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002679 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002680public:
Ted Kremenek02087932010-07-16 02:11:22 +00002681 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002682 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002683 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002684 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002685 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002686 Sema::VariadicCallType callType,
2687 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002688 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002689 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2690 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002691 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002692 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002693 inFunctionCall(inFunctionCall), CallType(callType),
2694 CheckedVarArgs(CheckedVarArgs) {
2695 CoveredArgs.resize(numDataArgs);
2696 CoveredArgs.reset();
2697 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002698
Ted Kremenek019d2242010-01-29 01:50:07 +00002699 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002700
Ted Kremenek02087932010-07-16 02:11:22 +00002701 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002702 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002703
Jordan Rose92303592012-09-08 04:00:03 +00002704 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002705 const analyze_format_string::FormatSpecifier &FS,
2706 const analyze_format_string::ConversionSpecifier &CS,
2707 const char *startSpecifier, unsigned specifierLen,
2708 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002709
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002710 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002711 const analyze_format_string::FormatSpecifier &FS,
2712 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002713
2714 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002715 const analyze_format_string::ConversionSpecifier &CS,
2716 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002717
Craig Toppere14c0f82014-03-12 04:55:44 +00002718 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002719
Craig Toppere14c0f82014-03-12 04:55:44 +00002720 void HandleInvalidPosition(const char *startSpecifier,
2721 unsigned specifierLen,
2722 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002723
Craig Toppere14c0f82014-03-12 04:55:44 +00002724 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002725
Craig Toppere14c0f82014-03-12 04:55:44 +00002726 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002727
Richard Trieu03cf7b72011-10-28 00:41:25 +00002728 template <typename Range>
2729 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2730 const Expr *ArgumentExpr,
2731 PartialDiagnostic PDiag,
2732 SourceLocation StringLoc,
2733 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002734 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002735
Ted Kremenek02087932010-07-16 02:11:22 +00002736protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002737 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2738 const char *startSpec,
2739 unsigned specifierLen,
2740 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002741
2742 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2743 const char *startSpec,
2744 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002745
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002746 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002747 CharSourceRange getSpecifierRange(const char *startSpecifier,
2748 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002749 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002750
Ted Kremenek5739de72010-01-29 01:06:55 +00002751 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002752
2753 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2754 const analyze_format_string::ConversionSpecifier &CS,
2755 const char *startSpecifier, unsigned specifierLen,
2756 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002757
2758 template <typename Range>
2759 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2760 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002761 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002762};
2763}
2764
Ted Kremenek02087932010-07-16 02:11:22 +00002765SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002766 return OrigFormatExpr->getSourceRange();
2767}
2768
Ted Kremenek02087932010-07-16 02:11:22 +00002769CharSourceRange CheckFormatHandler::
2770getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002771 SourceLocation Start = getLocationOfByte(startSpecifier);
2772 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2773
2774 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002775 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002776
2777 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002778}
2779
Ted Kremenek02087932010-07-16 02:11:22 +00002780SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002781 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002782}
2783
Ted Kremenek02087932010-07-16 02:11:22 +00002784void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2785 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002786 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2787 getLocationOfByte(startSpecifier),
2788 /*IsStringLocation*/true,
2789 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002790}
2791
Jordan Rose92303592012-09-08 04:00:03 +00002792void CheckFormatHandler::HandleInvalidLengthModifier(
2793 const analyze_format_string::FormatSpecifier &FS,
2794 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002795 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002796 using namespace analyze_format_string;
2797
2798 const LengthModifier &LM = FS.getLengthModifier();
2799 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2800
2801 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002802 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002803 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002804 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002805 getLocationOfByte(LM.getStart()),
2806 /*IsStringLocation*/true,
2807 getSpecifierRange(startSpecifier, specifierLen));
2808
2809 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2810 << FixedLM->toString()
2811 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2812
2813 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002814 FixItHint Hint;
2815 if (DiagID == diag::warn_format_nonsensical_length)
2816 Hint = FixItHint::CreateRemoval(LMRange);
2817
2818 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002819 getLocationOfByte(LM.getStart()),
2820 /*IsStringLocation*/true,
2821 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002822 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002823 }
2824}
2825
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002826void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002827 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002828 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002829 using namespace analyze_format_string;
2830
2831 const LengthModifier &LM = FS.getLengthModifier();
2832 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2833
2834 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002835 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002836 if (FixedLM) {
2837 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2838 << LM.toString() << 0,
2839 getLocationOfByte(LM.getStart()),
2840 /*IsStringLocation*/true,
2841 getSpecifierRange(startSpecifier, specifierLen));
2842
2843 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2844 << FixedLM->toString()
2845 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2846
2847 } else {
2848 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2849 << LM.toString() << 0,
2850 getLocationOfByte(LM.getStart()),
2851 /*IsStringLocation*/true,
2852 getSpecifierRange(startSpecifier, specifierLen));
2853 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002854}
2855
2856void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2857 const analyze_format_string::ConversionSpecifier &CS,
2858 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002859 using namespace analyze_format_string;
2860
2861 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002862 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002863 if (FixedCS) {
2864 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2865 << CS.toString() << /*conversion specifier*/1,
2866 getLocationOfByte(CS.getStart()),
2867 /*IsStringLocation*/true,
2868 getSpecifierRange(startSpecifier, specifierLen));
2869
2870 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2871 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2872 << FixedCS->toString()
2873 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2874 } else {
2875 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2876 << CS.toString() << /*conversion specifier*/1,
2877 getLocationOfByte(CS.getStart()),
2878 /*IsStringLocation*/true,
2879 getSpecifierRange(startSpecifier, specifierLen));
2880 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002881}
2882
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002883void CheckFormatHandler::HandlePosition(const char *startPos,
2884 unsigned posLen) {
2885 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2886 getLocationOfByte(startPos),
2887 /*IsStringLocation*/true,
2888 getSpecifierRange(startPos, posLen));
2889}
2890
Ted Kremenekd1668192010-02-27 01:41:03 +00002891void
Ted Kremenek02087932010-07-16 02:11:22 +00002892CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2893 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002894 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2895 << (unsigned) p,
2896 getLocationOfByte(startPos), /*IsStringLocation*/true,
2897 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002898}
2899
Ted Kremenek02087932010-07-16 02:11:22 +00002900void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002901 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002902 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2903 getLocationOfByte(startPos),
2904 /*IsStringLocation*/true,
2905 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002906}
2907
Ted Kremenek02087932010-07-16 02:11:22 +00002908void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002909 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002910 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002911 EmitFormatDiagnostic(
2912 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2913 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2914 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002915 }
Ted Kremenek02087932010-07-16 02:11:22 +00002916}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002917
Jordan Rose58bbe422012-07-19 18:10:08 +00002918// Note that this may return NULL if there was an error parsing or building
2919// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002920const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002921 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002922}
2923
2924void CheckFormatHandler::DoneProcessing() {
2925 // Does the number of data arguments exceed the number of
2926 // format conversions in the format string?
2927 if (!HasVAListArg) {
2928 // Find any arguments that weren't covered.
2929 CoveredArgs.flip();
2930 signed notCoveredArg = CoveredArgs.find_first();
2931 if (notCoveredArg >= 0) {
2932 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002933 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2934 SourceLocation Loc = E->getLocStart();
2935 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2936 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2937 Loc, /*IsStringLocation*/false,
2938 getFormatStringRange());
2939 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002940 }
Ted Kremenek02087932010-07-16 02:11:22 +00002941 }
2942 }
2943}
2944
Ted Kremenekce815422010-07-19 21:25:57 +00002945bool
2946CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2947 SourceLocation Loc,
2948 const char *startSpec,
2949 unsigned specifierLen,
2950 const char *csStart,
2951 unsigned csLen) {
2952
2953 bool keepGoing = true;
2954 if (argIndex < NumDataArgs) {
2955 // Consider the argument coverered, even though the specifier doesn't
2956 // make sense.
2957 CoveredArgs.set(argIndex);
2958 }
2959 else {
2960 // If argIndex exceeds the number of data arguments we
2961 // don't issue a warning because that is just a cascade of warnings (and
2962 // they may have intended '%%' anyway). We don't want to continue processing
2963 // the format string after this point, however, as we will like just get
2964 // gibberish when trying to match arguments.
2965 keepGoing = false;
2966 }
2967
Richard Trieu03cf7b72011-10-28 00:41:25 +00002968 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2969 << StringRef(csStart, csLen),
2970 Loc, /*IsStringLocation*/true,
2971 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002972
2973 return keepGoing;
2974}
2975
Richard Trieu03cf7b72011-10-28 00:41:25 +00002976void
2977CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2978 const char *startSpec,
2979 unsigned specifierLen) {
2980 EmitFormatDiagnostic(
2981 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2982 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2983}
2984
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002985bool
2986CheckFormatHandler::CheckNumArgs(
2987 const analyze_format_string::FormatSpecifier &FS,
2988 const analyze_format_string::ConversionSpecifier &CS,
2989 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2990
2991 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002992 PartialDiagnostic PDiag = FS.usesPositionalArg()
2993 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2994 << (argIndex+1) << NumDataArgs)
2995 : S.PDiag(diag::warn_printf_insufficient_data_args);
2996 EmitFormatDiagnostic(
2997 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2998 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002999 return false;
3000 }
3001 return true;
3002}
3003
Richard Trieu03cf7b72011-10-28 00:41:25 +00003004template<typename Range>
3005void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3006 SourceLocation Loc,
3007 bool IsStringLocation,
3008 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003009 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003010 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003011 Loc, IsStringLocation, StringRange, FixIt);
3012}
3013
3014/// \brief If the format string is not within the funcion call, emit a note
3015/// so that the function call and string are in diagnostic messages.
3016///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003017/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003018/// call and only one diagnostic message will be produced. Otherwise, an
3019/// extra note will be emitted pointing to location of the format string.
3020///
3021/// \param ArgumentExpr the expression that is passed as the format string
3022/// argument in the function call. Used for getting locations when two
3023/// diagnostics are emitted.
3024///
3025/// \param PDiag the callee should already have provided any strings for the
3026/// diagnostic message. This function only adds locations and fixits
3027/// to diagnostics.
3028///
3029/// \param Loc primary location for diagnostic. If two diagnostics are
3030/// required, one will be at Loc and a new SourceLocation will be created for
3031/// the other one.
3032///
3033/// \param IsStringLocation if true, Loc points to the format string should be
3034/// used for the note. Otherwise, Loc points to the argument list and will
3035/// be used with PDiag.
3036///
3037/// \param StringRange some or all of the string to highlight. This is
3038/// templated so it can accept either a CharSourceRange or a SourceRange.
3039///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003040/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003041template<typename Range>
3042void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3043 const Expr *ArgumentExpr,
3044 PartialDiagnostic PDiag,
3045 SourceLocation Loc,
3046 bool IsStringLocation,
3047 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003048 ArrayRef<FixItHint> FixIt) {
3049 if (InFunctionCall) {
3050 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3051 D << StringRange;
3052 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3053 I != E; ++I) {
3054 D << *I;
3055 }
3056 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003057 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3058 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003059
3060 const Sema::SemaDiagnosticBuilder &Note =
3061 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3062 diag::note_format_string_defined);
3063
3064 Note << StringRange;
3065 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3066 I != E; ++I) {
3067 Note << *I;
3068 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00003069 }
3070}
3071
Ted Kremenek02087932010-07-16 02:11:22 +00003072//===--- CHECK: Printf format string checking ------------------------------===//
3073
3074namespace {
3075class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003076 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003077public:
3078 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3079 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003080 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003081 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003082 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003083 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003084 Sema::VariadicCallType CallType,
3085 llvm::SmallBitVector &CheckedVarArgs)
3086 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3087 numDataArgs, beg, hasVAListArg, Args,
3088 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3089 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003090 {}
3091
Craig Toppere14c0f82014-03-12 04:55:44 +00003092
Ted Kremenek02087932010-07-16 02:11:22 +00003093 bool HandleInvalidPrintfConversionSpecifier(
3094 const analyze_printf::PrintfSpecifier &FS,
3095 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003096 unsigned specifierLen) override;
3097
Ted Kremenek02087932010-07-16 02:11:22 +00003098 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3099 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003100 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003101 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3102 const char *StartSpecifier,
3103 unsigned SpecifierLen,
3104 const Expr *E);
3105
Ted Kremenek02087932010-07-16 02:11:22 +00003106 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3107 const char *startSpecifier, unsigned specifierLen);
3108 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3109 const analyze_printf::OptionalAmount &Amt,
3110 unsigned type,
3111 const char *startSpecifier, unsigned specifierLen);
3112 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3113 const analyze_printf::OptionalFlag &flag,
3114 const char *startSpecifier, unsigned specifierLen);
3115 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3116 const analyze_printf::OptionalFlag &ignoredFlag,
3117 const analyze_printf::OptionalFlag &flag,
3118 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003119 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003120 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003121
Ted Kremenek02087932010-07-16 02:11:22 +00003122};
3123}
3124
3125bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3126 const analyze_printf::PrintfSpecifier &FS,
3127 const char *startSpecifier,
3128 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003129 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003130 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003131
Ted Kremenekce815422010-07-19 21:25:57 +00003132 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3133 getLocationOfByte(CS.getStart()),
3134 startSpecifier, specifierLen,
3135 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003136}
3137
Ted Kremenek02087932010-07-16 02:11:22 +00003138bool CheckPrintfHandler::HandleAmount(
3139 const analyze_format_string::OptionalAmount &Amt,
3140 unsigned k, const char *startSpecifier,
3141 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003142
3143 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003144 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003145 unsigned argIndex = Amt.getArgIndex();
3146 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003147 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3148 << k,
3149 getLocationOfByte(Amt.getStart()),
3150 /*IsStringLocation*/true,
3151 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003152 // Don't do any more checking. We will just emit
3153 // spurious errors.
3154 return false;
3155 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003156
Ted Kremenek5739de72010-01-29 01:06:55 +00003157 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003158 // Although not in conformance with C99, we also allow the argument to be
3159 // an 'unsigned int' as that is a reasonably safe case. GCC also
3160 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003161 CoveredArgs.set(argIndex);
3162 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003163 if (!Arg)
3164 return false;
3165
Ted Kremenek5739de72010-01-29 01:06:55 +00003166 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003167
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003168 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3169 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003170
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003171 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003172 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003173 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003174 << T << Arg->getSourceRange(),
3175 getLocationOfByte(Amt.getStart()),
3176 /*IsStringLocation*/true,
3177 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003178 // Don't do any more checking. We will just emit
3179 // spurious errors.
3180 return false;
3181 }
3182 }
3183 }
3184 return true;
3185}
Ted Kremenek5739de72010-01-29 01:06:55 +00003186
Tom Careb49ec692010-06-17 19:00:27 +00003187void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003188 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003189 const analyze_printf::OptionalAmount &Amt,
3190 unsigned type,
3191 const char *startSpecifier,
3192 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003193 const analyze_printf::PrintfConversionSpecifier &CS =
3194 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003195
Richard Trieu03cf7b72011-10-28 00:41:25 +00003196 FixItHint fixit =
3197 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3198 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3199 Amt.getConstantLength()))
3200 : FixItHint();
3201
3202 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3203 << type << CS.toString(),
3204 getLocationOfByte(Amt.getStart()),
3205 /*IsStringLocation*/true,
3206 getSpecifierRange(startSpecifier, specifierLen),
3207 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003208}
3209
Ted Kremenek02087932010-07-16 02:11:22 +00003210void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003211 const analyze_printf::OptionalFlag &flag,
3212 const char *startSpecifier,
3213 unsigned specifierLen) {
3214 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003215 const analyze_printf::PrintfConversionSpecifier &CS =
3216 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003217 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3218 << flag.toString() << CS.toString(),
3219 getLocationOfByte(flag.getPosition()),
3220 /*IsStringLocation*/true,
3221 getSpecifierRange(startSpecifier, specifierLen),
3222 FixItHint::CreateRemoval(
3223 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003224}
3225
3226void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003227 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003228 const analyze_printf::OptionalFlag &ignoredFlag,
3229 const analyze_printf::OptionalFlag &flag,
3230 const char *startSpecifier,
3231 unsigned specifierLen) {
3232 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003233 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3234 << ignoredFlag.toString() << flag.toString(),
3235 getLocationOfByte(ignoredFlag.getPosition()),
3236 /*IsStringLocation*/true,
3237 getSpecifierRange(startSpecifier, specifierLen),
3238 FixItHint::CreateRemoval(
3239 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003240}
3241
Richard Smith55ce3522012-06-25 20:30:08 +00003242// Determines if the specified is a C++ class or struct containing
3243// a member with the specified name and kind (e.g. a CXXMethodDecl named
3244// "c_str()").
3245template<typename MemberKind>
3246static llvm::SmallPtrSet<MemberKind*, 1>
3247CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3248 const RecordType *RT = Ty->getAs<RecordType>();
3249 llvm::SmallPtrSet<MemberKind*, 1> Results;
3250
3251 if (!RT)
3252 return Results;
3253 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003254 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003255 return Results;
3256
Alp Tokerb6cc5922014-05-03 03:45:55 +00003257 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003258 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003259 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003260
3261 // We just need to include all members of the right kind turned up by the
3262 // filter, at this point.
3263 if (S.LookupQualifiedName(R, RT->getDecl()))
3264 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3265 NamedDecl *decl = (*I)->getUnderlyingDecl();
3266 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3267 Results.insert(FK);
3268 }
3269 return Results;
3270}
3271
Richard Smith2868a732014-02-28 01:36:39 +00003272/// Check if we could call '.c_str()' on an object.
3273///
3274/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3275/// allow the call, or if it would be ambiguous).
3276bool Sema::hasCStrMethod(const Expr *E) {
3277 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3278 MethodSet Results =
3279 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3280 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3281 MI != ME; ++MI)
3282 if ((*MI)->getMinRequiredArguments() == 0)
3283 return true;
3284 return false;
3285}
3286
Richard Smith55ce3522012-06-25 20:30:08 +00003287// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003288// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003289// Returns true when a c_str() conversion method is found.
3290bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003291 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003292 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3293
3294 MethodSet Results =
3295 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3296
3297 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3298 MI != ME; ++MI) {
3299 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003300 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003301 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003302 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003303 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003304 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3305 << "c_str()"
3306 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3307 return true;
3308 }
3309 }
3310
3311 return false;
3312}
3313
Ted Kremenekab278de2010-01-28 23:39:18 +00003314bool
Ted Kremenek02087932010-07-16 02:11:22 +00003315CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003316 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003317 const char *startSpecifier,
3318 unsigned specifierLen) {
3319
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003320 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003321 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003322 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003323
Ted Kremenek6cd69422010-07-19 22:01:06 +00003324 if (FS.consumesDataArgument()) {
3325 if (atFirstArg) {
3326 atFirstArg = false;
3327 usesPositionalArgs = FS.usesPositionalArg();
3328 }
3329 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003330 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3331 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003332 return false;
3333 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003334 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003335
Ted Kremenekd1668192010-02-27 01:41:03 +00003336 // First check if the field width, precision, and conversion specifier
3337 // have matching data arguments.
3338 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3339 startSpecifier, specifierLen)) {
3340 return false;
3341 }
3342
3343 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3344 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003345 return false;
3346 }
3347
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003348 if (!CS.consumesDataArgument()) {
3349 // FIXME: Technically specifying a precision or field width here
3350 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003351 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003352 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003353
Ted Kremenek4a49d982010-02-26 19:18:41 +00003354 // Consume the argument.
3355 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003356 if (argIndex < NumDataArgs) {
3357 // The check to see if the argIndex is valid will come later.
3358 // We set the bit here because we may exit early from this
3359 // function if we encounter some other error.
3360 CoveredArgs.set(argIndex);
3361 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003362
3363 // Check for using an Objective-C specific conversion specifier
3364 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003365 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003366 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3367 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003368 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003369
Tom Careb49ec692010-06-17 19:00:27 +00003370 // Check for invalid use of field width
3371 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003372 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003373 startSpecifier, specifierLen);
3374 }
3375
3376 // Check for invalid use of precision
3377 if (!FS.hasValidPrecision()) {
3378 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3379 startSpecifier, specifierLen);
3380 }
3381
3382 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003383 if (!FS.hasValidThousandsGroupingPrefix())
3384 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003385 if (!FS.hasValidLeadingZeros())
3386 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3387 if (!FS.hasValidPlusPrefix())
3388 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003389 if (!FS.hasValidSpacePrefix())
3390 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003391 if (!FS.hasValidAlternativeForm())
3392 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3393 if (!FS.hasValidLeftJustified())
3394 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3395
3396 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003397 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3398 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3399 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003400 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3401 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3402 startSpecifier, specifierLen);
3403
3404 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003405 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003406 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3407 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003408 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003409 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003410 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003411 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3412 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003413
Jordan Rose92303592012-09-08 04:00:03 +00003414 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3415 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3416
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003417 // The remaining checks depend on the data arguments.
3418 if (HasVAListArg)
3419 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003420
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003421 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003422 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003423
Jordan Rose58bbe422012-07-19 18:10:08 +00003424 const Expr *Arg = getDataArg(argIndex);
3425 if (!Arg)
3426 return true;
3427
3428 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003429}
3430
Jordan Roseaee34382012-09-05 22:56:26 +00003431static bool requiresParensToAddCast(const Expr *E) {
3432 // FIXME: We should have a general way to reason about operator
3433 // precedence and whether parens are actually needed here.
3434 // Take care of a few common cases where they aren't.
3435 const Expr *Inside = E->IgnoreImpCasts();
3436 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3437 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3438
3439 switch (Inside->getStmtClass()) {
3440 case Stmt::ArraySubscriptExprClass:
3441 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003442 case Stmt::CharacterLiteralClass:
3443 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003444 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003445 case Stmt::FloatingLiteralClass:
3446 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003447 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003448 case Stmt::ObjCArrayLiteralClass:
3449 case Stmt::ObjCBoolLiteralExprClass:
3450 case Stmt::ObjCBoxedExprClass:
3451 case Stmt::ObjCDictionaryLiteralClass:
3452 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003453 case Stmt::ObjCIvarRefExprClass:
3454 case Stmt::ObjCMessageExprClass:
3455 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003456 case Stmt::ObjCStringLiteralClass:
3457 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003458 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003459 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003460 case Stmt::UnaryOperatorClass:
3461 return false;
3462 default:
3463 return true;
3464 }
3465}
3466
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003467static std::pair<QualType, StringRef>
3468shouldNotPrintDirectly(const ASTContext &Context,
3469 QualType IntendedTy,
3470 const Expr *E) {
3471 // Use a 'while' to peel off layers of typedefs.
3472 QualType TyTy = IntendedTy;
3473 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3474 StringRef Name = UserTy->getDecl()->getName();
3475 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3476 .Case("NSInteger", Context.LongTy)
3477 .Case("NSUInteger", Context.UnsignedLongTy)
3478 .Case("SInt32", Context.IntTy)
3479 .Case("UInt32", Context.UnsignedIntTy)
3480 .Default(QualType());
3481
3482 if (!CastTy.isNull())
3483 return std::make_pair(CastTy, Name);
3484
3485 TyTy = UserTy->desugar();
3486 }
3487
3488 // Strip parens if necessary.
3489 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3490 return shouldNotPrintDirectly(Context,
3491 PE->getSubExpr()->getType(),
3492 PE->getSubExpr());
3493
3494 // If this is a conditional expression, then its result type is constructed
3495 // via usual arithmetic conversions and thus there might be no necessary
3496 // typedef sugar there. Recurse to operands to check for NSInteger &
3497 // Co. usage condition.
3498 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3499 QualType TrueTy, FalseTy;
3500 StringRef TrueName, FalseName;
3501
3502 std::tie(TrueTy, TrueName) =
3503 shouldNotPrintDirectly(Context,
3504 CO->getTrueExpr()->getType(),
3505 CO->getTrueExpr());
3506 std::tie(FalseTy, FalseName) =
3507 shouldNotPrintDirectly(Context,
3508 CO->getFalseExpr()->getType(),
3509 CO->getFalseExpr());
3510
3511 if (TrueTy == FalseTy)
3512 return std::make_pair(TrueTy, TrueName);
3513 else if (TrueTy.isNull())
3514 return std::make_pair(FalseTy, FalseName);
3515 else if (FalseTy.isNull())
3516 return std::make_pair(TrueTy, TrueName);
3517 }
3518
3519 return std::make_pair(QualType(), StringRef());
3520}
3521
Richard Smith55ce3522012-06-25 20:30:08 +00003522bool
3523CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3524 const char *StartSpecifier,
3525 unsigned SpecifierLen,
3526 const Expr *E) {
3527 using namespace analyze_format_string;
3528 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003529 // Now type check the data expression that matches the
3530 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003531 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3532 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003533 if (!AT.isValid())
3534 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003535
Jordan Rose598ec092012-12-05 18:44:40 +00003536 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003537 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3538 ExprTy = TET->getUnderlyingExpr()->getType();
3539 }
3540
Jordan Rose598ec092012-12-05 18:44:40 +00003541 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003542 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003543
Jordan Rose22b74712012-09-05 22:56:19 +00003544 // Look through argument promotions for our error message's reported type.
3545 // This includes the integral and floating promotions, but excludes array
3546 // and function pointer decay; seeing that an argument intended to be a
3547 // string has type 'char [6]' is probably more confusing than 'char *'.
3548 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3549 if (ICE->getCastKind() == CK_IntegralCast ||
3550 ICE->getCastKind() == CK_FloatingCast) {
3551 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003552 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003553
3554 // Check if we didn't match because of an implicit cast from a 'char'
3555 // or 'short' to an 'int'. This is done because printf is a varargs
3556 // function.
3557 if (ICE->getType() == S.Context.IntTy ||
3558 ICE->getType() == S.Context.UnsignedIntTy) {
3559 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003560 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003561 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003562 }
Jordan Rose98709982012-06-04 22:48:57 +00003563 }
Jordan Rose598ec092012-12-05 18:44:40 +00003564 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3565 // Special case for 'a', which has type 'int' in C.
3566 // Note, however, that we do /not/ want to treat multibyte constants like
3567 // 'MooV' as characters! This form is deprecated but still exists.
3568 if (ExprTy == S.Context.IntTy)
3569 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3570 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003571 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003572
Jordan Rosebc53ed12014-05-31 04:12:14 +00003573 // Look through enums to their underlying type.
3574 bool IsEnum = false;
3575 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3576 ExprTy = EnumTy->getDecl()->getIntegerType();
3577 IsEnum = true;
3578 }
3579
Jordan Rose0e5badd2012-12-05 18:44:49 +00003580 // %C in an Objective-C context prints a unichar, not a wchar_t.
3581 // If the argument is an integer of some kind, believe the %C and suggest
3582 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003583 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003584 if (ObjCContext &&
3585 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3586 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3587 !ExprTy->isCharType()) {
3588 // 'unichar' is defined as a typedef of unsigned short, but we should
3589 // prefer using the typedef if it is visible.
3590 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003591
3592 // While we are here, check if the value is an IntegerLiteral that happens
3593 // to be within the valid range.
3594 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3595 const llvm::APInt &V = IL->getValue();
3596 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3597 return true;
3598 }
3599
Jordan Rose0e5badd2012-12-05 18:44:49 +00003600 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3601 Sema::LookupOrdinaryName);
3602 if (S.LookupName(Result, S.getCurScope())) {
3603 NamedDecl *ND = Result.getFoundDecl();
3604 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3605 if (TD->getUnderlyingType() == IntendedTy)
3606 IntendedTy = S.Context.getTypedefType(TD);
3607 }
3608 }
3609 }
3610
3611 // Special-case some of Darwin's platform-independence types by suggesting
3612 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003613 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003614 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003615 QualType CastTy;
3616 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3617 if (!CastTy.isNull()) {
3618 IntendedTy = CastTy;
3619 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003620 }
3621 }
3622
Jordan Rose22b74712012-09-05 22:56:19 +00003623 // We may be able to offer a FixItHint if it is a supported type.
3624 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003625 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003626 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003627
Jordan Rose22b74712012-09-05 22:56:19 +00003628 if (success) {
3629 // Get the fix string from the fixed format specifier
3630 SmallString<16> buf;
3631 llvm::raw_svector_ostream os(buf);
3632 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003633
Jordan Roseaee34382012-09-05 22:56:26 +00003634 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3635
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003636 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Jordan Rose0e5badd2012-12-05 18:44:49 +00003637 // In this case, the specifier is wrong and should be changed to match
3638 // the argument.
3639 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003640 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3641 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003642 << E->getSourceRange(),
3643 E->getLocStart(),
3644 /*IsStringLocation*/false,
3645 SpecRange,
3646 FixItHint::CreateReplacement(SpecRange, os.str()));
3647
3648 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003649 // The canonical type for formatting this value is different from the
3650 // actual type of the expression. (This occurs, for example, with Darwin's
3651 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3652 // should be printed as 'long' for 64-bit compatibility.)
3653 // Rather than emitting a normal format/argument mismatch, we want to
3654 // add a cast to the recommended type (and correct the format string
3655 // if necessary).
3656 SmallString<16> CastBuf;
3657 llvm::raw_svector_ostream CastFix(CastBuf);
3658 CastFix << "(";
3659 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3660 CastFix << ")";
3661
3662 SmallVector<FixItHint,4> Hints;
3663 if (!AT.matchesType(S.Context, IntendedTy))
3664 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3665
3666 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3667 // If there's already a cast present, just replace it.
3668 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3669 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3670
3671 } else if (!requiresParensToAddCast(E)) {
3672 // If the expression has high enough precedence,
3673 // just write the C-style cast.
3674 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3675 CastFix.str()));
3676 } else {
3677 // Otherwise, add parens around the expression as well as the cast.
3678 CastFix << "(";
3679 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3680 CastFix.str()));
3681
Alp Tokerb6cc5922014-05-03 03:45:55 +00003682 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003683 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3684 }
3685
Jordan Rose0e5badd2012-12-05 18:44:49 +00003686 if (ShouldNotPrintDirectly) {
3687 // The expression has a type that should not be printed directly.
3688 // We extract the name from the typedef because we don't want to show
3689 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003690 StringRef Name;
3691 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3692 Name = TypedefTy->getDecl()->getName();
3693 else
3694 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003695 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003696 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003697 << E->getSourceRange(),
3698 E->getLocStart(), /*IsStringLocation=*/false,
3699 SpecRange, Hints);
3700 } else {
3701 // In this case, the expression could be printed using a different
3702 // specifier, but we've decided that the specifier is probably correct
3703 // and we should cast instead. Just use the normal warning message.
3704 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003705 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3706 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003707 << E->getSourceRange(),
3708 E->getLocStart(), /*IsStringLocation*/false,
3709 SpecRange, Hints);
3710 }
Jordan Roseaee34382012-09-05 22:56:26 +00003711 }
Jordan Rose22b74712012-09-05 22:56:19 +00003712 } else {
3713 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3714 SpecifierLen);
3715 // Since the warning for passing non-POD types to variadic functions
3716 // was deferred until now, we emit a warning for non-POD
3717 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003718 switch (S.isValidVarArgType(ExprTy)) {
3719 case Sema::VAK_Valid:
3720 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003721 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003722 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3723 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003724 << CSR
3725 << E->getSourceRange(),
3726 E->getLocStart(), /*IsStringLocation*/false, CSR);
3727 break;
3728
3729 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003730 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003731 EmitFormatDiagnostic(
3732 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003733 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003734 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003735 << CallType
3736 << AT.getRepresentativeTypeName(S.Context)
3737 << CSR
3738 << E->getSourceRange(),
3739 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003740 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003741 break;
3742
3743 case Sema::VAK_Invalid:
3744 if (ExprTy->isObjCObjectType())
3745 EmitFormatDiagnostic(
3746 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3747 << S.getLangOpts().CPlusPlus11
3748 << ExprTy
3749 << CallType
3750 << AT.getRepresentativeTypeName(S.Context)
3751 << CSR
3752 << E->getSourceRange(),
3753 E->getLocStart(), /*IsStringLocation*/false, CSR);
3754 else
3755 // FIXME: If this is an initializer list, suggest removing the braces
3756 // or inserting a cast to the target type.
3757 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3758 << isa<InitListExpr>(E) << ExprTy << CallType
3759 << AT.getRepresentativeTypeName(S.Context)
3760 << E->getSourceRange();
3761 break;
3762 }
3763
3764 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3765 "format string specifier index out of range");
3766 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003767 }
3768
Ted Kremenekab278de2010-01-28 23:39:18 +00003769 return true;
3770}
3771
Ted Kremenek02087932010-07-16 02:11:22 +00003772//===--- CHECK: Scanf format string checking ------------------------------===//
3773
3774namespace {
3775class CheckScanfHandler : public CheckFormatHandler {
3776public:
3777 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3778 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003779 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003780 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003781 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003782 Sema::VariadicCallType CallType,
3783 llvm::SmallBitVector &CheckedVarArgs)
3784 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3785 numDataArgs, beg, hasVAListArg,
3786 Args, formatIdx, inFunctionCall, CallType,
3787 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003788 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003789
3790 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3791 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003792 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003793
3794 bool HandleInvalidScanfConversionSpecifier(
3795 const analyze_scanf::ScanfSpecifier &FS,
3796 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003797 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003798
Craig Toppere14c0f82014-03-12 04:55:44 +00003799 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003800};
Ted Kremenek019d2242010-01-29 01:50:07 +00003801}
Ted Kremenekab278de2010-01-28 23:39:18 +00003802
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003803void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3804 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003805 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3806 getLocationOfByte(end), /*IsStringLocation*/true,
3807 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003808}
3809
Ted Kremenekce815422010-07-19 21:25:57 +00003810bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3811 const analyze_scanf::ScanfSpecifier &FS,
3812 const char *startSpecifier,
3813 unsigned specifierLen) {
3814
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003815 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003816 FS.getConversionSpecifier();
3817
3818 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3819 getLocationOfByte(CS.getStart()),
3820 startSpecifier, specifierLen,
3821 CS.getStart(), CS.getLength());
3822}
3823
Ted Kremenek02087932010-07-16 02:11:22 +00003824bool CheckScanfHandler::HandleScanfSpecifier(
3825 const analyze_scanf::ScanfSpecifier &FS,
3826 const char *startSpecifier,
3827 unsigned specifierLen) {
3828
3829 using namespace analyze_scanf;
3830 using namespace analyze_format_string;
3831
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003832 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003833
Ted Kremenek6cd69422010-07-19 22:01:06 +00003834 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3835 // be used to decide if we are using positional arguments consistently.
3836 if (FS.consumesDataArgument()) {
3837 if (atFirstArg) {
3838 atFirstArg = false;
3839 usesPositionalArgs = FS.usesPositionalArg();
3840 }
3841 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003842 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3843 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003844 return false;
3845 }
Ted Kremenek02087932010-07-16 02:11:22 +00003846 }
3847
3848 // Check if the field with is non-zero.
3849 const OptionalAmount &Amt = FS.getFieldWidth();
3850 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3851 if (Amt.getConstantAmount() == 0) {
3852 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3853 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003854 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3855 getLocationOfByte(Amt.getStart()),
3856 /*IsStringLocation*/true, R,
3857 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003858 }
3859 }
3860
3861 if (!FS.consumesDataArgument()) {
3862 // FIXME: Technically specifying a precision or field width here
3863 // makes no sense. Worth issuing a warning at some point.
3864 return true;
3865 }
3866
3867 // Consume the argument.
3868 unsigned argIndex = FS.getArgIndex();
3869 if (argIndex < NumDataArgs) {
3870 // The check to see if the argIndex is valid will come later.
3871 // We set the bit here because we may exit early from this
3872 // function if we encounter some other error.
3873 CoveredArgs.set(argIndex);
3874 }
3875
Ted Kremenek4407ea42010-07-20 20:04:47 +00003876 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003877 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003878 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3879 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003880 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003881 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003882 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003883 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3884 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003885
Jordan Rose92303592012-09-08 04:00:03 +00003886 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3887 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3888
Ted Kremenek02087932010-07-16 02:11:22 +00003889 // The remaining checks depend on the data arguments.
3890 if (HasVAListArg)
3891 return true;
3892
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003893 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003894 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003895
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003896 // Check that the argument type matches the format specifier.
3897 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003898 if (!Ex)
3899 return true;
3900
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003901 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3902 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003903 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003904 bool success = fixedFS.fixType(Ex->getType(),
3905 Ex->IgnoreImpCasts()->getType(),
3906 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003907
3908 if (success) {
3909 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003910 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003911 llvm::raw_svector_ostream os(buf);
3912 fixedFS.toString(os);
3913
3914 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003915 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3916 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003917 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003918 Ex->getLocStart(),
3919 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003920 getSpecifierRange(startSpecifier, specifierLen),
3921 FixItHint::CreateReplacement(
3922 getSpecifierRange(startSpecifier, specifierLen),
3923 os.str()));
3924 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003925 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003926 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3927 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003928 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003929 Ex->getLocStart(),
3930 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003931 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003932 }
3933 }
3934
Ted Kremenek02087932010-07-16 02:11:22 +00003935 return true;
3936}
3937
3938void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003939 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003940 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003941 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003942 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003943 bool inFunctionCall, VariadicCallType CallType,
3944 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003945
Ted Kremenekab278de2010-01-28 23:39:18 +00003946 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003947 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003948 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003949 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003950 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3951 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003952 return;
3953 }
Ted Kremenek02087932010-07-16 02:11:22 +00003954
Ted Kremenekab278de2010-01-28 23:39:18 +00003955 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003956 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003957 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003958 // Account for cases where the string literal is truncated in a declaration.
3959 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3960 assert(T && "String literal not of constant array type!");
3961 size_t TypeSize = T->getSize().getZExtValue();
3962 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003963 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003964
3965 // Emit a warning if the string literal is truncated and does not contain an
3966 // embedded null character.
3967 if (TypeSize <= StrRef.size() &&
3968 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3969 CheckFormatHandler::EmitFormatDiagnostic(
3970 *this, inFunctionCall, Args[format_idx],
3971 PDiag(diag::warn_printf_format_string_not_null_terminated),
3972 FExpr->getLocStart(),
3973 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3974 return;
3975 }
3976
Ted Kremenekab278de2010-01-28 23:39:18 +00003977 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003978 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003979 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003980 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003981 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3982 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003983 return;
3984 }
Ted Kremenek02087932010-07-16 02:11:22 +00003985
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003986 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003987 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003988 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003989 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003990 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003991
Hans Wennborg23926bd2011-12-15 10:25:47 +00003992 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003993 getLangOpts(),
3994 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003995 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003996 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003997 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003998 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003999 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004000
Hans Wennborg23926bd2011-12-15 10:25:47 +00004001 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004002 getLangOpts(),
4003 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004004 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004005 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004006}
4007
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004008bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4009 // Str - The format string. NOTE: this is NOT null-terminated!
4010 StringRef StrRef = FExpr->getString();
4011 const char *Str = StrRef.data();
4012 // Account for cases where the string literal is truncated in a declaration.
4013 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4014 assert(T && "String literal not of constant array type!");
4015 size_t TypeSize = T->getSize().getZExtValue();
4016 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4017 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4018 getLangOpts(),
4019 Context.getTargetInfo());
4020}
4021
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004022//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4023
4024// Returns the related absolute value function that is larger, of 0 if one
4025// does not exist.
4026static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4027 switch (AbsFunction) {
4028 default:
4029 return 0;
4030
4031 case Builtin::BI__builtin_abs:
4032 return Builtin::BI__builtin_labs;
4033 case Builtin::BI__builtin_labs:
4034 return Builtin::BI__builtin_llabs;
4035 case Builtin::BI__builtin_llabs:
4036 return 0;
4037
4038 case Builtin::BI__builtin_fabsf:
4039 return Builtin::BI__builtin_fabs;
4040 case Builtin::BI__builtin_fabs:
4041 return Builtin::BI__builtin_fabsl;
4042 case Builtin::BI__builtin_fabsl:
4043 return 0;
4044
4045 case Builtin::BI__builtin_cabsf:
4046 return Builtin::BI__builtin_cabs;
4047 case Builtin::BI__builtin_cabs:
4048 return Builtin::BI__builtin_cabsl;
4049 case Builtin::BI__builtin_cabsl:
4050 return 0;
4051
4052 case Builtin::BIabs:
4053 return Builtin::BIlabs;
4054 case Builtin::BIlabs:
4055 return Builtin::BIllabs;
4056 case Builtin::BIllabs:
4057 return 0;
4058
4059 case Builtin::BIfabsf:
4060 return Builtin::BIfabs;
4061 case Builtin::BIfabs:
4062 return Builtin::BIfabsl;
4063 case Builtin::BIfabsl:
4064 return 0;
4065
4066 case Builtin::BIcabsf:
4067 return Builtin::BIcabs;
4068 case Builtin::BIcabs:
4069 return Builtin::BIcabsl;
4070 case Builtin::BIcabsl:
4071 return 0;
4072 }
4073}
4074
4075// Returns the argument type of the absolute value function.
4076static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4077 unsigned AbsType) {
4078 if (AbsType == 0)
4079 return QualType();
4080
4081 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4082 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4083 if (Error != ASTContext::GE_None)
4084 return QualType();
4085
4086 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4087 if (!FT)
4088 return QualType();
4089
4090 if (FT->getNumParams() != 1)
4091 return QualType();
4092
4093 return FT->getParamType(0);
4094}
4095
4096// Returns the best absolute value function, or zero, based on type and
4097// current absolute value function.
4098static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4099 unsigned AbsFunctionKind) {
4100 unsigned BestKind = 0;
4101 uint64_t ArgSize = Context.getTypeSize(ArgType);
4102 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4103 Kind = getLargerAbsoluteValueFunction(Kind)) {
4104 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4105 if (Context.getTypeSize(ParamType) >= ArgSize) {
4106 if (BestKind == 0)
4107 BestKind = Kind;
4108 else if (Context.hasSameType(ParamType, ArgType)) {
4109 BestKind = Kind;
4110 break;
4111 }
4112 }
4113 }
4114 return BestKind;
4115}
4116
4117enum AbsoluteValueKind {
4118 AVK_Integer,
4119 AVK_Floating,
4120 AVK_Complex
4121};
4122
4123static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4124 if (T->isIntegralOrEnumerationType())
4125 return AVK_Integer;
4126 if (T->isRealFloatingType())
4127 return AVK_Floating;
4128 if (T->isAnyComplexType())
4129 return AVK_Complex;
4130
4131 llvm_unreachable("Type not integer, floating, or complex");
4132}
4133
4134// Changes the absolute value function to a different type. Preserves whether
4135// the function is a builtin.
4136static unsigned changeAbsFunction(unsigned AbsKind,
4137 AbsoluteValueKind ValueKind) {
4138 switch (ValueKind) {
4139 case AVK_Integer:
4140 switch (AbsKind) {
4141 default:
4142 return 0;
4143 case Builtin::BI__builtin_fabsf:
4144 case Builtin::BI__builtin_fabs:
4145 case Builtin::BI__builtin_fabsl:
4146 case Builtin::BI__builtin_cabsf:
4147 case Builtin::BI__builtin_cabs:
4148 case Builtin::BI__builtin_cabsl:
4149 return Builtin::BI__builtin_abs;
4150 case Builtin::BIfabsf:
4151 case Builtin::BIfabs:
4152 case Builtin::BIfabsl:
4153 case Builtin::BIcabsf:
4154 case Builtin::BIcabs:
4155 case Builtin::BIcabsl:
4156 return Builtin::BIabs;
4157 }
4158 case AVK_Floating:
4159 switch (AbsKind) {
4160 default:
4161 return 0;
4162 case Builtin::BI__builtin_abs:
4163 case Builtin::BI__builtin_labs:
4164 case Builtin::BI__builtin_llabs:
4165 case Builtin::BI__builtin_cabsf:
4166 case Builtin::BI__builtin_cabs:
4167 case Builtin::BI__builtin_cabsl:
4168 return Builtin::BI__builtin_fabsf;
4169 case Builtin::BIabs:
4170 case Builtin::BIlabs:
4171 case Builtin::BIllabs:
4172 case Builtin::BIcabsf:
4173 case Builtin::BIcabs:
4174 case Builtin::BIcabsl:
4175 return Builtin::BIfabsf;
4176 }
4177 case AVK_Complex:
4178 switch (AbsKind) {
4179 default:
4180 return 0;
4181 case Builtin::BI__builtin_abs:
4182 case Builtin::BI__builtin_labs:
4183 case Builtin::BI__builtin_llabs:
4184 case Builtin::BI__builtin_fabsf:
4185 case Builtin::BI__builtin_fabs:
4186 case Builtin::BI__builtin_fabsl:
4187 return Builtin::BI__builtin_cabsf;
4188 case Builtin::BIabs:
4189 case Builtin::BIlabs:
4190 case Builtin::BIllabs:
4191 case Builtin::BIfabsf:
4192 case Builtin::BIfabs:
4193 case Builtin::BIfabsl:
4194 return Builtin::BIcabsf;
4195 }
4196 }
4197 llvm_unreachable("Unable to convert function");
4198}
4199
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004200static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004201 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4202 if (!FnInfo)
4203 return 0;
4204
4205 switch (FDecl->getBuiltinID()) {
4206 default:
4207 return 0;
4208 case Builtin::BI__builtin_abs:
4209 case Builtin::BI__builtin_fabs:
4210 case Builtin::BI__builtin_fabsf:
4211 case Builtin::BI__builtin_fabsl:
4212 case Builtin::BI__builtin_labs:
4213 case Builtin::BI__builtin_llabs:
4214 case Builtin::BI__builtin_cabs:
4215 case Builtin::BI__builtin_cabsf:
4216 case Builtin::BI__builtin_cabsl:
4217 case Builtin::BIabs:
4218 case Builtin::BIlabs:
4219 case Builtin::BIllabs:
4220 case Builtin::BIfabs:
4221 case Builtin::BIfabsf:
4222 case Builtin::BIfabsl:
4223 case Builtin::BIcabs:
4224 case Builtin::BIcabsf:
4225 case Builtin::BIcabsl:
4226 return FDecl->getBuiltinID();
4227 }
4228 llvm_unreachable("Unknown Builtin type");
4229}
4230
4231// If the replacement is valid, emit a note with replacement function.
4232// Additionally, suggest including the proper header if not already included.
4233static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004234 unsigned AbsKind, QualType ArgType) {
4235 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004236 const char *HeaderName = nullptr;
4237 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004238 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4239 FunctionName = "std::abs";
4240 if (ArgType->isIntegralOrEnumerationType()) {
4241 HeaderName = "cstdlib";
4242 } else if (ArgType->isRealFloatingType()) {
4243 HeaderName = "cmath";
4244 } else {
4245 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004246 }
Richard Trieubeffb832014-04-15 23:47:53 +00004247
4248 // Lookup all std::abs
4249 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004250 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004251 R.suppressDiagnostics();
4252 S.LookupQualifiedName(R, Std);
4253
4254 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004255 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004256 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4257 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4258 } else {
4259 FDecl = dyn_cast<FunctionDecl>(I);
4260 }
4261 if (!FDecl)
4262 continue;
4263
4264 // Found std::abs(), check that they are the right ones.
4265 if (FDecl->getNumParams() != 1)
4266 continue;
4267
4268 // Check that the parameter type can handle the argument.
4269 QualType ParamType = FDecl->getParamDecl(0)->getType();
4270 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4271 S.Context.getTypeSize(ArgType) <=
4272 S.Context.getTypeSize(ParamType)) {
4273 // Found a function, don't need the header hint.
4274 EmitHeaderHint = false;
4275 break;
4276 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004277 }
Richard Trieubeffb832014-04-15 23:47:53 +00004278 }
4279 } else {
4280 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4281 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4282
4283 if (HeaderName) {
4284 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4285 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4286 R.suppressDiagnostics();
4287 S.LookupName(R, S.getCurScope());
4288
4289 if (R.isSingleResult()) {
4290 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4291 if (FD && FD->getBuiltinID() == AbsKind) {
4292 EmitHeaderHint = false;
4293 } else {
4294 return;
4295 }
4296 } else if (!R.empty()) {
4297 return;
4298 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004299 }
4300 }
4301
4302 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004303 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004304
Richard Trieubeffb832014-04-15 23:47:53 +00004305 if (!HeaderName)
4306 return;
4307
4308 if (!EmitHeaderHint)
4309 return;
4310
Alp Toker5d96e0a2014-07-11 20:53:51 +00004311 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4312 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004313}
4314
4315static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4316 if (!FDecl)
4317 return false;
4318
4319 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4320 return false;
4321
4322 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4323
4324 while (ND && ND->isInlineNamespace()) {
4325 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004326 }
Richard Trieubeffb832014-04-15 23:47:53 +00004327
4328 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4329 return false;
4330
4331 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4332 return false;
4333
4334 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004335}
4336
4337// Warn when using the wrong abs() function.
4338void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4339 const FunctionDecl *FDecl,
4340 IdentifierInfo *FnInfo) {
4341 if (Call->getNumArgs() != 1)
4342 return;
4343
4344 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004345 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4346 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004347 return;
4348
4349 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4350 QualType ParamType = Call->getArg(0)->getType();
4351
Alp Toker5d96e0a2014-07-11 20:53:51 +00004352 // Unsigned types cannot be negative. Suggest removing the absolute value
4353 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004354 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004355 const char *FunctionName =
4356 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004357 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4358 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004359 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004360 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4361 return;
4362 }
4363
Richard Trieubeffb832014-04-15 23:47:53 +00004364 // std::abs has overloads which prevent most of the absolute value problems
4365 // from occurring.
4366 if (IsStdAbs)
4367 return;
4368
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004369 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4370 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4371
4372 // The argument and parameter are the same kind. Check if they are the right
4373 // size.
4374 if (ArgValueKind == ParamValueKind) {
4375 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4376 return;
4377
4378 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4379 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4380 << FDecl << ArgType << ParamType;
4381
4382 if (NewAbsKind == 0)
4383 return;
4384
4385 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004386 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004387 return;
4388 }
4389
4390 // ArgValueKind != ParamValueKind
4391 // The wrong type of absolute value function was used. Attempt to find the
4392 // proper one.
4393 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4394 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4395 if (NewAbsKind == 0)
4396 return;
4397
4398 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4399 << FDecl << ParamValueKind << ArgValueKind;
4400
4401 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004402 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004403 return;
4404}
4405
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004406//===--- CHECK: Standard memory functions ---------------------------------===//
4407
Nico Weber0e6daef2013-12-26 23:38:39 +00004408/// \brief Takes the expression passed to the size_t parameter of functions
4409/// such as memcmp, strncat, etc and warns if it's a comparison.
4410///
4411/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4412static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4413 IdentifierInfo *FnName,
4414 SourceLocation FnLoc,
4415 SourceLocation RParenLoc) {
4416 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4417 if (!Size)
4418 return false;
4419
4420 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4421 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4422 return false;
4423
Nico Weber0e6daef2013-12-26 23:38:39 +00004424 SourceRange SizeRange = Size->getSourceRange();
4425 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4426 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004427 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004428 << FnName << FixItHint::CreateInsertion(
4429 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004430 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004431 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004432 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004433 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4434 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004435
4436 return true;
4437}
4438
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004439/// \brief Determine whether the given type is or contains a dynamic class type
4440/// (e.g., whether it has a vtable).
4441static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4442 bool &IsContained) {
4443 // Look through array types while ignoring qualifiers.
4444 const Type *Ty = T->getBaseElementTypeUnsafe();
4445 IsContained = false;
4446
4447 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4448 RD = RD ? RD->getDefinition() : nullptr;
4449 if (!RD)
4450 return nullptr;
4451
4452 if (RD->isDynamicClass())
4453 return RD;
4454
4455 // Check all the fields. If any bases were dynamic, the class is dynamic.
4456 // It's impossible for a class to transitively contain itself by value, so
4457 // infinite recursion is impossible.
4458 for (auto *FD : RD->fields()) {
4459 bool SubContained;
4460 if (const CXXRecordDecl *ContainedRD =
4461 getContainedDynamicClass(FD->getType(), SubContained)) {
4462 IsContained = true;
4463 return ContainedRD;
4464 }
4465 }
4466
4467 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004468}
4469
Chandler Carruth889ed862011-06-21 23:04:20 +00004470/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004471/// otherwise returns NULL.
4472static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004473 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004474 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4475 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4476 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004477
Craig Topperc3ec1492014-05-26 06:22:03 +00004478 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004479}
4480
Chandler Carruth889ed862011-06-21 23:04:20 +00004481/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004482static QualType getSizeOfArgType(const Expr* E) {
4483 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4484 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4485 if (SizeOf->getKind() == clang::UETT_SizeOf)
4486 return SizeOf->getTypeOfArgument();
4487
4488 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004489}
4490
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004491/// \brief Check for dangerous or invalid arguments to memset().
4492///
Chandler Carruthac687262011-06-03 06:23:57 +00004493/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004494/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4495/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004496///
4497/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004498void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004499 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004500 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004501 assert(BId != 0);
4502
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004503 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004504 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004505 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004506 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004507 return;
4508
Anna Zaks22122702012-01-17 00:37:07 +00004509 unsigned LastArg = (BId == Builtin::BImemset ||
4510 BId == Builtin::BIstrndup ? 1 : 2);
4511 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004512 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004513
Nico Weber0e6daef2013-12-26 23:38:39 +00004514 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4515 Call->getLocStart(), Call->getRParenLoc()))
4516 return;
4517
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004518 // We have special checking when the length is a sizeof expression.
4519 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4520 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4521 llvm::FoldingSetNodeID SizeOfArgID;
4522
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004523 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4524 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004525 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004526
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004527 QualType DestTy = Dest->getType();
4528 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4529 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004530
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004531 // Never warn about void type pointers. This can be used to suppress
4532 // false positives.
4533 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004534 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004535
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004536 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4537 // actually comparing the expressions for equality. Because computing the
4538 // expression IDs can be expensive, we only do this if the diagnostic is
4539 // enabled.
4540 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004541 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4542 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004543 // We only compute IDs for expressions if the warning is enabled, and
4544 // cache the sizeof arg's ID.
4545 if (SizeOfArgID == llvm::FoldingSetNodeID())
4546 SizeOfArg->Profile(SizeOfArgID, Context, true);
4547 llvm::FoldingSetNodeID DestID;
4548 Dest->Profile(DestID, Context, true);
4549 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004550 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4551 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004552 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004553 StringRef ReadableName = FnName->getName();
4554
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004555 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004556 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004557 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004558 if (!PointeeTy->isIncompleteType() &&
4559 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004560 ActionIdx = 2; // If the pointee's size is sizeof(char),
4561 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004562
4563 // If the function is defined as a builtin macro, do not show macro
4564 // expansion.
4565 SourceLocation SL = SizeOfArg->getExprLoc();
4566 SourceRange DSR = Dest->getSourceRange();
4567 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004568 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004569
4570 if (SM.isMacroArgExpansion(SL)) {
4571 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4572 SL = SM.getSpellingLoc(SL);
4573 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4574 SM.getSpellingLoc(DSR.getEnd()));
4575 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4576 SM.getSpellingLoc(SSR.getEnd()));
4577 }
4578
Anna Zaksd08d9152012-05-30 23:14:52 +00004579 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004580 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004581 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004582 << PointeeTy
4583 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004584 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004585 << SSR);
4586 DiagRuntimeBehavior(SL, SizeOfArg,
4587 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4588 << ActionIdx
4589 << SSR);
4590
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004591 break;
4592 }
4593 }
4594
4595 // Also check for cases where the sizeof argument is the exact same
4596 // type as the memory argument, and where it points to a user-defined
4597 // record type.
4598 if (SizeOfArgTy != QualType()) {
4599 if (PointeeTy->isRecordType() &&
4600 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4601 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4602 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4603 << FnName << SizeOfArgTy << ArgIdx
4604 << PointeeTy << Dest->getSourceRange()
4605 << LenExpr->getSourceRange());
4606 break;
4607 }
Nico Weberc5e73862011-06-14 16:14:58 +00004608 }
4609
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004610 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004611 bool IsContained;
4612 if (const CXXRecordDecl *ContainedRD =
4613 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004614
4615 unsigned OperationType = 0;
4616 // "overwritten" if we're warning about the destination for any call
4617 // but memcmp; otherwise a verb appropriate to the call.
4618 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4619 if (BId == Builtin::BImemcpy)
4620 OperationType = 1;
4621 else if(BId == Builtin::BImemmove)
4622 OperationType = 2;
4623 else if (BId == Builtin::BImemcmp)
4624 OperationType = 3;
4625 }
4626
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004627 DiagRuntimeBehavior(
4628 Dest->getExprLoc(), Dest,
4629 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004630 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004631 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004632 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004633 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4634 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004635 DiagRuntimeBehavior(
4636 Dest->getExprLoc(), Dest,
4637 PDiag(diag::warn_arc_object_memaccess)
4638 << ArgIdx << FnName << PointeeTy
4639 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004640 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004641 continue;
John McCall31168b02011-06-15 23:02:42 +00004642
4643 DiagRuntimeBehavior(
4644 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004645 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004646 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4647 break;
4648 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004649 }
4650}
4651
Ted Kremenek6865f772011-08-18 20:55:45 +00004652// A little helper routine: ignore addition and subtraction of integer literals.
4653// This intentionally does not ignore all integer constant expressions because
4654// we don't want to remove sizeof().
4655static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4656 Ex = Ex->IgnoreParenCasts();
4657
4658 for (;;) {
4659 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4660 if (!BO || !BO->isAdditiveOp())
4661 break;
4662
4663 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4664 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4665
4666 if (isa<IntegerLiteral>(RHS))
4667 Ex = LHS;
4668 else if (isa<IntegerLiteral>(LHS))
4669 Ex = RHS;
4670 else
4671 break;
4672 }
4673
4674 return Ex;
4675}
4676
Anna Zaks13b08572012-08-08 21:42:23 +00004677static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4678 ASTContext &Context) {
4679 // Only handle constant-sized or VLAs, but not flexible members.
4680 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4681 // Only issue the FIXIT for arrays of size > 1.
4682 if (CAT->getSize().getSExtValue() <= 1)
4683 return false;
4684 } else if (!Ty->isVariableArrayType()) {
4685 return false;
4686 }
4687 return true;
4688}
4689
Ted Kremenek6865f772011-08-18 20:55:45 +00004690// Warn if the user has made the 'size' argument to strlcpy or strlcat
4691// be the size of the source, instead of the destination.
4692void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4693 IdentifierInfo *FnName) {
4694
4695 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004696 unsigned NumArgs = Call->getNumArgs();
4697 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004698 return;
4699
4700 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4701 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004702 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004703
4704 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4705 Call->getLocStart(), Call->getRParenLoc()))
4706 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004707
4708 // Look for 'strlcpy(dst, x, sizeof(x))'
4709 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4710 CompareWithSrc = Ex;
4711 else {
4712 // Look for 'strlcpy(dst, x, strlen(x))'
4713 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004714 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4715 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004716 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4717 }
4718 }
4719
4720 if (!CompareWithSrc)
4721 return;
4722
4723 // Determine if the argument to sizeof/strlen is equal to the source
4724 // argument. In principle there's all kinds of things you could do
4725 // here, for instance creating an == expression and evaluating it with
4726 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4727 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4728 if (!SrcArgDRE)
4729 return;
4730
4731 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4732 if (!CompareWithSrcDRE ||
4733 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4734 return;
4735
4736 const Expr *OriginalSizeArg = Call->getArg(2);
4737 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4738 << OriginalSizeArg->getSourceRange() << FnName;
4739
4740 // Output a FIXIT hint if the destination is an array (rather than a
4741 // pointer to an array). This could be enhanced to handle some
4742 // pointers if we know the actual size, like if DstArg is 'array+2'
4743 // we could say 'sizeof(array)-2'.
4744 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004745 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004746 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004747
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004748 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004749 llvm::raw_svector_ostream OS(sizeString);
4750 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004751 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004752 OS << ")";
4753
4754 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4755 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4756 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004757}
4758
Anna Zaks314cd092012-02-01 19:08:57 +00004759/// Check if two expressions refer to the same declaration.
4760static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4761 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4762 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4763 return D1->getDecl() == D2->getDecl();
4764 return false;
4765}
4766
4767static const Expr *getStrlenExprArg(const Expr *E) {
4768 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4769 const FunctionDecl *FD = CE->getDirectCallee();
4770 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004771 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004772 return CE->getArg(0)->IgnoreParenCasts();
4773 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004774 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004775}
4776
4777// Warn on anti-patterns as the 'size' argument to strncat.
4778// The correct size argument should look like following:
4779// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4780void Sema::CheckStrncatArguments(const CallExpr *CE,
4781 IdentifierInfo *FnName) {
4782 // Don't crash if the user has the wrong number of arguments.
4783 if (CE->getNumArgs() < 3)
4784 return;
4785 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4786 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4787 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4788
Nico Weber0e6daef2013-12-26 23:38:39 +00004789 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4790 CE->getRParenLoc()))
4791 return;
4792
Anna Zaks314cd092012-02-01 19:08:57 +00004793 // Identify common expressions, which are wrongly used as the size argument
4794 // to strncat and may lead to buffer overflows.
4795 unsigned PatternType = 0;
4796 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4797 // - sizeof(dst)
4798 if (referToTheSameDecl(SizeOfArg, DstArg))
4799 PatternType = 1;
4800 // - sizeof(src)
4801 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4802 PatternType = 2;
4803 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4804 if (BE->getOpcode() == BO_Sub) {
4805 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4806 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4807 // - sizeof(dst) - strlen(dst)
4808 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4809 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4810 PatternType = 1;
4811 // - sizeof(src) - (anything)
4812 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4813 PatternType = 2;
4814 }
4815 }
4816
4817 if (PatternType == 0)
4818 return;
4819
Anna Zaks5069aa32012-02-03 01:27:37 +00004820 // Generate the diagnostic.
4821 SourceLocation SL = LenArg->getLocStart();
4822 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004823 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004824
4825 // If the function is defined as a builtin macro, do not show macro expansion.
4826 if (SM.isMacroArgExpansion(SL)) {
4827 SL = SM.getSpellingLoc(SL);
4828 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4829 SM.getSpellingLoc(SR.getEnd()));
4830 }
4831
Anna Zaks13b08572012-08-08 21:42:23 +00004832 // Check if the destination is an array (rather than a pointer to an array).
4833 QualType DstTy = DstArg->getType();
4834 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4835 Context);
4836 if (!isKnownSizeArray) {
4837 if (PatternType == 1)
4838 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4839 else
4840 Diag(SL, diag::warn_strncat_src_size) << SR;
4841 return;
4842 }
4843
Anna Zaks314cd092012-02-01 19:08:57 +00004844 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004845 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004846 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004847 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004848
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004849 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004850 llvm::raw_svector_ostream OS(sizeString);
4851 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004852 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004853 OS << ") - ";
4854 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004855 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004856 OS << ") - 1";
4857
Anna Zaks5069aa32012-02-03 01:27:37 +00004858 Diag(SL, diag::note_strncat_wrong_size)
4859 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004860}
4861
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004862//===--- CHECK: Return Address of Stack Variable --------------------------===//
4863
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004864static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4865 Decl *ParentDecl);
4866static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4867 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004868
4869/// CheckReturnStackAddr - Check if a return statement returns the address
4870/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004871static void
4872CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4873 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004874
Craig Topperc3ec1492014-05-26 06:22:03 +00004875 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004876 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004877
4878 // Perform checking for returned stack addresses, local blocks,
4879 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004880 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004881 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004882 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004883 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004884 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004885 }
4886
Craig Topperc3ec1492014-05-26 06:22:03 +00004887 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004888 return; // Nothing suspicious was found.
4889
4890 SourceLocation diagLoc;
4891 SourceRange diagRange;
4892 if (refVars.empty()) {
4893 diagLoc = stackE->getLocStart();
4894 diagRange = stackE->getSourceRange();
4895 } else {
4896 // We followed through a reference variable. 'stackE' contains the
4897 // problematic expression but we will warn at the return statement pointing
4898 // at the reference variable. We will later display the "trail" of
4899 // reference variables using notes.
4900 diagLoc = refVars[0]->getLocStart();
4901 diagRange = refVars[0]->getSourceRange();
4902 }
4903
4904 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004905 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004906 : diag::warn_ret_stack_addr)
4907 << DR->getDecl()->getDeclName() << diagRange;
4908 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004909 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004910 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004911 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004912 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004913 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4914 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004915 << diagRange;
4916 }
4917
4918 // Display the "trail" of reference variables that we followed until we
4919 // found the problematic expression using notes.
4920 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4921 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4922 // If this var binds to another reference var, show the range of the next
4923 // var, otherwise the var binds to the problematic expression, in which case
4924 // show the range of the expression.
4925 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4926 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004927 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4928 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004929 }
4930}
4931
4932/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4933/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004934/// to a location on the stack, a local block, an address of a label, or a
4935/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004936/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004937/// encounter a subexpression that (1) clearly does not lead to one of the
4938/// above problematic expressions (2) is something we cannot determine leads to
4939/// a problematic expression based on such local checking.
4940///
4941/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4942/// the expression that they point to. Such variables are added to the
4943/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004944///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004945/// EvalAddr processes expressions that are pointers that are used as
4946/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004947/// At the base case of the recursion is a check for the above problematic
4948/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004949///
4950/// This implementation handles:
4951///
4952/// * pointer-to-pointer casts
4953/// * implicit conversions from array references to pointers
4954/// * taking the address of fields
4955/// * arbitrary interplay between "&" and "*" operators
4956/// * pointer arithmetic from an address of a stack variable
4957/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004958static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4959 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004960 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004961 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004962
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004963 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004964 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004965 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004966 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004967 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004968
Peter Collingbourne91147592011-04-15 00:35:48 +00004969 E = E->IgnoreParens();
4970
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004971 // Our "symbolic interpreter" is just a dispatch off the currently
4972 // viewed AST node. We then recursively traverse the AST by calling
4973 // EvalAddr and EvalVal appropriately.
4974 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004975 case Stmt::DeclRefExprClass: {
4976 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4977
Richard Smith40f08eb2014-01-30 22:05:38 +00004978 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00004979 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00004980 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004981
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004982 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4983 // If this is a reference variable, follow through to the expression that
4984 // it points to.
4985 if (V->hasLocalStorage() &&
4986 V->getType()->isReferenceType() && V->hasInit()) {
4987 // Add the reference variable to the "trail".
4988 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004989 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004990 }
4991
Craig Topperc3ec1492014-05-26 06:22:03 +00004992 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004993 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004994
Chris Lattner934edb22007-12-28 05:31:15 +00004995 case Stmt::UnaryOperatorClass: {
4996 // The only unary operator that make sense to handle here
4997 // is AddrOf. All others don't make sense as pointers.
4998 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004999
John McCalle3027922010-08-25 11:45:40 +00005000 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005001 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005002 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005003 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005004 }
Mike Stump11289f42009-09-09 15:08:12 +00005005
Chris Lattner934edb22007-12-28 05:31:15 +00005006 case Stmt::BinaryOperatorClass: {
5007 // Handle pointer arithmetic. All other binary operators are not valid
5008 // in this context.
5009 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005010 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005011
John McCalle3027922010-08-25 11:45:40 +00005012 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005013 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005014
Chris Lattner934edb22007-12-28 05:31:15 +00005015 Expr *Base = B->getLHS();
5016
5017 // Determine which argument is the real pointer base. It could be
5018 // the RHS argument instead of the LHS.
5019 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005020
Chris Lattner934edb22007-12-28 05:31:15 +00005021 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005022 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005023 }
Steve Naroff2752a172008-09-10 19:17:48 +00005024
Chris Lattner934edb22007-12-28 05:31:15 +00005025 // For conditional operators we need to see if either the LHS or RHS are
5026 // valid DeclRefExpr*s. If one of them is valid, we return it.
5027 case Stmt::ConditionalOperatorClass: {
5028 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005029
Chris Lattner934edb22007-12-28 05:31:15 +00005030 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005031 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5032 if (Expr *LHSExpr = C->getLHS()) {
5033 // In C++, we can have a throw-expression, which has 'void' type.
5034 if (!LHSExpr->getType()->isVoidType())
5035 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005036 return LHS;
5037 }
Chris Lattner934edb22007-12-28 05:31:15 +00005038
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005039 // In C++, we can have a throw-expression, which has 'void' type.
5040 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005041 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005042
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005043 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005044 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005045
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005046 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005047 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005048 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005049 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005050
5051 case Stmt::AddrLabelExprClass:
5052 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005053
John McCall28fc7092011-11-10 05:35:25 +00005054 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005055 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5056 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005057
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005058 // For casts, we need to handle conversions from arrays to
5059 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005060 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005061 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005062 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005063 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005064 case Stmt::CXXStaticCastExprClass:
5065 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005066 case Stmt::CXXConstCastExprClass:
5067 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005068 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5069 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005070 case CK_LValueToRValue:
5071 case CK_NoOp:
5072 case CK_BaseToDerived:
5073 case CK_DerivedToBase:
5074 case CK_UncheckedDerivedToBase:
5075 case CK_Dynamic:
5076 case CK_CPointerToObjCPointerCast:
5077 case CK_BlockPointerToObjCPointerCast:
5078 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005079 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005080
5081 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005082 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005083
Richard Trieudadefde2014-07-02 04:39:38 +00005084 case CK_BitCast:
5085 if (SubExpr->getType()->isAnyPointerType() ||
5086 SubExpr->getType()->isBlockPointerType() ||
5087 SubExpr->getType()->isObjCQualifiedIdType())
5088 return EvalAddr(SubExpr, refVars, ParentDecl);
5089 else
5090 return nullptr;
5091
Eli Friedman8195ad72012-02-23 23:04:32 +00005092 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005093 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005094 }
Chris Lattner934edb22007-12-28 05:31:15 +00005095 }
Mike Stump11289f42009-09-09 15:08:12 +00005096
Douglas Gregorfe314812011-06-21 17:03:29 +00005097 case Stmt::MaterializeTemporaryExprClass:
5098 if (Expr *Result = EvalAddr(
5099 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005100 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005101 return Result;
5102
5103 return E;
5104
Chris Lattner934edb22007-12-28 05:31:15 +00005105 // Everything else: we simply don't reason about them.
5106 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005107 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005108 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005109}
Mike Stump11289f42009-09-09 15:08:12 +00005110
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005111
5112/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5113/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005114static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5115 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005116do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005117 // We should only be called for evaluating non-pointer expressions, or
5118 // expressions with a pointer type that are not used as references but instead
5119 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005120
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005121 // Our "symbolic interpreter" is just a dispatch off the currently
5122 // viewed AST node. We then recursively traverse the AST by calling
5123 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005124
5125 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005126 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005127 case Stmt::ImplicitCastExprClass: {
5128 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005129 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005130 E = IE->getSubExpr();
5131 continue;
5132 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005133 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005134 }
5135
John McCall28fc7092011-11-10 05:35:25 +00005136 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005137 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005138
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005139 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005140 // When we hit a DeclRefExpr we are looking at code that refers to a
5141 // variable's name. If it's not a reference variable we check if it has
5142 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005143 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005144
Richard Smith40f08eb2014-01-30 22:05:38 +00005145 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005146 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005147 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005148
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005149 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5150 // Check if it refers to itself, e.g. "int& i = i;".
5151 if (V == ParentDecl)
5152 return DR;
5153
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005154 if (V->hasLocalStorage()) {
5155 if (!V->getType()->isReferenceType())
5156 return DR;
5157
5158 // Reference variable, follow through to the expression that
5159 // it points to.
5160 if (V->hasInit()) {
5161 // Add the reference variable to the "trail".
5162 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005163 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005164 }
5165 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005166 }
Mike Stump11289f42009-09-09 15:08:12 +00005167
Craig Topperc3ec1492014-05-26 06:22:03 +00005168 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005169 }
Mike Stump11289f42009-09-09 15:08:12 +00005170
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005171 case Stmt::UnaryOperatorClass: {
5172 // The only unary operator that make sense to handle here
5173 // is Deref. All others don't resolve to a "name." This includes
5174 // handling all sorts of rvalues passed to a unary operator.
5175 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005176
John McCalle3027922010-08-25 11:45:40 +00005177 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005178 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005179
Craig Topperc3ec1492014-05-26 06:22:03 +00005180 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005181 }
Mike Stump11289f42009-09-09 15:08:12 +00005182
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005183 case Stmt::ArraySubscriptExprClass: {
5184 // Array subscripts are potential references to data on the stack. We
5185 // retrieve the DeclRefExpr* for the array variable if it indeed
5186 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005187 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005188 }
Mike Stump11289f42009-09-09 15:08:12 +00005189
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005190 case Stmt::ConditionalOperatorClass: {
5191 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005192 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005193 ConditionalOperator *C = cast<ConditionalOperator>(E);
5194
Anders Carlsson801c5c72007-11-30 19:04:31 +00005195 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005196 if (Expr *LHSExpr = C->getLHS()) {
5197 // In C++, we can have a throw-expression, which has 'void' type.
5198 if (!LHSExpr->getType()->isVoidType())
5199 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5200 return LHS;
5201 }
5202
5203 // In C++, we can have a throw-expression, which has 'void' type.
5204 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005205 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005206
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005207 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005208 }
Mike Stump11289f42009-09-09 15:08:12 +00005209
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005210 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005211 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005212 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005213
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005214 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005215 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005216 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005217
5218 // Check whether the member type is itself a reference, in which case
5219 // we're not going to refer to the member, but to what the member refers to.
5220 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005221 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005222
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005223 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005224 }
Mike Stump11289f42009-09-09 15:08:12 +00005225
Douglas Gregorfe314812011-06-21 17:03:29 +00005226 case Stmt::MaterializeTemporaryExprClass:
5227 if (Expr *Result = EvalVal(
5228 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005229 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005230 return Result;
5231
5232 return E;
5233
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005234 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005235 // Check that we don't return or take the address of a reference to a
5236 // temporary. This is only useful in C++.
5237 if (!E->isTypeDependent() && E->isRValue())
5238 return E;
5239
5240 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005241 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005242 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005243} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005244}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005245
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005246void
5247Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5248 SourceLocation ReturnLoc,
5249 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005250 const AttrVec *Attrs,
5251 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005252 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5253
5254 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005255 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5256 CheckNonNullExpr(*this, RetValExp))
5257 Diag(ReturnLoc, diag::warn_null_ret)
5258 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005259
5260 // C++11 [basic.stc.dynamic.allocation]p4:
5261 // If an allocation function declared with a non-throwing
5262 // exception-specification fails to allocate storage, it shall return
5263 // a null pointer. Any other allocation function that fails to allocate
5264 // storage shall indicate failure only by throwing an exception [...]
5265 if (FD) {
5266 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5267 if (Op == OO_New || Op == OO_Array_New) {
5268 const FunctionProtoType *Proto
5269 = FD->getType()->castAs<FunctionProtoType>();
5270 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5271 CheckNonNullExpr(*this, RetValExp))
5272 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5273 << FD << getLangOpts().CPlusPlus11;
5274 }
5275 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005276}
5277
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005278//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5279
5280/// Check for comparisons of floating point operands using != and ==.
5281/// Issue a warning if these are no self-comparisons, as they are not likely
5282/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005283void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005284 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5285 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005286
5287 // Special case: check for x == x (which is OK).
5288 // Do not emit warnings for such cases.
5289 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5290 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5291 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005292 return;
Mike Stump11289f42009-09-09 15:08:12 +00005293
5294
Ted Kremenekeda40e22007-11-29 00:59:04 +00005295 // Special case: check for comparisons against literals that can be exactly
5296 // represented by APFloat. In such cases, do not emit a warning. This
5297 // is a heuristic: often comparison against such literals are used to
5298 // detect if a value in a variable has not changed. This clearly can
5299 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005300 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5301 if (FLL->isExact())
5302 return;
5303 } else
5304 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5305 if (FLR->isExact())
5306 return;
Mike Stump11289f42009-09-09 15:08:12 +00005307
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005308 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005309 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005310 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005311 return;
Mike Stump11289f42009-09-09 15:08:12 +00005312
David Blaikie1f4ff152012-07-16 20:47:22 +00005313 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005314 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005315 return;
Mike Stump11289f42009-09-09 15:08:12 +00005316
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005317 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005318 Diag(Loc, diag::warn_floatingpoint_eq)
5319 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005320}
John McCallca01b222010-01-04 23:21:16 +00005321
John McCall70aa5392010-01-06 05:24:50 +00005322//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5323//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005324
John McCall70aa5392010-01-06 05:24:50 +00005325namespace {
John McCallca01b222010-01-04 23:21:16 +00005326
John McCall70aa5392010-01-06 05:24:50 +00005327/// Structure recording the 'active' range of an integer-valued
5328/// expression.
5329struct IntRange {
5330 /// The number of bits active in the int.
5331 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005332
John McCall70aa5392010-01-06 05:24:50 +00005333 /// True if the int is known not to have negative values.
5334 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005335
John McCall70aa5392010-01-06 05:24:50 +00005336 IntRange(unsigned Width, bool NonNegative)
5337 : Width(Width), NonNegative(NonNegative)
5338 {}
John McCallca01b222010-01-04 23:21:16 +00005339
John McCall817d4af2010-11-10 23:38:19 +00005340 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005341 static IntRange forBoolType() {
5342 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005343 }
5344
John McCall817d4af2010-11-10 23:38:19 +00005345 /// Returns the range of an opaque value of the given integral type.
5346 static IntRange forValueOfType(ASTContext &C, QualType T) {
5347 return forValueOfCanonicalType(C,
5348 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005349 }
5350
John McCall817d4af2010-11-10 23:38:19 +00005351 /// Returns the range of an opaque value of a canonical integral type.
5352 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005353 assert(T->isCanonicalUnqualified());
5354
5355 if (const VectorType *VT = dyn_cast<VectorType>(T))
5356 T = VT->getElementType().getTypePtr();
5357 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5358 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005359 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5360 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005361
David Majnemer6a426652013-06-07 22:07:20 +00005362 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005363 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005364 EnumDecl *Enum = ET->getDecl();
5365 if (!Enum->isCompleteDefinition())
5366 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005367
David Majnemer6a426652013-06-07 22:07:20 +00005368 unsigned NumPositive = Enum->getNumPositiveBits();
5369 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005370
David Majnemer6a426652013-06-07 22:07:20 +00005371 if (NumNegative == 0)
5372 return IntRange(NumPositive, true/*NonNegative*/);
5373 else
5374 return IntRange(std::max(NumPositive + 1, NumNegative),
5375 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005376 }
John McCall70aa5392010-01-06 05:24:50 +00005377
5378 const BuiltinType *BT = cast<BuiltinType>(T);
5379 assert(BT->isInteger());
5380
5381 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5382 }
5383
John McCall817d4af2010-11-10 23:38:19 +00005384 /// Returns the "target" range of a canonical integral type, i.e.
5385 /// the range of values expressible in the type.
5386 ///
5387 /// This matches forValueOfCanonicalType except that enums have the
5388 /// full range of their type, not the range of their enumerators.
5389 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5390 assert(T->isCanonicalUnqualified());
5391
5392 if (const VectorType *VT = dyn_cast<VectorType>(T))
5393 T = VT->getElementType().getTypePtr();
5394 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5395 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005396 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5397 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005398 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005399 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005400
5401 const BuiltinType *BT = cast<BuiltinType>(T);
5402 assert(BT->isInteger());
5403
5404 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5405 }
5406
5407 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005408 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005409 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005410 L.NonNegative && R.NonNegative);
5411 }
5412
John McCall817d4af2010-11-10 23:38:19 +00005413 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005414 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005415 return IntRange(std::min(L.Width, R.Width),
5416 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005417 }
5418};
5419
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005420static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5421 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005422 if (value.isSigned() && value.isNegative())
5423 return IntRange(value.getMinSignedBits(), false);
5424
5425 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005426 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005427
5428 // isNonNegative() just checks the sign bit without considering
5429 // signedness.
5430 return IntRange(value.getActiveBits(), true);
5431}
5432
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005433static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5434 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005435 if (result.isInt())
5436 return GetValueRange(C, result.getInt(), MaxWidth);
5437
5438 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005439 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5440 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5441 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5442 R = IntRange::join(R, El);
5443 }
John McCall70aa5392010-01-06 05:24:50 +00005444 return R;
5445 }
5446
5447 if (result.isComplexInt()) {
5448 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5449 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5450 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005451 }
5452
5453 // This can happen with lossless casts to intptr_t of "based" lvalues.
5454 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005455 // FIXME: The only reason we need to pass the type in here is to get
5456 // the sign right on this one case. It would be nice if APValue
5457 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005458 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005459 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005460}
John McCall70aa5392010-01-06 05:24:50 +00005461
Eli Friedmane6d33952013-07-08 20:20:06 +00005462static QualType GetExprType(Expr *E) {
5463 QualType Ty = E->getType();
5464 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5465 Ty = AtomicRHS->getValueType();
5466 return Ty;
5467}
5468
John McCall70aa5392010-01-06 05:24:50 +00005469/// Pseudo-evaluate the given integer expression, estimating the
5470/// range of values it might take.
5471///
5472/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005473static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005474 E = E->IgnoreParens();
5475
5476 // Try a full evaluation first.
5477 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005478 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005479 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005480
5481 // I think we only want to look through implicit casts here; if the
5482 // user has an explicit widening cast, we should treat the value as
5483 // being of the new, wider type.
5484 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005485 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005486 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5487
Eli Friedmane6d33952013-07-08 20:20:06 +00005488 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005489
John McCalle3027922010-08-25 11:45:40 +00005490 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005491
John McCall70aa5392010-01-06 05:24:50 +00005492 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005493 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005494 return OutputTypeRange;
5495
5496 IntRange SubRange
5497 = GetExprRange(C, CE->getSubExpr(),
5498 std::min(MaxWidth, OutputTypeRange.Width));
5499
5500 // Bail out if the subexpr's range is as wide as the cast type.
5501 if (SubRange.Width >= OutputTypeRange.Width)
5502 return OutputTypeRange;
5503
5504 // Otherwise, we take the smaller width, and we're non-negative if
5505 // either the output type or the subexpr is.
5506 return IntRange(SubRange.Width,
5507 SubRange.NonNegative || OutputTypeRange.NonNegative);
5508 }
5509
5510 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5511 // If we can fold the condition, just take that operand.
5512 bool CondResult;
5513 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5514 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5515 : CO->getFalseExpr(),
5516 MaxWidth);
5517
5518 // Otherwise, conservatively merge.
5519 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5520 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5521 return IntRange::join(L, R);
5522 }
5523
5524 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5525 switch (BO->getOpcode()) {
5526
5527 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005528 case BO_LAnd:
5529 case BO_LOr:
5530 case BO_LT:
5531 case BO_GT:
5532 case BO_LE:
5533 case BO_GE:
5534 case BO_EQ:
5535 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005536 return IntRange::forBoolType();
5537
John McCallc3688382011-07-13 06:35:24 +00005538 // The type of the assignments is the type of the LHS, so the RHS
5539 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005540 case BO_MulAssign:
5541 case BO_DivAssign:
5542 case BO_RemAssign:
5543 case BO_AddAssign:
5544 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005545 case BO_XorAssign:
5546 case BO_OrAssign:
5547 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005548 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005549
John McCallc3688382011-07-13 06:35:24 +00005550 // Simple assignments just pass through the RHS, which will have
5551 // been coerced to the LHS type.
5552 case BO_Assign:
5553 // TODO: bitfields?
5554 return GetExprRange(C, BO->getRHS(), MaxWidth);
5555
John McCall70aa5392010-01-06 05:24:50 +00005556 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005557 case BO_PtrMemD:
5558 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005559 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005560
John McCall2ce81ad2010-01-06 22:07:33 +00005561 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005562 case BO_And:
5563 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005564 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5565 GetExprRange(C, BO->getRHS(), MaxWidth));
5566
John McCall70aa5392010-01-06 05:24:50 +00005567 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005568 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005569 // ...except that we want to treat '1 << (blah)' as logically
5570 // positive. It's an important idiom.
5571 if (IntegerLiteral *I
5572 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5573 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005574 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005575 return IntRange(R.Width, /*NonNegative*/ true);
5576 }
5577 }
5578 // fallthrough
5579
John McCalle3027922010-08-25 11:45:40 +00005580 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005581 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005582
John McCall2ce81ad2010-01-06 22:07:33 +00005583 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005584 case BO_Shr:
5585 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005586 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5587
5588 // If the shift amount is a positive constant, drop the width by
5589 // that much.
5590 llvm::APSInt shift;
5591 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5592 shift.isNonNegative()) {
5593 unsigned zext = shift.getZExtValue();
5594 if (zext >= L.Width)
5595 L.Width = (L.NonNegative ? 0 : 1);
5596 else
5597 L.Width -= zext;
5598 }
5599
5600 return L;
5601 }
5602
5603 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005604 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005605 return GetExprRange(C, BO->getRHS(), MaxWidth);
5606
John McCall2ce81ad2010-01-06 22:07:33 +00005607 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005608 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005609 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005610 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005611 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005612
John McCall51431812011-07-14 22:39:48 +00005613 // The width of a division result is mostly determined by the size
5614 // of the LHS.
5615 case BO_Div: {
5616 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005617 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005618 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5619
5620 // If the divisor is constant, use that.
5621 llvm::APSInt divisor;
5622 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5623 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5624 if (log2 >= L.Width)
5625 L.Width = (L.NonNegative ? 0 : 1);
5626 else
5627 L.Width = std::min(L.Width - log2, MaxWidth);
5628 return L;
5629 }
5630
5631 // Otherwise, just use the LHS's width.
5632 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5633 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5634 }
5635
5636 // The result of a remainder can't be larger than the result of
5637 // either side.
5638 case BO_Rem: {
5639 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005640 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005641 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5642 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5643
5644 IntRange meet = IntRange::meet(L, R);
5645 meet.Width = std::min(meet.Width, MaxWidth);
5646 return meet;
5647 }
5648
5649 // The default behavior is okay for these.
5650 case BO_Mul:
5651 case BO_Add:
5652 case BO_Xor:
5653 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005654 break;
5655 }
5656
John McCall51431812011-07-14 22:39:48 +00005657 // The default case is to treat the operation as if it were closed
5658 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005659 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5660 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5661 return IntRange::join(L, R);
5662 }
5663
5664 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5665 switch (UO->getOpcode()) {
5666 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005667 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005668 return IntRange::forBoolType();
5669
5670 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005671 case UO_Deref:
5672 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005673 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005674
5675 default:
5676 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5677 }
5678 }
5679
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005680 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5681 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5682
John McCalld25db7e2013-05-06 21:39:12 +00005683 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005684 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005685 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005686
Eli Friedmane6d33952013-07-08 20:20:06 +00005687 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005688}
John McCall263a48b2010-01-04 23:31:57 +00005689
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005690static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005691 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005692}
5693
John McCall263a48b2010-01-04 23:31:57 +00005694/// Checks whether the given value, which currently has the given
5695/// source semantics, has the same value when coerced through the
5696/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005697static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5698 const llvm::fltSemantics &Src,
5699 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005700 llvm::APFloat truncated = value;
5701
5702 bool ignored;
5703 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5704 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5705
5706 return truncated.bitwiseIsEqual(value);
5707}
5708
5709/// Checks whether the given value, which currently has the given
5710/// source semantics, has the same value when coerced through the
5711/// target semantics.
5712///
5713/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005714static bool IsSameFloatAfterCast(const APValue &value,
5715 const llvm::fltSemantics &Src,
5716 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005717 if (value.isFloat())
5718 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5719
5720 if (value.isVector()) {
5721 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5722 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5723 return false;
5724 return true;
5725 }
5726
5727 assert(value.isComplexFloat());
5728 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5729 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5730}
5731
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005732static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005733
Ted Kremenek6274be42010-09-23 21:43:44 +00005734static bool IsZero(Sema &S, Expr *E) {
5735 // Suppress cases where we are comparing against an enum constant.
5736 if (const DeclRefExpr *DR =
5737 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5738 if (isa<EnumConstantDecl>(DR->getDecl()))
5739 return false;
5740
5741 // Suppress cases where the '0' value is expanded from a macro.
5742 if (E->getLocStart().isMacroID())
5743 return false;
5744
John McCallcc7e5bf2010-05-06 08:58:33 +00005745 llvm::APSInt Value;
5746 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5747}
5748
John McCall2551c1b2010-10-06 00:25:24 +00005749static bool HasEnumType(Expr *E) {
5750 // Strip off implicit integral promotions.
5751 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005752 if (ICE->getCastKind() != CK_IntegralCast &&
5753 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005754 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005755 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005756 }
5757
5758 return E->getType()->isEnumeralType();
5759}
5760
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005761static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005762 // Disable warning in template instantiations.
5763 if (!S.ActiveTemplateInstantiations.empty())
5764 return;
5765
John McCalle3027922010-08-25 11:45:40 +00005766 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005767 if (E->isValueDependent())
5768 return;
5769
John McCalle3027922010-08-25 11:45:40 +00005770 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005771 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005772 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005773 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005774 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005775 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005776 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005777 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005778 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005779 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005780 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005781 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005782 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005783 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005784 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005785 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5786 }
5787}
5788
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005789static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005790 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005791 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005792 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005793 // Disable warning in template instantiations.
5794 if (!S.ActiveTemplateInstantiations.empty())
5795 return;
5796
Richard Trieu0f097742014-04-04 04:13:47 +00005797 // TODO: Investigate using GetExprRange() to get tighter bounds
5798 // on the bit ranges.
5799 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005800 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5801 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005802 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5803 unsigned OtherWidth = OtherRange.Width;
5804
5805 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5806
Richard Trieu560910c2012-11-14 22:50:24 +00005807 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005808 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005809 return;
5810
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005811 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005812 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005813
Richard Trieu0f097742014-04-04 04:13:47 +00005814 // Used for diagnostic printout.
5815 enum {
5816 LiteralConstant = 0,
5817 CXXBoolLiteralTrue,
5818 CXXBoolLiteralFalse
5819 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005820
Richard Trieu0f097742014-04-04 04:13:47 +00005821 if (!OtherIsBooleanType) {
5822 QualType ConstantT = Constant->getType();
5823 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005824
Richard Trieu0f097742014-04-04 04:13:47 +00005825 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5826 return;
5827 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5828 "comparison with non-integer type");
5829
5830 bool ConstantSigned = ConstantT->isSignedIntegerType();
5831 bool CommonSigned = CommonT->isSignedIntegerType();
5832
5833 bool EqualityOnly = false;
5834
5835 if (CommonSigned) {
5836 // The common type is signed, therefore no signed to unsigned conversion.
5837 if (!OtherRange.NonNegative) {
5838 // Check that the constant is representable in type OtherT.
5839 if (ConstantSigned) {
5840 if (OtherWidth >= Value.getMinSignedBits())
5841 return;
5842 } else { // !ConstantSigned
5843 if (OtherWidth >= Value.getActiveBits() + 1)
5844 return;
5845 }
5846 } else { // !OtherSigned
5847 // Check that the constant is representable in type OtherT.
5848 // Negative values are out of range.
5849 if (ConstantSigned) {
5850 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5851 return;
5852 } else { // !ConstantSigned
5853 if (OtherWidth >= Value.getActiveBits())
5854 return;
5855 }
Richard Trieu560910c2012-11-14 22:50:24 +00005856 }
Richard Trieu0f097742014-04-04 04:13:47 +00005857 } else { // !CommonSigned
5858 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005859 if (OtherWidth >= Value.getActiveBits())
5860 return;
Craig Toppercf360162014-06-18 05:13:11 +00005861 } else { // OtherSigned
5862 assert(!ConstantSigned &&
5863 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005864 // Check to see if the constant is representable in OtherT.
5865 if (OtherWidth > Value.getActiveBits())
5866 return;
5867 // Check to see if the constant is equivalent to a negative value
5868 // cast to CommonT.
5869 if (S.Context.getIntWidth(ConstantT) ==
5870 S.Context.getIntWidth(CommonT) &&
5871 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5872 return;
5873 // The constant value rests between values that OtherT can represent
5874 // after conversion. Relational comparison still works, but equality
5875 // comparisons will be tautological.
5876 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005877 }
5878 }
Richard Trieu0f097742014-04-04 04:13:47 +00005879
5880 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5881
5882 if (op == BO_EQ || op == BO_NE) {
5883 IsTrue = op == BO_NE;
5884 } else if (EqualityOnly) {
5885 return;
5886 } else if (RhsConstant) {
5887 if (op == BO_GT || op == BO_GE)
5888 IsTrue = !PositiveConstant;
5889 else // op == BO_LT || op == BO_LE
5890 IsTrue = PositiveConstant;
5891 } else {
5892 if (op == BO_LT || op == BO_LE)
5893 IsTrue = !PositiveConstant;
5894 else // op == BO_GT || op == BO_GE
5895 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005896 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005897 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005898 // Other isKnownToHaveBooleanValue
5899 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5900 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5901 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5902
5903 static const struct LinkedConditions {
5904 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5905 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5906 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5907 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5908 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5909 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5910
5911 } TruthTable = {
5912 // Constant on LHS. | Constant on RHS. |
5913 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5914 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5915 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5916 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5917 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5918 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5919 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5920 };
5921
5922 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5923
5924 enum ConstantValue ConstVal = Zero;
5925 if (Value.isUnsigned() || Value.isNonNegative()) {
5926 if (Value == 0) {
5927 LiteralOrBoolConstant =
5928 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5929 ConstVal = Zero;
5930 } else if (Value == 1) {
5931 LiteralOrBoolConstant =
5932 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5933 ConstVal = One;
5934 } else {
5935 LiteralOrBoolConstant = LiteralConstant;
5936 ConstVal = GT_One;
5937 }
5938 } else {
5939 ConstVal = LT_Zero;
5940 }
5941
5942 CompareBoolWithConstantResult CmpRes;
5943
5944 switch (op) {
5945 case BO_LT:
5946 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5947 break;
5948 case BO_GT:
5949 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5950 break;
5951 case BO_LE:
5952 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5953 break;
5954 case BO_GE:
5955 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5956 break;
5957 case BO_EQ:
5958 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5959 break;
5960 case BO_NE:
5961 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5962 break;
5963 default:
5964 CmpRes = Unkwn;
5965 break;
5966 }
5967
5968 if (CmpRes == AFals) {
5969 IsTrue = false;
5970 } else if (CmpRes == ATrue) {
5971 IsTrue = true;
5972 } else {
5973 return;
5974 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005975 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005976
5977 // If this is a comparison to an enum constant, include that
5978 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005979 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005980 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5981 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5982
5983 SmallString<64> PrettySourceValue;
5984 llvm::raw_svector_ostream OS(PrettySourceValue);
5985 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005986 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005987 else
5988 OS << Value;
5989
Richard Trieu0f097742014-04-04 04:13:47 +00005990 S.DiagRuntimeBehavior(
5991 E->getOperatorLoc(), E,
5992 S.PDiag(diag::warn_out_of_range_compare)
5993 << OS.str() << LiteralOrBoolConstant
5994 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5995 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005996}
5997
John McCallcc7e5bf2010-05-06 08:58:33 +00005998/// Analyze the operands of the given comparison. Implements the
5999/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006000static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006001 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6002 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006003}
John McCall263a48b2010-01-04 23:31:57 +00006004
John McCallca01b222010-01-04 23:21:16 +00006005/// \brief Implements -Wsign-compare.
6006///
Richard Trieu82402a02011-09-15 21:56:47 +00006007/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006008static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006009 // The type the comparison is being performed in.
6010 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006011
6012 // Only analyze comparison operators where both sides have been converted to
6013 // the same type.
6014 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6015 return AnalyzeImpConvsInComparison(S, E);
6016
6017 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006018 if (E->isValueDependent())
6019 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006020
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006021 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6022 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006023
6024 bool IsComparisonConstant = false;
6025
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006026 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006027 // of 'true' or 'false'.
6028 if (T->isIntegralType(S.Context)) {
6029 llvm::APSInt RHSValue;
6030 bool IsRHSIntegralLiteral =
6031 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6032 llvm::APSInt LHSValue;
6033 bool IsLHSIntegralLiteral =
6034 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6035 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6036 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6037 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6038 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6039 else
6040 IsComparisonConstant =
6041 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006042 } else if (!T->hasUnsignedIntegerRepresentation())
6043 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006044
John McCallcc7e5bf2010-05-06 08:58:33 +00006045 // We don't do anything special if this isn't an unsigned integral
6046 // comparison: we're only interested in integral comparisons, and
6047 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006048 //
6049 // We also don't care about value-dependent expressions or expressions
6050 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006051 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006052 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006053
John McCallcc7e5bf2010-05-06 08:58:33 +00006054 // Check to see if one of the (unmodified) operands is of different
6055 // signedness.
6056 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006057 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6058 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006059 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006060 signedOperand = LHS;
6061 unsignedOperand = RHS;
6062 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6063 signedOperand = RHS;
6064 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006065 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006066 CheckTrivialUnsignedComparison(S, E);
6067 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006068 }
6069
John McCallcc7e5bf2010-05-06 08:58:33 +00006070 // Otherwise, calculate the effective range of the signed operand.
6071 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006072
John McCallcc7e5bf2010-05-06 08:58:33 +00006073 // Go ahead and analyze implicit conversions in the operands. Note
6074 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006075 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6076 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006077
John McCallcc7e5bf2010-05-06 08:58:33 +00006078 // If the signed range is non-negative, -Wsign-compare won't fire,
6079 // but we should still check for comparisons which are always true
6080 // or false.
6081 if (signedRange.NonNegative)
6082 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006083
6084 // For (in)equality comparisons, if the unsigned operand is a
6085 // constant which cannot collide with a overflowed signed operand,
6086 // then reinterpreting the signed operand as unsigned will not
6087 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006088 if (E->isEqualityOp()) {
6089 unsigned comparisonWidth = S.Context.getIntWidth(T);
6090 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006091
John McCallcc7e5bf2010-05-06 08:58:33 +00006092 // We should never be unable to prove that the unsigned operand is
6093 // non-negative.
6094 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6095
6096 if (unsignedRange.Width < comparisonWidth)
6097 return;
6098 }
6099
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006100 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6101 S.PDiag(diag::warn_mixed_sign_comparison)
6102 << LHS->getType() << RHS->getType()
6103 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006104}
6105
John McCall1f425642010-11-11 03:21:53 +00006106/// Analyzes an attempt to assign the given value to a bitfield.
6107///
6108/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006109static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6110 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006111 assert(Bitfield->isBitField());
6112 if (Bitfield->isInvalidDecl())
6113 return false;
6114
John McCalldeebbcf2010-11-11 05:33:51 +00006115 // White-list bool bitfields.
6116 if (Bitfield->getType()->isBooleanType())
6117 return false;
6118
Douglas Gregor789adec2011-02-04 13:09:01 +00006119 // Ignore value- or type-dependent expressions.
6120 if (Bitfield->getBitWidth()->isValueDependent() ||
6121 Bitfield->getBitWidth()->isTypeDependent() ||
6122 Init->isValueDependent() ||
6123 Init->isTypeDependent())
6124 return false;
6125
John McCall1f425642010-11-11 03:21:53 +00006126 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6127
Richard Smith5fab0c92011-12-28 19:48:30 +00006128 llvm::APSInt Value;
6129 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006130 return false;
6131
John McCall1f425642010-11-11 03:21:53 +00006132 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006133 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006134
6135 if (OriginalWidth <= FieldWidth)
6136 return false;
6137
Eli Friedmanc267a322012-01-26 23:11:39 +00006138 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006139 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006140 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006141
Eli Friedmanc267a322012-01-26 23:11:39 +00006142 // Check whether the stored value is equal to the original value.
6143 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006144 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006145 return false;
6146
Eli Friedmanc267a322012-01-26 23:11:39 +00006147 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006148 // therefore don't strictly fit into a signed bitfield of width 1.
6149 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006150 return false;
6151
John McCall1f425642010-11-11 03:21:53 +00006152 std::string PrettyValue = Value.toString(10);
6153 std::string PrettyTrunc = TruncatedValue.toString(10);
6154
6155 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6156 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6157 << Init->getSourceRange();
6158
6159 return true;
6160}
6161
John McCalld2a53122010-11-09 23:24:47 +00006162/// Analyze the given simple or compound assignment for warning-worthy
6163/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006164static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006165 // Just recurse on the LHS.
6166 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6167
6168 // We want to recurse on the RHS as normal unless we're assigning to
6169 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006170 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006171 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006172 E->getOperatorLoc())) {
6173 // Recurse, ignoring any implicit conversions on the RHS.
6174 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6175 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006176 }
6177 }
6178
6179 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6180}
6181
John McCall263a48b2010-01-04 23:31:57 +00006182/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006183static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006184 SourceLocation CContext, unsigned diag,
6185 bool pruneControlFlow = false) {
6186 if (pruneControlFlow) {
6187 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6188 S.PDiag(diag)
6189 << SourceType << T << E->getSourceRange()
6190 << SourceRange(CContext));
6191 return;
6192 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006193 S.Diag(E->getExprLoc(), diag)
6194 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6195}
6196
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006197/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006198static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006199 SourceLocation CContext, unsigned diag,
6200 bool pruneControlFlow = false) {
6201 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006202}
6203
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006204/// Diagnose an implicit cast from a literal expression. Does not warn when the
6205/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006206void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6207 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006208 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006209 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006210 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006211 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6212 T->hasUnsignedIntegerRepresentation());
6213 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006214 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006215 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006216 return;
6217
Eli Friedman07185912013-08-29 23:44:43 +00006218 // FIXME: Force the precision of the source value down so we don't print
6219 // digits which are usually useless (we don't really care here if we
6220 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6221 // would automatically print the shortest representation, but it's a bit
6222 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006223 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006224 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6225 precision = (precision * 59 + 195) / 196;
6226 Value.toString(PrettySourceValue, precision);
6227
David Blaikie9b88cc02012-05-15 17:18:27 +00006228 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006229 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6230 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6231 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006232 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006233
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006234 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006235 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6236 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006237}
6238
John McCall18a2c2c2010-11-09 22:22:12 +00006239std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6240 if (!Range.Width) return "0";
6241
6242 llvm::APSInt ValueInRange = Value;
6243 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006244 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006245 return ValueInRange.toString(10);
6246}
6247
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006248static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6249 if (!isa<ImplicitCastExpr>(Ex))
6250 return false;
6251
6252 Expr *InnerE = Ex->IgnoreParenImpCasts();
6253 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6254 const Type *Source =
6255 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6256 if (Target->isDependentType())
6257 return false;
6258
6259 const BuiltinType *FloatCandidateBT =
6260 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6261 const Type *BoolCandidateType = ToBool ? Target : Source;
6262
6263 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6264 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6265}
6266
6267void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6268 SourceLocation CC) {
6269 unsigned NumArgs = TheCall->getNumArgs();
6270 for (unsigned i = 0; i < NumArgs; ++i) {
6271 Expr *CurrA = TheCall->getArg(i);
6272 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6273 continue;
6274
6275 bool IsSwapped = ((i > 0) &&
6276 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6277 IsSwapped |= ((i < (NumArgs - 1)) &&
6278 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6279 if (IsSwapped) {
6280 // Warn on this floating-point to bool conversion.
6281 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6282 CurrA->getType(), CC,
6283 diag::warn_impcast_floating_point_to_bool);
6284 }
6285 }
6286}
6287
Richard Trieu5b993502014-10-15 03:42:06 +00006288static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6289 SourceLocation CC) {
6290 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6291 E->getExprLoc()))
6292 return;
6293
6294 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6295 const Expr::NullPointerConstantKind NullKind =
6296 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6297 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6298 return;
6299
6300 // Return if target type is a safe conversion.
6301 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6302 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6303 return;
6304
6305 SourceLocation Loc = E->getSourceRange().getBegin();
6306
6307 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6308 if (NullKind == Expr::NPCK_GNUNull) {
6309 if (Loc.isMacroID())
6310 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6311 }
6312
6313 // Only warn if the null and context location are in the same macro expansion.
6314 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6315 return;
6316
6317 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6318 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6319 << FixItHint::CreateReplacement(Loc,
6320 S.getFixItZeroLiteralForType(T, Loc));
6321}
6322
John McCallcc7e5bf2010-05-06 08:58:33 +00006323void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006324 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006325 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006326
John McCallcc7e5bf2010-05-06 08:58:33 +00006327 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6328 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6329 if (Source == Target) return;
6330 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006331
Chandler Carruthc22845a2011-07-26 05:40:03 +00006332 // If the conversion context location is invalid don't complain. We also
6333 // don't want to emit a warning if the issue occurs from the expansion of
6334 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6335 // delay this check as long as possible. Once we detect we are in that
6336 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006337 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006338 return;
6339
Richard Trieu021baa32011-09-23 20:10:00 +00006340 // Diagnose implicit casts to bool.
6341 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6342 if (isa<StringLiteral>(E))
6343 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006344 // and expressions, for instance, assert(0 && "error here"), are
6345 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006346 return DiagnoseImpCast(S, E, T, CC,
6347 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006348 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6349 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6350 // This covers the literal expressions that evaluate to Objective-C
6351 // objects.
6352 return DiagnoseImpCast(S, E, T, CC,
6353 diag::warn_impcast_objective_c_literal_to_bool);
6354 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006355 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6356 // Warn on pointer to bool conversion that is always true.
6357 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6358 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006359 }
Richard Trieu021baa32011-09-23 20:10:00 +00006360 }
John McCall263a48b2010-01-04 23:31:57 +00006361
6362 // Strip vector types.
6363 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006364 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006365 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006366 return;
John McCallacf0ee52010-10-08 02:01:28 +00006367 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006368 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006369
6370 // If the vector cast is cast between two vectors of the same size, it is
6371 // a bitcast, not a conversion.
6372 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6373 return;
John McCall263a48b2010-01-04 23:31:57 +00006374
6375 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6376 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6377 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006378 if (auto VecTy = dyn_cast<VectorType>(Target))
6379 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006380
6381 // Strip complex types.
6382 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006383 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006384 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006385 return;
6386
John McCallacf0ee52010-10-08 02:01:28 +00006387 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006388 }
John McCall263a48b2010-01-04 23:31:57 +00006389
6390 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6391 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6392 }
6393
6394 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6395 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6396
6397 // If the source is floating point...
6398 if (SourceBT && SourceBT->isFloatingPoint()) {
6399 // ...and the target is floating point...
6400 if (TargetBT && TargetBT->isFloatingPoint()) {
6401 // ...then warn if we're dropping FP rank.
6402
6403 // Builtin FP kinds are ordered by increasing FP rank.
6404 if (SourceBT->getKind() > TargetBT->getKind()) {
6405 // Don't warn about float constants that are precisely
6406 // representable in the target type.
6407 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006408 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006409 // Value might be a float, a float vector, or a float complex.
6410 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006411 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6412 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006413 return;
6414 }
6415
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006416 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006417 return;
6418
John McCallacf0ee52010-10-08 02:01:28 +00006419 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006420 }
6421 return;
6422 }
6423
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006424 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006425 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006426 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006427 return;
6428
Chandler Carruth22c7a792011-02-17 11:05:49 +00006429 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006430 // We also want to warn on, e.g., "int i = -1.234"
6431 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6432 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6433 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6434
Chandler Carruth016ef402011-04-10 08:36:24 +00006435 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6436 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006437 } else {
6438 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6439 }
6440 }
John McCall263a48b2010-01-04 23:31:57 +00006441
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006442 // If the target is bool, warn if expr is a function or method call.
6443 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6444 isa<CallExpr>(E)) {
6445 // Check last argument of function call to see if it is an
6446 // implicit cast from a type matching the type the result
6447 // is being cast to.
6448 CallExpr *CEx = cast<CallExpr>(E);
6449 unsigned NumArgs = CEx->getNumArgs();
6450 if (NumArgs > 0) {
6451 Expr *LastA = CEx->getArg(NumArgs - 1);
6452 Expr *InnerE = LastA->IgnoreParenImpCasts();
6453 const Type *InnerType =
6454 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6455 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6456 // Warn on this floating-point to bool conversion
6457 DiagnoseImpCast(S, E, T, CC,
6458 diag::warn_impcast_floating_point_to_bool);
6459 }
6460 }
6461 }
John McCall263a48b2010-01-04 23:31:57 +00006462 return;
6463 }
6464
Richard Trieu5b993502014-10-15 03:42:06 +00006465 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006466
David Blaikie9366d2b2012-06-19 21:19:06 +00006467 if (!Source->isIntegerType() || !Target->isIntegerType())
6468 return;
6469
David Blaikie7555b6a2012-05-15 16:56:36 +00006470 // TODO: remove this early return once the false positives for constant->bool
6471 // in templates, macros, etc, are reduced or removed.
6472 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6473 return;
6474
John McCallcc7e5bf2010-05-06 08:58:33 +00006475 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006476 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006477
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006478 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006479 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006480 // TODO: this should happen for bitfield stores, too.
6481 llvm::APSInt Value(32);
6482 if (E->isIntegerConstantExpr(Value, S.Context)) {
6483 if (S.SourceMgr.isInSystemMacro(CC))
6484 return;
6485
John McCall18a2c2c2010-11-09 22:22:12 +00006486 std::string PrettySourceValue = Value.toString(10);
6487 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006488
Ted Kremenek33ba9952011-10-22 02:37:33 +00006489 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6490 S.PDiag(diag::warn_impcast_integer_precision_constant)
6491 << PrettySourceValue << PrettyTargetValue
6492 << E->getType() << T << E->getSourceRange()
6493 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006494 return;
6495 }
6496
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006497 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6498 if (S.SourceMgr.isInSystemMacro(CC))
6499 return;
6500
David Blaikie9455da02012-04-12 22:40:54 +00006501 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006502 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6503 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006504 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006505 }
6506
6507 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6508 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6509 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006510
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006511 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006512 return;
6513
John McCallcc7e5bf2010-05-06 08:58:33 +00006514 unsigned DiagID = diag::warn_impcast_integer_sign;
6515
6516 // Traditionally, gcc has warned about this under -Wsign-compare.
6517 // We also want to warn about it in -Wconversion.
6518 // So if -Wconversion is off, use a completely identical diagnostic
6519 // in the sign-compare group.
6520 // The conditional-checking code will
6521 if (ICContext) {
6522 DiagID = diag::warn_impcast_integer_sign_conditional;
6523 *ICContext = true;
6524 }
6525
John McCallacf0ee52010-10-08 02:01:28 +00006526 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006527 }
6528
Douglas Gregora78f1932011-02-22 02:45:07 +00006529 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006530 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6531 // type, to give us better diagnostics.
6532 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006533 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006534 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6535 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6536 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6537 SourceType = S.Context.getTypeDeclType(Enum);
6538 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6539 }
6540 }
6541
Douglas Gregora78f1932011-02-22 02:45:07 +00006542 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6543 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006544 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6545 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006546 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006547 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006548 return;
6549
Douglas Gregor364f7db2011-03-12 00:14:31 +00006550 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006551 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006552 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006553
John McCall263a48b2010-01-04 23:31:57 +00006554 return;
6555}
6556
David Blaikie18e9ac72012-05-15 21:57:38 +00006557void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6558 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006559
6560void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006561 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006562 E = E->IgnoreParenImpCasts();
6563
6564 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006565 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006566
John McCallacf0ee52010-10-08 02:01:28 +00006567 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006568 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006569 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006570 return;
6571}
6572
David Blaikie18e9ac72012-05-15 21:57:38 +00006573void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6574 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006575 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006576
6577 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006578 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6579 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006580
6581 // If -Wconversion would have warned about either of the candidates
6582 // for a signedness conversion to the context type...
6583 if (!Suspicious) return;
6584
6585 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006586 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006587 return;
6588
John McCallcc7e5bf2010-05-06 08:58:33 +00006589 // ...then check whether it would have warned about either of the
6590 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006591 if (E->getType() == T) return;
6592
6593 Suspicious = false;
6594 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6595 E->getType(), CC, &Suspicious);
6596 if (!Suspicious)
6597 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006598 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006599}
6600
Richard Trieu65724892014-11-15 06:37:39 +00006601/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6602/// Input argument E is a logical expression.
6603static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6604 if (S.getLangOpts().Bool)
6605 return;
6606 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6607}
6608
John McCallcc7e5bf2010-05-06 08:58:33 +00006609/// AnalyzeImplicitConversions - Find and report any interesting
6610/// implicit conversions in the given expression. There are a couple
6611/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006612void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006613 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006614 Expr *E = OrigE->IgnoreParenImpCasts();
6615
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006616 if (E->isTypeDependent() || E->isValueDependent())
6617 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006618
John McCallcc7e5bf2010-05-06 08:58:33 +00006619 // For conditional operators, we analyze the arguments as if they
6620 // were being fed directly into the output.
6621 if (isa<ConditionalOperator>(E)) {
6622 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006623 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006624 return;
6625 }
6626
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006627 // Check implicit argument conversions for function calls.
6628 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6629 CheckImplicitArgumentConversions(S, Call, CC);
6630
John McCallcc7e5bf2010-05-06 08:58:33 +00006631 // Go ahead and check any implicit conversions we might have skipped.
6632 // The non-canonical typecheck is just an optimization;
6633 // CheckImplicitConversion will filter out dead implicit conversions.
6634 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006635 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006636
6637 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006638
6639 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006640 if (POE->getResultExpr())
6641 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006642 }
6643
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006644 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6645 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6646
John McCallcc7e5bf2010-05-06 08:58:33 +00006647 // Skip past explicit casts.
6648 if (isa<ExplicitCastExpr>(E)) {
6649 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006650 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006651 }
6652
John McCalld2a53122010-11-09 23:24:47 +00006653 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6654 // Do a somewhat different check with comparison operators.
6655 if (BO->isComparisonOp())
6656 return AnalyzeComparison(S, BO);
6657
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006658 // And with simple assignments.
6659 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006660 return AnalyzeAssignment(S, BO);
6661 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006662
6663 // These break the otherwise-useful invariant below. Fortunately,
6664 // we don't really need to recurse into them, because any internal
6665 // expressions should have been analyzed already when they were
6666 // built into statements.
6667 if (isa<StmtExpr>(E)) return;
6668
6669 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006670 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006671
6672 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006673 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006674 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006675 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006676 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006677 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006678 if (!ChildExpr)
6679 continue;
6680
Richard Trieu955231d2014-01-25 01:10:35 +00006681 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006682 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006683 // Ignore checking string literals that are in logical and operators.
6684 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006685 continue;
6686 AnalyzeImplicitConversions(S, ChildExpr, CC);
6687 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006688
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006689 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006690 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6691 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006692 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006693
6694 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6695 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006696 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006697 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006698
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006699 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6700 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006701 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006702}
6703
6704} // end anonymous namespace
6705
Richard Trieu3bb8b562014-02-26 02:36:06 +00006706enum {
6707 AddressOf,
6708 FunctionPointer,
6709 ArrayPointer
6710};
6711
Richard Trieuc1888e02014-06-28 23:25:37 +00006712// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6713// Returns true when emitting a warning about taking the address of a reference.
6714static bool CheckForReference(Sema &SemaRef, const Expr *E,
6715 PartialDiagnostic PD) {
6716 E = E->IgnoreParenImpCasts();
6717
6718 const FunctionDecl *FD = nullptr;
6719
6720 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6721 if (!DRE->getDecl()->getType()->isReferenceType())
6722 return false;
6723 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6724 if (!M->getMemberDecl()->getType()->isReferenceType())
6725 return false;
6726 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6727 if (!Call->getCallReturnType()->isReferenceType())
6728 return false;
6729 FD = Call->getDirectCallee();
6730 } else {
6731 return false;
6732 }
6733
6734 SemaRef.Diag(E->getExprLoc(), PD);
6735
6736 // If possible, point to location of function.
6737 if (FD) {
6738 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6739 }
6740
6741 return true;
6742}
6743
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006744// Returns true if the SourceLocation is expanded from any macro body.
6745// Returns false if the SourceLocation is invalid, is from not in a macro
6746// expansion, or is from expanded from a top-level macro argument.
6747static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6748 if (Loc.isInvalid())
6749 return false;
6750
6751 while (Loc.isMacroID()) {
6752 if (SM.isMacroBodyExpansion(Loc))
6753 return true;
6754 Loc = SM.getImmediateMacroCallerLoc(Loc);
6755 }
6756
6757 return false;
6758}
6759
Richard Trieu3bb8b562014-02-26 02:36:06 +00006760/// \brief Diagnose pointers that are always non-null.
6761/// \param E the expression containing the pointer
6762/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6763/// compared to a null pointer
6764/// \param IsEqual True when the comparison is equal to a null pointer
6765/// \param Range Extra SourceRange to highlight in the diagnostic
6766void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6767 Expr::NullPointerConstantKind NullKind,
6768 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006769 if (!E)
6770 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006771
6772 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006773 if (E->getExprLoc().isMacroID()) {
6774 const SourceManager &SM = getSourceManager();
6775 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6776 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006777 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006778 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006779 E = E->IgnoreImpCasts();
6780
6781 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6782
Richard Trieuf7432752014-06-06 21:39:26 +00006783 if (isa<CXXThisExpr>(E)) {
6784 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6785 : diag::warn_this_bool_conversion;
6786 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6787 return;
6788 }
6789
Richard Trieu3bb8b562014-02-26 02:36:06 +00006790 bool IsAddressOf = false;
6791
6792 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6793 if (UO->getOpcode() != UO_AddrOf)
6794 return;
6795 IsAddressOf = true;
6796 E = UO->getSubExpr();
6797 }
6798
Richard Trieuc1888e02014-06-28 23:25:37 +00006799 if (IsAddressOf) {
6800 unsigned DiagID = IsCompare
6801 ? diag::warn_address_of_reference_null_compare
6802 : diag::warn_address_of_reference_bool_conversion;
6803 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6804 << IsEqual;
6805 if (CheckForReference(*this, E, PD)) {
6806 return;
6807 }
6808 }
6809
Richard Trieu3bb8b562014-02-26 02:36:06 +00006810 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006811 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006812 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6813 D = R->getDecl();
6814 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6815 D = M->getMemberDecl();
6816 }
6817
6818 // Weak Decls can be null.
6819 if (!D || D->isWeak())
6820 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006821
6822 // Check for parameter decl with nonnull attribute
6823 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6824 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6825 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6826 unsigned NumArgs = FD->getNumParams();
6827 llvm::SmallBitVector AttrNonNull(NumArgs);
6828 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6829 if (!NonNull->args_size()) {
6830 AttrNonNull.set(0, NumArgs);
6831 break;
6832 }
6833 for (unsigned Val : NonNull->args()) {
6834 if (Val >= NumArgs)
6835 continue;
6836 AttrNonNull.set(Val);
6837 }
6838 }
6839 if (!AttrNonNull.empty())
6840 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00006841 if (FD->getParamDecl(i) == PV &&
6842 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006843 std::string Str;
6844 llvm::raw_string_ostream S(Str);
6845 E->printPretty(S, nullptr, getPrintingPolicy());
6846 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6847 : diag::warn_cast_nonnull_to_bool;
6848 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6849 << Range << IsEqual;
6850 return;
6851 }
6852 }
6853 }
6854
Richard Trieu3bb8b562014-02-26 02:36:06 +00006855 QualType T = D->getType();
6856 const bool IsArray = T->isArrayType();
6857 const bool IsFunction = T->isFunctionType();
6858
Richard Trieuc1888e02014-06-28 23:25:37 +00006859 // Address of function is used to silence the function warning.
6860 if (IsAddressOf && IsFunction) {
6861 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006862 }
6863
6864 // Found nothing.
6865 if (!IsAddressOf && !IsFunction && !IsArray)
6866 return;
6867
6868 // Pretty print the expression for the diagnostic.
6869 std::string Str;
6870 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006871 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006872
6873 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6874 : diag::warn_impcast_pointer_to_bool;
6875 unsigned DiagType;
6876 if (IsAddressOf)
6877 DiagType = AddressOf;
6878 else if (IsFunction)
6879 DiagType = FunctionPointer;
6880 else if (IsArray)
6881 DiagType = ArrayPointer;
6882 else
6883 llvm_unreachable("Could not determine diagnostic.");
6884 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6885 << Range << IsEqual;
6886
6887 if (!IsFunction)
6888 return;
6889
6890 // Suggest '&' to silence the function warning.
6891 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6892 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6893
6894 // Check to see if '()' fixit should be emitted.
6895 QualType ReturnType;
6896 UnresolvedSet<4> NonTemplateOverloads;
6897 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6898 if (ReturnType.isNull())
6899 return;
6900
6901 if (IsCompare) {
6902 // There are two cases here. If there is null constant, the only suggest
6903 // for a pointer return type. If the null is 0, then suggest if the return
6904 // type is a pointer or an integer type.
6905 if (!ReturnType->isPointerType()) {
6906 if (NullKind == Expr::NPCK_ZeroExpression ||
6907 NullKind == Expr::NPCK_ZeroLiteral) {
6908 if (!ReturnType->isIntegerType())
6909 return;
6910 } else {
6911 return;
6912 }
6913 }
6914 } else { // !IsCompare
6915 // For function to bool, only suggest if the function pointer has bool
6916 // return type.
6917 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6918 return;
6919 }
6920 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006921 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006922}
6923
6924
John McCallcc7e5bf2010-05-06 08:58:33 +00006925/// Diagnoses "dangerous" implicit conversions within the given
6926/// expression (which is a full expression). Implements -Wconversion
6927/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006928///
6929/// \param CC the "context" location of the implicit conversion, i.e.
6930/// the most location of the syntactic entity requiring the implicit
6931/// conversion
6932void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006933 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006934 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006935 return;
6936
6937 // Don't diagnose for value- or type-dependent expressions.
6938 if (E->isTypeDependent() || E->isValueDependent())
6939 return;
6940
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006941 // Check for array bounds violations in cases where the check isn't triggered
6942 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6943 // ArraySubscriptExpr is on the RHS of a variable initialization.
6944 CheckArrayAccess(E);
6945
John McCallacf0ee52010-10-08 02:01:28 +00006946 // This is not the right CC for (e.g.) a variable initialization.
6947 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006948}
6949
Richard Trieu65724892014-11-15 06:37:39 +00006950/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6951/// Input argument E is a logical expression.
6952void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
6953 ::CheckBoolLikeConversion(*this, E, CC);
6954}
6955
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006956/// Diagnose when expression is an integer constant expression and its evaluation
6957/// results in integer overflow
6958void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00006959 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
6960 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006961}
6962
Richard Smithc406cb72013-01-17 01:17:56 +00006963namespace {
6964/// \brief Visitor for expressions which looks for unsequenced operations on the
6965/// same object.
6966class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006967 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6968
Richard Smithc406cb72013-01-17 01:17:56 +00006969 /// \brief A tree of sequenced regions within an expression. Two regions are
6970 /// unsequenced if one is an ancestor or a descendent of the other. When we
6971 /// finish processing an expression with sequencing, such as a comma
6972 /// expression, we fold its tree nodes into its parent, since they are
6973 /// unsequenced with respect to nodes we will visit later.
6974 class SequenceTree {
6975 struct Value {
6976 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6977 unsigned Parent : 31;
6978 bool Merged : 1;
6979 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006980 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006981
6982 public:
6983 /// \brief A region within an expression which may be sequenced with respect
6984 /// to some other region.
6985 class Seq {
6986 explicit Seq(unsigned N) : Index(N) {}
6987 unsigned Index;
6988 friend class SequenceTree;
6989 public:
6990 Seq() : Index(0) {}
6991 };
6992
6993 SequenceTree() { Values.push_back(Value(0)); }
6994 Seq root() const { return Seq(0); }
6995
6996 /// \brief Create a new sequence of operations, which is an unsequenced
6997 /// subset of \p Parent. This sequence of operations is sequenced with
6998 /// respect to other children of \p Parent.
6999 Seq allocate(Seq Parent) {
7000 Values.push_back(Value(Parent.Index));
7001 return Seq(Values.size() - 1);
7002 }
7003
7004 /// \brief Merge a sequence of operations into its parent.
7005 void merge(Seq S) {
7006 Values[S.Index].Merged = true;
7007 }
7008
7009 /// \brief Determine whether two operations are unsequenced. This operation
7010 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7011 /// should have been merged into its parent as appropriate.
7012 bool isUnsequenced(Seq Cur, Seq Old) {
7013 unsigned C = representative(Cur.Index);
7014 unsigned Target = representative(Old.Index);
7015 while (C >= Target) {
7016 if (C == Target)
7017 return true;
7018 C = Values[C].Parent;
7019 }
7020 return false;
7021 }
7022
7023 private:
7024 /// \brief Pick a representative for a sequence.
7025 unsigned representative(unsigned K) {
7026 if (Values[K].Merged)
7027 // Perform path compression as we go.
7028 return Values[K].Parent = representative(Values[K].Parent);
7029 return K;
7030 }
7031 };
7032
7033 /// An object for which we can track unsequenced uses.
7034 typedef NamedDecl *Object;
7035
7036 /// Different flavors of object usage which we track. We only track the
7037 /// least-sequenced usage of each kind.
7038 enum UsageKind {
7039 /// A read of an object. Multiple unsequenced reads are OK.
7040 UK_Use,
7041 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007042 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007043 UK_ModAsValue,
7044 /// A modification of an object which is not sequenced before the value
7045 /// computation of the expression, such as n++.
7046 UK_ModAsSideEffect,
7047
7048 UK_Count = UK_ModAsSideEffect + 1
7049 };
7050
7051 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007052 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007053 Expr *Use;
7054 SequenceTree::Seq Seq;
7055 };
7056
7057 struct UsageInfo {
7058 UsageInfo() : Diagnosed(false) {}
7059 Usage Uses[UK_Count];
7060 /// Have we issued a diagnostic for this variable already?
7061 bool Diagnosed;
7062 };
7063 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7064
7065 Sema &SemaRef;
7066 /// Sequenced regions within the expression.
7067 SequenceTree Tree;
7068 /// Declaration modifications and references which we have seen.
7069 UsageInfoMap UsageMap;
7070 /// The region we are currently within.
7071 SequenceTree::Seq Region;
7072 /// Filled in with declarations which were modified as a side-effect
7073 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007074 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007075 /// Expressions to check later. We defer checking these to reduce
7076 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007077 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007078
7079 /// RAII object wrapping the visitation of a sequenced subexpression of an
7080 /// expression. At the end of this process, the side-effects of the evaluation
7081 /// become sequenced with respect to the value computation of the result, so
7082 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7083 /// UK_ModAsValue.
7084 struct SequencedSubexpression {
7085 SequencedSubexpression(SequenceChecker &Self)
7086 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7087 Self.ModAsSideEffect = &ModAsSideEffect;
7088 }
7089 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007090 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7091 MI != ME; ++MI) {
7092 UsageInfo &U = Self.UsageMap[MI->first];
7093 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7094 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7095 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007096 }
7097 Self.ModAsSideEffect = OldModAsSideEffect;
7098 }
7099
7100 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007101 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7102 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007103 };
7104
Richard Smith40238f02013-06-20 22:21:56 +00007105 /// RAII object wrapping the visitation of a subexpression which we might
7106 /// choose to evaluate as a constant. If any subexpression is evaluated and
7107 /// found to be non-constant, this allows us to suppress the evaluation of
7108 /// the outer expression.
7109 class EvaluationTracker {
7110 public:
7111 EvaluationTracker(SequenceChecker &Self)
7112 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7113 Self.EvalTracker = this;
7114 }
7115 ~EvaluationTracker() {
7116 Self.EvalTracker = Prev;
7117 if (Prev)
7118 Prev->EvalOK &= EvalOK;
7119 }
7120
7121 bool evaluate(const Expr *E, bool &Result) {
7122 if (!EvalOK || E->isValueDependent())
7123 return false;
7124 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7125 return EvalOK;
7126 }
7127
7128 private:
7129 SequenceChecker &Self;
7130 EvaluationTracker *Prev;
7131 bool EvalOK;
7132 } *EvalTracker;
7133
Richard Smithc406cb72013-01-17 01:17:56 +00007134 /// \brief Find the object which is produced by the specified expression,
7135 /// if any.
7136 Object getObject(Expr *E, bool Mod) const {
7137 E = E->IgnoreParenCasts();
7138 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7139 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7140 return getObject(UO->getSubExpr(), Mod);
7141 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7142 if (BO->getOpcode() == BO_Comma)
7143 return getObject(BO->getRHS(), Mod);
7144 if (Mod && BO->isAssignmentOp())
7145 return getObject(BO->getLHS(), Mod);
7146 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7147 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7148 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7149 return ME->getMemberDecl();
7150 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7151 // FIXME: If this is a reference, map through to its value.
7152 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007153 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007154 }
7155
7156 /// \brief Note that an object was modified or used by an expression.
7157 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7158 Usage &U = UI.Uses[UK];
7159 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7160 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7161 ModAsSideEffect->push_back(std::make_pair(O, U));
7162 U.Use = Ref;
7163 U.Seq = Region;
7164 }
7165 }
7166 /// \brief Check whether a modification or use conflicts with a prior usage.
7167 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7168 bool IsModMod) {
7169 if (UI.Diagnosed)
7170 return;
7171
7172 const Usage &U = UI.Uses[OtherKind];
7173 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7174 return;
7175
7176 Expr *Mod = U.Use;
7177 Expr *ModOrUse = Ref;
7178 if (OtherKind == UK_Use)
7179 std::swap(Mod, ModOrUse);
7180
7181 SemaRef.Diag(Mod->getExprLoc(),
7182 IsModMod ? diag::warn_unsequenced_mod_mod
7183 : diag::warn_unsequenced_mod_use)
7184 << O << SourceRange(ModOrUse->getExprLoc());
7185 UI.Diagnosed = true;
7186 }
7187
7188 void notePreUse(Object O, Expr *Use) {
7189 UsageInfo &U = UsageMap[O];
7190 // Uses conflict with other modifications.
7191 checkUsage(O, U, Use, UK_ModAsValue, false);
7192 }
7193 void notePostUse(Object O, Expr *Use) {
7194 UsageInfo &U = UsageMap[O];
7195 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7196 addUsage(U, O, Use, UK_Use);
7197 }
7198
7199 void notePreMod(Object O, Expr *Mod) {
7200 UsageInfo &U = UsageMap[O];
7201 // Modifications conflict with other modifications and with uses.
7202 checkUsage(O, U, Mod, UK_ModAsValue, true);
7203 checkUsage(O, U, Mod, UK_Use, false);
7204 }
7205 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7206 UsageInfo &U = UsageMap[O];
7207 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7208 addUsage(U, O, Use, UK);
7209 }
7210
7211public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007212 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007213 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7214 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007215 Visit(E);
7216 }
7217
7218 void VisitStmt(Stmt *S) {
7219 // Skip all statements which aren't expressions for now.
7220 }
7221
7222 void VisitExpr(Expr *E) {
7223 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007224 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007225 }
7226
7227 void VisitCastExpr(CastExpr *E) {
7228 Object O = Object();
7229 if (E->getCastKind() == CK_LValueToRValue)
7230 O = getObject(E->getSubExpr(), false);
7231
7232 if (O)
7233 notePreUse(O, E);
7234 VisitExpr(E);
7235 if (O)
7236 notePostUse(O, E);
7237 }
7238
7239 void VisitBinComma(BinaryOperator *BO) {
7240 // C++11 [expr.comma]p1:
7241 // Every value computation and side effect associated with the left
7242 // expression is sequenced before every value computation and side
7243 // effect associated with the right expression.
7244 SequenceTree::Seq LHS = Tree.allocate(Region);
7245 SequenceTree::Seq RHS = Tree.allocate(Region);
7246 SequenceTree::Seq OldRegion = Region;
7247
7248 {
7249 SequencedSubexpression SeqLHS(*this);
7250 Region = LHS;
7251 Visit(BO->getLHS());
7252 }
7253
7254 Region = RHS;
7255 Visit(BO->getRHS());
7256
7257 Region = OldRegion;
7258
7259 // Forget that LHS and RHS are sequenced. They are both unsequenced
7260 // with respect to other stuff.
7261 Tree.merge(LHS);
7262 Tree.merge(RHS);
7263 }
7264
7265 void VisitBinAssign(BinaryOperator *BO) {
7266 // The modification is sequenced after the value computation of the LHS
7267 // and RHS, so check it before inspecting the operands and update the
7268 // map afterwards.
7269 Object O = getObject(BO->getLHS(), true);
7270 if (!O)
7271 return VisitExpr(BO);
7272
7273 notePreMod(O, BO);
7274
7275 // C++11 [expr.ass]p7:
7276 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7277 // only once.
7278 //
7279 // Therefore, for a compound assignment operator, O is considered used
7280 // everywhere except within the evaluation of E1 itself.
7281 if (isa<CompoundAssignOperator>(BO))
7282 notePreUse(O, BO);
7283
7284 Visit(BO->getLHS());
7285
7286 if (isa<CompoundAssignOperator>(BO))
7287 notePostUse(O, BO);
7288
7289 Visit(BO->getRHS());
7290
Richard Smith83e37bee2013-06-26 23:16:51 +00007291 // C++11 [expr.ass]p1:
7292 // the assignment is sequenced [...] before the value computation of the
7293 // assignment expression.
7294 // C11 6.5.16/3 has no such rule.
7295 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7296 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007297 }
7298 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7299 VisitBinAssign(CAO);
7300 }
7301
7302 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7303 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7304 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7305 Object O = getObject(UO->getSubExpr(), true);
7306 if (!O)
7307 return VisitExpr(UO);
7308
7309 notePreMod(O, UO);
7310 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007311 // C++11 [expr.pre.incr]p1:
7312 // the expression ++x is equivalent to x+=1
7313 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7314 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007315 }
7316
7317 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7318 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7319 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7320 Object O = getObject(UO->getSubExpr(), true);
7321 if (!O)
7322 return VisitExpr(UO);
7323
7324 notePreMod(O, UO);
7325 Visit(UO->getSubExpr());
7326 notePostMod(O, UO, UK_ModAsSideEffect);
7327 }
7328
7329 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7330 void VisitBinLOr(BinaryOperator *BO) {
7331 // The side-effects of the LHS of an '&&' are sequenced before the
7332 // value computation of the RHS, and hence before the value computation
7333 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7334 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007335 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007336 {
7337 SequencedSubexpression Sequenced(*this);
7338 Visit(BO->getLHS());
7339 }
7340
7341 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007342 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007343 if (!Result)
7344 Visit(BO->getRHS());
7345 } else {
7346 // Check for unsequenced operations in the RHS, treating it as an
7347 // entirely separate evaluation.
7348 //
7349 // FIXME: If there are operations in the RHS which are unsequenced
7350 // with respect to operations outside the RHS, and those operations
7351 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007352 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007353 }
Richard Smithc406cb72013-01-17 01:17:56 +00007354 }
7355 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007356 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007357 {
7358 SequencedSubexpression Sequenced(*this);
7359 Visit(BO->getLHS());
7360 }
7361
7362 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007363 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007364 if (Result)
7365 Visit(BO->getRHS());
7366 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007367 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007368 }
Richard Smithc406cb72013-01-17 01:17:56 +00007369 }
7370
7371 // Only visit the condition, unless we can be sure which subexpression will
7372 // be chosen.
7373 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007374 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007375 {
7376 SequencedSubexpression Sequenced(*this);
7377 Visit(CO->getCond());
7378 }
Richard Smithc406cb72013-01-17 01:17:56 +00007379
7380 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007381 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007382 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007383 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007384 WorkList.push_back(CO->getTrueExpr());
7385 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007386 }
Richard Smithc406cb72013-01-17 01:17:56 +00007387 }
7388
Richard Smithe3dbfe02013-06-30 10:40:20 +00007389 void VisitCallExpr(CallExpr *CE) {
7390 // C++11 [intro.execution]p15:
7391 // When calling a function [...], every value computation and side effect
7392 // associated with any argument expression, or with the postfix expression
7393 // designating the called function, is sequenced before execution of every
7394 // expression or statement in the body of the function [and thus before
7395 // the value computation of its result].
7396 SequencedSubexpression Sequenced(*this);
7397 Base::VisitCallExpr(CE);
7398
7399 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7400 }
7401
Richard Smithc406cb72013-01-17 01:17:56 +00007402 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007403 // This is a call, so all subexpressions are sequenced before the result.
7404 SequencedSubexpression Sequenced(*this);
7405
Richard Smithc406cb72013-01-17 01:17:56 +00007406 if (!CCE->isListInitialization())
7407 return VisitExpr(CCE);
7408
7409 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007410 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007411 SequenceTree::Seq Parent = Region;
7412 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7413 E = CCE->arg_end();
7414 I != E; ++I) {
7415 Region = Tree.allocate(Parent);
7416 Elts.push_back(Region);
7417 Visit(*I);
7418 }
7419
7420 // Forget that the initializers are sequenced.
7421 Region = Parent;
7422 for (unsigned I = 0; I < Elts.size(); ++I)
7423 Tree.merge(Elts[I]);
7424 }
7425
7426 void VisitInitListExpr(InitListExpr *ILE) {
7427 if (!SemaRef.getLangOpts().CPlusPlus11)
7428 return VisitExpr(ILE);
7429
7430 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007431 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007432 SequenceTree::Seq Parent = Region;
7433 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7434 Expr *E = ILE->getInit(I);
7435 if (!E) continue;
7436 Region = Tree.allocate(Parent);
7437 Elts.push_back(Region);
7438 Visit(E);
7439 }
7440
7441 // Forget that the initializers are sequenced.
7442 Region = Parent;
7443 for (unsigned I = 0; I < Elts.size(); ++I)
7444 Tree.merge(Elts[I]);
7445 }
7446};
7447}
7448
7449void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007450 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007451 WorkList.push_back(E);
7452 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007453 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007454 SequenceChecker(*this, Item, WorkList);
7455 }
Richard Smithc406cb72013-01-17 01:17:56 +00007456}
7457
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007458void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7459 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007460 CheckImplicitConversions(E, CheckLoc);
7461 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007462 if (!IsConstexpr && !E->isValueDependent())
7463 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007464}
7465
John McCall1f425642010-11-11 03:21:53 +00007466void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7467 FieldDecl *BitField,
7468 Expr *Init) {
7469 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7470}
7471
Mike Stump0c2ec772010-01-21 03:59:47 +00007472/// CheckParmsForFunctionDef - Check that the parameters of the given
7473/// function are appropriate for the definition of a function. This
7474/// takes care of any checks that cannot be performed on the
7475/// declaration itself, e.g., that the types of each of the function
7476/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007477bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7478 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007479 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007480 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007481 for (; P != PEnd; ++P) {
7482 ParmVarDecl *Param = *P;
7483
Mike Stump0c2ec772010-01-21 03:59:47 +00007484 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7485 // function declarator that is part of a function definition of
7486 // that function shall not have incomplete type.
7487 //
7488 // This is also C++ [dcl.fct]p6.
7489 if (!Param->isInvalidDecl() &&
7490 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007491 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007492 Param->setInvalidDecl();
7493 HasInvalidParm = true;
7494 }
7495
7496 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7497 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007498 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007499 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007500 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007501 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007502 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007503
7504 // C99 6.7.5.3p12:
7505 // If the function declarator is not part of a definition of that
7506 // function, parameters may have incomplete type and may use the [*]
7507 // notation in their sequences of declarator specifiers to specify
7508 // variable length array types.
7509 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007510 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007511 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007512 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007513 // information is added for it.
7514 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007515 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007516 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007517 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007518 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007519
7520 // MSVC destroys objects passed by value in the callee. Therefore a
7521 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007522 // object's destructor. However, we don't perform any direct access check
7523 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007524 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7525 .getCXXABI()
7526 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007527 if (!Param->isInvalidDecl()) {
7528 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7529 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7530 if (!ClassDecl->isInvalidDecl() &&
7531 !ClassDecl->hasIrrelevantDestructor() &&
7532 !ClassDecl->isDependentContext()) {
7533 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7534 MarkFunctionReferenced(Param->getLocation(), Destructor);
7535 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7536 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007537 }
7538 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007539 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007540 }
7541
7542 return HasInvalidParm;
7543}
John McCall2b5c1b22010-08-12 21:44:57 +00007544
7545/// CheckCastAlign - Implements -Wcast-align, which warns when a
7546/// pointer cast increases the alignment requirements.
7547void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7548 // This is actually a lot of work to potentially be doing on every
7549 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007550 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007551 return;
7552
7553 // Ignore dependent types.
7554 if (T->isDependentType() || Op->getType()->isDependentType())
7555 return;
7556
7557 // Require that the destination be a pointer type.
7558 const PointerType *DestPtr = T->getAs<PointerType>();
7559 if (!DestPtr) return;
7560
7561 // If the destination has alignment 1, we're done.
7562 QualType DestPointee = DestPtr->getPointeeType();
7563 if (DestPointee->isIncompleteType()) return;
7564 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7565 if (DestAlign.isOne()) return;
7566
7567 // Require that the source be a pointer type.
7568 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7569 if (!SrcPtr) return;
7570 QualType SrcPointee = SrcPtr->getPointeeType();
7571
7572 // Whitelist casts from cv void*. We already implicitly
7573 // whitelisted casts to cv void*, since they have alignment 1.
7574 // Also whitelist casts involving incomplete types, which implicitly
7575 // includes 'void'.
7576 if (SrcPointee->isIncompleteType()) return;
7577
7578 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7579 if (SrcAlign >= DestAlign) return;
7580
7581 Diag(TRange.getBegin(), diag::warn_cast_align)
7582 << Op->getType() << T
7583 << static_cast<unsigned>(SrcAlign.getQuantity())
7584 << static_cast<unsigned>(DestAlign.getQuantity())
7585 << TRange << Op->getSourceRange();
7586}
7587
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007588static const Type* getElementType(const Expr *BaseExpr) {
7589 const Type* EltType = BaseExpr->getType().getTypePtr();
7590 if (EltType->isAnyPointerType())
7591 return EltType->getPointeeType().getTypePtr();
7592 else if (EltType->isArrayType())
7593 return EltType->getBaseElementTypeUnsafe();
7594 return EltType;
7595}
7596
Chandler Carruth28389f02011-08-05 09:10:50 +00007597/// \brief Check whether this array fits the idiom of a size-one tail padded
7598/// array member of a struct.
7599///
7600/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7601/// commonly used to emulate flexible arrays in C89 code.
7602static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7603 const NamedDecl *ND) {
7604 if (Size != 1 || !ND) return false;
7605
7606 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7607 if (!FD) return false;
7608
7609 // Don't consider sizes resulting from macro expansions or template argument
7610 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007611
7612 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007613 while (TInfo) {
7614 TypeLoc TL = TInfo->getTypeLoc();
7615 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007616 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7617 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007618 TInfo = TDL->getTypeSourceInfo();
7619 continue;
7620 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007621 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7622 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007623 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7624 return false;
7625 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007626 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007627 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007628
7629 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007630 if (!RD) return false;
7631 if (RD->isUnion()) return false;
7632 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7633 if (!CRD->isStandardLayout()) return false;
7634 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007635
Benjamin Kramer8c543672011-08-06 03:04:42 +00007636 // See if this is the last field decl in the record.
7637 const Decl *D = FD;
7638 while ((D = D->getNextDeclInContext()))
7639 if (isa<FieldDecl>(D))
7640 return false;
7641 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007642}
7643
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007644void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007645 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007646 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007647 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007648 if (IndexExpr->isValueDependent())
7649 return;
7650
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007651 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007652 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007653 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007654 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007655 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007656 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007657
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007658 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007659 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007660 return;
Richard Smith13f67182011-12-16 19:31:14 +00007661 if (IndexNegated)
7662 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007663
Craig Topperc3ec1492014-05-26 06:22:03 +00007664 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007665 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7666 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007667 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007668 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007669
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007670 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007671 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007672 if (!size.isStrictlyPositive())
7673 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007674
7675 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007676 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007677 // Make sure we're comparing apples to apples when comparing index to size
7678 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7679 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007680 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007681 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007682 if (ptrarith_typesize != array_typesize) {
7683 // There's a cast to a different size type involved
7684 uint64_t ratio = array_typesize / ptrarith_typesize;
7685 // TODO: Be smarter about handling cases where array_typesize is not a
7686 // multiple of ptrarith_typesize
7687 if (ptrarith_typesize * ratio == array_typesize)
7688 size *= llvm::APInt(size.getBitWidth(), ratio);
7689 }
7690 }
7691
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007692 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007693 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007694 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007695 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007696
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007697 // For array subscripting the index must be less than size, but for pointer
7698 // arithmetic also allow the index (offset) to be equal to size since
7699 // computing the next address after the end of the array is legal and
7700 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007701 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007702 return;
7703
7704 // Also don't warn for arrays of size 1 which are members of some
7705 // structure. These are often used to approximate flexible arrays in C89
7706 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007707 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007708 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007709
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007710 // Suppress the warning if the subscript expression (as identified by the
7711 // ']' location) and the index expression are both from macro expansions
7712 // within a system header.
7713 if (ASE) {
7714 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7715 ASE->getRBracketLoc());
7716 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7717 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7718 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007719 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007720 return;
7721 }
7722 }
7723
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007724 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007725 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007726 DiagID = diag::warn_array_index_exceeds_bounds;
7727
7728 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7729 PDiag(DiagID) << index.toString(10, true)
7730 << size.toString(10, true)
7731 << (unsigned)size.getLimitedValue(~0U)
7732 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007733 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007734 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007735 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007736 DiagID = diag::warn_ptr_arith_precedes_bounds;
7737 if (index.isNegative()) index = -index;
7738 }
7739
7740 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7741 PDiag(DiagID) << index.toString(10, true)
7742 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007743 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007744
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007745 if (!ND) {
7746 // Try harder to find a NamedDecl to point at in the note.
7747 while (const ArraySubscriptExpr *ASE =
7748 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7749 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7750 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7751 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7752 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7753 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7754 }
7755
Chandler Carruth1af88f12011-02-17 21:10:52 +00007756 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007757 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7758 PDiag(diag::note_array_index_out_of_bounds)
7759 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007760}
7761
Ted Kremenekdf26df72011-03-01 18:41:00 +00007762void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007763 int AllowOnePastEnd = 0;
7764 while (expr) {
7765 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007766 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007767 case Stmt::ArraySubscriptExprClass: {
7768 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007769 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007770 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007771 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007772 }
7773 case Stmt::UnaryOperatorClass: {
7774 // Only unwrap the * and & unary operators
7775 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7776 expr = UO->getSubExpr();
7777 switch (UO->getOpcode()) {
7778 case UO_AddrOf:
7779 AllowOnePastEnd++;
7780 break;
7781 case UO_Deref:
7782 AllowOnePastEnd--;
7783 break;
7784 default:
7785 return;
7786 }
7787 break;
7788 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007789 case Stmt::ConditionalOperatorClass: {
7790 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7791 if (const Expr *lhs = cond->getLHS())
7792 CheckArrayAccess(lhs);
7793 if (const Expr *rhs = cond->getRHS())
7794 CheckArrayAccess(rhs);
7795 return;
7796 }
7797 default:
7798 return;
7799 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007800 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007801}
John McCall31168b02011-06-15 23:02:42 +00007802
7803//===--- CHECK: Objective-C retain cycles ----------------------------------//
7804
7805namespace {
7806 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007807 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007808 VarDecl *Variable;
7809 SourceRange Range;
7810 SourceLocation Loc;
7811 bool Indirect;
7812
7813 void setLocsFrom(Expr *e) {
7814 Loc = e->getExprLoc();
7815 Range = e->getSourceRange();
7816 }
7817 };
7818}
7819
7820/// Consider whether capturing the given variable can possibly lead to
7821/// a retain cycle.
7822static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007823 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007824 // lifetime. In MRR, it's captured strongly if the variable is
7825 // __block and has an appropriate type.
7826 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7827 return false;
7828
7829 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007830 if (ref)
7831 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007832 return true;
7833}
7834
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007835static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007836 while (true) {
7837 e = e->IgnoreParens();
7838 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7839 switch (cast->getCastKind()) {
7840 case CK_BitCast:
7841 case CK_LValueBitCast:
7842 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007843 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007844 e = cast->getSubExpr();
7845 continue;
7846
John McCall31168b02011-06-15 23:02:42 +00007847 default:
7848 return false;
7849 }
7850 }
7851
7852 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7853 ObjCIvarDecl *ivar = ref->getDecl();
7854 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7855 return false;
7856
7857 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007858 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007859 return false;
7860
7861 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7862 owner.Indirect = true;
7863 return true;
7864 }
7865
7866 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7867 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7868 if (!var) return false;
7869 return considerVariable(var, ref, owner);
7870 }
7871
John McCall31168b02011-06-15 23:02:42 +00007872 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7873 if (member->isArrow()) return false;
7874
7875 // Don't count this as an indirect ownership.
7876 e = member->getBase();
7877 continue;
7878 }
7879
John McCallfe96e0b2011-11-06 09:01:30 +00007880 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7881 // Only pay attention to pseudo-objects on property references.
7882 ObjCPropertyRefExpr *pre
7883 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7884 ->IgnoreParens());
7885 if (!pre) return false;
7886 if (pre->isImplicitProperty()) return false;
7887 ObjCPropertyDecl *property = pre->getExplicitProperty();
7888 if (!property->isRetaining() &&
7889 !(property->getPropertyIvarDecl() &&
7890 property->getPropertyIvarDecl()->getType()
7891 .getObjCLifetime() == Qualifiers::OCL_Strong))
7892 return false;
7893
7894 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007895 if (pre->isSuperReceiver()) {
7896 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7897 if (!owner.Variable)
7898 return false;
7899 owner.Loc = pre->getLocation();
7900 owner.Range = pre->getSourceRange();
7901 return true;
7902 }
John McCallfe96e0b2011-11-06 09:01:30 +00007903 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7904 ->getSourceExpr());
7905 continue;
7906 }
7907
John McCall31168b02011-06-15 23:02:42 +00007908 // Array ivars?
7909
7910 return false;
7911 }
7912}
7913
7914namespace {
7915 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7916 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7917 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007918 Context(Context), Variable(variable), Capturer(nullptr),
7919 VarWillBeReased(false) {}
7920 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007921 VarDecl *Variable;
7922 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007923 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007924
7925 void VisitDeclRefExpr(DeclRefExpr *ref) {
7926 if (ref->getDecl() == Variable && !Capturer)
7927 Capturer = ref;
7928 }
7929
John McCall31168b02011-06-15 23:02:42 +00007930 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7931 if (Capturer) return;
7932 Visit(ref->getBase());
7933 if (Capturer && ref->isFreeIvar())
7934 Capturer = ref;
7935 }
7936
7937 void VisitBlockExpr(BlockExpr *block) {
7938 // Look inside nested blocks
7939 if (block->getBlockDecl()->capturesVariable(Variable))
7940 Visit(block->getBlockDecl()->getBody());
7941 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007942
7943 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7944 if (Capturer) return;
7945 if (OVE->getSourceExpr())
7946 Visit(OVE->getSourceExpr());
7947 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007948 void VisitBinaryOperator(BinaryOperator *BinOp) {
7949 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7950 return;
7951 Expr *LHS = BinOp->getLHS();
7952 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7953 if (DRE->getDecl() != Variable)
7954 return;
7955 if (Expr *RHS = BinOp->getRHS()) {
7956 RHS = RHS->IgnoreParenCasts();
7957 llvm::APSInt Value;
7958 VarWillBeReased =
7959 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7960 }
7961 }
7962 }
John McCall31168b02011-06-15 23:02:42 +00007963 };
7964}
7965
7966/// Check whether the given argument is a block which captures a
7967/// variable.
7968static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7969 assert(owner.Variable && owner.Loc.isValid());
7970
7971 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007972
7973 // Look through [^{...} copy] and Block_copy(^{...}).
7974 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7975 Selector Cmd = ME->getSelector();
7976 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7977 e = ME->getInstanceReceiver();
7978 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007979 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007980 e = e->IgnoreParenCasts();
7981 }
7982 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7983 if (CE->getNumArgs() == 1) {
7984 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007985 if (Fn) {
7986 const IdentifierInfo *FnI = Fn->getIdentifier();
7987 if (FnI && FnI->isStr("_Block_copy")) {
7988 e = CE->getArg(0)->IgnoreParenCasts();
7989 }
7990 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007991 }
7992 }
7993
John McCall31168b02011-06-15 23:02:42 +00007994 BlockExpr *block = dyn_cast<BlockExpr>(e);
7995 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007996 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007997
7998 FindCaptureVisitor visitor(S.Context, owner.Variable);
7999 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008000 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008001}
8002
8003static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8004 RetainCycleOwner &owner) {
8005 assert(capturer);
8006 assert(owner.Variable && owner.Loc.isValid());
8007
8008 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8009 << owner.Variable << capturer->getSourceRange();
8010 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8011 << owner.Indirect << owner.Range;
8012}
8013
8014/// Check for a keyword selector that starts with the word 'add' or
8015/// 'set'.
8016static bool isSetterLikeSelector(Selector sel) {
8017 if (sel.isUnarySelector()) return false;
8018
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008019 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008020 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008021 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008022 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008023 else if (str.startswith("add")) {
8024 // Specially whitelist 'addOperationWithBlock:'.
8025 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8026 return false;
8027 str = str.substr(3);
8028 }
John McCall31168b02011-06-15 23:02:42 +00008029 else
8030 return false;
8031
8032 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008033 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008034}
8035
8036/// Check a message send to see if it's likely to cause a retain cycle.
8037void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8038 // Only check instance methods whose selector looks like a setter.
8039 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8040 return;
8041
8042 // Try to find a variable that the receiver is strongly owned by.
8043 RetainCycleOwner owner;
8044 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008045 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008046 return;
8047 } else {
8048 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8049 owner.Variable = getCurMethodDecl()->getSelfDecl();
8050 owner.Loc = msg->getSuperLoc();
8051 owner.Range = msg->getSuperLoc();
8052 }
8053
8054 // Check whether the receiver is captured by any of the arguments.
8055 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8056 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8057 return diagnoseRetainCycle(*this, capturer, owner);
8058}
8059
8060/// Check a property assign to see if it's likely to cause a retain cycle.
8061void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8062 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008063 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008064 return;
8065
8066 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8067 diagnoseRetainCycle(*this, capturer, owner);
8068}
8069
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008070void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8071 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008072 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008073 return;
8074
8075 // Because we don't have an expression for the variable, we have to set the
8076 // location explicitly here.
8077 Owner.Loc = Var->getLocation();
8078 Owner.Range = Var->getSourceRange();
8079
8080 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8081 diagnoseRetainCycle(*this, Capturer, Owner);
8082}
8083
Ted Kremenek9304da92012-12-21 08:04:28 +00008084static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8085 Expr *RHS, bool isProperty) {
8086 // Check if RHS is an Objective-C object literal, which also can get
8087 // immediately zapped in a weak reference. Note that we explicitly
8088 // allow ObjCStringLiterals, since those are designed to never really die.
8089 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008090
Ted Kremenek64873352012-12-21 22:46:35 +00008091 // This enum needs to match with the 'select' in
8092 // warn_objc_arc_literal_assign (off-by-1).
8093 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8094 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8095 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008096
8097 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008098 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008099 << (isProperty ? 0 : 1)
8100 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008101
8102 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008103}
8104
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008105static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8106 Qualifiers::ObjCLifetime LT,
8107 Expr *RHS, bool isProperty) {
8108 // Strip off any implicit cast added to get to the one ARC-specific.
8109 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8110 if (cast->getCastKind() == CK_ARCConsumeObject) {
8111 S.Diag(Loc, diag::warn_arc_retained_assign)
8112 << (LT == Qualifiers::OCL_ExplicitNone)
8113 << (isProperty ? 0 : 1)
8114 << RHS->getSourceRange();
8115 return true;
8116 }
8117 RHS = cast->getSubExpr();
8118 }
8119
8120 if (LT == Qualifiers::OCL_Weak &&
8121 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8122 return true;
8123
8124 return false;
8125}
8126
Ted Kremenekb36234d2012-12-21 08:04:20 +00008127bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8128 QualType LHS, Expr *RHS) {
8129 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8130
8131 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8132 return false;
8133
8134 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8135 return true;
8136
8137 return false;
8138}
8139
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008140void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8141 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008142 QualType LHSType;
8143 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008144 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008145 ObjCPropertyRefExpr *PRE
8146 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8147 if (PRE && !PRE->isImplicitProperty()) {
8148 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8149 if (PD)
8150 LHSType = PD->getType();
8151 }
8152
8153 if (LHSType.isNull())
8154 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008155
8156 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8157
8158 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008159 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008160 getCurFunction()->markSafeWeakUse(LHS);
8161 }
8162
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008163 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8164 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008165
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008166 // FIXME. Check for other life times.
8167 if (LT != Qualifiers::OCL_None)
8168 return;
8169
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008170 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008171 if (PRE->isImplicitProperty())
8172 return;
8173 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8174 if (!PD)
8175 return;
8176
Bill Wendling44426052012-12-20 19:22:21 +00008177 unsigned Attributes = PD->getPropertyAttributes();
8178 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008179 // when 'assign' attribute was not explicitly specified
8180 // by user, ignore it and rely on property type itself
8181 // for lifetime info.
8182 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8183 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8184 LHSType->isObjCRetainableType())
8185 return;
8186
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008187 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008188 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008189 Diag(Loc, diag::warn_arc_retained_property_assign)
8190 << RHS->getSourceRange();
8191 return;
8192 }
8193 RHS = cast->getSubExpr();
8194 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008195 }
Bill Wendling44426052012-12-20 19:22:21 +00008196 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008197 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8198 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008199 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008200 }
8201}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008202
8203//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8204
8205namespace {
8206bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8207 SourceLocation StmtLoc,
8208 const NullStmt *Body) {
8209 // Do not warn if the body is a macro that expands to nothing, e.g:
8210 //
8211 // #define CALL(x)
8212 // if (condition)
8213 // CALL(0);
8214 //
8215 if (Body->hasLeadingEmptyMacro())
8216 return false;
8217
8218 // Get line numbers of statement and body.
8219 bool StmtLineInvalid;
8220 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8221 &StmtLineInvalid);
8222 if (StmtLineInvalid)
8223 return false;
8224
8225 bool BodyLineInvalid;
8226 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8227 &BodyLineInvalid);
8228 if (BodyLineInvalid)
8229 return false;
8230
8231 // Warn if null statement and body are on the same line.
8232 if (StmtLine != BodyLine)
8233 return false;
8234
8235 return true;
8236}
8237} // Unnamed namespace
8238
8239void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8240 const Stmt *Body,
8241 unsigned DiagID) {
8242 // Since this is a syntactic check, don't emit diagnostic for template
8243 // instantiations, this just adds noise.
8244 if (CurrentInstantiationScope)
8245 return;
8246
8247 // The body should be a null statement.
8248 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8249 if (!NBody)
8250 return;
8251
8252 // Do the usual checks.
8253 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8254 return;
8255
8256 Diag(NBody->getSemiLoc(), DiagID);
8257 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8258}
8259
8260void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8261 const Stmt *PossibleBody) {
8262 assert(!CurrentInstantiationScope); // Ensured by caller
8263
8264 SourceLocation StmtLoc;
8265 const Stmt *Body;
8266 unsigned DiagID;
8267 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8268 StmtLoc = FS->getRParenLoc();
8269 Body = FS->getBody();
8270 DiagID = diag::warn_empty_for_body;
8271 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8272 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8273 Body = WS->getBody();
8274 DiagID = diag::warn_empty_while_body;
8275 } else
8276 return; // Neither `for' nor `while'.
8277
8278 // The body should be a null statement.
8279 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8280 if (!NBody)
8281 return;
8282
8283 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008284 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008285 return;
8286
8287 // Do the usual checks.
8288 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8289 return;
8290
8291 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8292 // noise level low, emit diagnostics only if for/while is followed by a
8293 // CompoundStmt, e.g.:
8294 // for (int i = 0; i < n; i++);
8295 // {
8296 // a(i);
8297 // }
8298 // or if for/while is followed by a statement with more indentation
8299 // than for/while itself:
8300 // for (int i = 0; i < n; i++);
8301 // a(i);
8302 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8303 if (!ProbableTypo) {
8304 bool BodyColInvalid;
8305 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8306 PossibleBody->getLocStart(),
8307 &BodyColInvalid);
8308 if (BodyColInvalid)
8309 return;
8310
8311 bool StmtColInvalid;
8312 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8313 S->getLocStart(),
8314 &StmtColInvalid);
8315 if (StmtColInvalid)
8316 return;
8317
8318 if (BodyCol > StmtCol)
8319 ProbableTypo = true;
8320 }
8321
8322 if (ProbableTypo) {
8323 Diag(NBody->getSemiLoc(), DiagID);
8324 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8325 }
8326}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008327
8328//===--- Layout compatibility ----------------------------------------------//
8329
8330namespace {
8331
8332bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8333
8334/// \brief Check if two enumeration types are layout-compatible.
8335bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8336 // C++11 [dcl.enum] p8:
8337 // Two enumeration types are layout-compatible if they have the same
8338 // underlying type.
8339 return ED1->isComplete() && ED2->isComplete() &&
8340 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8341}
8342
8343/// \brief Check if two fields are layout-compatible.
8344bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8345 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8346 return false;
8347
8348 if (Field1->isBitField() != Field2->isBitField())
8349 return false;
8350
8351 if (Field1->isBitField()) {
8352 // Make sure that the bit-fields are the same length.
8353 unsigned Bits1 = Field1->getBitWidthValue(C);
8354 unsigned Bits2 = Field2->getBitWidthValue(C);
8355
8356 if (Bits1 != Bits2)
8357 return false;
8358 }
8359
8360 return true;
8361}
8362
8363/// \brief Check if two standard-layout structs are layout-compatible.
8364/// (C++11 [class.mem] p17)
8365bool isLayoutCompatibleStruct(ASTContext &C,
8366 RecordDecl *RD1,
8367 RecordDecl *RD2) {
8368 // If both records are C++ classes, check that base classes match.
8369 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8370 // If one of records is a CXXRecordDecl we are in C++ mode,
8371 // thus the other one is a CXXRecordDecl, too.
8372 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8373 // Check number of base classes.
8374 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8375 return false;
8376
8377 // Check the base classes.
8378 for (CXXRecordDecl::base_class_const_iterator
8379 Base1 = D1CXX->bases_begin(),
8380 BaseEnd1 = D1CXX->bases_end(),
8381 Base2 = D2CXX->bases_begin();
8382 Base1 != BaseEnd1;
8383 ++Base1, ++Base2) {
8384 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8385 return false;
8386 }
8387 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8388 // If only RD2 is a C++ class, it should have zero base classes.
8389 if (D2CXX->getNumBases() > 0)
8390 return false;
8391 }
8392
8393 // Check the fields.
8394 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8395 Field2End = RD2->field_end(),
8396 Field1 = RD1->field_begin(),
8397 Field1End = RD1->field_end();
8398 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8399 if (!isLayoutCompatible(C, *Field1, *Field2))
8400 return false;
8401 }
8402 if (Field1 != Field1End || Field2 != Field2End)
8403 return false;
8404
8405 return true;
8406}
8407
8408/// \brief Check if two standard-layout unions are layout-compatible.
8409/// (C++11 [class.mem] p18)
8410bool isLayoutCompatibleUnion(ASTContext &C,
8411 RecordDecl *RD1,
8412 RecordDecl *RD2) {
8413 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008414 for (auto *Field2 : RD2->fields())
8415 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008416
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008417 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008418 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8419 I = UnmatchedFields.begin(),
8420 E = UnmatchedFields.end();
8421
8422 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008423 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008424 bool Result = UnmatchedFields.erase(*I);
8425 (void) Result;
8426 assert(Result);
8427 break;
8428 }
8429 }
8430 if (I == E)
8431 return false;
8432 }
8433
8434 return UnmatchedFields.empty();
8435}
8436
8437bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8438 if (RD1->isUnion() != RD2->isUnion())
8439 return false;
8440
8441 if (RD1->isUnion())
8442 return isLayoutCompatibleUnion(C, RD1, RD2);
8443 else
8444 return isLayoutCompatibleStruct(C, RD1, RD2);
8445}
8446
8447/// \brief Check if two types are layout-compatible in C++11 sense.
8448bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8449 if (T1.isNull() || T2.isNull())
8450 return false;
8451
8452 // C++11 [basic.types] p11:
8453 // If two types T1 and T2 are the same type, then T1 and T2 are
8454 // layout-compatible types.
8455 if (C.hasSameType(T1, T2))
8456 return true;
8457
8458 T1 = T1.getCanonicalType().getUnqualifiedType();
8459 T2 = T2.getCanonicalType().getUnqualifiedType();
8460
8461 const Type::TypeClass TC1 = T1->getTypeClass();
8462 const Type::TypeClass TC2 = T2->getTypeClass();
8463
8464 if (TC1 != TC2)
8465 return false;
8466
8467 if (TC1 == Type::Enum) {
8468 return isLayoutCompatible(C,
8469 cast<EnumType>(T1)->getDecl(),
8470 cast<EnumType>(T2)->getDecl());
8471 } else if (TC1 == Type::Record) {
8472 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8473 return false;
8474
8475 return isLayoutCompatible(C,
8476 cast<RecordType>(T1)->getDecl(),
8477 cast<RecordType>(T2)->getDecl());
8478 }
8479
8480 return false;
8481}
8482}
8483
8484//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8485
8486namespace {
8487/// \brief Given a type tag expression find the type tag itself.
8488///
8489/// \param TypeExpr Type tag expression, as it appears in user's code.
8490///
8491/// \param VD Declaration of an identifier that appears in a type tag.
8492///
8493/// \param MagicValue Type tag magic value.
8494bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8495 const ValueDecl **VD, uint64_t *MagicValue) {
8496 while(true) {
8497 if (!TypeExpr)
8498 return false;
8499
8500 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8501
8502 switch (TypeExpr->getStmtClass()) {
8503 case Stmt::UnaryOperatorClass: {
8504 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8505 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8506 TypeExpr = UO->getSubExpr();
8507 continue;
8508 }
8509 return false;
8510 }
8511
8512 case Stmt::DeclRefExprClass: {
8513 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8514 *VD = DRE->getDecl();
8515 return true;
8516 }
8517
8518 case Stmt::IntegerLiteralClass: {
8519 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8520 llvm::APInt MagicValueAPInt = IL->getValue();
8521 if (MagicValueAPInt.getActiveBits() <= 64) {
8522 *MagicValue = MagicValueAPInt.getZExtValue();
8523 return true;
8524 } else
8525 return false;
8526 }
8527
8528 case Stmt::BinaryConditionalOperatorClass:
8529 case Stmt::ConditionalOperatorClass: {
8530 const AbstractConditionalOperator *ACO =
8531 cast<AbstractConditionalOperator>(TypeExpr);
8532 bool Result;
8533 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8534 if (Result)
8535 TypeExpr = ACO->getTrueExpr();
8536 else
8537 TypeExpr = ACO->getFalseExpr();
8538 continue;
8539 }
8540 return false;
8541 }
8542
8543 case Stmt::BinaryOperatorClass: {
8544 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8545 if (BO->getOpcode() == BO_Comma) {
8546 TypeExpr = BO->getRHS();
8547 continue;
8548 }
8549 return false;
8550 }
8551
8552 default:
8553 return false;
8554 }
8555 }
8556}
8557
8558/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8559///
8560/// \param TypeExpr Expression that specifies a type tag.
8561///
8562/// \param MagicValues Registered magic values.
8563///
8564/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8565/// kind.
8566///
8567/// \param TypeInfo Information about the corresponding C type.
8568///
8569/// \returns true if the corresponding C type was found.
8570bool GetMatchingCType(
8571 const IdentifierInfo *ArgumentKind,
8572 const Expr *TypeExpr, const ASTContext &Ctx,
8573 const llvm::DenseMap<Sema::TypeTagMagicValue,
8574 Sema::TypeTagData> *MagicValues,
8575 bool &FoundWrongKind,
8576 Sema::TypeTagData &TypeInfo) {
8577 FoundWrongKind = false;
8578
8579 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008580 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008581
8582 uint64_t MagicValue;
8583
8584 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8585 return false;
8586
8587 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008588 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008589 if (I->getArgumentKind() != ArgumentKind) {
8590 FoundWrongKind = true;
8591 return false;
8592 }
8593 TypeInfo.Type = I->getMatchingCType();
8594 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8595 TypeInfo.MustBeNull = I->getMustBeNull();
8596 return true;
8597 }
8598 return false;
8599 }
8600
8601 if (!MagicValues)
8602 return false;
8603
8604 llvm::DenseMap<Sema::TypeTagMagicValue,
8605 Sema::TypeTagData>::const_iterator I =
8606 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8607 if (I == MagicValues->end())
8608 return false;
8609
8610 TypeInfo = I->second;
8611 return true;
8612}
8613} // unnamed namespace
8614
8615void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8616 uint64_t MagicValue, QualType Type,
8617 bool LayoutCompatible,
8618 bool MustBeNull) {
8619 if (!TypeTagForDatatypeMagicValues)
8620 TypeTagForDatatypeMagicValues.reset(
8621 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8622
8623 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8624 (*TypeTagForDatatypeMagicValues)[Magic] =
8625 TypeTagData(Type, LayoutCompatible, MustBeNull);
8626}
8627
8628namespace {
8629bool IsSameCharType(QualType T1, QualType T2) {
8630 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8631 if (!BT1)
8632 return false;
8633
8634 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8635 if (!BT2)
8636 return false;
8637
8638 BuiltinType::Kind T1Kind = BT1->getKind();
8639 BuiltinType::Kind T2Kind = BT2->getKind();
8640
8641 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8642 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8643 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8644 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8645}
8646} // unnamed namespace
8647
8648void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8649 const Expr * const *ExprArgs) {
8650 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8651 bool IsPointerAttr = Attr->getIsPointer();
8652
8653 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8654 bool FoundWrongKind;
8655 TypeTagData TypeInfo;
8656 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8657 TypeTagForDatatypeMagicValues.get(),
8658 FoundWrongKind, TypeInfo)) {
8659 if (FoundWrongKind)
8660 Diag(TypeTagExpr->getExprLoc(),
8661 diag::warn_type_tag_for_datatype_wrong_kind)
8662 << TypeTagExpr->getSourceRange();
8663 return;
8664 }
8665
8666 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8667 if (IsPointerAttr) {
8668 // Skip implicit cast of pointer to `void *' (as a function argument).
8669 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008670 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008671 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008672 ArgumentExpr = ICE->getSubExpr();
8673 }
8674 QualType ArgumentType = ArgumentExpr->getType();
8675
8676 // Passing a `void*' pointer shouldn't trigger a warning.
8677 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8678 return;
8679
8680 if (TypeInfo.MustBeNull) {
8681 // Type tag with matching void type requires a null pointer.
8682 if (!ArgumentExpr->isNullPointerConstant(Context,
8683 Expr::NPC_ValueDependentIsNotNull)) {
8684 Diag(ArgumentExpr->getExprLoc(),
8685 diag::warn_type_safety_null_pointer_required)
8686 << ArgumentKind->getName()
8687 << ArgumentExpr->getSourceRange()
8688 << TypeTagExpr->getSourceRange();
8689 }
8690 return;
8691 }
8692
8693 QualType RequiredType = TypeInfo.Type;
8694 if (IsPointerAttr)
8695 RequiredType = Context.getPointerType(RequiredType);
8696
8697 bool mismatch = false;
8698 if (!TypeInfo.LayoutCompatible) {
8699 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8700
8701 // C++11 [basic.fundamental] p1:
8702 // Plain char, signed char, and unsigned char are three distinct types.
8703 //
8704 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8705 // char' depending on the current char signedness mode.
8706 if (mismatch)
8707 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8708 RequiredType->getPointeeType())) ||
8709 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8710 mismatch = false;
8711 } else
8712 if (IsPointerAttr)
8713 mismatch = !isLayoutCompatible(Context,
8714 ArgumentType->getPointeeType(),
8715 RequiredType->getPointeeType());
8716 else
8717 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8718
8719 if (mismatch)
8720 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008721 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008722 << TypeInfo.LayoutCompatible << RequiredType
8723 << ArgumentExpr->getSourceRange()
8724 << TypeTagExpr->getSourceRange();
8725}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008726